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 commit34f693b65046791b12b57a82b35a5386b722f4b2Parent: 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
29 changed files +655 -110
- crates/iz-core/migrations/0006_decision_skipped.sql +20 -0
- crates/iz-core/src/archive.rs +1 -1
- crates/iz-core/src/authz.rs +8 -1
- crates/iz-core/src/limits.rs +6 -0
- crates/iz-core/src/sender.rs +3 -0
- crates/iz-core/src/sheet.rs +159 -29
- crates/iz-core/src/store/attachments.rs +81 -17
- crates/iz-core/src/store/members.rs +90 -27
- crates/iz-core/src/store/migrate.rs +4 -0
- crates/iz-core/src/store/mod.rs +2 -1
- crates/iz-core/src/store/rules_engine.rs +54 -5
- crates/iz-core/src/store/sender.rs +2 -0
- crates/iz-core/src/store/sessions.rs +14 -0
- crates/iz-core/src/store/tasks.rs +3 -0
- crates/iz-core/src/time.rs +31 -1
- crates/iz-web/src/auth.rs +25 -2
- crates/iz-web/src/cli/fsck.rs +1 -0
- crates/iz-web/src/directory.rs +4 -0
- crates/iz-web/src/i18n/task.rs +8 -0
- crates/iz-web/src/in_store.rs +1 -0
- crates/iz-web/src/live.rs +65 -10
- crates/iz-web/src/oidc.rs +3 -0
- crates/iz-web/src/pages/backchannel.rs +6 -3
- crates/iz-web/src/pages/board.rs +10 -1
- crates/iz-web/src/pages/files.rs +29 -8
- crates/iz-web/src/pages/photo.rs +4 -1
- crates/iz-web/src/pages/settings.rs +13 -1
- crates/iz-web/src/pages/sign_in.rs +7 -1
- docs/architecture.md +1 -1
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, | |
| 2 | 2 | //! so one of them can expand to far more than it weighs. Every such file is checked here before any parser |
| 3 | 3 | //! sees it (`docs/architecture.md`, attack plan section 6: zip bombs). |
| 4 | 4 | //! |
crates/iz-core/src/authz.rsmodified+8 -1
| @@ -128,7 +128,14 @@ enum Level { | ||
| 128 | 128 | pub fn authorize(actor: &Actor, action: &Action) -> Result<(), Denied> { |
| 129 | 129 | let (sub, level) = match actor { |
| 130 | 130 | 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 | + } | |
| 132 | 139 | Actor::Member { |
| 133 | 140 | sub, |
| 134 | 141 | im_admin: true, |
crates/iz-core/src/limits.rsmodified+6 -0
| @@ -31,6 +31,9 @@ pub const REMINDER_MINUTES_MAX: u32 = 1440; | ||
| 31 | 31 | pub const BATCH_MINUTES_MAX: u32 = 120; |
| 32 | 32 | /// Default per-file attachment limit, in MiB. Reason: the starting value of the setting; an admin raises it. |
| 33 | 33 | 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; | |
| 34 | 37 | /// Most file parts one upload request may carry. Reason: bounds the work one form can cause. |
| 35 | 38 | pub const UPLOAD_FILES_MAX: usize = 10; |
| 36 | 39 | /// 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; | ||
| 39 | 42 | pub const TEXT_PREVIEW_BYTES: u64 = 256 * 1024; |
| 40 | 43 | /// Largest compressed spreadsheet or CSV the viewer parses, in bytes. Reason: bounds the work of one preview. |
| 41 | 44 | 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; | |
| 42 | 48 | /// Largest compressed slide deck the viewer parses, in bytes. Reason: decks carry pictures, so the cap is higher. |
| 43 | 49 | pub const SLIDES_INPUT_MAX_BYTES: u64 = 20 * 1024 * 1024; |
| 44 | 50 | /// 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"; | ||
| 14 | 14 | pub const DEFAULT_PORT: u16 = 587; |
| 15 | 15 | /// Reminders per member per hour when the setting was never saved. Reason: a guard against a burst. |
| 16 | 16 | 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; | |
| 17 | 20 | |
| 18 | 21 | /// How the connection to the mail server is protected. |
| 19 | 22 | #[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 | |
| 2 | 2 | //! `limits.rs`: at most 20 sheets, 1000 rows, 100 columns and 1000 characters a cell. Formulas, formats, |
| 3 | 3 | //! charts and macros are not read; a cell is its displayed value. The caller turns the result into HTML, |
| 4 | 4 | //! where every cell is escaped, so a cell that holds markup is shown as text. |
| 5 | 5 | //! |
| 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. | |
| 8 | 13 | |
| 14 | +use std::collections::BTreeMap; | |
| 9 | 15 | use std::fs::File; |
| 16 | +use std::io::BufReader; | |
| 10 | 17 | use std::path::Path; |
| 11 | 18 | |
| 12 | -use calamine::{Data, Reader, open_workbook_auto}; | |
| 19 | +use calamine::{Data, DataRef, Reader, Sheets, Xlsx, open_workbook_auto}; | |
| 13 | 20 | |
| 14 | 21 | use crate::archive; |
| 15 | 22 | use crate::error::{Error, Result}; |
| 16 | 23 | 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, | |
| 18 | 26 | }; |
| 19 | 27 | |
| 20 | 28 | /// 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 { | ||
| 42 | 50 | text.chars().take(CELL_TEXT_MAX).collect() |
| 43 | 51 | } |
| 44 | 52 | |
| 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. | |
| 46 | 65 | 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 | + } | |
| 48 | 71 | let mut workbook = |
| 49 | 72 | open_workbook_auto(path).map_err(|_| Error::Invalid("bad_workbook".into()))?; |
| 50 | 73 | let names = workbook.sheet_names(); |
| 51 | 74 | let sheet_count = names.len(); |
| 52 | 75 | let mut sheets = Vec::new(); |
| 53 | 76 | 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); | |
| 76 | 82 | } |
| 77 | 83 | Ok(Book { |
| 78 | 84 | sheets, |
| @@ -80,6 +86,74 @@ pub fn read_workbook(path: &Path) -> Result<Book> { | ||
| 80 | 86 | }) |
| 81 | 87 | } |
| 82 | 88 | |
| 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 | + | |
| 83 | 157 | /// Reads a CSV file as one sheet. Invalid UTF-8 is shown with replacement characters. |
| 84 | 158 | pub fn read_csv(path: &Path, name: &str) -> Result<Book> { |
| 85 | 159 | let len = std::fs::metadata(path)?.len(); |
| @@ -154,6 +228,19 @@ mod tests { | ||
| 154 | 228 | assert!(read_workbook(&path).is_err()); |
| 155 | 229 | } |
| 156 | 230 | |
| 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 | + | |
| 157 | 244 | #[test] |
| 158 | 245 | fn a_csv_stops_at_the_row_cap() { |
| 159 | 246 | let dir = tempfile::tempdir().expect("dir"); |
| @@ -165,6 +252,49 @@ mod tests { | ||
| 165 | 252 | assert!(book.sheets[0].rows_cut); |
| 166 | 253 | } |
| 167 | 254 | |
| 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 | + | |
| 168 | 298 | #[test] |
| 169 | 299 | fn a_cell_is_cut_to_its_cap() { |
| 170 | 300 | assert_eq!( |
crates/iz-core/src/store/attachments.rsmodified+81 -17
| @@ -9,13 +9,15 @@ | ||
| 9 | 9 | |
| 10 | 10 | use serde_json::json; |
| 11 | 11 | use turso::Connection; |
| 12 | +use turso::transaction::Transaction; | |
| 12 | 13 | |
| 13 | 14 | use super::activity::{self, NewActivity}; |
| 14 | 15 | use super::{col_int, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; |
| 15 | 16 | use crate::authz::{Action, Actor, authorize}; |
| 16 | 17 | use crate::error::{Error, Result}; |
| 17 | 18 | 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, | |
| 19 | 21 | }; |
| 20 | 22 | use crate::store::Store; |
| 21 | 23 | use crate::time::{now_stamp, stamp_after}; |
| @@ -25,6 +27,8 @@ use std::time::Duration; | ||
| 25 | 27 | pub const SETTING_LIMIT_MIB: &str = "attachment_limit_mib"; |
| 26 | 28 | /// The setting that holds the allowed extensions, separated by spaces or commas. |
| 27 | 29 | 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"; | |
| 28 | 32 | /// The setting that holds where new and existing attachments belong: `local` (default) or `in`. |
| 29 | 33 | pub const SETTING_LOCATION: &str = "attachment_location"; |
| 30 | 34 | /// 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 { | ||
| 94 | 98 | const ATTACHMENT_COLS: &str = |
| 95 | 99 | "a.id, a.task_id, a.name, a.mime, a.size, a.sha256, a.uploaded_by, a.created_at, a.location"; |
| 96 | 100 | |
| 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 | + | |
| 97 | 151 | fn map_attachment(row: &turso::Row) -> Result<Attachment> { |
| 98 | 152 | Ok(Attachment { |
| 99 | 153 | id: col_text(row, 0)?, |
| @@ -180,7 +234,8 @@ impl Store { | ||
| 180 | 234 | } |
| 181 | 235 | |
| 182 | 236 | /// 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. | |
| 184 | 239 | pub async fn add_attachment( |
| 185 | 240 | &self, |
| 186 | 241 | board_id: &str, |
| @@ -213,6 +268,29 @@ impl Store { | ||
| 213 | 268 | if live.is_none() { |
| 214 | 269 | return Err(Error::NotFound); |
| 215 | 270 | } |
| 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 | + } | |
| 216 | 294 | tx.execute( |
| 217 | 295 | "INSERT INTO attachments (id, task_id, comment_id, name, mime, size, sha256, uploaded_by, created_at, location) \ |
| 218 | 296 | VALUES (?1, ?2, NULL, ?3, ?4, ?5, ?6, ?7, ?8, 'local')", |
| @@ -336,21 +414,7 @@ impl Store { | ||
| 336 | 414 | ) |
| 337 | 415 | .await |
| 338 | 416 | .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, ¤t.location, &now).await?; | |
| 354 | 418 | activity::record( |
| 355 | 419 | &tx, |
| 356 | 420 | NewActivity { |
crates/iz-core/src/store/members.rsmodified+90 -27
| @@ -14,7 +14,7 @@ use crate::authz::Role; | ||
| 14 | 14 | use crate::error::{Error, Result}; |
| 15 | 15 | use crate::limits::DISPLAY_NAME_MAX; |
| 16 | 16 | use crate::store::Store; |
| 17 | -use crate::time::now_stamp; | |
| 17 | +use crate::time::{normalize_stamp, now_stamp}; | |
| 18 | 18 | use crate::zones::parse_zone; |
| 19 | 19 | |
| 20 | 20 | /// Longest email address accepted from the directory, in characters (RFC 5321 path limit). |
| @@ -78,6 +78,9 @@ pub struct DirectoryMember { | ||
| 78 | 78 | pub zoneinfo: String, |
| 79 | 79 | /// Photo version from `im`. |
| 80 | 80 | 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, | |
| 81 | 84 | } |
| 82 | 85 | |
| 83 | 86 | const MEMBER_COLS: &str = "sub, email, name, im_admin, disabled, locale, locale_override, zoneinfo, \ |
| @@ -144,6 +147,7 @@ fn validate(m: &DirectoryMember) -> Result<DirectoryMember> { | ||
| 144 | 147 | locale: m.locale.clone().filter(|l| LOCALES.contains(&l.as_str())), |
| 145 | 148 | zoneinfo, |
| 146 | 149 | picture_version: m.picture_version, |
| 150 | + updated_at: m.updated_at.trim().to_owned(), | |
| 147 | 151 | }) |
| 148 | 152 | } |
| 149 | 153 | |
| @@ -182,23 +186,55 @@ impl Store { | ||
| 182 | 186 | member: &DirectoryMember, |
| 183 | 187 | default_role: Role, |
| 184 | 188 | ) -> 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 | |
| 186 | 226 | } |
| 187 | 227 | |
| 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`. | |
| 189 | 233 | pub async fn upsert_from_claims( |
| 190 | 234 | &self, |
| 191 | 235 | member: &DirectoryMember, |
| 192 | 236 | 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, | |
| 202 | 238 | ) -> Result<Member> { |
| 203 | 239 | let m = validate(member)?; |
| 204 | 240 | let now = now_stamp(); |
| @@ -206,36 +242,35 @@ impl Store { | ||
| 206 | 242 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 207 | 243 | let outcome: Result<Member> = async { |
| 208 | 244 | 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, \ | |
| 210 | 246 | 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) \ | |
| 212 | 248 | 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", | |
| 216 | 253 | ( |
| 217 | 254 | m.sub.clone(), |
| 218 | 255 | m.email.clone(), |
| 219 | 256 | m.name.clone(), |
| 220 | 257 | i64::from(m.im_admin), |
| 221 | - i64::from(m.disabled), | |
| 222 | 258 | m.locale.clone(), |
| 223 | 259 | m.zoneinfo.clone(), |
| 224 | 260 | m.picture_version, |
| 225 | - now.clone(), | |
| 261 | + claims_at.to_owned(), | |
| 226 | 262 | default_role.as_str(), |
| 263 | + now.clone(), | |
| 227 | 264 | ), |
| 228 | 265 | ) |
| 229 | 266 | .await |
| 230 | 267 | .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)?; | |
| 239 | 274 | select_member(&tx, &m.sub) |
| 240 | 275 | .await? |
| 241 | 276 | .ok_or_else(|| Error::Database("member vanished after upsert".into())) |
| @@ -372,6 +407,7 @@ mod tests { | ||
| 372 | 407 | locale: Some("de".into()), |
| 373 | 408 | zoneinfo: "Europe/Istanbul".into(), |
| 374 | 409 | picture_version: 0, |
| 410 | + updated_at: "2026-10-28T09:00:00.000000000Z".into(), | |
| 375 | 411 | }; |
| 376 | 412 | let v = validate(&raw).unwrap(); |
| 377 | 413 | assert_eq!(v.sub, "u1"); |
| @@ -385,6 +421,33 @@ mod tests { | ||
| 385 | 421 | assert!(validate(&bad).is_err()); |
| 386 | 422 | } |
| 387 | 423 | |
| 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 | + | |
| 388 | 451 | #[tokio::test] |
| 389 | 452 | async fn last_administrator_cannot_be_demoted() { |
| 390 | 453 | 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)] = &[ | ||
| 20 | 20 | 5, |
| 21 | 21 | include_str!("../../migrations/0005_blob_deletions_by_place.sql"), |
| 22 | 22 | ), |
| 23 | + ( | |
| 24 | + 6, | |
| 25 | + include_str!("../../migrations/0006_decision_skipped.sql"), | |
| 26 | + ), | |
| 23 | 27 | ]; |
| 24 | 28 | |
| 25 | 29 | 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 { | ||
| 347 | 347 | locale: None, |
| 348 | 348 | zoneinfo: "UTC".into(), |
| 349 | 349 | picture_version: 0, |
| 350 | + updated_at: "2026-10-28T09:00:00.000000000Z".into(), | |
| 350 | 351 | }; |
| 351 | 352 | store.apply_directory_member(&member, role).await.unwrap(); |
| 352 | 353 | } |
| @@ -403,7 +404,7 @@ mod tests { | ||
| 403 | 404 | }) |
| 404 | 405 | .await |
| 405 | 406 | .unwrap(); |
| 406 | - assert_eq!(versions, vec![1, 2, 3, 4, 5]); | |
| 407 | + assert_eq!(versions, vec![1, 2, 3, 4, 5, 6]); | |
| 407 | 408 | } |
| 408 | 409 | |
| 409 | 410 | #[tokio::test] |
crates/iz-core/src/store/rules_engine.rsmodified+54 -5
| @@ -19,9 +19,18 @@ use crate::clock::stamp_of; | ||
| 19 | 19 | use crate::error::Result; |
| 20 | 20 | use crate::mail_text::{MailLang, RuleMail, rule_body, when_text}; |
| 21 | 21 | use crate::rules::{Audience, EventFacts, RuleFacts, TaskFacts, Verdict, evaluate, render_subject}; |
| 22 | +use crate::sender::DEFAULT_RULE_CAP; | |
| 22 | 23 | use crate::store::Store; |
| 24 | +use crate::store::sender::KEY_RULE_CAP; | |
| 23 | 25 | use crate::time::now_stamp; |
| 24 | 26 | |
| 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 | + | |
| 25 | 34 | /// One unprocessed event as read back. |
| 26 | 35 | struct QueuedEvent { |
| 27 | 36 | id: String, |
| @@ -159,7 +168,14 @@ pub fn task_link(base_url: &str, key: &str) -> String { | ||
| 159 | 168 | } |
| 160 | 169 | |
| 161 | 170 | /// 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> { | |
| 163 | 179 | let rules = fetch_all( |
| 164 | 180 | tx, |
| 165 | 181 | "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 | ||
| 231 | 247 | Verdict::Owed(recipients) => ("owed", String::new(), recipients.clone()), |
| 232 | 248 | }; |
| 233 | 249 | let mut queued = 0; |
| 250 | + let mut capped = 0; | |
| 234 | 251 | if let (Some(row), Some(task_id)) = (&task, &event.task_id) { |
| 235 | 252 | let column_id = event |
| 236 | 253 | .column_id |
| @@ -248,6 +265,19 @@ async fn handle(tx: &Transaction<'_>, event: &QueuedEvent, base_url: &str) -> Re | ||
| 248 | 265 | let Some(member) = eligible.iter().find(|m| &m.sub == sub) else { |
| 249 | 266 | continue; |
| 250 | 267 | }; |
| 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 | + } | |
| 251 | 281 | let when = row |
| 252 | 282 | .meeting_at |
| 253 | 283 | .as_deref() |
| @@ -294,10 +324,13 @@ async fn handle(tx: &Transaction<'_>, event: &QueuedEvent, base_url: &str) -> Re | ||
| 294 | 324 | } |
| 295 | 325 | } |
| 296 | 326 | 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) | |
| 299 | 332 | } else { |
| 300 | - outcome | |
| 333 | + (outcome, detail) | |
| 301 | 334 | }; |
| 302 | 335 | tx.execute( |
| 303 | 336 | "INSERT INTO mail_decisions (id, rule_id, event_id, task_id, outcome, detail, created_at) \ |
| @@ -350,8 +383,23 @@ impl Store { | ||
| 350 | 383 | .await?; |
| 351 | 384 | let mut report = PassReport::default(); |
| 352 | 385 | 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 | + }; | |
| 353 | 401 | for event in &events { |
| 354 | - report.mails += handle(&tx, event, base_url).await?; | |
| 402 | + report.mails += handle(&tx, event, base_url, limits).await?; | |
| 355 | 403 | tx.execute( |
| 356 | 404 | "UPDATE mail_events SET processed_at = ?2 WHERE id = ?1", |
| 357 | 405 | (event.id.clone(), stamp.clone()), |
| @@ -464,6 +512,7 @@ mod tests { | ||
| 464 | 512 | locale: None, |
| 465 | 513 | zoneinfo: "UTC".into(), |
| 466 | 514 | picture_version: 0, |
| 515 | + updated_at: "2026-10-28T09:00:00.000000000Z".into(), | |
| 467 | 516 | }; |
| 468 | 517 | store |
| 469 | 518 | .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"; | ||
| 28 | 28 | pub const KEY_REMINDER_MINUTES: &str = "reminder_minutes"; |
| 29 | 29 | /// Settings key of the reminder cap per member per hour. |
| 30 | 30 | 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"; | |
| 31 | 33 | |
| 32 | 34 | /// What the store knows about the sender. The password is only represented by its sealed text. |
| 33 | 35 | #[derive(Debug, Clone, PartialEq, Eq)] |
crates/iz-core/src/store/sessions.rsmodified+14 -0
| @@ -187,6 +187,20 @@ impl Store { | ||
| 187 | 187 | Ok(inserted == 0) |
| 188 | 188 | } |
| 189 | 189 | |
| 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 | + | |
| 190 | 204 | /// Deletes replay records whose lifetime has passed. Returns the count. |
| 191 | 205 | pub async fn sweep_jti(&self) -> Result<u64> { |
| 192 | 206 | let conn = self.inner.conn.lock().await; |
crates/iz-core/src/store/tasks.rsmodified+3 -0
| @@ -813,6 +813,9 @@ impl Store { | ||
| 813 | 813 | .map_err(db_err)?; |
| 814 | 814 | log(&tx, id, actor, "task_deleted", None, serde_json::json!({})).await?; |
| 815 | 815 | } |
| 816 | + for id in &doomed { | |
| 817 | + super::attachments::owe_task_bytes(&tx, id, &now).await?; | |
| 818 | + } | |
| 816 | 819 | queue_event(&tx, board_id, task_id, "deleted", actor, None, None).await?; |
| 817 | 820 | let doomed_set: HashSet<&str> = doomed.iter().map(String::as_str).collect(); |
| 818 | 821 | let mut edges: Vec<(String, String)> = Vec::new(); |
crates/iz-core/src/time.rsmodified+31 -1
| @@ -4,7 +4,8 @@ | ||
| 4 | 4 | use std::time::Duration; |
| 5 | 5 | |
| 6 | 6 | 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, | |
| 8 | 9 | }; |
| 9 | 10 | |
| 10 | 11 | const FORMAT: &[FormatItem<'static>] = |
| @@ -22,6 +23,21 @@ pub fn now_stamp() -> String { | ||
| 22 | 23 | format_stamp(OffsetDateTime::now_utc()) |
| 23 | 24 | } |
| 24 | 25 | |
| 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 | + | |
| 25 | 41 | /// The stamp for `now + after`. Saturates at the largest representable time instead of panicking. |
| 26 | 42 | pub fn stamp_after(after: Duration) -> String { |
| 27 | 43 | let delta = SignedDuration::try_from(after).unwrap_or(SignedDuration::MAX); |
| @@ -33,6 +49,20 @@ mod tests { | ||
| 33 | 49 | use super::*; |
| 34 | 50 | use time::macros::datetime; |
| 35 | 51 | |
| 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 | + | |
| 36 | 66 | #[test] |
| 37 | 67 | fn stamp_is_fixed_width_utc_with_nine_digits() { |
| 38 | 68 | 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; | ||
| 9 | 9 | |
| 10 | 10 | use iz_core::authz::{Action, Actor, Denied, authorize}; |
| 11 | 11 | use iz_core::secret; |
| 12 | +use iz_core::store::Store; | |
| 12 | 13 | use iz_core::store::members::Member; |
| 13 | 14 | use iz_core::store::sessions::SessionRecord; |
| 14 | 15 | use iz_core::token::constant_time_eq; |
| @@ -102,8 +103,21 @@ pub async fn current_member(cx: &Cx) -> Result<Option<CurrentMember>> { | ||
| 102 | 103 | let Some(cookie) = jar(cx).get(SESSION_COOKIE) else { |
| 103 | 104 | return Ok(None); |
| 104 | 105 | }; |
| 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 { | |
| 107 | 121 | return Ok(None); |
| 108 | 122 | }; |
| 109 | 123 | let Some(member) = store.member(&session.sub).await? else { |
| @@ -112,6 +126,15 @@ pub async fn current_member(cx: &Cx) -> Result<Option<CurrentMember>> { | ||
| 112 | 126 | Ok(Some(CurrentMember { session, member })) |
| 113 | 127 | } |
| 114 | 128 | |
| 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 | + | |
| 115 | 138 | /// The signed-in member. Without a session, redirects to `/login?next=<this page>`. |
| 116 | 139 | pub async fn require_member(cx: &Cx) -> Result<CurrentMember> { |
| 117 | 140 | match current_member(cx).await? { |
crates/iz-web/src/cli/fsck.rsmodified+1 -0
| @@ -283,6 +283,7 @@ mod tests { | ||
| 283 | 283 | locale: None, |
| 284 | 284 | zoneinfo: "UTC".into(), |
| 285 | 285 | picture_version: 0, |
| 286 | + updated_at: "2026-10-28T09:00:00.000000000Z".into(), | |
| 286 | 287 | }; |
| 287 | 288 | store |
| 288 | 289 | .apply_directory_member(&member, Role::Admin) |
crates/iz-web/src/directory.rsmodified+4 -0
| @@ -71,6 +71,9 @@ struct WireMember { | ||
| 71 | 71 | zoneinfo: String, |
| 72 | 72 | #[serde(default)] |
| 73 | 73 | 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, | |
| 74 | 77 | } |
| 75 | 78 | |
| 76 | 79 | fn utc() -> String { |
| @@ -324,6 +327,7 @@ fn parse_member(raw: Value) -> Option<DirectoryMember> { | ||
| 324 | 327 | locale: wire.locale, |
| 325 | 328 | zoneinfo: wire.zoneinfo, |
| 326 | 329 | picture_version: wire.picture_version, |
| 330 | + updated_at: wire.updated_at, | |
| 327 | 331 | }) |
| 328 | 332 | } |
| 329 | 333 |
crates/iz-web/src/i18n/task.rsmodified+8 -0
| @@ -211,6 +211,8 @@ pub enum K { | ||
| 211 | 211 | ErrTooManyFiles, |
| 212 | 212 | /// Refused: the file could not be stored; nothing was kept. |
| 213 | 213 | ErrFileStore, |
| 214 | + /// Refused: the attachment storage of the board is full. | |
| 215 | + ErrFileStorageFull, | |
| 214 | 216 | /// The viewer message for a file that cannot be previewed (refused, or too large to read). |
| 215 | 217 | ViewerRefused, |
| 216 | 218 | /// The viewer message for a type with no preview. |
| @@ -458,6 +460,12 @@ pub fn t(lang: Lang, key: K) -> &'static str { | ||
| 458 | 460 | (K::ErrTooManyFiles, Lang::Tr) => "Bir seferde daha az dosya yükleyin.", |
| 459 | 461 | (K::ErrFileStore, Lang::En) => "The file could not be saved. Try again.", |
| 460 | 462 | (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 | + } | |
| 461 | 469 | (K::ViewerRefused, Lang::En) => "This file cannot be previewed. Download it to open it.", |
| 462 | 470 | (K::ViewerRefused, Lang::Tr) => "Bu dosya önizlenemiyor. Açmak için indirin.", |
| 463 | 471 | (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 { | ||
| 440 | 440 | locale: None, |
| 441 | 441 | zoneinfo: "UTC".into(), |
| 442 | 442 | picture_version: 0, |
| 443 | + updated_at: "2026-10-28T09:00:00.000000000Z".into(), | |
| 443 | 444 | }; |
| 444 | 445 | store |
| 445 | 446 | .apply_directory_member(&member, role) |
crates/iz-web/src/live.rsmodified+65 -10
| @@ -7,15 +7,16 @@ | ||
| 7 | 7 | //! page wrong for long. Nothing polls, and a topic nobody listens to is dropped. |
| 8 | 8 | //! |
| 9 | 9 | //! 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. | |
| 11 | 12 | //! |
| 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. | |
| 14 | 14 | |
| 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. | |
| 16 | 16 | |
| 17 | 17 | use std::collections::HashMap; |
| 18 | 18 | use std::future::Future; |
| 19 | +use std::sync::atomic::{AtomicUsize, Ordering}; | |
| 19 | 20 | use std::sync::{Mutex, MutexGuard, PoisonError}; |
| 20 | 21 | use std::time::Duration; |
| 21 | 22 | |
| @@ -25,7 +26,13 @@ use topcoat::Result; | ||
| 25 | 26 | use topcoat::context::Cx; |
| 26 | 27 | use topcoat::router::content::sse::{Event, KeepAlive, Sse}; |
| 27 | 28 | 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); | |
| 29 | 36 | |
| 30 | 37 | /// How long a client waits before it reconnects when a stream ends. Sent once, at the start. |
| 31 | 38 | pub const STREAM_RETRY: Duration = Duration::from_millis(1000); |
| @@ -108,9 +115,10 @@ impl LiveHub { | ||
| 108 | 115 | } |
| 109 | 116 | |
| 110 | 117 | /// The state a stream carries between wakes. |
| 111 | -struct Follow<F> { | |
| 118 | +struct Follow<F, G> { | |
| 112 | 119 | wakes: Vec<watch::Receiver<u64>>, |
| 113 | 120 | fingerprint: F, |
| 121 | + still_allowed: G, | |
| 114 | 122 | last: String, |
| 115 | 123 | } |
| 116 | 124 | |
| @@ -118,17 +126,22 @@ struct Follow<F> { | ||
| 118 | 126 | /// differs from the value it last sent, so a bump that changes nothing the viewer sees sends |
| 119 | 127 | /// nothing. Nothing is sent on connect: the page already shows the state that `fingerprint` read. |
| 120 | 128 | /// |
| 129 | +/// `still_allowed` is run before each event. When it says no, or fails, the stream ends. | |
| 130 | +/// | |
| 121 | 131 | /// `fingerprint` must be cheap and must describe everything the page shows. A read that fails ends |
| 122 | 132 | /// the stream, and the browser reconnects. |
| 123 | -pub async fn stream_changes<F, Fut>( | |
| 133 | +pub async fn stream_changes<F, Fut, G, GFut>( | |
| 124 | 134 | cx: &Cx, |
| 125 | 135 | hub: &LiveHub, |
| 126 | 136 | topics: &[Topic], |
| 127 | 137 | fingerprint: F, |
| 138 | + still_allowed: G, | |
| 128 | 139 | ) -> Result<Response> |
| 129 | 140 | where |
| 130 | 141 | F: Fn() -> Fut + Send + 'static, |
| 131 | 142 | Fut: Future<Output = Result<String>> + Send, |
| 143 | + G: Fn() -> GFut + Send + 'static, | |
| 144 | + GFut: Future<Output = Result<bool>> + Send, | |
| 132 | 145 | { |
| 133 | 146 | // Subscribed before the first read, so a change in between still wakes the stream. |
| 134 | 147 | let wakes: Vec<watch::Receiver<u64>> = |
| @@ -137,6 +150,7 @@ where | ||
| 137 | 150 | let follow = Follow { |
| 138 | 151 | wakes, |
| 139 | 152 | fingerprint, |
| 153 | + still_allowed, | |
| 140 | 154 | last, |
| 141 | 155 | }; |
| 142 | 156 | let events = stream::unfold(follow, |mut follow| async move { |
| @@ -146,6 +160,19 @@ where | ||
| 146 | 160 | } |
| 147 | 161 | match (follow.fingerprint)().await { |
| 148 | 162 | 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 | + } | |
| 149 | 176 | follow.last = now; |
| 150 | 177 | return Some((changed_event(), follow)); |
| 151 | 178 | } |
| @@ -192,10 +219,38 @@ pub fn events_response( | ||
| 192 | 219 | Ok(response) |
| 193 | 220 | } |
| 194 | 221 | |
| 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 | + | |
| 195 | 243 | /// `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`. | |
| 198 | 246 | #[route(GET "/-/alive")] |
| 199 | 247 | 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) | |
| 201 | 256 | } |
crates/iz-web/src/oidc.rsmodified+3 -0
| @@ -134,6 +134,9 @@ pub struct IdClaims { | ||
| 134 | 134 | /// Bumps when the photo changes. Used as the avatar cache key. |
| 135 | 135 | #[serde(default)] |
| 136 | 136 | 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, | |
| 137 | 140 | } |
| 138 | 141 | |
| 139 | 142 | /// 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 { | ||
| 49 | 49 | /// again. A `sid` ends that browser session; a token with only a `sub` ends every session of the |
| 50 | 50 | /// user (a disabled or deleted member). Returns how many sessions ended. |
| 51 | 51 | /// |
| 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. | |
| 54 | 55 | pub async fn end_sessions( |
| 55 | 56 | store: &Store, |
| 56 | 57 | claims: &LogoutClaims, |
| 57 | 58 | ) -> std::result::Result<u64, BackchannelError> { |
| 58 | - if store.seen_jti(&claims.jti, JTI_LIFETIME).await? { | |
| 59 | + if store.jti_recorded(&claims.jti).await? { | |
| 59 | 60 | return Err(BackchannelError::Replay); |
| 60 | 61 | } |
| 61 | 62 | let ended = match (&claims.sid, &claims.sub) { |
| @@ -64,6 +65,7 @@ pub async fn end_sessions( | ||
| 64 | 65 | // The verifier requires one of the two, so this arm is unreachable in practice. |
| 65 | 66 | (None, None) => 0, |
| 66 | 67 | }; |
| 68 | + store.seen_jti(&claims.jti, JTI_LIFETIME).await?; | |
| 67 | 69 | Ok(ended) |
| 68 | 70 | } |
| 69 | 71 | |
| @@ -180,6 +182,7 @@ mod tests { | ||
| 180 | 182 | locale: None, |
| 181 | 183 | zoneinfo: "UTC".into(), |
| 182 | 184 | picture_version: 0, |
| 185 | + updated_at: "2026-10-28T09:00:00.000000000Z".into(), | |
| 183 | 186 | }; |
| 184 | 187 | store |
| 185 | 188 | .apply_directory_member(&member, Role::Member) |
crates/iz-web/src/pages/board.rsmodified+10 -1
| @@ -25,7 +25,8 @@ use topcoat::view::view; | ||
| 25 | 25 | |
| 26 | 26 | use crate::assets::BOARD_JS_HREF; |
| 27 | 27 | 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, | |
| 29 | 30 | }; |
| 30 | 31 | use crate::i18n::board::K; |
| 31 | 32 | use crate::i18n::{Lang, lang}; |
| @@ -376,6 +377,8 @@ async fn board_live(cx: &Cx) -> Result<Response> { | ||
| 376 | 377 | let board = the_board(&state.store).await?; |
| 377 | 378 | let store = state.store.clone(); |
| 378 | 379 | let board_id = board.id.clone(); |
| 380 | + let token = session_cookie(cx); | |
| 381 | + let allowed_store = state.store.clone(); | |
| 379 | 382 | stream_changes( |
| 380 | 383 | cx, |
| 381 | 384 | &state.live, |
| @@ -388,6 +391,11 @@ async fn board_live(cx: &Cx) -> Result<Response> { | ||
| 388 | 391 | Ok(fingerprint?) |
| 389 | 392 | } |
| 390 | 393 | }, |
| 394 | + move || { | |
| 395 | + let store = allowed_store.clone(); | |
| 396 | + let token = token.clone(); | |
| 397 | + async move { still_reads_board(&store, &token).await } | |
| 398 | + }, | |
| 391 | 399 | ) |
| 392 | 400 | .await |
| 393 | 401 | } |
| @@ -436,6 +444,7 @@ pub(crate) async fn sign_in_as(state: &AppState, sub: &str, role: Role) -> (Stri | ||
| 436 | 444 | locale: None, |
| 437 | 445 | zoneinfo: "Europe/Istanbul".into(), |
| 438 | 446 | picture_version: 0, |
| 447 | + updated_at: "2026-10-28T09:00:00.000000000Z".into(), | |
| 439 | 448 | }; |
| 440 | 449 | state |
| 441 | 450 | .store |
crates/iz-web/src/pages/files.rsmodified+29 -8
| @@ -59,9 +59,9 @@ use crate::views::{ViewerInfo, message_page, respond, shell}; | ||
| 59 | 59 | const FIELD_MAX_BYTES: usize = 2048; |
| 60 | 60 | /// The MIME types of the spreadsheets and the decks the viewers read. |
| 61 | 61 | 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. | |
| 65 | 65 | const PPTX: &str = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; |
| 66 | 66 | |
| 67 | 67 | /// 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 { | ||
| 77 | 77 | Pdf, |
| 78 | 78 | /// Plain text, escaped, cut to the preview size. |
| 79 | 79 | Text, |
| 80 | - /// An `.xlsx` or `.ods` workbook, read as values. | |
| 80 | + /// An `.xlsx` workbook, read as values. | |
| 81 | 81 | Workbook, |
| 82 | + /// A file the viewer does not parse (an `.ods`): shown as refused, and it can only be downloaded. | |
| 83 | + Refused, | |
| 82 | 84 | /// A CSV file, read as one sheet. |
| 83 | 85 | Csv, |
| 84 | 86 | /// A `.pptx` deck, read as the text of each slide. |
| @@ -99,7 +101,8 @@ pub fn kind_of(attachment: &Attachment) -> Kind { | ||
| 99 | 101 | .trim() |
| 100 | 102 | .to_ascii_lowercase(); |
| 101 | 103 | match essence.as_str() { |
| 102 | - XLSX | ODS => return Kind::Workbook, | |
| 104 | + XLSX => return Kind::Workbook, | |
| 105 | + ODS_MIME => return Kind::Refused, | |
| 103 | 106 | PPTX => return Kind::Deck, |
| 104 | 107 | _ => {} |
| 105 | 108 | } |
| @@ -224,6 +227,7 @@ pub async fn load_view( | ||
| 224 | 227 | Kind::Audio => ViewBody::Audio, |
| 225 | 228 | Kind::Pdf => ViewBody::Pdf, |
| 226 | 229 | Kind::Nothing => ViewBody::Nothing, |
| 230 | + Kind::Refused => ViewBody::Refused, | |
| 227 | 231 | Kind::Text => match blocking(move || read_text_head(&path, TEXT_PREVIEW_BYTES)).await { |
| 228 | 232 | Some((text, cut)) => ViewBody::Text { text, cut }, |
| 229 | 233 | None => ViewBody::Refused, |
| @@ -385,6 +389,8 @@ enum Refusal { | ||
| 385 | 389 | NoFile, |
| 386 | 390 | /// The bytes could not be stored. |
| 387 | 391 | Store, |
| 392 | + /// The board's attachment storage is full. | |
| 393 | + StorageFull, | |
| 388 | 394 | } |
| 389 | 395 | |
| 390 | 396 | /// The message of a refusal. |
| @@ -396,6 +402,7 @@ fn refusal_key(refusal: Refusal) -> K { | ||
| 396 | 402 | Refusal::TooMany => K::ErrTooManyFiles, |
| 397 | 403 | Refusal::NoFile => K::ErrNoFile, |
| 398 | 404 | Refusal::Store => K::ErrFileStore, |
| 405 | + Refusal::StorageFull => K::ErrFileStorageFull, | |
| 399 | 406 | } |
| 400 | 407 | } |
| 401 | 408 | |
| @@ -467,6 +474,9 @@ async fn store_one( | ||
| 467 | 474 | if let Err(remove) = remove_blob(data_dir, &id).await { |
| 468 | 475 | tracing::error!(error = %remove, "removing bytes of a refused upload failed"); |
| 469 | 476 | } |
| 477 | + if matches!(&error, iz_core::Error::Invalid(code) if code == "storage_full") { | |
| 478 | + return Ok(Err(Refusal::StorageFull)); | |
| 479 | + } | |
| 470 | 480 | Err(core_err(error)) |
| 471 | 481 | } |
| 472 | 482 | } |
| @@ -480,6 +490,8 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result<Response> { | ||
| 480 | 490 | let task_id = path_param_segment(cx, "id").to_owned(); |
| 481 | 491 | let mut member: Option<CurrentMember> = None; |
| 482 | 492 | 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(); | |
| 483 | 495 | let mut key = String::new(); |
| 484 | 496 | let mut next = String::new(); |
| 485 | 497 | let mut policy: Option<Policy> = None; |
| @@ -498,6 +510,7 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result<Response> { | ||
| 498 | 510 | .await |
| 499 | 511 | .map_err(core_err)?; |
| 500 | 512 | key = detail.task.key.clone(); |
| 513 | + task_uid = detail.task.id.clone(); | |
| 501 | 514 | board_id = board.id; |
| 502 | 515 | policy = Some(state.store.policy().await.map_err(core_err)?); |
| 503 | 516 | member = Some(me); |
| @@ -520,7 +533,7 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result<Response> { | ||
| 520 | 533 | return Err(forbidden().into()); |
| 521 | 534 | }; |
| 522 | 535 | 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, | |
| 524 | 537 | ) |
| 525 | 538 | .await? |
| 526 | 539 | { |
| @@ -538,7 +551,7 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result<Response> { | ||
| 538 | 551 | return Err(forbidden().into()); |
| 539 | 552 | }; |
| 540 | 553 | if saved > 0 { |
| 541 | - bump(state, &board_id, &task_id); | |
| 554 | + bump(state, &board_id, &task_uid); | |
| 542 | 555 | } |
| 543 | 556 | let language = lang(cx, me.member.locale_override.as_deref()); |
| 544 | 557 | let reason = match (refusal, saved) { |
| @@ -552,7 +565,14 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result<Response> { | ||
| 552 | 565 | error: Some(t(language, refusal_key(reason))), |
| 553 | 566 | ..Draft::default() |
| 554 | 567 | }; |
| 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) | |
| 556 | 576 | } |
| 557 | 577 | None => back(&next, Some(key.as_str())), |
| 558 | 578 | } |
| @@ -720,6 +740,7 @@ mod tests { | ||
| 720 | 740 | assert_eq!(kind_of(&attachment("a.csv", "text/html")), Kind::Csv); |
| 721 | 741 | assert_eq!(kind_of(&attachment("a.txt", "text/plain")), Kind::Text); |
| 722 | 742 | assert_eq!(kind_of(&attachment("a.xlsx", XLSX)), Kind::Workbook); |
| 743 | + assert_eq!(kind_of(&attachment("a.ods", ODS_MIME)), Kind::Refused); | |
| 723 | 744 | assert_eq!(kind_of(&attachment("a.pptx", PPTX)), Kind::Deck); |
| 724 | 745 | } |
| 725 | 746 |
crates/iz-web/src/pages/photo.rsmodified+4 -1
| @@ -16,6 +16,8 @@ use topcoat::router::error::not_found; | ||
| 16 | 16 | use topcoat::router::request::{headers, uri}; |
| 17 | 17 | use topcoat::router::{HeaderMap, HeaderValue, StatusCode, path_param_segment, route}; |
| 18 | 18 | |
| 19 | +use iz_core::authz::Role; | |
| 20 | + | |
| 19 | 21 | use crate::auth::current_member; |
| 20 | 22 | use crate::directory::{PHOTO_TYPES, fetch_photo}; |
| 21 | 23 | use crate::state::AppState; |
| @@ -38,7 +40,8 @@ async fn photo(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec<u8>)> { | ||
| 38 | 40 | let Some(member) = state.store.member(&sub).await? else { |
| 39 | 41 | return Err(not_found().into()); |
| 40 | 42 | }; |
| 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 { | |
| 42 | 45 | return Err(not_found().into()); |
| 43 | 46 | } |
| 44 | 47 |
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 | ||
| 256 | 256 | from_address: form.from_address.clone(), |
| 257 | 257 | from_name: form.from_name.clone(), |
| 258 | 258 | })?; |
| 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. | |
| 260 | 261 | 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 | + } | |
| 261 | 273 | None |
| 262 | 274 | } else { |
| 263 | 275 | 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> { | ||
| 228 | 228 | .clone() |
| 229 | 229 | .filter(|zone| parse_zone(zone).is_ok()) |
| 230 | 230 | .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); | |
| 231 | 235 | let member_input = DirectoryMember { |
| 232 | 236 | sub: claims.sub.clone(), |
| 233 | 237 | email, |
| @@ -237,11 +241,12 @@ async fn callback(cx: &Cx) -> Result<impl View> { | ||
| 237 | 241 | locale: claims.locale.clone(), |
| 238 | 242 | zoneinfo, |
| 239 | 243 | picture_version: claims.picture_version, |
| 244 | + updated_at: claims_at.clone(), | |
| 240 | 245 | }; |
| 241 | 246 | let default_role = directory::default_role(&state.store).await?; |
| 242 | 247 | let stored = match state |
| 243 | 248 | .store |
| 244 | - .upsert_from_claims(&member_input, default_role) | |
| 249 | + .upsert_from_claims(&member_input, default_role, &claims_at) | |
| 245 | 250 | .await |
| 246 | 251 | { |
| 247 | 252 | Ok(stored) => stored, |
| @@ -374,6 +379,7 @@ mod tests { | ||
| 374 | 379 | locale: None, |
| 375 | 380 | zoneinfo: "UTC".into(), |
| 376 | 381 | picture_version: 0, |
| 382 | + updated_at: "2026-10-28T09:00:00.000000000Z".into(), | |
| 377 | 383 | }; |
| 378 | 384 | state |
| 379 | 385 | .store |
docs/architecture.mdmodified+1 -1
| @@ -42,7 +42,7 @@ iz/ | ||
| 42 | 42 | `clock.rs` (deadline + meeting time rules, inventory 2.4) |
| 43 | 43 | - `rules/` (mail rule engine: triggers, audiences, decisions; pure where possible), `mail_text.rs` (subjects and |
| 44 | 44 | 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 | |
| 46 | 46 | for ranges not starting at A1), `slides.rs` (pptx text outline via `zip` + `quick-xml`, size and entry limits |
| 47 | 47 | against zip bombs) |
| 48 | 48 | - `store/`: `members.rs`, `sessions.rs`, `board.rs`, `tasks.rs`, `deps.rs`, `comments.rs`, `attachments.rs`, |