forge
Explore
Log in

Don't you dare go Hollow

Audit findings: streamed xlsx preview, no ODS preview, back-channel jti after session end, sign-in never re-enables, directory ordering by im time, rule mail cap, live streams re-check access, alive cap, SMTP password on host change, storage cap, avatar/authz role none, deleted task bytes, upload id resolved first

Browse files at this commit

34f693b65046791b12b57a82b35a5386b722f4b2Ahmet Kaan GümüşParent: 5346e82
  • fix
    • audit findings: streamed xlsx preview, no ODS preview, back-channel jti after session end, sign-in never re-enables, directory ordering by im time, rule mail cap, live streams re-check access, alive cap, SMTP password on host change, storage cap, avatar/authz role none, deleted task bytes, upload id resolved first
Show full message
🔒 fix: audit findings: streamed xlsx preview, no ODS preview, back-channel jti after session end, sign-in never re-enables, directory ordering by im time, rule mail cap, live streams re-check access, alive cap, SMTP password on host change, storage cap, avatar/authz role none, deleted task bytes, upload id resolved first
crates/iz-core/migrations/0006_decision_skipped.sqladded+20 -0
@@ -0,0 +1,20 @@
1+-- 0006: a rule decision can be 'skipped' (the owed mails were all held back by the hourly per-recipient cap,
2+-- with detail 'rate_limited'). The outcome CHECK gains 'skipped'; SQLite cannot alter a CHECK, so the table is
3+-- rebuilt. Rows of 0001 carry over unchanged.
4+CREATE TABLE mail_decisions_by_outcome (
5+ id TEXT PRIMARY KEY,
6+ rule_id TEXT NOT NULL REFERENCES mail_rules(id) ON DELETE CASCADE,
7+ event_id TEXT NOT NULL,
8+ task_id TEXT,
9+ outcome TEXT NOT NULL CHECK (outcome IN (
10+ 'owed', 'already_owed', 'no_recipients', 'not_matched', 'disabled', 'task_gone', 'skipped'
11+ )),
12+ detail TEXT NOT NULL DEFAULT '',
13+ created_at TEXT NOT NULL,
14+ UNIQUE (rule_id, event_id, task_id)
15+);
16+INSERT INTO mail_decisions_by_outcome (id, rule_id, event_id, task_id, outcome, detail, created_at)
17+ SELECT id, rule_id, event_id, task_id, outcome, detail, created_at FROM mail_decisions;
18+DROP TABLE mail_decisions;
19+ALTER TABLE mail_decisions_by_outcome RENAME TO mail_decisions;
20+CREATE INDEX mail_decisions_recent ON mail_decisions(created_at);
crates/iz-core/src/archive.rsmodified+1 -1
@@ -1,4 +1,4 @@
1-//! Zip-container guards for the spreadsheet and slide viewers. A `.xlsx`, `.ods` or `.pptx` is a zip file,
1+//! Zip-container guards for the spreadsheet and slide viewers. A `.xlsx` or `.pptx` is a zip file,
22 //! so one of them can expand to far more than it weighs. Every such file is checked here before any parser
33 //! sees it (`docs/architecture.md`, attack plan section 6: zip bombs).
44 //!
crates/iz-core/src/authz.rsmodified+8 -1
@@ -128,7 +128,14 @@ enum Level {
128128 pub fn authorize(actor: &Actor, action: &Action) -> Result<(), Denied> {
129129 let (sub, level) = match actor {
130130 Actor::Anonymous => return Err(Denied::Forbidden),
131- Actor::Member { disabled: true, .. } => return Err(Denied::NotFound),
131+ // A disabled member and a member with no role have no access, even when `im` makes them an admin.
132+ Actor::Member { disabled: true, .. }
133+ | Actor::Member {
134+ role: Role::NoAccess,
135+ ..
136+ } => {
137+ return Err(Denied::NotFound);
138+ }
132139 Actor::Member {
133140 sub,
134141 im_admin: true,
crates/iz-core/src/limits.rsmodified+6 -0
@@ -31,6 +31,9 @@ pub const REMINDER_MINUTES_MAX: u32 = 1440;
3131 pub const BATCH_MINUTES_MAX: u32 = 120;
3232 /// Default per-file attachment limit, in MiB. Reason: the starting value of the setting; an admin raises it.
3333 pub const ATTACHMENT_DEFAULT_MIB: u32 = 100;
34+/// Total size of the attachments of one board when the setting was never saved, in bytes. Reason: the
35+/// disk is shared with the database and the backups; an admin raises it deliberately.
36+pub const ATTACHMENT_TOTAL_DEFAULT_BYTES: u64 = 20 * 1024 * 1024 * 1024;
3437 /// Most file parts one upload request may carry. Reason: bounds the work one form can cause.
3538 pub const UPLOAD_FILES_MAX: usize = 10;
3639 /// Leading bytes of an upload that the sniffer reads. Reason: enough for every signature it knows.
@@ -39,6 +42,9 @@ pub const SNIFF_BYTES: usize = 8192;
3942 pub const TEXT_PREVIEW_BYTES: u64 = 256 * 1024;
4043 /// Largest compressed spreadsheet or CSV the viewer parses, in bytes. Reason: bounds the work of one preview.
4144 pub const SHEET_INPUT_MAX_BYTES: u64 = 5 * 1024 * 1024;
45+/// Most cells one `.xlsx` sheet preview visits, kept or not. Reason: bounds the work on a sheet with a huge
46+/// used range, whatever the caps keep.
47+pub const SHEET_VISITS_MAX: usize = 200_000;
4248 /// Largest compressed slide deck the viewer parses, in bytes. Reason: decks carry pictures, so the cap is higher.
4349 pub const SLIDES_INPUT_MAX_BYTES: u64 = 20 * 1024 * 1024;
4450 /// Largest total uncompressed size of a zip container the viewers read, in bytes. Reason: a zip bomb is
crates/iz-core/src/sender.rsmodified+3 -0
@@ -14,6 +14,9 @@ pub const DEFAULT_FROM_NAME: &str = "iz";
1414 pub const DEFAULT_PORT: u16 = 587;
1515 /// Reminders per member per hour when the setting was never saved. Reason: a guard against a burst.
1616 pub const DEFAULT_REMINDER_CAP: u32 = 20;
17+/// Rule mails per recipient per hour when the setting was never saved. Reason: a rule fires on every
18+/// matching event, so one busy board must not flood one member's inbox.
19+pub const DEFAULT_RULE_CAP: u32 = 30;
1720
1821 /// How the connection to the mail server is protected.
1922 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
crates/iz-core/src/sheet.rsmodified+159 -29
@@ -1,20 +1,28 @@
1-//! Spreadsheet previews: a workbook (`.xlsx`, `.ods`) or a CSV file read as values only, with the caps of
1+//! Spreadsheet previews: a workbook (`.xlsx`) or a CSV file read as values only, with the caps of
22 //! `limits.rs`: at most 20 sheets, 1000 rows, 100 columns and 1000 characters a cell. Formulas, formats,
33 //! charts and macros are not read; a cell is its displayed value. The caller turns the result into HTML,
44 //! where every cell is escaped, so a cell that holds markup is shown as text.
55 //!
6-//! A workbook is a zip container, so it passes `archive::open_checked` before calamine parses it. A CSV is
7-//! read record by record and stops at the row cap, so a long file costs no more than the cap.
6+//! A workbook is a zip container, so it passes `archive::open_checked` before calamine parses it. An `.xlsx`
7+//! is read cell by cell as a stream: a cell outside the caps is dropped as it is read, and the reading stops
8+//! after a fixed number of visited cells, so a sheet whose used range is huge (a stray cell at `XFD1048576`)
9+//! costs no more than the caps. An `.ods` is not previewed at all: calamine has no cell stream for it and reads
10+//! its `content.xml` whole, and a tiny file can declare huge repeat counts that allocate gigabytes. The viewer
11+//! shows such a file as refused, and it can still be downloaded. A CSV is read record by record and stops at
12+//! the row cap, so a long file costs no more than the cap.
813
14+use std::collections::BTreeMap;
915 use std::fs::File;
16+use std::io::BufReader;
1017 use std::path::Path;
1118
12-use calamine::{Data, Reader, open_workbook_auto};
19+use calamine::{Data, DataRef, Reader, Sheets, Xlsx, open_workbook_auto};
1320
1421 use crate::archive;
1522 use crate::error::{Error, Result};
1623 use crate::limits::{
17- CELL_TEXT_MAX, SHEET_COLS_MAX, SHEET_INPUT_MAX_BYTES, SHEET_ROWS_MAX, SHEETS_MAX,
24+ CELL_TEXT_MAX, SHEET_COLS_MAX, SHEET_INPUT_MAX_BYTES, SHEET_ROWS_MAX, SHEET_VISITS_MAX,
25+ SHEETS_MAX,
1826 };
1927
2028 /// One sheet of a book, as text cells. `rows_cut` is set when the sheet had more rows than the cap.
@@ -42,37 +50,35 @@ fn cell_text(text: &str) -> String {
4250 text.chars().take(CELL_TEXT_MAX).collect()
4351 }
4452
45-/// Reads an `.xlsx` or `.ods` workbook. Refused (as `Invalid`) when the zip checks fail.
53+/// The shown text of a streamed `.xlsx` cell, cut to the cap as it is read.
54+fn data_ref_text(value: &DataRef<'_>) -> String {
55+ match value {
56+ DataRef::SharedString(text) => cell_text(text),
57+ DataRef::String(text) => cell_text(text),
58+ other => cell_text(&Data::from(other.clone()).to_string()),
59+ }
60+}
61+
62+/// Reads an `.xlsx` workbook (`.xls` and `.xlsb` too). Refused (as `Invalid`) when the zip checks fail, and
63+/// for an OpenDocument file: it is refused before calamine opens it, because calamine reads its `content.xml`
64+/// whole.
4665 pub fn read_workbook(path: &Path) -> Result<Book> {
47- archive::open_checked(path, SHEET_INPUT_MAX_BYTES)?;
66+ let mut zip = archive::open_checked(path, SHEET_INPUT_MAX_BYTES)?;
67+ if zip.by_name("content.xml").is_ok() {
68+ // Only an OpenDocument file has a root `content.xml`. Such files are not previewed.
69+ return Err(Error::Invalid("ods_not_previewed".into()));
70+ }
4871 let mut workbook =
4972 open_workbook_auto(path).map_err(|_| Error::Invalid("bad_workbook".into()))?;
5073 let names = workbook.sheet_names();
5174 let sheet_count = names.len();
5275 let mut sheets = Vec::new();
5376 for name in names.into_iter().take(SHEETS_MAX) {
54- let range = workbook
55- .worksheet_range(&name)
56- .map_err(|_| Error::Invalid("bad_workbook".into()))?;
57- let mut rows = Vec::new();
58- let mut rows_cut = false;
59- for (index, row) in range.rows().enumerate() {
60- if index == SHEET_ROWS_MAX {
61- rows_cut = true;
62- break;
63- }
64- rows.push(
65- row.iter()
66- .take(SHEET_COLS_MAX)
67- .map(|cell: &Data| cell_text(&cell.to_string()))
68- .collect(),
69- );
70- }
71- sheets.push(Sheet {
72- name,
73- rows,
74- rows_cut,
75- });
77+ let sheet = match &mut workbook {
78+ Sheets::Xlsx(xlsx) => read_xlsx_sheet(xlsx, &name)?,
79+ _ => read_range_sheet(&mut workbook, &name)?,
80+ };
81+ sheets.push(sheet);
7682 }
7783 Ok(Book {
7884 sheets,
@@ -80,6 +86,74 @@ pub fn read_workbook(path: &Path) -> Result<Book> {
8086 })
8187 }
8288
89+/// Streams one `.xlsx` sheet. Only cells inside the caps are kept, in a sparse map, and the table is built
90+/// from them. `rows_cut` is set when a kept-out cell has text, or when the visit budget ended the read early.
91+fn read_xlsx_sheet(xlsx: &mut Xlsx<BufReader<File>>, name: &str) -> Result<Sheet> {
92+ let bad = || Error::Invalid("bad_workbook".into());
93+ let mut reader = xlsx.worksheet_cells_reader(name).map_err(|_| bad())?;
94+ let mut cells: BTreeMap<(usize, usize), String> = BTreeMap::new();
95+ let mut rows_cut = false;
96+ let mut visits = 0usize;
97+ while let Some(cell) = reader.next_cell().map_err(|_| bad())? {
98+ visits += 1;
99+ if visits > SHEET_VISITS_MAX {
100+ rows_cut = true;
101+ break;
102+ }
103+ let (row, col) = cell.get_position();
104+ let (row, col) = (row as usize, col as usize);
105+ let text = data_ref_text(cell.get_value());
106+ if text.is_empty() {
107+ continue;
108+ }
109+ if row >= SHEET_ROWS_MAX {
110+ rows_cut = true;
111+ continue;
112+ }
113+ if col >= SHEET_COLS_MAX {
114+ continue;
115+ }
116+ cells.insert((row, col), text);
117+ }
118+ let rows_used = cells.keys().map(|(row, _)| row + 1).max().unwrap_or(0);
119+ let cols_used = cells.keys().map(|(_, col)| col + 1).max().unwrap_or(0);
120+ let mut rows = vec![vec![String::new(); cols_used]; rows_used];
121+ for ((row, col), text) in cells {
122+ rows[row][col] = text;
123+ }
124+ Ok(Sheet {
125+ name: name.to_owned(),
126+ rows,
127+ rows_cut,
128+ })
129+}
130+
131+/// Reads one sheet of a workbook that is not streamed (`.xls`, `.xlsb`) as a whole range.
132+fn read_range_sheet(workbook: &mut Sheets<BufReader<File>>, name: &str) -> Result<Sheet> {
133+ let range = workbook
134+ .worksheet_range(name)
135+ .map_err(|_| Error::Invalid("bad_workbook".into()))?;
136+ let mut rows = Vec::new();
137+ let mut rows_cut = false;
138+ for (index, row) in range.rows().enumerate() {
139+ if index == SHEET_ROWS_MAX {
140+ rows_cut = true;
141+ break;
142+ }
143+ rows.push(
144+ row.iter()
145+ .take(SHEET_COLS_MAX)
146+ .map(|cell: &Data| cell_text(&cell.to_string()))
147+ .collect(),
148+ );
149+ }
150+ Ok(Sheet {
151+ name: name.to_owned(),
152+ rows,
153+ rows_cut,
154+ })
155+}
156+
83157 /// Reads a CSV file as one sheet. Invalid UTF-8 is shown with replacement characters.
84158 pub fn read_csv(path: &Path, name: &str) -> Result<Book> {
85159 let len = std::fs::metadata(path)?.len();
@@ -154,6 +228,19 @@ mod tests {
154228 assert!(read_workbook(&path).is_err());
155229 }
156230
231+ #[test]
232+ fn an_opendocument_workbook_is_not_previewed() {
233+ let dir = tempfile::tempdir().expect("dir");
234+ let path = dir.path().join("sheet.ods");
235+ let file = std::fs::File::create(&path).expect("create");
236+ let mut writer = zip::ZipWriter::new(file);
237+ let options = zip::write::SimpleFileOptions::default();
238+ writer.start_file("content.xml", options).expect("start");
239+ std::io::Write::write_all(&mut writer, b"<office:document-content/>").expect("write");
240+ writer.finish().expect("finish");
241+ assert!(read_workbook(&path).is_err());
242+ }
243+
157244 #[test]
158245 fn a_csv_stops_at_the_row_cap() {
159246 let dir = tempfile::tempdir().expect("dir");
@@ -165,6 +252,49 @@ mod tests {
165252 assert!(book.sheets[0].rows_cut);
166253 }
167254
255+ /// A minimal `.xlsx`: A1 holds "hello" and XFD1048576 (the far corner) holds a number.
256+ #[test]
257+ fn a_far_cell_does_not_blow_up_the_preview() {
258+ use std::io::Write;
259+ let dir = tempfile::tempdir().expect("dir");
260+ let path = dir.path().join("far.xlsx");
261+ let file = std::fs::File::create(&path).expect("create");
262+ let mut writer = zip::ZipWriter::new(file);
263+ let options = zip::write::SimpleFileOptions::default()
264+ .compression_method(zip::CompressionMethod::Deflated);
265+ let parts = [
266+ (
267+ "[Content_Types].xml",
268+ r#"<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>"#,
269+ ),
270+ (
271+ "_rels/.rels",
272+ r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>"#,
273+ ),
274+ (
275+ "xl/workbook.xml",
276+ r#"<?xml version="1.0" encoding="UTF-8"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Far" sheetId="1" r:id="rId1"/></sheets></workbook>"#,
277+ ),
278+ (
279+ "xl/_rels/workbook.xml.rels",
280+ r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>"#,
281+ ),
282+ (
283+ "xl/worksheets/sheet1.xml",
284+ r#"<?xml version="1.0" encoding="UTF-8"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>hello</t></is></c></row><row r="1048576"><c r="XFD1048576"><v>7</v></c></row></sheetData></worksheet>"#,
285+ ),
286+ ];
287+ for (name, body) in parts {
288+ writer.start_file(name, options).expect("start");
289+ writer.write_all(body.as_bytes()).expect("write");
290+ }
291+ writer.finish().expect("finish");
292+ let book = read_workbook(&path).expect("workbook");
293+ assert_eq!(book.sheet_count, 1);
294+ assert_eq!(book.sheets[0].rows, vec![vec!["hello".to_owned()]]);
295+ assert!(book.sheets[0].rows_cut);
296+ }
297+
168298 #[test]
169299 fn a_cell_is_cut_to_its_cap() {
170300 assert_eq!(
crates/iz-core/src/store/attachments.rsmodified+81 -17
@@ -9,13 +9,15 @@
99
1010 use serde_json::json;
1111 use turso::Connection;
12+use turso::transaction::Transaction;
1213
1314 use super::activity::{self, NewActivity};
1415 use super::{col_int, col_text, db_err, fetch_all, fetch_opt, finish, new_id};
1516 use crate::authz::{Action, Actor, authorize};
1617 use crate::error::{Error, Result};
1718 use crate::limits::{
18- ATTACHMENT_DEFAULT_MIB, ATTACHMENT_LIMIT_MIB_MAX, ATTACHMENT_LIMIT_MIB_MIN, FILE_NAME_MAX,
19+ ATTACHMENT_DEFAULT_MIB, ATTACHMENT_LIMIT_MIB_MAX, ATTACHMENT_LIMIT_MIB_MIN,
20+ ATTACHMENT_TOTAL_DEFAULT_BYTES, FILE_NAME_MAX,
1921 };
2022 use crate::store::Store;
2123 use crate::time::{now_stamp, stamp_after};
@@ -25,6 +27,8 @@ use std::time::Duration;
2527 pub const SETTING_LIMIT_MIB: &str = "attachment_limit_mib";
2628 /// The setting that holds the allowed extensions, separated by spaces or commas.
2729 pub const SETTING_EXTENSIONS: &str = "attachment_extensions";
30+/// The setting that holds the total size of the attachments of one board, in bytes.
31+pub const SETTING_TOTAL_BYTES: &str = "attachments_total_bytes";
2832 /// The setting that holds where new and existing attachments belong: `local` (default) or `in`.
2933 pub const SETTING_LOCATION: &str = "attachment_location";
3034 /// Where the bytes of an attachment are, as its row says: this disk, the Files service, or in between.
@@ -94,6 +98,56 @@ pub struct NewAttachment {
9498 const ATTACHMENT_COLS: &str =
9599 "a.id, a.task_id, a.name, a.mime, a.size, a.sha256, a.uploaded_by, a.created_at, a.location";
96100
101+/// Records the copies of one attachment's bytes as owed to deletion, in the caller's transaction. A moving
102+/// row may have a copy in each place, so both are owed; a settled row has one copy.
103+pub(super) async fn owe_bytes(
104+ tx: &Transaction<'_>,
105+ attachment_id: &str,
106+ location: &str,
107+ now: &str,
108+) -> Result<()> {
109+ let owed: &[&str] = match location {
110+ LOCATION_LOCAL => &[LOCATION_LOCAL],
111+ LOCATION_IN => &[LOCATION_IN],
112+ _ => &[LOCATION_LOCAL, LOCATION_IN],
113+ };
114+ for place in owed {
115+ tx.execute(
116+ "INSERT INTO blob_deletions (attachment_id, location, attempts, next_attempt_at, created_at) \
117+ VALUES (?1, ?2, 0, ?3, ?4)",
118+ (
119+ attachment_id.to_owned(),
120+ (*place).to_owned(),
121+ now.to_owned(),
122+ now.to_owned(),
123+ ),
124+ )
125+ .await
126+ .map_err(db_err)?;
127+ }
128+ Ok(())
129+}
130+
131+/// Queues the bytes of every attachment of a task that is being deleted, and removes the rows, in the
132+/// caller's transaction. Without this the rows would go with the task at purge and the bytes would be
133+/// orphaned; with it the deleter removes them.
134+pub(super) async fn owe_task_bytes(tx: &Transaction<'_>, task_id: &str, now: &str) -> Result<()> {
135+ let rows = fetch_all(
136+ tx,
137+ "SELECT id, location FROM attachments WHERE task_id = ?1",
138+ (task_id.to_owned(),),
139+ |row| Ok((col_text(row, 0)?, col_text(row, 1)?)),
140+ )
141+ .await?;
142+ for (id, location) in rows {
143+ owe_bytes(tx, &id, &location, now).await?;
144+ tx.execute("DELETE FROM attachments WHERE id = ?1", (id,))
145+ .await
146+ .map_err(db_err)?;
147+ }
148+ Ok(())
149+}
150+
97151 fn map_attachment(row: &turso::Row) -> Result<Attachment> {
98152 Ok(Attachment {
99153 id: col_text(row, 0)?,
@@ -180,7 +234,8 @@ impl Store {
180234 }
181235
182236 /// Stores an attachment on a live task of `board_id`, with its `file_added` activity row. The bytes must
183- /// already be in place under `new.id`; if this fails, the caller removes them.
237+ /// already be in place under `new.id`; if this fails, the caller removes them. Refused as
238+ /// `storage_full` when the board's attachments, with this one, would pass the total cap.
184239 pub async fn add_attachment(
185240 &self,
186241 board_id: &str,
@@ -213,6 +268,29 @@ impl Store {
213268 if live.is_none() {
214269 return Err(Error::NotFound);
215270 }
271+ // The board's total must stay within its cap, counted in the same transaction as the insert.
272+ let cap = fetch_opt(
273+ &tx,
274+ "SELECT value FROM settings WHERE key = ?1",
275+ (SETTING_TOTAL_BYTES.to_owned(),),
276+ |row| col_text(row, 0),
277+ )
278+ .await?
279+ .and_then(|v| v.trim().parse::<u64>().ok())
280+ .unwrap_or(ATTACHMENT_TOTAL_DEFAULT_BYTES);
281+ let used = fetch_opt(
282+ &tx,
283+ "SELECT COALESCE(SUM(a.size), 0) FROM attachments a JOIN tasks t ON t.id = a.task_id \
284+ WHERE t.board_id = ?1",
285+ (board_id.to_owned(),),
286+ |row| col_int(row, 0),
287+ )
288+ .await?
289+ .unwrap_or(0);
290+ let used = u64::try_from(used).unwrap_or(u64::MAX);
291+ if used.saturating_add(new.size) > cap {
292+ return Err(Error::Invalid("storage_full".into()));
293+ }
216294 tx.execute(
217295 "INSERT INTO attachments (id, task_id, comment_id, name, mime, size, sha256, uploaded_by, created_at, location) \
218296 VALUES (?1, ?2, NULL, ?3, ?4, ?5, ?6, ?7, ?8, 'local')",
@@ -336,21 +414,7 @@ impl Store {
336414 )
337415 .await
338416 .map_err(db_err)?;
339- // A moving row may have a copy in each place, so both are owed. A settled row has one copy.
340- let owed: &[&str] = match current.location.as_str() {
341- LOCATION_LOCAL => &[LOCATION_LOCAL],
342- LOCATION_IN => &[LOCATION_IN],
343- _ => &[LOCATION_LOCAL, LOCATION_IN],
344- };
345- for place in owed {
346- tx.execute(
347- "INSERT INTO blob_deletions (attachment_id, location, attempts, next_attempt_at, created_at) \
348- VALUES (?1, ?2, 0, ?3, ?4)",
349- (attachment_id.to_owned(), (*place).to_owned(), now.clone(), now.clone()),
350- )
351- .await
352- .map_err(db_err)?;
353- }
417+ owe_bytes(&tx, attachment_id, &current.location, &now).await?;
354418 activity::record(
355419 &tx,
356420 NewActivity {
crates/iz-core/src/store/members.rsmodified+90 -27
@@ -14,7 +14,7 @@ use crate::authz::Role;
1414 use crate::error::{Error, Result};
1515 use crate::limits::DISPLAY_NAME_MAX;
1616 use crate::store::Store;
17-use crate::time::now_stamp;
17+use crate::time::{normalize_stamp, now_stamp};
1818 use crate::zones::parse_zone;
1919
2020 /// Longest email address accepted from the directory, in characters (RFC 5321 path limit).
@@ -78,6 +78,9 @@ pub struct DirectoryMember {
7878 pub zoneinfo: String,
7979 /// Photo version from `im`.
8080 pub picture_version: i64,
81+ /// The directory's `updated_at` (an RFC 3339 time). Normalised to the stored stamp form; empty or
82+ /// unparseable values fall back to the local time. Orders this write against other directory data.
83+ pub updated_at: String,
8184 }
8285
8386 const MEMBER_COLS: &str = "sub, email, name, im_admin, disabled, locale, locale_override, zoneinfo, \
@@ -144,6 +147,7 @@ fn validate(m: &DirectoryMember) -> Result<DirectoryMember> {
144147 locale: m.locale.clone().filter(|l| LOCALES.contains(&l.as_str())),
145148 zoneinfo,
146149 picture_version: m.picture_version,
150+ updated_at: m.updated_at.trim().to_owned(),
147151 })
148152 }
149153
@@ -182,23 +186,55 @@ impl Store {
182186 member: &DirectoryMember,
183187 default_role: Role,
184188 ) -> Result<Member> {
185- self.upsert_member(member, default_role, false).await
189+ let m = validate(member)?;
190+ let stamp = normalize_stamp(&m.updated_at).unwrap_or_else(now_stamp);
191+ let now = now_stamp();
192+ let conn = self.inner.conn.lock().await;
193+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
194+ let outcome: Result<Member> = async {
195+ tx.execute(
196+ "INSERT INTO members (sub, email, name, im_admin, disabled, locale, zoneinfo, \
197+ picture_version, im_updated_at, role, first_seen_at) \
198+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11) \
199+ ON CONFLICT(sub) DO UPDATE SET email = excluded.email, name = excluded.name, \
200+ im_admin = excluded.im_admin, disabled = excluded.disabled, \
201+ locale = excluded.locale, zoneinfo = excluded.zoneinfo, \
202+ picture_version = excluded.picture_version, im_updated_at = excluded.im_updated_at \
203+ WHERE excluded.im_updated_at >= members.im_updated_at",
204+ (
205+ m.sub.clone(),
206+ m.email.clone(),
207+ m.name.clone(),
208+ i64::from(m.im_admin),
209+ i64::from(m.disabled),
210+ m.locale.clone(),
211+ m.zoneinfo.clone(),
212+ m.picture_version,
213+ stamp,
214+ default_role.as_str(),
215+ now,
216+ ),
217+ )
218+ .await
219+ .map_err(db_err)?;
220+ select_member(&tx, &m.sub)
221+ .await?
222+ .ok_or_else(|| Error::Database("member vanished after upsert".into()))
223+ }
224+ .await;
225+ finish(tx, outcome).await
186226 }
187227
188- /// Creates or refreshes a member at sign-in (from the ID token claims) and stamps the sign-in time.
228+ /// Records a sign-in. A new member gets `default_role`. An existing member gets the claim fields
229+ /// refreshed only when `claims_at` (the ID token's `iat`, as a stamp) is not older than the stored
230+ /// `im_updated_at`, so a stale sign-in cannot roll back a newer change. `disabled` is never written
231+ /// here: the directory owns it, so a sign-in cannot re-enable a disabled member. Always stamps
232+ /// `last_sign_in_at`.
189233 pub async fn upsert_from_claims(
190234 &self,
191235 member: &DirectoryMember,
192236 default_role: Role,
193- ) -> Result<Member> {
194- self.upsert_member(member, default_role, true).await
195- }
196-
197- async fn upsert_member(
198- &self,
199- member: &DirectoryMember,
200- default_role: Role,
201- signed_in: bool,
237+ claims_at: &str,
202238 ) -> Result<Member> {
203239 let m = validate(member)?;
204240 let now = now_stamp();
@@ -206,36 +242,35 @@ impl Store {
206242 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
207243 let outcome: Result<Member> = async {
208244 tx.execute(
209- "INSERT INTO members (sub, email, name, im_admin, disabled, locale, zoneinfo, \
245+ "INSERT INTO members (sub, email, name, im_admin, locale, zoneinfo, \
210246 picture_version, im_updated_at, role, first_seen_at) \
211- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?9) \
247+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10) \
212248 ON CONFLICT(sub) DO UPDATE SET email = excluded.email, name = excluded.name, \
213- im_admin = excluded.im_admin, disabled = excluded.disabled, \
214- locale = excluded.locale, zoneinfo = excluded.zoneinfo, \
215- picture_version = excluded.picture_version, im_updated_at = excluded.im_updated_at",
249+ im_admin = excluded.im_admin, locale = excluded.locale, \
250+ zoneinfo = excluded.zoneinfo, picture_version = excluded.picture_version, \
251+ im_updated_at = excluded.im_updated_at \
252+ WHERE excluded.im_updated_at >= members.im_updated_at",
216253 (
217254 m.sub.clone(),
218255 m.email.clone(),
219256 m.name.clone(),
220257 i64::from(m.im_admin),
221- i64::from(m.disabled),
222258 m.locale.clone(),
223259 m.zoneinfo.clone(),
224260 m.picture_version,
225- now.clone(),
261+ claims_at.to_owned(),
226262 default_role.as_str(),
263+ now.clone(),
227264 ),
228265 )
229266 .await
230267 .map_err(db_err)?;
231- if signed_in {
232- tx.execute(
233- "UPDATE members SET last_sign_in_at = ?2 WHERE sub = ?1",
234- (m.sub.clone(), now.clone()),
235- )
236- .await
237- .map_err(db_err)?;
238- }
268+ tx.execute(
269+ "UPDATE members SET last_sign_in_at = ?2 WHERE sub = ?1",
270+ (m.sub.clone(), now),
271+ )
272+ .await
273+ .map_err(db_err)?;
239274 select_member(&tx, &m.sub)
240275 .await?
241276 .ok_or_else(|| Error::Database("member vanished after upsert".into()))
@@ -372,6 +407,7 @@ mod tests {
372407 locale: Some("de".into()),
373408 zoneinfo: "Europe/Istanbul".into(),
374409 picture_version: 0,
410+ updated_at: "2026-10-28T09:00:00.000000000Z".into(),
375411 };
376412 let v = validate(&raw).unwrap();
377413 assert_eq!(v.sub, "u1");
@@ -385,6 +421,33 @@ mod tests {
385421 assert!(validate(&bad).is_err());
386422 }
387423
424+ #[tokio::test]
425+ async fn older_directory_event_does_not_roll_back_a_newer_one() {
426+ let (_dir, store, _board) = crate::store::test_support::seeded().await;
427+ let mut member = DirectoryMember {
428+ sub: "cy".into(),
429+ email: "cy@example.com".into(),
430+ name: "Newer".into(),
431+ im_admin: false,
432+ disabled: false,
433+ locale: None,
434+ zoneinfo: "UTC".into(),
435+ picture_version: 0,
436+ updated_at: "2026-10-28T10:00:00+01:00".into(),
437+ };
438+ store
439+ .apply_directory_member(&member, Role::Member)
440+ .await
441+ .unwrap();
442+ member.name = "Older".into();
443+ member.updated_at = "2026-10-28T08:00:00.000000000Z".into();
444+ let kept = store
445+ .apply_directory_member(&member, Role::Member)
446+ .await
447+ .unwrap();
448+ assert_eq!(kept.name, "Newer");
449+ }
450+
388451 #[tokio::test]
389452 async fn last_administrator_cannot_be_demoted() {
390453 let (_dir, store, _board) = crate::store::test_support::seeded().await;
crates/iz-core/src/store/migrate.rsmodified+4 -0
@@ -20,6 +20,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
2020 5,
2121 include_str!("../../migrations/0005_blob_deletions_by_place.sql"),
2222 ),
23+ (
24+ 6,
25+ include_str!("../../migrations/0006_decision_skipped.sql"),
26+ ),
2327 ];
2428
2529 fn migration_err(e: turso::Error) -> Error {
crates/iz-core/src/store/mod.rsmodified+2 -1
@@ -347,6 +347,7 @@ pub(crate) mod test_support {
347347 locale: None,
348348 zoneinfo: "UTC".into(),
349349 picture_version: 0,
350+ updated_at: "2026-10-28T09:00:00.000000000Z".into(),
350351 };
351352 store.apply_directory_member(&member, role).await.unwrap();
352353 }
@@ -403,7 +404,7 @@ mod tests {
403404 })
404405 .await
405406 .unwrap();
406- assert_eq!(versions, vec![1, 2, 3, 4, 5]);
407+ assert_eq!(versions, vec![1, 2, 3, 4, 5, 6]);
407408 }
408409
409410 #[tokio::test]
crates/iz-core/src/store/rules_engine.rsmodified+54 -5
@@ -19,9 +19,18 @@ use crate::clock::stamp_of;
1919 use crate::error::Result;
2020 use crate::mail_text::{MailLang, RuleMail, rule_body, when_text};
2121 use crate::rules::{Audience, EventFacts, RuleFacts, TaskFacts, Verdict, evaluate, render_subject};
22+use crate::sender::DEFAULT_RULE_CAP;
2223 use crate::store::Store;
24+use crate::store::sender::KEY_RULE_CAP;
2325 use crate::time::now_stamp;
2426
27+/// What one event's handling needs from the pass: the hourly cap and where its window starts.
28+#[derive(Clone, Copy)]
29+struct Limits<'a> {
30+ cap: i64,
31+ window_start: &'a str,
32+}
33+
2534 /// One unprocessed event as read back.
2635 struct QueuedEvent {
2736 id: String,
@@ -159,7 +168,14 @@ pub fn task_link(base_url: &str, key: &str) -> String {
159168 }
160169
161170 /// Handles one event: every rule of its trigger gets a decision, and mail rows for the owed recipients.
162-async fn handle(tx: &Transaction<'_>, event: &QueuedEvent, base_url: &str) -> Result<usize> {
171+/// A recipient already queued `limits.cap` rule mails since `limits.window_start` gets none; the decision
172+/// then records `skipped` with the detail `rate_limited`.
173+async fn handle(
174+ tx: &Transaction<'_>,
175+ event: &QueuedEvent,
176+ base_url: &str,
177+ limits: Limits<'_>,
178+) -> Result<usize> {
163179 let rules = fetch_all(
164180 tx,
165181 "SELECT id, column_id, tag_id, audience, enabled, subject_template, include_details FROM mail_rules \
@@ -231,6 +247,7 @@ async fn handle(tx: &Transaction<'_>, event: &QueuedEvent, base_url: &str) -> Re
231247 Verdict::Owed(recipients) => ("owed", String::new(), recipients.clone()),
232248 };
233249 let mut queued = 0;
250+ let mut capped = 0;
234251 if let (Some(row), Some(task_id)) = (&task, &event.task_id) {
235252 let column_id = event
236253 .column_id
@@ -248,6 +265,19 @@ async fn handle(tx: &Transaction<'_>, event: &QueuedEvent, base_url: &str) -> Re
248265 let Some(member) = eligible.iter().find(|m| &m.sub == sub) else {
249266 continue;
250267 };
268+ let sent_before = fetch_opt(
269+ tx,
270+ "SELECT COUNT(*) FROM mail_outbox WHERE recipient = ?1 AND kind = 'rule' AND created_at >= ?2",
271+ (sub.clone(), limits.window_start.to_owned()),
272+ |row| col_int(row, 0),
273+ )
274+ .await?
275+ .unwrap_or(0);
276+ if sent_before >= limits.cap {
277+ capped += 1;
278+ tracing::warn!(recipient = %sub, cap = limits.cap, "rule mail held back by the hourly cap");
279+ continue;
280+ }
251281 let when = row
252282 .meeting_at
253283 .as_deref()
@@ -294,10 +324,13 @@ async fn handle(tx: &Transaction<'_>, event: &QueuedEvent, base_url: &str) -> Re
294324 }
295325 }
296326 mails += queued;
297- let outcome = if outcome == "owed" && queued == 0 {
298- "already_owed"
327+ let (outcome, detail) = if capped > 0 {
328+ let outcome = if queued == 0 { "skipped" } else { outcome };
329+ (outcome, "rate_limited".to_owned())
330+ } else if outcome == "owed" && queued == 0 {
331+ ("already_owed", detail)
299332 } else {
300- outcome
333+ (outcome, detail)
301334 };
302335 tx.execute(
303336 "INSERT INTO mail_decisions (id, rule_id, event_id, task_id, outcome, detail, created_at) \
@@ -350,8 +383,23 @@ impl Store {
350383 .await?;
351384 let mut report = PassReport::default();
352385 let stamp = stamp_of(now)?;
386+ let cap = fetch_opt(
387+ &tx,
388+ "SELECT value FROM settings WHERE key = ?1",
389+ (KEY_RULE_CAP.to_owned(),),
390+ |row| col_text(row, 0),
391+ )
392+ .await?
393+ .and_then(|v| v.parse::<u32>().ok())
394+ .unwrap_or(DEFAULT_RULE_CAP)
395+ .min(crate::limits::REMINDER_CAP_MAX);
396+ let window_start = stamp_of(now - jiff::SignedDuration::from_hours(1))?;
397+ let limits = Limits {
398+ cap: i64::from(cap),
399+ window_start: &window_start,
400+ };
353401 for event in &events {
354- report.mails += handle(&tx, event, base_url).await?;
402+ report.mails += handle(&tx, event, base_url, limits).await?;
355403 tx.execute(
356404 "UPDATE mail_events SET processed_at = ?2 WHERE id = ?1",
357405 (event.id.clone(), stamp.clone()),
@@ -464,6 +512,7 @@ mod tests {
464512 locale: None,
465513 zoneinfo: "UTC".into(),
466514 picture_version: 0,
515+ updated_at: "2026-10-28T09:00:00.000000000Z".into(),
467516 };
468517 store
469518 .apply_directory_member(&ghost, crate::authz::Role::Member)
crates/iz-core/src/store/sender.rsmodified+2 -0
@@ -28,6 +28,8 @@ pub const KEY_PASSWORD: &str = "mail_password";
2828 pub const KEY_REMINDER_MINUTES: &str = "reminder_minutes";
2929 /// Settings key of the reminder cap per member per hour.
3030 pub const KEY_REMINDER_CAP: &str = "reminder_hourly_cap";
31+/// Settings key of the cap on rule mails per recipient per hour.
32+pub const KEY_RULE_CAP: &str = "rule_hourly_cap";
3133
3234 /// What the store knows about the sender. The password is only represented by its sealed text.
3335 #[derive(Debug, Clone, PartialEq, Eq)]
crates/iz-core/src/store/sessions.rsmodified+14 -0
@@ -187,6 +187,20 @@ impl Store {
187187 Ok(inserted == 0)
188188 }
189189
190+ /// Whether a logout-token id is already recorded. Reads only; a caller that acts on the answer
191+ /// records the id afterwards with [`Store::seen_jti`].
192+ pub async fn jti_recorded(&self, jti: &str) -> Result<bool> {
193+ let conn = self.read_conn().await;
194+ let row = fetch_opt(
195+ &conn,
196+ "SELECT 1 FROM seen_logout_jti WHERE jti = ?1",
197+ (jti.to_owned(),),
198+ |_| Ok(()),
199+ )
200+ .await?;
201+ Ok(row.is_some())
202+ }
203+
190204 /// Deletes replay records whose lifetime has passed. Returns the count.
191205 pub async fn sweep_jti(&self) -> Result<u64> {
192206 let conn = self.inner.conn.lock().await;
crates/iz-core/src/store/tasks.rsmodified+3 -0
@@ -813,6 +813,9 @@ impl Store {
813813 .map_err(db_err)?;
814814 log(&tx, id, actor, "task_deleted", None, serde_json::json!({})).await?;
815815 }
816+ for id in &doomed {
817+ super::attachments::owe_task_bytes(&tx, id, &now).await?;
818+ }
816819 queue_event(&tx, board_id, task_id, "deleted", actor, None, None).await?;
817820 let doomed_set: HashSet<&str> = doomed.iter().map(String::as_str).collect();
818821 let mut edges: Vec<(String, String)> = Vec::new();
crates/iz-core/src/time.rsmodified+31 -1
@@ -4,7 +4,8 @@
44 use std::time::Duration;
55
66 use time::{
7- OffsetDateTime, SignedDuration, format_description::FormatItem, macros::format_description,
7+ OffsetDateTime, SignedDuration, format_description::FormatItem,
8+ format_description::well_known::Rfc3339, macros::format_description,
89 };
910
1011 const FORMAT: &[FormatItem<'static>] =
@@ -22,6 +23,21 @@ pub fn now_stamp() -> String {
2223 format_stamp(OffsetDateTime::now_utc())
2324 }
2425
26+/// The stamp of a Unix time in whole seconds (an ID token's `iat`), or `None` when it is out of range.
27+pub fn stamp_from_unix(secs: i64) -> Option<String> {
28+ OffsetDateTime::from_unix_timestamp(secs)
29+ .ok()
30+ .map(format_stamp)
31+}
32+
33+/// Parses an RFC 3339 time (any offset, any fraction length) and re-formats it as a stamp. `None` when
34+/// the text does not parse. This brings directory times into the stored form so text comparison works.
35+pub fn normalize_stamp(raw: &str) -> Option<String> {
36+ OffsetDateTime::parse(raw.trim(), &Rfc3339)
37+ .ok()
38+ .map(format_stamp)
39+}
40+
2541 /// The stamp for `now + after`. Saturates at the largest representable time instead of panicking.
2642 pub fn stamp_after(after: Duration) -> String {
2743 let delta = SignedDuration::try_from(after).unwrap_or(SignedDuration::MAX);
@@ -33,6 +49,20 @@ mod tests {
3349 use super::*;
3450 use time::macros::datetime;
3551
52+ #[test]
53+ fn normalize_brings_rfc3339_into_stamp_form() {
54+ assert_eq!(
55+ normalize_stamp("2026-10-28T12:00:00+03:00").as_deref(),
56+ Some("2026-10-28T09:00:00.000000000Z")
57+ );
58+ assert_eq!(
59+ normalize_stamp("2026-10-28T09:00:00.5Z").as_deref(),
60+ Some("2026-10-28T09:00:00.500000000Z")
61+ );
62+ assert_eq!(normalize_stamp(""), None);
63+ assert_eq!(normalize_stamp("yesterday"), None);
64+ }
65+
3666 #[test]
3767 fn stamp_is_fixed_width_utc_with_nine_digits() {
3868 let s = format_stamp(datetime!(2026-10-28 09:05:00.5 UTC));
crates/iz-web/src/auth.rsmodified+25 -2
@@ -9,6 +9,7 @@ use std::time::Duration;
99
1010 use iz_core::authz::{Action, Actor, Denied, authorize};
1111 use iz_core::secret;
12+use iz_core::store::Store;
1213 use iz_core::store::members::Member;
1314 use iz_core::store::sessions::SessionRecord;
1415 use iz_core::token::constant_time_eq;
@@ -102,8 +103,21 @@ pub async fn current_member(cx: &Cx) -> Result<Option<CurrentMember>> {
102103 let Some(cookie) = jar(cx).get(SESSION_COOKIE) else {
103104 return Ok(None);
104105 };
105- let store = &app_context::<AppState>(cx).store;
106- let Some(session) = store.session_by_token(cookie.value()).await? else {
106+ member_of_token(&app_context::<AppState>(cx).store, cookie.value()).await
107+}
108+
109+/// The value of the session cookie, or an empty string when there is none. A live stream keeps it, so
110+/// it can check the session again after the request has ended.
111+pub fn session_cookie(cx: &Cx) -> String {
112+ jar(cx)
113+ .get(SESSION_COOKIE)
114+ .map(|cookie| cookie.value().to_owned())
115+ .unwrap_or_default()
116+}
117+
118+/// The member of a session cookie `token`, under the same rules as [`current_member`].
119+pub async fn member_of_token(store: &Store, token: &str) -> Result<Option<CurrentMember>> {
120+ let Some(session) = store.session_by_token(token).await? else {
107121 return Ok(None);
108122 };
109123 let Some(member) = store.member(&session.sub).await? else {
@@ -112,6 +126,15 @@ pub async fn current_member(cx: &Cx) -> Result<Option<CurrentMember>> {
112126 Ok(Some(CurrentMember { session, member }))
113127 }
114128
129+/// Whether the session `token` still belongs to a member who may read the board. A live stream asks
130+/// this before each event, so a signed-out or disabled viewer stops receiving them.
131+pub async fn still_reads_board(store: &Store, token: &str) -> Result<bool> {
132+ let Some(me) = member_of_token(store, token).await? else {
133+ return Ok(false);
134+ };
135+ Ok(authorize(&me.actor(), &Action::ReadBoard).is_ok())
136+}
137+
115138 /// The signed-in member. Without a session, redirects to `/login?next=<this page>`.
116139 pub async fn require_member(cx: &Cx) -> Result<CurrentMember> {
117140 match current_member(cx).await? {
crates/iz-web/src/cli/fsck.rsmodified+1 -0
@@ -283,6 +283,7 @@ mod tests {
283283 locale: None,
284284 zoneinfo: "UTC".into(),
285285 picture_version: 0,
286+ updated_at: "2026-10-28T09:00:00.000000000Z".into(),
286287 };
287288 store
288289 .apply_directory_member(&member, Role::Admin)
crates/iz-web/src/directory.rsmodified+4 -0
@@ -71,6 +71,9 @@ struct WireMember {
7171 zoneinfo: String,
7272 #[serde(default)]
7373 picture_version: i64,
74+ /// The directory's change time (RFC 3339). Empty when `im` does not send one.
75+ #[serde(default)]
76+ updated_at: String,
7477 }
7578
7679 fn utc() -> String {
@@ -324,6 +327,7 @@ fn parse_member(raw: Value) -> Option<DirectoryMember> {
324327 locale: wire.locale,
325328 zoneinfo: wire.zoneinfo,
326329 picture_version: wire.picture_version,
330+ updated_at: wire.updated_at,
327331 })
328332 }
329333
crates/iz-web/src/i18n/task.rsmodified+8 -0
@@ -211,6 +211,8 @@ pub enum K {
211211 ErrTooManyFiles,
212212 /// Refused: the file could not be stored; nothing was kept.
213213 ErrFileStore,
214+ /// Refused: the attachment storage of the board is full.
215+ ErrFileStorageFull,
214216 /// The viewer message for a file that cannot be previewed (refused, or too large to read).
215217 ViewerRefused,
216218 /// The viewer message for a type with no preview.
@@ -458,6 +460,12 @@ pub fn t(lang: Lang, key: K) -> &'static str {
458460 (K::ErrTooManyFiles, Lang::Tr) => "Bir seferde daha az dosya yükleyin.",
459461 (K::ErrFileStore, Lang::En) => "The file could not be saved. Try again.",
460462 (K::ErrFileStore, Lang::Tr) => "Dosya kaydedilemedi. Tekrar deneyin.",
463+ (K::ErrFileStorageFull, Lang::En) => {
464+ "Attachment storage is full. Remove a file or ask an administrator."
465+ }
466+ (K::ErrFileStorageFull, Lang::Tr) => {
467+ "Ek dosya depolama alanı dolu. Bir dosyayı silin ya da yöneticiye sorun."
468+ }
461469 (K::ViewerRefused, Lang::En) => "This file cannot be previewed. Download it to open it.",
462470 (K::ViewerRefused, Lang::Tr) => "Bu dosya önizlenemiyor. Açmak için indirin.",
463471 (K::NoPreview, Lang::En) => "No preview for this type. Download it to open it.",
crates/iz-web/src/in_store.rsmodified+1 -0
@@ -440,6 +440,7 @@ pub(crate) mod test_support {
440440 locale: None,
441441 zoneinfo: "UTC".into(),
442442 picture_version: 0,
443+ updated_at: "2026-10-28T09:00:00.000000000Z".into(),
443444 };
444445 store
445446 .apply_directory_member(&member, role)
crates/iz-web/src/live.rsmodified+65 -10
@@ -7,15 +7,16 @@
77 //! page wrong for long. Nothing polls, and a topic nobody listens to is dropped.
88 //!
99 //! The hub is not a queue and not an authorisation check. Each route that opens a stream
10-//! authenticates and authorises first, then calls [`stream_changes`].
10+//! authenticates and authorises first, then calls [`stream_changes`], which checks the viewer again
11+//! before every event: a session that ends in the middle of a stream ends the stream too.
1112 //!
12-//! Nothing bumps a topic or opens [`stream_changes`] yet, so the items here are kept ahead of the
13-//! pages that use them.
13+//! The anonymous `/-/alive` stream is the one stream with no viewer to check. It is capped instead.
1414
15-#![allow(dead_code)] // The hub and its topics wait for the pages that bump and follow them.
15+#![allow(dead_code)] // Some topics wait for the pages that bump and follow them.
1616
1717 use std::collections::HashMap;
1818 use std::future::Future;
19+use std::sync::atomic::{AtomicUsize, Ordering};
1920 use std::sync::{Mutex, MutexGuard, PoisonError};
2021 use std::time::Duration;
2122
@@ -25,7 +26,13 @@ use topcoat::Result;
2526 use topcoat::context::Cx;
2627 use topcoat::router::content::sse::{Event, KeepAlive, Sse};
2728 use topcoat::router::response::{IntoResponse, Response};
28-use topcoat::router::{HeaderValue, route};
29+use topcoat::router::{HeaderValue, StatusCode, route};
30+
31+/// Most `/-/alive` streams held at once, over all anonymous viewers. Reason: every page holds one, so
32+/// the count is the number of open tabs; past it a new stream waits for a tab to close.
33+pub const ALIVE_STREAMS_MAX: usize = 256;
34+/// The `/-/alive` streams open now. Each open stream holds one count, given back when it is dropped.
35+static ALIVE_OPEN: AtomicUsize = AtomicUsize::new(0);
2936
3037 /// How long a client waits before it reconnects when a stream ends. Sent once, at the start.
3138 pub const STREAM_RETRY: Duration = Duration::from_millis(1000);
@@ -108,9 +115,10 @@ impl LiveHub {
108115 }
109116
110117 /// The state a stream carries between wakes.
111-struct Follow<F> {
118+struct Follow<F, G> {
112119 wakes: Vec<watch::Receiver<u64>>,
113120 fingerprint: F,
121+ still_allowed: G,
114122 last: String,
115123 }
116124
@@ -118,17 +126,22 @@ struct Follow<F> {
118126 /// differs from the value it last sent, so a bump that changes nothing the viewer sees sends
119127 /// nothing. Nothing is sent on connect: the page already shows the state that `fingerprint` read.
120128 ///
129+/// `still_allowed` is run before each event. When it says no, or fails, the stream ends.
130+///
121131 /// `fingerprint` must be cheap and must describe everything the page shows. A read that fails ends
122132 /// the stream, and the browser reconnects.
123-pub async fn stream_changes<F, Fut>(
133+pub async fn stream_changes<F, Fut, G, GFut>(
124134 cx: &Cx,
125135 hub: &LiveHub,
126136 topics: &[Topic],
127137 fingerprint: F,
138+ still_allowed: G,
128139 ) -> Result<Response>
129140 where
130141 F: Fn() -> Fut + Send + 'static,
131142 Fut: Future<Output = Result<String>> + Send,
143+ G: Fn() -> GFut + Send + 'static,
144+ GFut: Future<Output = Result<bool>> + Send,
132145 {
133146 // Subscribed before the first read, so a change in between still wakes the stream.
134147 let wakes: Vec<watch::Receiver<u64>> =
@@ -137,6 +150,7 @@ where
137150 let follow = Follow {
138151 wakes,
139152 fingerprint,
153+ still_allowed,
140154 last,
141155 };
142156 let events = stream::unfold(follow, |mut follow| async move {
@@ -146,6 +160,19 @@ where
146160 }
147161 match (follow.fingerprint)().await {
148162 Ok(now) if now != follow.last => {
163+ match (follow.still_allowed)().await {
164+ Ok(true) => {}
165+ Ok(false) => {
166+ tracing::info!(
167+ "live: the viewer may no longer read this; stream ended"
168+ );
169+ return None;
170+ }
171+ Err(error) => {
172+ tracing::error!(error = %error, "live: could not check the viewer");
173+ return None;
174+ }
175+ }
149176 follow.last = now;
150177 return Some((changed_event(), follow));
151178 }
@@ -192,10 +219,38 @@ pub fn events_response(
192219 Ok(response)
193220 }
194221
222+/// One open `/-/alive` stream. Given back when the stream is dropped, so a closed tab frees its slot.
223+struct AliveSlot;
224+
225+impl AliveSlot {
226+ /// Takes a slot, or `None` when [`ALIVE_STREAMS_MAX`] streams are already open.
227+ fn take() -> Option<Self> {
228+ if ALIVE_OPEN.fetch_add(1, Ordering::SeqCst) < ALIVE_STREAMS_MAX {
229+ Some(Self)
230+ } else {
231+ ALIVE_OPEN.fetch_sub(1, Ordering::SeqCst);
232+ None
233+ }
234+ }
235+}
236+
237+impl Drop for AliveSlot {
238+ fn drop(&mut self) {
239+ ALIVE_OPEN.fetch_sub(1, Ordering::SeqCst);
240+ }
241+}
242+
195243 /// `GET /-/alive`. Every page holds this stream, so the browser learns when the server stops and
196-/// starts again. Anonymous viewers may hold it, and it reveals nothing: for now it sends only the
197-/// `retry` hint and keep-alives.
244+/// starts again. Anonymous viewers may hold it, and it reveals nothing: it sends only the `retry`
245+/// hint and keep-alives. Past [`ALIVE_STREAMS_MAX`] open streams the answer is `429`.
198246 #[route(GET "/-/alive")]
199247 async fn alive(cx: &Cx) -> Result<Response> {
200- events_response(cx, stream::pending::<Result<Event>>())
248+ let Some(slot) = AliveSlot::take() else {
249+ return StatusCode::TOO_MANY_REQUESTS.into_response(cx);
250+ };
251+ // The closure owns the slot, so the slot lives as long as the stream does.
252+ let events = stream::pending::<Result<Event>>().inspect(move |_| {
253+ let _ = &slot;
254+ });
255+ events_response(cx, events)
201256 }
crates/iz-web/src/oidc.rsmodified+3 -0
@@ -134,6 +134,9 @@ pub struct IdClaims {
134134 /// Bumps when the photo changes. Used as the avatar cache key.
135135 #[serde(default)]
136136 pub picture_version: i64,
137+ /// When `im` issued the token, in Unix seconds. Orders a sign-in against directory changes.
138+ #[serde(default)]
139+ pub iat: i64,
137140 }
138141
139142 /// The claims of a back-channel logout token that iz uses.
crates/iz-web/src/pages/backchannel.rsmodified+6 -3
@@ -49,13 +49,14 @@ struct BackchannelForm {
4949 /// again. A `sid` ends that browser session; a token with only a `sub` ends every session of the
5050 /// user (a disabled or deleted member). Returns how many sessions ended.
5151 ///
52-/// The id is recorded first and atomically (`seen_jti` inserts and reports a repeat), so two copies
53-/// of one token cannot both succeed.
52+/// The id is recorded only after the sessions are gone. A failed delete then leaves no record, so im's
53+/// retry is accepted instead of being refused as a replay. Two copies of one token racing each other
54+/// both end the same sessions, which is harmless, since the delete is idempotent.
5455 pub async fn end_sessions(
5556 store: &Store,
5657 claims: &LogoutClaims,
5758 ) -> std::result::Result<u64, BackchannelError> {
58- if store.seen_jti(&claims.jti, JTI_LIFETIME).await? {
59+ if store.jti_recorded(&claims.jti).await? {
5960 return Err(BackchannelError::Replay);
6061 }
6162 let ended = match (&claims.sid, &claims.sub) {
@@ -64,6 +65,7 @@ pub async fn end_sessions(
6465 // The verifier requires one of the two, so this arm is unreachable in practice.
6566 (None, None) => 0,
6667 };
68+ store.seen_jti(&claims.jti, JTI_LIFETIME).await?;
6769 Ok(ended)
6870 }
6971
@@ -180,6 +182,7 @@ mod tests {
180182 locale: None,
181183 zoneinfo: "UTC".into(),
182184 picture_version: 0,
185+ updated_at: "2026-10-28T09:00:00.000000000Z".into(),
183186 };
184187 store
185188 .apply_directory_member(&member, Role::Member)
crates/iz-web/src/pages/board.rsmodified+10 -1
@@ -25,7 +25,8 @@ use topcoat::view::view;
2525
2626 use crate::assets::BOARD_JS_HREF;
2727 use crate::auth::{
28- CurrentMember, Need, current_member, percent_encode, query_param, require_role, uri_query,
28+ CurrentMember, Need, current_member, percent_encode, query_param, require_role, session_cookie,
29+ still_reads_board, uri_query,
2930 };
3031 use crate::i18n::board::K;
3132 use crate::i18n::{Lang, lang};
@@ -376,6 +377,8 @@ async fn board_live(cx: &Cx) -> Result<Response> {
376377 let board = the_board(&state.store).await?;
377378 let store = state.store.clone();
378379 let board_id = board.id.clone();
380+ let token = session_cookie(cx);
381+ let allowed_store = state.store.clone();
379382 stream_changes(
380383 cx,
381384 &state.live,
@@ -388,6 +391,11 @@ async fn board_live(cx: &Cx) -> Result<Response> {
388391 Ok(fingerprint?)
389392 }
390393 },
394+ move || {
395+ let store = allowed_store.clone();
396+ let token = token.clone();
397+ async move { still_reads_board(&store, &token).await }
398+ },
391399 )
392400 .await
393401 }
@@ -436,6 +444,7 @@ pub(crate) async fn sign_in_as(state: &AppState, sub: &str, role: Role) -> (Stri
436444 locale: None,
437445 zoneinfo: "Europe/Istanbul".into(),
438446 picture_version: 0,
447+ updated_at: "2026-10-28T09:00:00.000000000Z".into(),
439448 };
440449 state
441450 .store
crates/iz-web/src/pages/files.rsmodified+29 -8
@@ -59,9 +59,9 @@ use crate::views::{ViewerInfo, message_page, respond, shell};
5959 const FIELD_MAX_BYTES: usize = 2048;
6060 /// The MIME types of the spreadsheets and the decks the viewers read.
6161 const XLSX: &str = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
62-/// See [`XLSX`].
63-const ODS: &str = "application/vnd.oasis.opendocument.spreadsheet";
64-/// See [`XLSX`].
62+/// The MIME type of an OpenDocument spreadsheet. The viewer refuses it: it is only downloaded.
63+const ODS_MIME: &str = "application/vnd.oasis.opendocument.spreadsheet";
64+/// The MIME type of a `.pptx` deck, read as the text of each slide.
6565 const PPTX: &str = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
6666
6767 /// What a file is shown as. Decided from the sniffed type, and from the name for CSV and plain text.
@@ -77,8 +77,10 @@ pub enum Kind {
7777 Pdf,
7878 /// Plain text, escaped, cut to the preview size.
7979 Text,
80- /// An `.xlsx` or `.ods` workbook, read as values.
80+ /// An `.xlsx` workbook, read as values.
8181 Workbook,
82+ /// A file the viewer does not parse (an `.ods`): shown as refused, and it can only be downloaded.
83+ Refused,
8284 /// A CSV file, read as one sheet.
8385 Csv,
8486 /// A `.pptx` deck, read as the text of each slide.
@@ -99,7 +101,8 @@ pub fn kind_of(attachment: &Attachment) -> Kind {
99101 .trim()
100102 .to_ascii_lowercase();
101103 match essence.as_str() {
102- XLSX | ODS => return Kind::Workbook,
104+ XLSX => return Kind::Workbook,
105+ ODS_MIME => return Kind::Refused,
103106 PPTX => return Kind::Deck,
104107 _ => {}
105108 }
@@ -224,6 +227,7 @@ pub async fn load_view(
224227 Kind::Audio => ViewBody::Audio,
225228 Kind::Pdf => ViewBody::Pdf,
226229 Kind::Nothing => ViewBody::Nothing,
230+ Kind::Refused => ViewBody::Refused,
227231 Kind::Text => match blocking(move || read_text_head(&path, TEXT_PREVIEW_BYTES)).await {
228232 Some((text, cut)) => ViewBody::Text { text, cut },
229233 None => ViewBody::Refused,
@@ -385,6 +389,8 @@ enum Refusal {
385389 NoFile,
386390 /// The bytes could not be stored.
387391 Store,
392+ /// The board's attachment storage is full.
393+ StorageFull,
388394 }
389395
390396 /// The message of a refusal.
@@ -396,6 +402,7 @@ fn refusal_key(refusal: Refusal) -> K {
396402 Refusal::TooMany => K::ErrTooManyFiles,
397403 Refusal::NoFile => K::ErrNoFile,
398404 Refusal::Store => K::ErrFileStore,
405+ Refusal::StorageFull => K::ErrFileStorageFull,
399406 }
400407 }
401408
@@ -467,6 +474,9 @@ async fn store_one(
467474 if let Err(remove) = remove_blob(data_dir, &id).await {
468475 tracing::error!(error = %remove, "removing bytes of a refused upload failed");
469476 }
477+ if matches!(&error, iz_core::Error::Invalid(code) if code == "storage_full") {
478+ return Ok(Err(Refusal::StorageFull));
479+ }
470480 Err(core_err(error))
471481 }
472482 }
@@ -480,6 +490,8 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result<Response> {
480490 let task_id = path_param_segment(cx, "id").to_owned();
481491 let mut member: Option<CurrentMember> = None;
482492 let mut board_id = String::new();
493+ // The task id the path names, resolved from its id or key before any byte is read.
494+ let mut task_uid = String::new();
483495 let mut key = String::new();
484496 let mut next = String::new();
485497 let mut policy: Option<Policy> = None;
@@ -498,6 +510,7 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result<Response> {
498510 .await
499511 .map_err(core_err)?;
500512 key = detail.task.key.clone();
513+ task_uid = detail.task.id.clone();
501514 board_id = board.id;
502515 policy = Some(state.store.policy().await.map_err(core_err)?);
503516 member = Some(me);
@@ -520,7 +533,7 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result<Response> {
520533 return Err(forbidden().into());
521534 };
522535 match store_one(
523- state, me, &board_id, &task_id, &raw_name, &mut field, policy,
536+ state, me, &board_id, &task_uid, &raw_name, &mut field, policy,
524537 )
525538 .await?
526539 {
@@ -538,7 +551,7 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result<Response> {
538551 return Err(forbidden().into());
539552 };
540553 if saved > 0 {
541- bump(state, &board_id, &task_id);
554+ bump(state, &board_id, &task_uid);
542555 }
543556 let language = lang(cx, me.member.locale_override.as_deref());
544557 let reason = match (refusal, saved) {
@@ -552,7 +565,14 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result<Response> {
552565 error: Some(t(language, refusal_key(reason))),
553566 ..Draft::default()
554567 };
555- refuse(cx, &me, language, &next, &key, draft).await
568+ let mut response = refuse(cx, &me, language, &next, &key, draft).await?;
569+ // A full storage is `413`; the refusal page keeps its own status when the task is gone.
570+ if reason == Refusal::StorageFull
571+ && response.status() == StatusCode::UNPROCESSABLE_ENTITY
572+ {
573+ *response.status_mut() = StatusCode::PAYLOAD_TOO_LARGE;
574+ }
575+ Ok(response)
556576 }
557577 None => back(&next, Some(key.as_str())),
558578 }
@@ -720,6 +740,7 @@ mod tests {
720740 assert_eq!(kind_of(&attachment("a.csv", "text/html")), Kind::Csv);
721741 assert_eq!(kind_of(&attachment("a.txt", "text/plain")), Kind::Text);
722742 assert_eq!(kind_of(&attachment("a.xlsx", XLSX)), Kind::Workbook);
743+ assert_eq!(kind_of(&attachment("a.ods", ODS_MIME)), Kind::Refused);
723744 assert_eq!(kind_of(&attachment("a.pptx", PPTX)), Kind::Deck);
724745 }
725746
crates/iz-web/src/pages/photo.rsmodified+4 -1
@@ -16,6 +16,8 @@ use topcoat::router::error::not_found;
1616 use topcoat::router::request::{headers, uri};
1717 use topcoat::router::{HeaderMap, HeaderValue, StatusCode, path_param_segment, route};
1818
19+use iz_core::authz::Role;
20+
1921 use crate::auth::current_member;
2022 use crate::directory::{PHOTO_TYPES, fetch_photo};
2123 use crate::state::AppState;
@@ -38,7 +40,8 @@ async fn photo(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
3840 let Some(member) = state.store.member(&sub).await? else {
3941 return Err(not_found().into());
4042 };
41- if member.disabled {
43+ // A disabled member, or one with no role, has no access to the board, so no photo either.
44+ if member.disabled || member.role == Role::NoAccess {
4245 return Err(not_found().into());
4346 }
4447
crates/iz-web/src/pages/settings.rsmodified+13 -1
@@ -256,8 +256,20 @@ async fn save_sender(cx: &Cx, form: Option<Form<SenderSubmit>>) -> Result<Respon
256256 from_address: form.from_address.clone(),
257257 from_name: form.from_name.clone(),
258258 })?;
259- // An empty password keeps the stored one; a typed one is checked and sealed here, once.
259+ // An empty password keeps the stored one, but only while the server and the user name are the
260+ // same: a password for one server must not be sent to another host.
260261 let sealed = if form.password.is_empty() {
262+ let stored = state.store.load_sender().await?;
263+ let same_server = stored.sender.as_ref().is_some_and(|old| {
264+ old.host == sender.host
265+ && old.port == sender.port
266+ && old.username == sender.username
267+ });
268+ if stored.password_set && !same_server {
269+ return Err(iz_core::Error::Invalid(
270+ "the host, port or user name changed: type the password again".into(),
271+ ));
272+ }
261273 None
262274 } else {
263275 validate_password(&form.password)?;
crates/iz-web/src/pages/sign_in.rsmodified+7 -1
@@ -228,6 +228,10 @@ async fn callback(cx: &Cx) -> Result<impl View> {
228228 .clone()
229229 .filter(|zone| parse_zone(zone).is_ok())
230230 .unwrap_or_else(|| "UTC".to_owned());
231+ // The token's issue time orders this sign-in against directory changes. `iat` is checked on
232+ // verify, so it is in range; the store never writes `disabled` from a sign-in.
233+ let claims_at =
234+ iz_core::time::stamp_from_unix(claims.iat).unwrap_or_else(iz_core::time::now_stamp);
231235 let member_input = DirectoryMember {
232236 sub: claims.sub.clone(),
233237 email,
@@ -237,11 +241,12 @@ async fn callback(cx: &Cx) -> Result<impl View> {
237241 locale: claims.locale.clone(),
238242 zoneinfo,
239243 picture_version: claims.picture_version,
244+ updated_at: claims_at.clone(),
240245 };
241246 let default_role = directory::default_role(&state.store).await?;
242247 let stored = match state
243248 .store
244- .upsert_from_claims(&member_input, default_role)
249+ .upsert_from_claims(&member_input, default_role, &claims_at)
245250 .await
246251 {
247252 Ok(stored) => stored,
@@ -374,6 +379,7 @@ mod tests {
374379 locale: None,
375380 zoneinfo: "UTC".into(),
376381 picture_version: 0,
382+ updated_at: "2026-10-28T09:00:00.000000000Z".into(),
377383 };
378384 state
379385 .store
docs/architecture.mdmodified+1 -1
@@ -42,7 +42,7 @@ iz/
4242 `clock.rs` (deadline + meeting time rules, inventory 2.4)
4343 - `rules/` (mail rule engine: triggers, audiences, decisions; pure where possible), `mail_text.rs` (subjects and
4444 bodies for every mail kind, both languages)
45-- `sniff.rs`, `sheet.rs` (`calamine`: xlsx, xls, ods; values only; paging 50 rows × 12 columns; correct offsets
45+- `sniff.rs`, `sheet.rs` (`calamine`: xlsx, xls, xlsb; values only; `.ods` is refused, not previewed; paging 50 rows × 12 columns; correct offsets
4646 for ranges not starting at A1), `slides.rs` (pptx text outline via `zip` + `quick-xml`, size and entry limits
4747 against zip bombs)
4848 - `store/`: `members.rs`, `sessions.rs`, `board.rs`, `tasks.rs`, `deps.rs`, `comments.rs`, `attachments.rs`,