From 34f693b65046791b12b57a82b35a5386b722f4b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 11:27:09 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=92=20fix:=20audit=20findings:=20strea?= =?UTF-8?q?med=20xlsx=20preview,=20no=20ODS=20preview,=20back-channel=20jt?= =?UTF-8?q?i=20after=20session=20end,=20sign-in=20never=20re-enables,=20di?= =?UTF-8?q?rectory=20ordering=20by=20im=20time,=20rule=20mail=20cap,=20liv?= =?UTF-8?q?e=20streams=20re-check=20access,=20alive=20cap,=20SMTP=20passwo?= =?UTF-8?q?rd=20on=20host=20change,=20storage=20cap,=20avatar/authz=20role?= =?UTF-8?q?=20none,=20deleted=20task=20bytes,=20upload=20id=20resolved=20f?= =?UTF-8?q?irst?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../migrations/0006_decision_skipped.sql | 20 ++ crates/iz-core/src/archive.rs | 2 +- crates/iz-core/src/authz.rs | 9 +- crates/iz-core/src/limits.rs | 6 + crates/iz-core/src/sender.rs | 3 + crates/iz-core/src/sheet.rs | 188 +++++++++++++++--- crates/iz-core/src/store/attachments.rs | 98 +++++++-- crates/iz-core/src/store/members.rs | 117 ++++++++--- crates/iz-core/src/store/migrate.rs | 4 + crates/iz-core/src/store/mod.rs | 3 +- crates/iz-core/src/store/rules_engine.rs | 59 +++++- crates/iz-core/src/store/sender.rs | 2 + crates/iz-core/src/store/sessions.rs | 14 ++ crates/iz-core/src/store/tasks.rs | 3 + crates/iz-core/src/time.rs | 32 ++- crates/iz-web/src/auth.rs | 27 ++- crates/iz-web/src/cli/fsck.rs | 1 + crates/iz-web/src/directory.rs | 4 + crates/iz-web/src/i18n/task.rs | 8 + crates/iz-web/src/in_store.rs | 1 + crates/iz-web/src/live.rs | 75 ++++++- crates/iz-web/src/oidc.rs | 3 + crates/iz-web/src/pages/backchannel.rs | 9 +- crates/iz-web/src/pages/board.rs | 11 +- crates/iz-web/src/pages/files.rs | 37 +++- crates/iz-web/src/pages/photo.rs | 5 +- crates/iz-web/src/pages/settings.rs | 14 +- crates/iz-web/src/pages/sign_in.rs | 8 +- docs/architecture.md | 2 +- 29 files changed, 655 insertions(+), 110 deletions(-) create mode 100644 crates/iz-core/migrations/0006_decision_skipped.sql diff --git a/crates/iz-core/migrations/0006_decision_skipped.sql b/crates/iz-core/migrations/0006_decision_skipped.sql new file mode 100644 index 0000000..ceda783 --- /dev/null +++ b/crates/iz-core/migrations/0006_decision_skipped.sql @@ -0,0 +1,20 @@ +-- 0006: a rule decision can be 'skipped' (the owed mails were all held back by the hourly per-recipient cap, +-- with detail 'rate_limited'). The outcome CHECK gains 'skipped'; SQLite cannot alter a CHECK, so the table is +-- rebuilt. Rows of 0001 carry over unchanged. +CREATE TABLE mail_decisions_by_outcome ( + id TEXT PRIMARY KEY, + rule_id TEXT NOT NULL REFERENCES mail_rules(id) ON DELETE CASCADE, + event_id TEXT NOT NULL, + task_id TEXT, + outcome TEXT NOT NULL CHECK (outcome IN ( + 'owed', 'already_owed', 'no_recipients', 'not_matched', 'disabled', 'task_gone', 'skipped' + )), + detail TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL, + UNIQUE (rule_id, event_id, task_id) +); +INSERT INTO mail_decisions_by_outcome (id, rule_id, event_id, task_id, outcome, detail, created_at) + SELECT id, rule_id, event_id, task_id, outcome, detail, created_at FROM mail_decisions; +DROP TABLE mail_decisions; +ALTER TABLE mail_decisions_by_outcome RENAME TO mail_decisions; +CREATE INDEX mail_decisions_recent ON mail_decisions(created_at); diff --git a/crates/iz-core/src/archive.rs b/crates/iz-core/src/archive.rs index 8870d42..197cce8 100644 --- a/crates/iz-core/src/archive.rs +++ b/crates/iz-core/src/archive.rs @@ -1,4 +1,4 @@ -//! Zip-container guards for the spreadsheet and slide viewers. A `.xlsx`, `.ods` or `.pptx` is a zip file, +//! Zip-container guards for the spreadsheet and slide viewers. A `.xlsx` or `.pptx` is a zip file, //! so one of them can expand to far more than it weighs. Every such file is checked here before any parser //! sees it (`docs/architecture.md`, attack plan section 6: zip bombs). //! diff --git a/crates/iz-core/src/authz.rs b/crates/iz-core/src/authz.rs index bf1bc58..800330c 100644 --- a/crates/iz-core/src/authz.rs +++ b/crates/iz-core/src/authz.rs @@ -128,7 +128,14 @@ enum Level { pub fn authorize(actor: &Actor, action: &Action) -> Result<(), Denied> { let (sub, level) = match actor { Actor::Anonymous => return Err(Denied::Forbidden), - Actor::Member { disabled: true, .. } => return Err(Denied::NotFound), + // A disabled member and a member with no role have no access, even when `im` makes them an admin. + Actor::Member { disabled: true, .. } + | Actor::Member { + role: Role::NoAccess, + .. + } => { + return Err(Denied::NotFound); + } Actor::Member { sub, im_admin: true, diff --git a/crates/iz-core/src/limits.rs b/crates/iz-core/src/limits.rs index 59957d4..287d555 100644 --- a/crates/iz-core/src/limits.rs +++ b/crates/iz-core/src/limits.rs @@ -31,6 +31,9 @@ pub const REMINDER_MINUTES_MAX: u32 = 1440; pub const BATCH_MINUTES_MAX: u32 = 120; /// Default per-file attachment limit, in MiB. Reason: the starting value of the setting; an admin raises it. pub const ATTACHMENT_DEFAULT_MIB: u32 = 100; +/// Total size of the attachments of one board when the setting was never saved, in bytes. Reason: the +/// disk is shared with the database and the backups; an admin raises it deliberately. +pub const ATTACHMENT_TOTAL_DEFAULT_BYTES: u64 = 20 * 1024 * 1024 * 1024; /// Most file parts one upload request may carry. Reason: bounds the work one form can cause. pub const UPLOAD_FILES_MAX: usize = 10; /// 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; pub const TEXT_PREVIEW_BYTES: u64 = 256 * 1024; /// Largest compressed spreadsheet or CSV the viewer parses, in bytes. Reason: bounds the work of one preview. pub const SHEET_INPUT_MAX_BYTES: u64 = 5 * 1024 * 1024; +/// Most cells one `.xlsx` sheet preview visits, kept or not. Reason: bounds the work on a sheet with a huge +/// used range, whatever the caps keep. +pub const SHEET_VISITS_MAX: usize = 200_000; /// Largest compressed slide deck the viewer parses, in bytes. Reason: decks carry pictures, so the cap is higher. pub const SLIDES_INPUT_MAX_BYTES: u64 = 20 * 1024 * 1024; /// Largest total uncompressed size of a zip container the viewers read, in bytes. Reason: a zip bomb is diff --git a/crates/iz-core/src/sender.rs b/crates/iz-core/src/sender.rs index b90e109..e7b9601 100644 --- a/crates/iz-core/src/sender.rs +++ b/crates/iz-core/src/sender.rs @@ -14,6 +14,9 @@ pub const DEFAULT_FROM_NAME: &str = "iz"; pub const DEFAULT_PORT: u16 = 587; /// Reminders per member per hour when the setting was never saved. Reason: a guard against a burst. pub const DEFAULT_REMINDER_CAP: u32 = 20; +/// Rule mails per recipient per hour when the setting was never saved. Reason: a rule fires on every +/// matching event, so one busy board must not flood one member's inbox. +pub const DEFAULT_RULE_CAP: u32 = 30; /// How the connection to the mail server is protected. #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/iz-core/src/sheet.rs b/crates/iz-core/src/sheet.rs index 29c5e61..c2d829c 100644 --- a/crates/iz-core/src/sheet.rs +++ b/crates/iz-core/src/sheet.rs @@ -1,20 +1,28 @@ -//! Spreadsheet previews: a workbook (`.xlsx`, `.ods`) or a CSV file read as values only, with the caps of +//! Spreadsheet previews: a workbook (`.xlsx`) or a CSV file read as values only, with the caps of //! `limits.rs`: at most 20 sheets, 1000 rows, 100 columns and 1000 characters a cell. Formulas, formats, //! charts and macros are not read; a cell is its displayed value. The caller turns the result into HTML, //! where every cell is escaped, so a cell that holds markup is shown as text. //! -//! A workbook is a zip container, so it passes `archive::open_checked` before calamine parses it. A CSV is -//! read record by record and stops at the row cap, so a long file costs no more than the cap. +//! A workbook is a zip container, so it passes `archive::open_checked` before calamine parses it. An `.xlsx` +//! is read cell by cell as a stream: a cell outside the caps is dropped as it is read, and the reading stops +//! after a fixed number of visited cells, so a sheet whose used range is huge (a stray cell at `XFD1048576`) +//! costs no more than the caps. An `.ods` is not previewed at all: calamine has no cell stream for it and reads +//! its `content.xml` whole, and a tiny file can declare huge repeat counts that allocate gigabytes. The viewer +//! shows such a file as refused, and it can still be downloaded. A CSV is read record by record and stops at +//! the row cap, so a long file costs no more than the cap. +use std::collections::BTreeMap; use std::fs::File; +use std::io::BufReader; use std::path::Path; -use calamine::{Data, Reader, open_workbook_auto}; +use calamine::{Data, DataRef, Reader, Sheets, Xlsx, open_workbook_auto}; use crate::archive; use crate::error::{Error, Result}; use crate::limits::{ - CELL_TEXT_MAX, SHEET_COLS_MAX, SHEET_INPUT_MAX_BYTES, SHEET_ROWS_MAX, SHEETS_MAX, + CELL_TEXT_MAX, SHEET_COLS_MAX, SHEET_INPUT_MAX_BYTES, SHEET_ROWS_MAX, SHEET_VISITS_MAX, + SHEETS_MAX, }; /// 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 { text.chars().take(CELL_TEXT_MAX).collect() } -/// Reads an `.xlsx` or `.ods` workbook. Refused (as `Invalid`) when the zip checks fail. +/// The shown text of a streamed `.xlsx` cell, cut to the cap as it is read. +fn data_ref_text(value: &DataRef<'_>) -> String { + match value { + DataRef::SharedString(text) => cell_text(text), + DataRef::String(text) => cell_text(text), + other => cell_text(&Data::from(other.clone()).to_string()), + } +} + +/// Reads an `.xlsx` workbook (`.xls` and `.xlsb` too). Refused (as `Invalid`) when the zip checks fail, and +/// for an OpenDocument file: it is refused before calamine opens it, because calamine reads its `content.xml` +/// whole. pub fn read_workbook(path: &Path) -> Result { - archive::open_checked(path, SHEET_INPUT_MAX_BYTES)?; + let mut zip = archive::open_checked(path, SHEET_INPUT_MAX_BYTES)?; + if zip.by_name("content.xml").is_ok() { + // Only an OpenDocument file has a root `content.xml`. Such files are not previewed. + return Err(Error::Invalid("ods_not_previewed".into())); + } let mut workbook = open_workbook_auto(path).map_err(|_| Error::Invalid("bad_workbook".into()))?; let names = workbook.sheet_names(); let sheet_count = names.len(); let mut sheets = Vec::new(); for name in names.into_iter().take(SHEETS_MAX) { - let range = workbook - .worksheet_range(&name) - .map_err(|_| Error::Invalid("bad_workbook".into()))?; - let mut rows = Vec::new(); - let mut rows_cut = false; - for (index, row) in range.rows().enumerate() { - if index == SHEET_ROWS_MAX { - rows_cut = true; - break; - } - rows.push( - row.iter() - .take(SHEET_COLS_MAX) - .map(|cell: &Data| cell_text(&cell.to_string())) - .collect(), - ); - } - sheets.push(Sheet { - name, - rows, - rows_cut, - }); + let sheet = match &mut workbook { + Sheets::Xlsx(xlsx) => read_xlsx_sheet(xlsx, &name)?, + _ => read_range_sheet(&mut workbook, &name)?, + }; + sheets.push(sheet); } Ok(Book { sheets, @@ -80,6 +86,74 @@ pub fn read_workbook(path: &Path) -> Result { }) } +/// Streams one `.xlsx` sheet. Only cells inside the caps are kept, in a sparse map, and the table is built +/// from them. `rows_cut` is set when a kept-out cell has text, or when the visit budget ended the read early. +fn read_xlsx_sheet(xlsx: &mut Xlsx>, name: &str) -> Result { + let bad = || Error::Invalid("bad_workbook".into()); + let mut reader = xlsx.worksheet_cells_reader(name).map_err(|_| bad())?; + let mut cells: BTreeMap<(usize, usize), String> = BTreeMap::new(); + let mut rows_cut = false; + let mut visits = 0usize; + while let Some(cell) = reader.next_cell().map_err(|_| bad())? { + visits += 1; + if visits > SHEET_VISITS_MAX { + rows_cut = true; + break; + } + let (row, col) = cell.get_position(); + let (row, col) = (row as usize, col as usize); + let text = data_ref_text(cell.get_value()); + if text.is_empty() { + continue; + } + if row >= SHEET_ROWS_MAX { + rows_cut = true; + continue; + } + if col >= SHEET_COLS_MAX { + continue; + } + cells.insert((row, col), text); + } + let rows_used = cells.keys().map(|(row, _)| row + 1).max().unwrap_or(0); + let cols_used = cells.keys().map(|(_, col)| col + 1).max().unwrap_or(0); + let mut rows = vec![vec![String::new(); cols_used]; rows_used]; + for ((row, col), text) in cells { + rows[row][col] = text; + } + Ok(Sheet { + name: name.to_owned(), + rows, + rows_cut, + }) +} + +/// Reads one sheet of a workbook that is not streamed (`.xls`, `.xlsb`) as a whole range. +fn read_range_sheet(workbook: &mut Sheets>, name: &str) -> Result { + let range = workbook + .worksheet_range(name) + .map_err(|_| Error::Invalid("bad_workbook".into()))?; + let mut rows = Vec::new(); + let mut rows_cut = false; + for (index, row) in range.rows().enumerate() { + if index == SHEET_ROWS_MAX { + rows_cut = true; + break; + } + rows.push( + row.iter() + .take(SHEET_COLS_MAX) + .map(|cell: &Data| cell_text(&cell.to_string())) + .collect(), + ); + } + Ok(Sheet { + name: name.to_owned(), + rows, + rows_cut, + }) +} + /// Reads a CSV file as one sheet. Invalid UTF-8 is shown with replacement characters. pub fn read_csv(path: &Path, name: &str) -> Result { let len = std::fs::metadata(path)?.len(); @@ -154,6 +228,19 @@ mod tests { assert!(read_workbook(&path).is_err()); } + #[test] + fn an_opendocument_workbook_is_not_previewed() { + let dir = tempfile::tempdir().expect("dir"); + let path = dir.path().join("sheet.ods"); + let file = std::fs::File::create(&path).expect("create"); + let mut writer = zip::ZipWriter::new(file); + let options = zip::write::SimpleFileOptions::default(); + writer.start_file("content.xml", options).expect("start"); + std::io::Write::write_all(&mut writer, b"").expect("write"); + writer.finish().expect("finish"); + assert!(read_workbook(&path).is_err()); + } + #[test] fn a_csv_stops_at_the_row_cap() { let dir = tempfile::tempdir().expect("dir"); @@ -165,6 +252,49 @@ mod tests { assert!(book.sheets[0].rows_cut); } + /// A minimal `.xlsx`: A1 holds "hello" and XFD1048576 (the far corner) holds a number. + #[test] + fn a_far_cell_does_not_blow_up_the_preview() { + use std::io::Write; + let dir = tempfile::tempdir().expect("dir"); + let path = dir.path().join("far.xlsx"); + let file = std::fs::File::create(&path).expect("create"); + let mut writer = zip::ZipWriter::new(file); + let options = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated); + let parts = [ + ( + "[Content_Types].xml", + r#""#, + ), + ( + "_rels/.rels", + r#""#, + ), + ( + "xl/workbook.xml", + r#""#, + ), + ( + "xl/_rels/workbook.xml.rels", + r#""#, + ), + ( + "xl/worksheets/sheet1.xml", + r#"hello7"#, + ), + ]; + for (name, body) in parts { + writer.start_file(name, options).expect("start"); + writer.write_all(body.as_bytes()).expect("write"); + } + writer.finish().expect("finish"); + let book = read_workbook(&path).expect("workbook"); + assert_eq!(book.sheet_count, 1); + assert_eq!(book.sheets[0].rows, vec![vec!["hello".to_owned()]]); + assert!(book.sheets[0].rows_cut); + } + #[test] fn a_cell_is_cut_to_its_cap() { assert_eq!( diff --git a/crates/iz-core/src/store/attachments.rs b/crates/iz-core/src/store/attachments.rs index 964b3e2..06ffaaf 100644 --- a/crates/iz-core/src/store/attachments.rs +++ b/crates/iz-core/src/store/attachments.rs @@ -9,13 +9,15 @@ use serde_json::json; use turso::Connection; +use turso::transaction::Transaction; use super::activity::{self, NewActivity}; use super::{col_int, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; use crate::authz::{Action, Actor, authorize}; use crate::error::{Error, Result}; use crate::limits::{ - ATTACHMENT_DEFAULT_MIB, ATTACHMENT_LIMIT_MIB_MAX, ATTACHMENT_LIMIT_MIB_MIN, FILE_NAME_MAX, + ATTACHMENT_DEFAULT_MIB, ATTACHMENT_LIMIT_MIB_MAX, ATTACHMENT_LIMIT_MIB_MIN, + ATTACHMENT_TOTAL_DEFAULT_BYTES, FILE_NAME_MAX, }; use crate::store::Store; use crate::time::{now_stamp, stamp_after}; @@ -25,6 +27,8 @@ use std::time::Duration; pub const SETTING_LIMIT_MIB: &str = "attachment_limit_mib"; /// The setting that holds the allowed extensions, separated by spaces or commas. pub const SETTING_EXTENSIONS: &str = "attachment_extensions"; +/// The setting that holds the total size of the attachments of one board, in bytes. +pub const SETTING_TOTAL_BYTES: &str = "attachments_total_bytes"; /// The setting that holds where new and existing attachments belong: `local` (default) or `in`. pub const SETTING_LOCATION: &str = "attachment_location"; /// 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 { const ATTACHMENT_COLS: &str = "a.id, a.task_id, a.name, a.mime, a.size, a.sha256, a.uploaded_by, a.created_at, a.location"; +/// Records the copies of one attachment's bytes as owed to deletion, in the caller's transaction. A moving +/// row may have a copy in each place, so both are owed; a settled row has one copy. +pub(super) async fn owe_bytes( + tx: &Transaction<'_>, + attachment_id: &str, + location: &str, + now: &str, +) -> Result<()> { + let owed: &[&str] = match location { + LOCATION_LOCAL => &[LOCATION_LOCAL], + LOCATION_IN => &[LOCATION_IN], + _ => &[LOCATION_LOCAL, LOCATION_IN], + }; + for place in owed { + tx.execute( + "INSERT INTO blob_deletions (attachment_id, location, attempts, next_attempt_at, created_at) \ + VALUES (?1, ?2, 0, ?3, ?4)", + ( + attachment_id.to_owned(), + (*place).to_owned(), + now.to_owned(), + now.to_owned(), + ), + ) + .await + .map_err(db_err)?; + } + Ok(()) +} + +/// Queues the bytes of every attachment of a task that is being deleted, and removes the rows, in the +/// caller's transaction. Without this the rows would go with the task at purge and the bytes would be +/// orphaned; with it the deleter removes them. +pub(super) async fn owe_task_bytes(tx: &Transaction<'_>, task_id: &str, now: &str) -> Result<()> { + let rows = fetch_all( + tx, + "SELECT id, location FROM attachments WHERE task_id = ?1", + (task_id.to_owned(),), + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), + ) + .await?; + for (id, location) in rows { + owe_bytes(tx, &id, &location, now).await?; + tx.execute("DELETE FROM attachments WHERE id = ?1", (id,)) + .await + .map_err(db_err)?; + } + Ok(()) +} + fn map_attachment(row: &turso::Row) -> Result { Ok(Attachment { id: col_text(row, 0)?, @@ -180,7 +234,8 @@ impl Store { } /// Stores an attachment on a live task of `board_id`, with its `file_added` activity row. The bytes must - /// already be in place under `new.id`; if this fails, the caller removes them. + /// already be in place under `new.id`; if this fails, the caller removes them. Refused as + /// `storage_full` when the board's attachments, with this one, would pass the total cap. pub async fn add_attachment( &self, board_id: &str, @@ -213,6 +268,29 @@ impl Store { if live.is_none() { return Err(Error::NotFound); } + // The board's total must stay within its cap, counted in the same transaction as the insert. + let cap = fetch_opt( + &tx, + "SELECT value FROM settings WHERE key = ?1", + (SETTING_TOTAL_BYTES.to_owned(),), + |row| col_text(row, 0), + ) + .await? + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(ATTACHMENT_TOTAL_DEFAULT_BYTES); + let used = fetch_opt( + &tx, + "SELECT COALESCE(SUM(a.size), 0) FROM attachments a JOIN tasks t ON t.id = a.task_id \ + WHERE t.board_id = ?1", + (board_id.to_owned(),), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + let used = u64::try_from(used).unwrap_or(u64::MAX); + if used.saturating_add(new.size) > cap { + return Err(Error::Invalid("storage_full".into())); + } tx.execute( "INSERT INTO attachments (id, task_id, comment_id, name, mime, size, sha256, uploaded_by, created_at, location) \ VALUES (?1, ?2, NULL, ?3, ?4, ?5, ?6, ?7, ?8, 'local')", @@ -336,21 +414,7 @@ impl Store { ) .await .map_err(db_err)?; - // A moving row may have a copy in each place, so both are owed. A settled row has one copy. - let owed: &[&str] = match current.location.as_str() { - LOCATION_LOCAL => &[LOCATION_LOCAL], - LOCATION_IN => &[LOCATION_IN], - _ => &[LOCATION_LOCAL, LOCATION_IN], - }; - for place in owed { - tx.execute( - "INSERT INTO blob_deletions (attachment_id, location, attempts, next_attempt_at, created_at) \ - VALUES (?1, ?2, 0, ?3, ?4)", - (attachment_id.to_owned(), (*place).to_owned(), now.clone(), now.clone()), - ) - .await - .map_err(db_err)?; - } + owe_bytes(&tx, attachment_id, ¤t.location, &now).await?; activity::record( &tx, NewActivity { diff --git a/crates/iz-core/src/store/members.rs b/crates/iz-core/src/store/members.rs index 9fc689e..6e7e56a 100644 --- a/crates/iz-core/src/store/members.rs +++ b/crates/iz-core/src/store/members.rs @@ -14,7 +14,7 @@ use crate::authz::Role; use crate::error::{Error, Result}; use crate::limits::DISPLAY_NAME_MAX; use crate::store::Store; -use crate::time::now_stamp; +use crate::time::{normalize_stamp, now_stamp}; use crate::zones::parse_zone; /// Longest email address accepted from the directory, in characters (RFC 5321 path limit). @@ -78,6 +78,9 @@ pub struct DirectoryMember { pub zoneinfo: String, /// Photo version from `im`. pub picture_version: i64, + /// The directory's `updated_at` (an RFC 3339 time). Normalised to the stored stamp form; empty or + /// unparseable values fall back to the local time. Orders this write against other directory data. + pub updated_at: String, } const MEMBER_COLS: &str = "sub, email, name, im_admin, disabled, locale, locale_override, zoneinfo, \ @@ -144,6 +147,7 @@ fn validate(m: &DirectoryMember) -> Result { locale: m.locale.clone().filter(|l| LOCALES.contains(&l.as_str())), zoneinfo, picture_version: m.picture_version, + updated_at: m.updated_at.trim().to_owned(), }) } @@ -182,23 +186,55 @@ impl Store { member: &DirectoryMember, default_role: Role, ) -> Result { - self.upsert_member(member, default_role, false).await + let m = validate(member)?; + let stamp = normalize_stamp(&m.updated_at).unwrap_or_else(now_stamp); + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + tx.execute( + "INSERT INTO members (sub, email, name, im_admin, disabled, locale, zoneinfo, \ + picture_version, im_updated_at, role, first_seen_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11) \ + ON CONFLICT(sub) DO UPDATE SET email = excluded.email, name = excluded.name, \ + im_admin = excluded.im_admin, disabled = excluded.disabled, \ + locale = excluded.locale, zoneinfo = excluded.zoneinfo, \ + picture_version = excluded.picture_version, im_updated_at = excluded.im_updated_at \ + WHERE excluded.im_updated_at >= members.im_updated_at", + ( + m.sub.clone(), + m.email.clone(), + m.name.clone(), + i64::from(m.im_admin), + i64::from(m.disabled), + m.locale.clone(), + m.zoneinfo.clone(), + m.picture_version, + stamp, + default_role.as_str(), + now, + ), + ) + .await + .map_err(db_err)?; + select_member(&tx, &m.sub) + .await? + .ok_or_else(|| Error::Database("member vanished after upsert".into())) + } + .await; + finish(tx, outcome).await } - /// Creates or refreshes a member at sign-in (from the ID token claims) and stamps the sign-in time. + /// Records a sign-in. A new member gets `default_role`. An existing member gets the claim fields + /// refreshed only when `claims_at` (the ID token's `iat`, as a stamp) is not older than the stored + /// `im_updated_at`, so a stale sign-in cannot roll back a newer change. `disabled` is never written + /// here: the directory owns it, so a sign-in cannot re-enable a disabled member. Always stamps + /// `last_sign_in_at`. pub async fn upsert_from_claims( &self, member: &DirectoryMember, default_role: Role, - ) -> Result { - self.upsert_member(member, default_role, true).await - } - - async fn upsert_member( - &self, - member: &DirectoryMember, - default_role: Role, - signed_in: bool, + claims_at: &str, ) -> Result { let m = validate(member)?; let now = now_stamp(); @@ -206,36 +242,35 @@ impl Store { let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result = async { tx.execute( - "INSERT INTO members (sub, email, name, im_admin, disabled, locale, zoneinfo, \ + "INSERT INTO members (sub, email, name, im_admin, locale, zoneinfo, \ picture_version, im_updated_at, role, first_seen_at) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?9) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10) \ ON CONFLICT(sub) DO UPDATE SET email = excluded.email, name = excluded.name, \ - im_admin = excluded.im_admin, disabled = excluded.disabled, \ - locale = excluded.locale, zoneinfo = excluded.zoneinfo, \ - picture_version = excluded.picture_version, im_updated_at = excluded.im_updated_at", + im_admin = excluded.im_admin, locale = excluded.locale, \ + zoneinfo = excluded.zoneinfo, picture_version = excluded.picture_version, \ + im_updated_at = excluded.im_updated_at \ + WHERE excluded.im_updated_at >= members.im_updated_at", ( m.sub.clone(), m.email.clone(), m.name.clone(), i64::from(m.im_admin), - i64::from(m.disabled), m.locale.clone(), m.zoneinfo.clone(), m.picture_version, - now.clone(), + claims_at.to_owned(), default_role.as_str(), + now.clone(), ), ) .await .map_err(db_err)?; - if signed_in { - tx.execute( - "UPDATE members SET last_sign_in_at = ?2 WHERE sub = ?1", - (m.sub.clone(), now.clone()), - ) - .await - .map_err(db_err)?; - } + tx.execute( + "UPDATE members SET last_sign_in_at = ?2 WHERE sub = ?1", + (m.sub.clone(), now), + ) + .await + .map_err(db_err)?; select_member(&tx, &m.sub) .await? .ok_or_else(|| Error::Database("member vanished after upsert".into())) @@ -372,6 +407,7 @@ mod tests { locale: Some("de".into()), zoneinfo: "Europe/Istanbul".into(), picture_version: 0, + updated_at: "2026-10-28T09:00:00.000000000Z".into(), }; let v = validate(&raw).unwrap(); assert_eq!(v.sub, "u1"); @@ -385,6 +421,33 @@ mod tests { assert!(validate(&bad).is_err()); } + #[tokio::test] + async fn older_directory_event_does_not_roll_back_a_newer_one() { + let (_dir, store, _board) = crate::store::test_support::seeded().await; + let mut member = DirectoryMember { + sub: "cy".into(), + email: "cy@example.com".into(), + name: "Newer".into(), + im_admin: false, + disabled: false, + locale: None, + zoneinfo: "UTC".into(), + picture_version: 0, + updated_at: "2026-10-28T10:00:00+01:00".into(), + }; + store + .apply_directory_member(&member, Role::Member) + .await + .unwrap(); + member.name = "Older".into(); + member.updated_at = "2026-10-28T08:00:00.000000000Z".into(); + let kept = store + .apply_directory_member(&member, Role::Member) + .await + .unwrap(); + assert_eq!(kept.name, "Newer"); + } + #[tokio::test] async fn last_administrator_cannot_be_demoted() { let (_dir, store, _board) = crate::store::test_support::seeded().await; diff --git a/crates/iz-core/src/store/migrate.rs b/crates/iz-core/src/store/migrate.rs index c3660d3..6151041 100644 --- a/crates/iz-core/src/store/migrate.rs +++ b/crates/iz-core/src/store/migrate.rs @@ -20,6 +20,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ 5, include_str!("../../migrations/0005_blob_deletions_by_place.sql"), ), + ( + 6, + include_str!("../../migrations/0006_decision_skipped.sql"), + ), ]; fn migration_err(e: turso::Error) -> Error { diff --git a/crates/iz-core/src/store/mod.rs b/crates/iz-core/src/store/mod.rs index c64f555..ece8406 100644 --- a/crates/iz-core/src/store/mod.rs +++ b/crates/iz-core/src/store/mod.rs @@ -347,6 +347,7 @@ pub(crate) mod test_support { locale: None, zoneinfo: "UTC".into(), picture_version: 0, + updated_at: "2026-10-28T09:00:00.000000000Z".into(), }; store.apply_directory_member(&member, role).await.unwrap(); } @@ -403,7 +404,7 @@ mod tests { }) .await .unwrap(); - assert_eq!(versions, vec![1, 2, 3, 4, 5]); + assert_eq!(versions, vec![1, 2, 3, 4, 5, 6]); } #[tokio::test] diff --git a/crates/iz-core/src/store/rules_engine.rs b/crates/iz-core/src/store/rules_engine.rs index c9d7845..53ea2ee 100644 --- a/crates/iz-core/src/store/rules_engine.rs +++ b/crates/iz-core/src/store/rules_engine.rs @@ -19,9 +19,18 @@ use crate::clock::stamp_of; use crate::error::Result; use crate::mail_text::{MailLang, RuleMail, rule_body, when_text}; use crate::rules::{Audience, EventFacts, RuleFacts, TaskFacts, Verdict, evaluate, render_subject}; +use crate::sender::DEFAULT_RULE_CAP; use crate::store::Store; +use crate::store::sender::KEY_RULE_CAP; use crate::time::now_stamp; +/// What one event's handling needs from the pass: the hourly cap and where its window starts. +#[derive(Clone, Copy)] +struct Limits<'a> { + cap: i64, + window_start: &'a str, +} + /// One unprocessed event as read back. struct QueuedEvent { id: String, @@ -159,7 +168,14 @@ pub fn task_link(base_url: &str, key: &str) -> String { } /// Handles one event: every rule of its trigger gets a decision, and mail rows for the owed recipients. -async fn handle(tx: &Transaction<'_>, event: &QueuedEvent, base_url: &str) -> Result { +/// A recipient already queued `limits.cap` rule mails since `limits.window_start` gets none; the decision +/// then records `skipped` with the detail `rate_limited`. +async fn handle( + tx: &Transaction<'_>, + event: &QueuedEvent, + base_url: &str, + limits: Limits<'_>, +) -> Result { let rules = fetch_all( tx, "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 Verdict::Owed(recipients) => ("owed", String::new(), recipients.clone()), }; let mut queued = 0; + let mut capped = 0; if let (Some(row), Some(task_id)) = (&task, &event.task_id) { let column_id = event .column_id @@ -248,6 +265,19 @@ async fn handle(tx: &Transaction<'_>, event: &QueuedEvent, base_url: &str) -> Re let Some(member) = eligible.iter().find(|m| &m.sub == sub) else { continue; }; + let sent_before = fetch_opt( + tx, + "SELECT COUNT(*) FROM mail_outbox WHERE recipient = ?1 AND kind = 'rule' AND created_at >= ?2", + (sub.clone(), limits.window_start.to_owned()), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + if sent_before >= limits.cap { + capped += 1; + tracing::warn!(recipient = %sub, cap = limits.cap, "rule mail held back by the hourly cap"); + continue; + } let when = row .meeting_at .as_deref() @@ -294,10 +324,13 @@ async fn handle(tx: &Transaction<'_>, event: &QueuedEvent, base_url: &str) -> Re } } mails += queued; - let outcome = if outcome == "owed" && queued == 0 { - "already_owed" + let (outcome, detail) = if capped > 0 { + let outcome = if queued == 0 { "skipped" } else { outcome }; + (outcome, "rate_limited".to_owned()) + } else if outcome == "owed" && queued == 0 { + ("already_owed", detail) } else { - outcome + (outcome, detail) }; tx.execute( "INSERT INTO mail_decisions (id, rule_id, event_id, task_id, outcome, detail, created_at) \ @@ -350,8 +383,23 @@ impl Store { .await?; let mut report = PassReport::default(); let stamp = stamp_of(now)?; + let cap = fetch_opt( + &tx, + "SELECT value FROM settings WHERE key = ?1", + (KEY_RULE_CAP.to_owned(),), + |row| col_text(row, 0), + ) + .await? + .and_then(|v| v.parse::().ok()) + .unwrap_or(DEFAULT_RULE_CAP) + .min(crate::limits::REMINDER_CAP_MAX); + let window_start = stamp_of(now - jiff::SignedDuration::from_hours(1))?; + let limits = Limits { + cap: i64::from(cap), + window_start: &window_start, + }; for event in &events { - report.mails += handle(&tx, event, base_url).await?; + report.mails += handle(&tx, event, base_url, limits).await?; tx.execute( "UPDATE mail_events SET processed_at = ?2 WHERE id = ?1", (event.id.clone(), stamp.clone()), @@ -464,6 +512,7 @@ mod tests { locale: None, zoneinfo: "UTC".into(), picture_version: 0, + updated_at: "2026-10-28T09:00:00.000000000Z".into(), }; store .apply_directory_member(&ghost, crate::authz::Role::Member) diff --git a/crates/iz-core/src/store/sender.rs b/crates/iz-core/src/store/sender.rs index 1527481..d9e1a6c 100644 --- a/crates/iz-core/src/store/sender.rs +++ b/crates/iz-core/src/store/sender.rs @@ -28,6 +28,8 @@ pub const KEY_PASSWORD: &str = "mail_password"; pub const KEY_REMINDER_MINUTES: &str = "reminder_minutes"; /// Settings key of the reminder cap per member per hour. pub const KEY_REMINDER_CAP: &str = "reminder_hourly_cap"; +/// Settings key of the cap on rule mails per recipient per hour. +pub const KEY_RULE_CAP: &str = "rule_hourly_cap"; /// What the store knows about the sender. The password is only represented by its sealed text. #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/crates/iz-core/src/store/sessions.rs b/crates/iz-core/src/store/sessions.rs index 2304511..c620bea 100644 --- a/crates/iz-core/src/store/sessions.rs +++ b/crates/iz-core/src/store/sessions.rs @@ -187,6 +187,20 @@ impl Store { Ok(inserted == 0) } + /// Whether a logout-token id is already recorded. Reads only; a caller that acts on the answer + /// records the id afterwards with [`Store::seen_jti`]. + pub async fn jti_recorded(&self, jti: &str) -> Result { + let conn = self.read_conn().await; + let row = fetch_opt( + &conn, + "SELECT 1 FROM seen_logout_jti WHERE jti = ?1", + (jti.to_owned(),), + |_| Ok(()), + ) + .await?; + Ok(row.is_some()) + } + /// Deletes replay records whose lifetime has passed. Returns the count. pub async fn sweep_jti(&self) -> Result { let conn = self.inner.conn.lock().await; diff --git a/crates/iz-core/src/store/tasks.rs b/crates/iz-core/src/store/tasks.rs index 7890b3c..e137749 100644 --- a/crates/iz-core/src/store/tasks.rs +++ b/crates/iz-core/src/store/tasks.rs @@ -813,6 +813,9 @@ impl Store { .map_err(db_err)?; log(&tx, id, actor, "task_deleted", None, serde_json::json!({})).await?; } + for id in &doomed { + super::attachments::owe_task_bytes(&tx, id, &now).await?; + } queue_event(&tx, board_id, task_id, "deleted", actor, None, None).await?; let doomed_set: HashSet<&str> = doomed.iter().map(String::as_str).collect(); let mut edges: Vec<(String, String)> = Vec::new(); diff --git a/crates/iz-core/src/time.rs b/crates/iz-core/src/time.rs index 14283c0..267c243 100644 --- a/crates/iz-core/src/time.rs +++ b/crates/iz-core/src/time.rs @@ -4,7 +4,8 @@ use std::time::Duration; use time::{ - OffsetDateTime, SignedDuration, format_description::FormatItem, macros::format_description, + OffsetDateTime, SignedDuration, format_description::FormatItem, + format_description::well_known::Rfc3339, macros::format_description, }; const FORMAT: &[FormatItem<'static>] = @@ -22,6 +23,21 @@ pub fn now_stamp() -> String { format_stamp(OffsetDateTime::now_utc()) } +/// The stamp of a Unix time in whole seconds (an ID token's `iat`), or `None` when it is out of range. +pub fn stamp_from_unix(secs: i64) -> Option { + OffsetDateTime::from_unix_timestamp(secs) + .ok() + .map(format_stamp) +} + +/// Parses an RFC 3339 time (any offset, any fraction length) and re-formats it as a stamp. `None` when +/// the text does not parse. This brings directory times into the stored form so text comparison works. +pub fn normalize_stamp(raw: &str) -> Option { + OffsetDateTime::parse(raw.trim(), &Rfc3339) + .ok() + .map(format_stamp) +} + /// The stamp for `now + after`. Saturates at the largest representable time instead of panicking. pub fn stamp_after(after: Duration) -> String { let delta = SignedDuration::try_from(after).unwrap_or(SignedDuration::MAX); @@ -33,6 +49,20 @@ mod tests { use super::*; use time::macros::datetime; + #[test] + fn normalize_brings_rfc3339_into_stamp_form() { + assert_eq!( + normalize_stamp("2026-10-28T12:00:00+03:00").as_deref(), + Some("2026-10-28T09:00:00.000000000Z") + ); + assert_eq!( + normalize_stamp("2026-10-28T09:00:00.5Z").as_deref(), + Some("2026-10-28T09:00:00.500000000Z") + ); + assert_eq!(normalize_stamp(""), None); + assert_eq!(normalize_stamp("yesterday"), None); + } + #[test] fn stamp_is_fixed_width_utc_with_nine_digits() { let s = format_stamp(datetime!(2026-10-28 09:05:00.5 UTC)); diff --git a/crates/iz-web/src/auth.rs b/crates/iz-web/src/auth.rs index 234f04d..01252be 100644 --- a/crates/iz-web/src/auth.rs +++ b/crates/iz-web/src/auth.rs @@ -9,6 +9,7 @@ use std::time::Duration; use iz_core::authz::{Action, Actor, Denied, authorize}; use iz_core::secret; +use iz_core::store::Store; use iz_core::store::members::Member; use iz_core::store::sessions::SessionRecord; use iz_core::token::constant_time_eq; @@ -102,8 +103,21 @@ pub async fn current_member(cx: &Cx) -> Result> { let Some(cookie) = jar(cx).get(SESSION_COOKIE) else { return Ok(None); }; - let store = &app_context::(cx).store; - let Some(session) = store.session_by_token(cookie.value()).await? else { + member_of_token(&app_context::(cx).store, cookie.value()).await +} + +/// The value of the session cookie, or an empty string when there is none. A live stream keeps it, so +/// it can check the session again after the request has ended. +pub fn session_cookie(cx: &Cx) -> String { + jar(cx) + .get(SESSION_COOKIE) + .map(|cookie| cookie.value().to_owned()) + .unwrap_or_default() +} + +/// The member of a session cookie `token`, under the same rules as [`current_member`]. +pub async fn member_of_token(store: &Store, token: &str) -> Result> { + let Some(session) = store.session_by_token(token).await? else { return Ok(None); }; let Some(member) = store.member(&session.sub).await? else { @@ -112,6 +126,15 @@ pub async fn current_member(cx: &Cx) -> Result> { Ok(Some(CurrentMember { session, member })) } +/// Whether the session `token` still belongs to a member who may read the board. A live stream asks +/// this before each event, so a signed-out or disabled viewer stops receiving them. +pub async fn still_reads_board(store: &Store, token: &str) -> Result { + let Some(me) = member_of_token(store, token).await? else { + return Ok(false); + }; + Ok(authorize(&me.actor(), &Action::ReadBoard).is_ok()) +} + /// The signed-in member. Without a session, redirects to `/login?next=`. pub async fn require_member(cx: &Cx) -> Result { match current_member(cx).await? { diff --git a/crates/iz-web/src/cli/fsck.rs b/crates/iz-web/src/cli/fsck.rs index bb9b54a..b6ef8fd 100644 --- a/crates/iz-web/src/cli/fsck.rs +++ b/crates/iz-web/src/cli/fsck.rs @@ -283,6 +283,7 @@ mod tests { locale: None, zoneinfo: "UTC".into(), picture_version: 0, + updated_at: "2026-10-28T09:00:00.000000000Z".into(), }; store .apply_directory_member(&member, Role::Admin) diff --git a/crates/iz-web/src/directory.rs b/crates/iz-web/src/directory.rs index dd004aa..1fa34ad 100644 --- a/crates/iz-web/src/directory.rs +++ b/crates/iz-web/src/directory.rs @@ -71,6 +71,9 @@ struct WireMember { zoneinfo: String, #[serde(default)] picture_version: i64, + /// The directory's change time (RFC 3339). Empty when `im` does not send one. + #[serde(default)] + updated_at: String, } fn utc() -> String { @@ -324,6 +327,7 @@ fn parse_member(raw: Value) -> Option { locale: wire.locale, zoneinfo: wire.zoneinfo, picture_version: wire.picture_version, + updated_at: wire.updated_at, }) } diff --git a/crates/iz-web/src/i18n/task.rs b/crates/iz-web/src/i18n/task.rs index 0e4945d..edf92ce 100644 --- a/crates/iz-web/src/i18n/task.rs +++ b/crates/iz-web/src/i18n/task.rs @@ -211,6 +211,8 @@ pub enum K { ErrTooManyFiles, /// Refused: the file could not be stored; nothing was kept. ErrFileStore, + /// Refused: the attachment storage of the board is full. + ErrFileStorageFull, /// The viewer message for a file that cannot be previewed (refused, or too large to read). ViewerRefused, /// The viewer message for a type with no preview. @@ -458,6 +460,12 @@ pub fn t(lang: Lang, key: K) -> &'static str { (K::ErrTooManyFiles, Lang::Tr) => "Bir seferde daha az dosya yükleyin.", (K::ErrFileStore, Lang::En) => "The file could not be saved. Try again.", (K::ErrFileStore, Lang::Tr) => "Dosya kaydedilemedi. Tekrar deneyin.", + (K::ErrFileStorageFull, Lang::En) => { + "Attachment storage is full. Remove a file or ask an administrator." + } + (K::ErrFileStorageFull, Lang::Tr) => { + "Ek dosya depolama alanı dolu. Bir dosyayı silin ya da yöneticiye sorun." + } (K::ViewerRefused, Lang::En) => "This file cannot be previewed. Download it to open it.", (K::ViewerRefused, Lang::Tr) => "Bu dosya önizlenemiyor. Açmak için indirin.", (K::NoPreview, Lang::En) => "No preview for this type. Download it to open it.", diff --git a/crates/iz-web/src/in_store.rs b/crates/iz-web/src/in_store.rs index ff38de3..b74bd13 100644 --- a/crates/iz-web/src/in_store.rs +++ b/crates/iz-web/src/in_store.rs @@ -440,6 +440,7 @@ pub(crate) mod test_support { locale: None, zoneinfo: "UTC".into(), picture_version: 0, + updated_at: "2026-10-28T09:00:00.000000000Z".into(), }; store .apply_directory_member(&member, role) diff --git a/crates/iz-web/src/live.rs b/crates/iz-web/src/live.rs index aeb02d2..0ddd399 100644 --- a/crates/iz-web/src/live.rs +++ b/crates/iz-web/src/live.rs @@ -7,15 +7,16 @@ //! page wrong for long. Nothing polls, and a topic nobody listens to is dropped. //! //! The hub is not a queue and not an authorisation check. Each route that opens a stream -//! authenticates and authorises first, then calls [`stream_changes`]. +//! authenticates and authorises first, then calls [`stream_changes`], which checks the viewer again +//! before every event: a session that ends in the middle of a stream ends the stream too. //! -//! Nothing bumps a topic or opens [`stream_changes`] yet, so the items here are kept ahead of the -//! pages that use them. +//! The anonymous `/-/alive` stream is the one stream with no viewer to check. It is capped instead. -#![allow(dead_code)] // The hub and its topics wait for the pages that bump and follow them. +#![allow(dead_code)] // Some topics wait for the pages that bump and follow them. use std::collections::HashMap; use std::future::Future; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Mutex, MutexGuard, PoisonError}; use std::time::Duration; @@ -25,7 +26,13 @@ use topcoat::Result; use topcoat::context::Cx; use topcoat::router::content::sse::{Event, KeepAlive, Sse}; use topcoat::router::response::{IntoResponse, Response}; -use topcoat::router::{HeaderValue, route}; +use topcoat::router::{HeaderValue, StatusCode, route}; + +/// Most `/-/alive` streams held at once, over all anonymous viewers. Reason: every page holds one, so +/// the count is the number of open tabs; past it a new stream waits for a tab to close. +pub const ALIVE_STREAMS_MAX: usize = 256; +/// The `/-/alive` streams open now. Each open stream holds one count, given back when it is dropped. +static ALIVE_OPEN: AtomicUsize = AtomicUsize::new(0); /// How long a client waits before it reconnects when a stream ends. Sent once, at the start. pub const STREAM_RETRY: Duration = Duration::from_millis(1000); @@ -108,9 +115,10 @@ impl LiveHub { } /// The state a stream carries between wakes. -struct Follow { +struct Follow { wakes: Vec>, fingerprint: F, + still_allowed: G, last: String, } @@ -118,17 +126,22 @@ struct Follow { /// differs from the value it last sent, so a bump that changes nothing the viewer sees sends /// nothing. Nothing is sent on connect: the page already shows the state that `fingerprint` read. /// +/// `still_allowed` is run before each event. When it says no, or fails, the stream ends. +/// /// `fingerprint` must be cheap and must describe everything the page shows. A read that fails ends /// the stream, and the browser reconnects. -pub async fn stream_changes( +pub async fn stream_changes( cx: &Cx, hub: &LiveHub, topics: &[Topic], fingerprint: F, + still_allowed: G, ) -> Result where F: Fn() -> Fut + Send + 'static, Fut: Future> + Send, + G: Fn() -> GFut + Send + 'static, + GFut: Future> + Send, { // Subscribed before the first read, so a change in between still wakes the stream. let wakes: Vec> = @@ -137,6 +150,7 @@ where let follow = Follow { wakes, fingerprint, + still_allowed, last, }; let events = stream::unfold(follow, |mut follow| async move { @@ -146,6 +160,19 @@ where } match (follow.fingerprint)().await { Ok(now) if now != follow.last => { + match (follow.still_allowed)().await { + Ok(true) => {} + Ok(false) => { + tracing::info!( + "live: the viewer may no longer read this; stream ended" + ); + return None; + } + Err(error) => { + tracing::error!(error = %error, "live: could not check the viewer"); + return None; + } + } follow.last = now; return Some((changed_event(), follow)); } @@ -192,10 +219,38 @@ pub fn events_response( Ok(response) } +/// One open `/-/alive` stream. Given back when the stream is dropped, so a closed tab frees its slot. +struct AliveSlot; + +impl AliveSlot { + /// Takes a slot, or `None` when [`ALIVE_STREAMS_MAX`] streams are already open. + fn take() -> Option { + if ALIVE_OPEN.fetch_add(1, Ordering::SeqCst) < ALIVE_STREAMS_MAX { + Some(Self) + } else { + ALIVE_OPEN.fetch_sub(1, Ordering::SeqCst); + None + } + } +} + +impl Drop for AliveSlot { + fn drop(&mut self) { + ALIVE_OPEN.fetch_sub(1, Ordering::SeqCst); + } +} + /// `GET /-/alive`. Every page holds this stream, so the browser learns when the server stops and -/// starts again. Anonymous viewers may hold it, and it reveals nothing: for now it sends only the -/// `retry` hint and keep-alives. +/// starts again. Anonymous viewers may hold it, and it reveals nothing: it sends only the `retry` +/// hint and keep-alives. Past [`ALIVE_STREAMS_MAX`] open streams the answer is `429`. #[route(GET "/-/alive")] async fn alive(cx: &Cx) -> Result { - events_response(cx, stream::pending::>()) + let Some(slot) = AliveSlot::take() else { + return StatusCode::TOO_MANY_REQUESTS.into_response(cx); + }; + // The closure owns the slot, so the slot lives as long as the stream does. + let events = stream::pending::>().inspect(move |_| { + let _ = &slot; + }); + events_response(cx, events) } diff --git a/crates/iz-web/src/oidc.rs b/crates/iz-web/src/oidc.rs index 28372d0..e9fd597 100644 --- a/crates/iz-web/src/oidc.rs +++ b/crates/iz-web/src/oidc.rs @@ -134,6 +134,9 @@ pub struct IdClaims { /// Bumps when the photo changes. Used as the avatar cache key. #[serde(default)] pub picture_version: i64, + /// When `im` issued the token, in Unix seconds. Orders a sign-in against directory changes. + #[serde(default)] + pub iat: i64, } /// The claims of a back-channel logout token that iz uses. diff --git a/crates/iz-web/src/pages/backchannel.rs b/crates/iz-web/src/pages/backchannel.rs index d1c7a05..f3f9c53 100644 --- a/crates/iz-web/src/pages/backchannel.rs +++ b/crates/iz-web/src/pages/backchannel.rs @@ -49,13 +49,14 @@ struct BackchannelForm { /// again. A `sid` ends that browser session; a token with only a `sub` ends every session of the /// user (a disabled or deleted member). Returns how many sessions ended. /// -/// The id is recorded first and atomically (`seen_jti` inserts and reports a repeat), so two copies -/// of one token cannot both succeed. +/// The id is recorded only after the sessions are gone. A failed delete then leaves no record, so im's +/// retry is accepted instead of being refused as a replay. Two copies of one token racing each other +/// both end the same sessions, which is harmless, since the delete is idempotent. pub async fn end_sessions( store: &Store, claims: &LogoutClaims, ) -> std::result::Result { - if store.seen_jti(&claims.jti, JTI_LIFETIME).await? { + if store.jti_recorded(&claims.jti).await? { return Err(BackchannelError::Replay); } let ended = match (&claims.sid, &claims.sub) { @@ -64,6 +65,7 @@ pub async fn end_sessions( // The verifier requires one of the two, so this arm is unreachable in practice. (None, None) => 0, }; + store.seen_jti(&claims.jti, JTI_LIFETIME).await?; Ok(ended) } @@ -180,6 +182,7 @@ mod tests { locale: None, zoneinfo: "UTC".into(), picture_version: 0, + updated_at: "2026-10-28T09:00:00.000000000Z".into(), }; store .apply_directory_member(&member, Role::Member) diff --git a/crates/iz-web/src/pages/board.rs b/crates/iz-web/src/pages/board.rs index e49387d..8652da9 100644 --- a/crates/iz-web/src/pages/board.rs +++ b/crates/iz-web/src/pages/board.rs @@ -25,7 +25,8 @@ use topcoat::view::view; use crate::assets::BOARD_JS_HREF; use crate::auth::{ - CurrentMember, Need, current_member, percent_encode, query_param, require_role, uri_query, + CurrentMember, Need, current_member, percent_encode, query_param, require_role, session_cookie, + still_reads_board, uri_query, }; use crate::i18n::board::K; use crate::i18n::{Lang, lang}; @@ -376,6 +377,8 @@ async fn board_live(cx: &Cx) -> Result { let board = the_board(&state.store).await?; let store = state.store.clone(); let board_id = board.id.clone(); + let token = session_cookie(cx); + let allowed_store = state.store.clone(); stream_changes( cx, &state.live, @@ -388,6 +391,11 @@ async fn board_live(cx: &Cx) -> Result { Ok(fingerprint?) } }, + move || { + let store = allowed_store.clone(); + let token = token.clone(); + async move { still_reads_board(&store, &token).await } + }, ) .await } @@ -436,6 +444,7 @@ pub(crate) async fn sign_in_as(state: &AppState, sub: &str, role: Role) -> (Stri locale: None, zoneinfo: "Europe/Istanbul".into(), picture_version: 0, + updated_at: "2026-10-28T09:00:00.000000000Z".into(), }; state .store diff --git a/crates/iz-web/src/pages/files.rs b/crates/iz-web/src/pages/files.rs index a8858f0..ef6ffdc 100644 --- a/crates/iz-web/src/pages/files.rs +++ b/crates/iz-web/src/pages/files.rs @@ -59,9 +59,9 @@ use crate::views::{ViewerInfo, message_page, respond, shell}; const FIELD_MAX_BYTES: usize = 2048; /// The MIME types of the spreadsheets and the decks the viewers read. const XLSX: &str = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; -/// See [`XLSX`]. -const ODS: &str = "application/vnd.oasis.opendocument.spreadsheet"; -/// See [`XLSX`]. +/// The MIME type of an OpenDocument spreadsheet. The viewer refuses it: it is only downloaded. +const ODS_MIME: &str = "application/vnd.oasis.opendocument.spreadsheet"; +/// The MIME type of a `.pptx` deck, read as the text of each slide. const PPTX: &str = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; /// 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 { Pdf, /// Plain text, escaped, cut to the preview size. Text, - /// An `.xlsx` or `.ods` workbook, read as values. + /// An `.xlsx` workbook, read as values. Workbook, + /// A file the viewer does not parse (an `.ods`): shown as refused, and it can only be downloaded. + Refused, /// A CSV file, read as one sheet. Csv, /// A `.pptx` deck, read as the text of each slide. @@ -99,7 +101,8 @@ pub fn kind_of(attachment: &Attachment) -> Kind { .trim() .to_ascii_lowercase(); match essence.as_str() { - XLSX | ODS => return Kind::Workbook, + XLSX => return Kind::Workbook, + ODS_MIME => return Kind::Refused, PPTX => return Kind::Deck, _ => {} } @@ -224,6 +227,7 @@ pub async fn load_view( Kind::Audio => ViewBody::Audio, Kind::Pdf => ViewBody::Pdf, Kind::Nothing => ViewBody::Nothing, + Kind::Refused => ViewBody::Refused, Kind::Text => match blocking(move || read_text_head(&path, TEXT_PREVIEW_BYTES)).await { Some((text, cut)) => ViewBody::Text { text, cut }, None => ViewBody::Refused, @@ -385,6 +389,8 @@ enum Refusal { NoFile, /// The bytes could not be stored. Store, + /// The board's attachment storage is full. + StorageFull, } /// The message of a refusal. @@ -396,6 +402,7 @@ fn refusal_key(refusal: Refusal) -> K { Refusal::TooMany => K::ErrTooManyFiles, Refusal::NoFile => K::ErrNoFile, Refusal::Store => K::ErrFileStore, + Refusal::StorageFull => K::ErrFileStorageFull, } } @@ -467,6 +474,9 @@ async fn store_one( if let Err(remove) = remove_blob(data_dir, &id).await { tracing::error!(error = %remove, "removing bytes of a refused upload failed"); } + if matches!(&error, iz_core::Error::Invalid(code) if code == "storage_full") { + return Ok(Err(Refusal::StorageFull)); + } Err(core_err(error)) } } @@ -480,6 +490,8 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result { let task_id = path_param_segment(cx, "id").to_owned(); let mut member: Option = None; let mut board_id = String::new(); + // The task id the path names, resolved from its id or key before any byte is read. + let mut task_uid = String::new(); let mut key = String::new(); let mut next = String::new(); let mut policy: Option = None; @@ -498,6 +510,7 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result { .await .map_err(core_err)?; key = detail.task.key.clone(); + task_uid = detail.task.id.clone(); board_id = board.id; policy = Some(state.store.policy().await.map_err(core_err)?); member = Some(me); @@ -520,7 +533,7 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result { return Err(forbidden().into()); }; match store_one( - state, me, &board_id, &task_id, &raw_name, &mut field, policy, + state, me, &board_id, &task_uid, &raw_name, &mut field, policy, ) .await? { @@ -538,7 +551,7 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result { return Err(forbidden().into()); }; if saved > 0 { - bump(state, &board_id, &task_id); + bump(state, &board_id, &task_uid); } let language = lang(cx, me.member.locale_override.as_deref()); let reason = match (refusal, saved) { @@ -552,7 +565,14 @@ async fn upload(cx: &Cx, mut multipart: Multipart) -> Result { error: Some(t(language, refusal_key(reason))), ..Draft::default() }; - refuse(cx, &me, language, &next, &key, draft).await + let mut response = refuse(cx, &me, language, &next, &key, draft).await?; + // A full storage is `413`; the refusal page keeps its own status when the task is gone. + if reason == Refusal::StorageFull + && response.status() == StatusCode::UNPROCESSABLE_ENTITY + { + *response.status_mut() = StatusCode::PAYLOAD_TOO_LARGE; + } + Ok(response) } None => back(&next, Some(key.as_str())), } @@ -720,6 +740,7 @@ mod tests { assert_eq!(kind_of(&attachment("a.csv", "text/html")), Kind::Csv); assert_eq!(kind_of(&attachment("a.txt", "text/plain")), Kind::Text); assert_eq!(kind_of(&attachment("a.xlsx", XLSX)), Kind::Workbook); + assert_eq!(kind_of(&attachment("a.ods", ODS_MIME)), Kind::Refused); assert_eq!(kind_of(&attachment("a.pptx", PPTX)), Kind::Deck); } diff --git a/crates/iz-web/src/pages/photo.rs b/crates/iz-web/src/pages/photo.rs index 3c48ed8..6ee2a76 100644 --- a/crates/iz-web/src/pages/photo.rs +++ b/crates/iz-web/src/pages/photo.rs @@ -16,6 +16,8 @@ use topcoat::router::error::not_found; use topcoat::router::request::{headers, uri}; use topcoat::router::{HeaderMap, HeaderValue, StatusCode, path_param_segment, route}; +use iz_core::authz::Role; + use crate::auth::current_member; use crate::directory::{PHOTO_TYPES, fetch_photo}; use crate::state::AppState; @@ -38,7 +40,8 @@ async fn photo(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec)> { let Some(member) = state.store.member(&sub).await? else { return Err(not_found().into()); }; - if member.disabled { + // A disabled member, or one with no role, has no access to the board, so no photo either. + if member.disabled || member.role == Role::NoAccess { return Err(not_found().into()); } diff --git a/crates/iz-web/src/pages/settings.rs b/crates/iz-web/src/pages/settings.rs index b64c7ae..0e25b2a 100644 --- a/crates/iz-web/src/pages/settings.rs +++ b/crates/iz-web/src/pages/settings.rs @@ -256,8 +256,20 @@ async fn save_sender(cx: &Cx, form: Option>) -> Result Result { .clone() .filter(|zone| parse_zone(zone).is_ok()) .unwrap_or_else(|| "UTC".to_owned()); + // The token's issue time orders this sign-in against directory changes. `iat` is checked on + // verify, so it is in range; the store never writes `disabled` from a sign-in. + let claims_at = + iz_core::time::stamp_from_unix(claims.iat).unwrap_or_else(iz_core::time::now_stamp); let member_input = DirectoryMember { sub: claims.sub.clone(), email, @@ -237,11 +241,12 @@ async fn callback(cx: &Cx) -> Result { locale: claims.locale.clone(), zoneinfo, picture_version: claims.picture_version, + updated_at: claims_at.clone(), }; let default_role = directory::default_role(&state.store).await?; let stored = match state .store - .upsert_from_claims(&member_input, default_role) + .upsert_from_claims(&member_input, default_role, &claims_at) .await { Ok(stored) => stored, @@ -374,6 +379,7 @@ mod tests { locale: None, zoneinfo: "UTC".into(), picture_version: 0, + updated_at: "2026-10-28T09:00:00.000000000Z".into(), }; state .store diff --git a/docs/architecture.md b/docs/architecture.md index e47d5e3..8f5b0bf 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -42,7 +42,7 @@ iz/ `clock.rs` (deadline + meeting time rules, inventory 2.4) - `rules/` (mail rule engine: triggers, audiences, decisions; pure where possible), `mail_text.rs` (subjects and bodies for every mail kind, both languages) -- `sniff.rs`, `sheet.rs` (`calamine`: xlsx, xls, ods; values only; paging 50 rows × 12 columns; correct offsets +- `sniff.rs`, `sheet.rs` (`calamine`: xlsx, xls, xlsb; values only; `.ods` is refused, not previewed; paging 50 rows × 12 columns; correct offsets for ranges not starting at A1), `slides.rs` (pptx text outline via `zip` + `quick-xml`, size and entry limits against zip bombs) - `store/`: `members.rs`, `sessions.rs`, `board.rs`, `tasks.rs`, `deps.rs`, `comments.rs`, `attachments.rs`,