From 1f366fa7bad6efd80c22c5a7395e22c925c1d91b 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 13:07:10 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=92=20fix:=20refuse=20to=20start=20wit?= =?UTF-8?q?hout=20im.key=20when=20the=20database=20holds=20sealed=20data,?= =?UTF-8?q?=20email-change,=20authorize=20and=20token=20throttles,=20reset?= =?UTF-8?q?=20cooldown=20and=20pending=20cap,=20bounded=20failed-login=20a?= =?UTF-8?q?udit=20with=20retention=20sweep,=20foreign=20keys=20checked,=20?= =?UTF-8?q?outboxes=20pruned,=2016=20KiB=20form=20limit,=20per-user=20stre?= =?UTF-8?q?am=20cap;=20docs=20match=20the=20CLI=20and=20key=20rotation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 3 +- .../migrations/0006_mail_outbox_recipient.sql | 4 + crates/im-core/src/store/audit.rs | 14 ++- crates/im-core/src/store/backchannel.rs | 20 ++++- crates/im-core/src/store/mail.rs | 85 +++++++++++++++++-- crates/im-core/src/store/migrate.rs | 4 + crates/im-core/src/store/mod.rs | 36 ++++++-- crates/im-web/src/api/directory.rs | 27 +++--- crates/im-web/src/boot.rs | 41 ++++++++- crates/im-web/src/i18n/account.rs | 8 ++ crates/im-web/src/live.rs | 20 +++++ crates/im-web/src/mail/mod.rs | 3 +- crates/im-web/src/oidc/authorize.rs | 21 +++++ crates/im-web/src/oidc/token.rs | 20 ++++- crates/im-web/src/pages/email.rs | 17 +++- crates/im-web/src/pages/login.rs | 33 ++++--- crates/im-web/src/state.rs | 5 ++ crates/im-web/src/sweeper.rs | 34 +++++++- crates/im-web/src/throttle.rs | 55 ++++++++++++ docs/architecture.md | 30 ++++--- docs/conventions.md | 2 +- 21 files changed, 422 insertions(+), 60 deletions(-) create mode 100644 crates/im-core/migrations/0006_mail_outbox_recipient.sql diff --git a/README.md b/README.md index 330ca2b..6491164 100644 --- a/README.md +++ b/README.md @@ -129,7 +129,8 @@ To rotate now (for example after a suspected leak of a key file): im --config /etc/im/im.toml keys rotate ``` -The new key signs at once and the previous key stops signing at once; it stays published for the overlap. +The new key is published at once and starts signing one day later, so every app has fetched it by then; the +previous key keeps signing until that moment and stays published for the overlap. The admin Keys page shows every key, its state, and the same rotation. ## Command line diff --git a/crates/im-core/migrations/0006_mail_outbox_recipient.sql b/crates/im-core/migrations/0006_mail_outbox_recipient.sql new file mode 100644 index 0000000..5e3d4f8 --- /dev/null +++ b/crates/im-core/migrations/0006_mail_outbox_recipient.sql @@ -0,0 +1,4 @@ +-- 0006: an index for the per-recipient checks of the mail outbox: the cap on unsent rows per address and the +-- reset cooldown. Both read the rows of one address, which the existing due-time index cannot find quickly. + +CREATE INDEX mail_outbox_recipient ON mail_outbox (to_addr, state, created_at); diff --git a/crates/im-core/src/store/audit.rs b/crates/im-core/src/store/audit.rs index f1410ce..1f9255c 100644 --- a/crates/im-core/src/store/audit.rs +++ b/crates/im-core/src/store/audit.rs @@ -1,8 +1,8 @@ //! The audit log: append-only records of changes, and their listing with keyset paging. //! -//! Entries are never updated or deleted here. The only removal is the operator's purge command -//! (`docs/architecture.md` section 10), which is not part of this module. Entries sort by -//! `(at, id)`; both parts are fixed-width text, so a cursor can name a position exactly. +//! Entries are never updated here. Removal is [`Store::prune_audit`], run by the sweeper after the retention +//! window (`docs/architecture.md` section 3). Entries sort by `(at, id)`; both parts are fixed-width text, so +//! a cursor can name a position exactly. use crate::error::Result; use crate::model::AuditEntry; @@ -95,6 +95,14 @@ impl Store { Ok(()) } + /// Deletes entries stamped before `cutoff`. Returns how many were removed. Run by the sweeper. + pub async fn prune_audit(&self, cutoff: &str) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute("DELETE FROM audit_log WHERE at < ?1", (cutoff.to_string(),)) + .await + .map_err(db_err) + } + /// One page of the log, newest first, after `after` when given. Returns at most `limit` /// entries. When the page is full, the cursor for the next page is the last entry's position. /// diff --git a/crates/im-core/src/store/backchannel.rs b/crates/im-core/src/store/backchannel.rs index 49b0817..edd96b7 100644 --- a/crates/im-core/src/store/backchannel.rs +++ b/crates/im-core/src/store/backchannel.rs @@ -258,9 +258,9 @@ impl Store { } Attempt::Abandon { attempts, error } => { conn.execute( - "UPDATE backchannel_outbox SET state = 'abandoned', attempts = ?2, last_error = ?3 \ - WHERE id = ?1 AND state = 'pending'", - (id.to_string(), *attempts, error.clone()), + "UPDATE backchannel_outbox SET state = 'abandoned', attempts = ?2, last_error = ?3, \ + done_at = ?4 WHERE id = ?1 AND state = 'pending'", + (id.to_string(), *attempts, error.clone(), now.to_string()), ) .await } @@ -269,6 +269,20 @@ impl Store { Ok(()) } + /// Deletes rows that were delivered or given up before `cutoff`. Rows given up before `done_at` was + /// written have no finish time, so their queue time is used. Returns how many were removed. Run by the + /// sweeper. + pub async fn prune_backchannel_outbox(&self, cutoff: &str) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM backchannel_outbox WHERE state IN ('sent', 'abandoned') \ + AND COALESCE(done_at, created_at) < ?1", + (cutoff.to_string(),), + ) + .await + .map_err(db_err) + } + /// Every outbox row, oldest first. For inspection and tests. pub async fn backchannel_rows(&self) -> Result> { let conn = self.read_conn().await; diff --git a/crates/im-core/src/store/mail.rs b/crates/im-core/src/store/mail.rs index 3a3feb3..491ed7b 100644 --- a/crates/im-core/src/store/mail.rs +++ b/crates/im-core/src/store/mail.rs @@ -4,10 +4,25 @@ //! opens it only to send. Once a row is sent or abandoned its body is blanked, so a token-bearing body //! survives only until its first delivery attempt succeeds or the row gives up. Sent rows are deleted //! 30 days after they were sent. Nothing here logs a body or a recipient. +//! +//! Two limits keep one address from being mailed without end. An address may hold at most +//! [`PENDING_PER_ADDRESS`] unsent rows, and a reset mail is not queued again inside [`RESET_COOLDOWN`]. +//! A mail over either limit is dropped without any error, so the answer to the caller never depends on +//! whether the address has an account. + +use std::time::Duration; use crate::error::Result; -use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; -use crate::time::now_stamp; +use crate::store::{ + Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, missing_row, new_id, +}; +use crate::time::{now_stamp, stamp_before}; + +/// Most unsent rows (`pending` or `failed`) one recipient address may hold. Mail over it is dropped. +pub const PENDING_PER_ADDRESS: i64 = 10; + +/// The least time between two reset mails to one address. A reset mail inside it is dropped. +pub const RESET_COOLDOWN: Duration = Duration::from_secs(5 * 60); /// What a new outbox row holds. #[derive(Debug, Clone, Copy)] @@ -85,11 +100,37 @@ fn map_job(row: &turso::Row) -> Result { } impl Store { - /// Adds a mail to the outbox, to be sent as soon as the worker looks. Returns its id. - pub async fn enqueue_mail(&self, new: &NewMail<'_>) -> Result { + /// Adds a mail to the outbox, to be sent as soon as the worker looks. Returns its id, or `None` when the + /// mail is dropped by [`PENDING_PER_ADDRESS`] or by [`RESET_COOLDOWN`]. The checks and the insert run + /// under the writer, so parallel requests cannot pass a limit together. + pub async fn enqueue_mail(&self, new: &NewMail<'_>) -> Result> { let id = new_id(); let now = now_stamp(); let conn = self.inner.conn.lock().await; + let unsent = fetch_opt( + &conn, + "SELECT COUNT(*) FROM mail_outbox WHERE to_addr = ?1 AND state IN ('pending', 'failed')", + (new.to_addr.to_string(),), + |row| col_int(row, 0), + ) + .await? + .ok_or_else(missing_row)?; + if unsent >= PENDING_PER_ADDRESS { + return Ok(None); + } + if new.kind == "reset" { + let recent = fetch_opt( + &conn, + "SELECT COUNT(*) FROM mail_outbox WHERE to_addr = ?1 AND kind = 'reset' AND created_at >= ?2", + (new.to_addr.to_string(), stamp_before(RESET_COOLDOWN)), + |row| col_int(row, 0), + ) + .await? + .ok_or_else(missing_row)?; + if recent > 0 { + return Ok(None); + } + } conn.execute( "INSERT INTO mail_outbox (id, kind, to_addr, subject, body_text, state, attempts, \ next_attempt_at, created_at) VALUES (?1, ?2, ?3, ?4, ?5, 'pending', 0, ?6, ?6)", @@ -104,7 +145,7 @@ impl Store { ) .await .map_err(db_err)?; - Ok(id) + Ok(Some(id)) } /// Rows that are due: never tried, or failed and whose retry time has come. Oldest first. @@ -186,12 +227,43 @@ impl Store { .await .map_err(db_err) } + + /// Deletes failed and abandoned rows created before `cutoff`. Their links have expired by then, so the + /// rows only take space. Returns how many were removed. Run by the sweeper. + pub async fn prune_failed_mail(&self, cutoff: &str) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM mail_outbox WHERE state IN ('failed', 'abandoned') AND created_at < ?1", + (cutoff.to_string(),), + ) + .await + .map_err(db_err) + } } #[cfg(test)] mod tests { use super::*; + #[tokio::test] + async fn a_reset_mail_waits_out_the_cooldown_and_an_address_holds_a_capped_number_of_unsent_rows() + { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("im.db")).await.unwrap(); + let mail = |kind: &'static str| NewMail { + kind, + to_addr: "ada@example.com", + subject: "Subject", + sealed_body: "v1:sealed", + }; + assert!(store.enqueue_mail(&mail("reset")).await.unwrap().is_some()); + assert!(store.enqueue_mail(&mail("reset")).await.unwrap().is_none()); + for _ in 1..PENDING_PER_ADDRESS { + assert!(store.enqueue_mail(&mail("notice")).await.unwrap().is_some()); + } + assert!(store.enqueue_mail(&mail("notice")).await.unwrap().is_none()); + } + #[tokio::test] async fn a_failed_attempt_is_retried_and_the_last_one_blanks_the_body() { let dir = tempfile::tempdir().unwrap(); @@ -204,7 +276,8 @@ mod tests { sealed_body: "v1:sealed", }) .await - .unwrap(); + .unwrap() + .expect("queued"); let now = now_stamp(); assert_eq!(store.due_mail(&now, 10).await.unwrap().len(), 1); store diff --git a/crates/im-core/src/store/migrate.rs b/crates/im-core/src/store/migrate.rs index bc847c8..f1cf724 100644 --- a/crates/im-core/src/store/migrate.rs +++ b/crates/im-core/src/store/migrate.rs @@ -25,6 +25,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ include_str!("../../migrations/0004_revoked_access_tokens.sql"), ), (5, include_str!("../../migrations/0005_outbox_jti.sql")), + ( + 6, + include_str!("../../migrations/0006_mail_outbox_recipient.sql"), + ), ]; fn migration_err(e: turso::Error) -> Error { diff --git a/crates/im-core/src/store/mod.rs b/crates/im-core/src/store/mod.rs index d593e02..f43f21f 100644 --- a/crates/im-core/src/store/mod.rs +++ b/crates/im-core/src/store/mod.rs @@ -72,13 +72,13 @@ impl Store { })?; let db = Builder::new_local(path_str).build().await.map_err(db_err)?; let conn = db.connect().map_err(db_err)?; - apply_pragmas(&conn).await; + apply_pragmas(&conn).await?; migrate::migrate(&conn).await?; let mut readers = Vec::with_capacity(READER_COUNT); for _ in 0..READER_COUNT { let reader = db.connect().map_err(db_err)?; - apply_pragmas(&reader).await; + apply_pragmas(&reader).await?; apply_query_only(&reader).await?; readers.push(Mutex::new(reader)); } @@ -129,6 +129,21 @@ impl Store { u64::try_from(row).map_err(|_| Error::Database("negative count".into())) } + /// Whether the database holds an account or a signing key. Both are sealed with the instance key, so + /// a database like this one cannot be used with a different key. Used at boot before a key is created. + pub async fn holds_sealed_data(&self) -> Result { + let conn = self.read_conn().await; + let count = fetch_opt( + &conn, + "SELECT (SELECT COUNT(*) FROM users) + (SELECT COUNT(*) FROM signing_keys)", + (), + |row| col_int(row, 0), + ) + .await? + .ok_or_else(missing_row)?; + Ok(count > 0) + } + /// The stored value of a runtime setting, or `None` when it has no override. pub async fn setting(&self, key: &str) -> Result> { let conn = self.read_conn().await; @@ -198,7 +213,7 @@ pub(crate) fn db_err(e: turso::Error) -> Error { Error::Database(e.to_string()) } -fn missing_row() -> Error { +pub(crate) fn missing_row() -> Error { Error::Database("expected a row that is not there".into()) } @@ -213,9 +228,10 @@ async fn apply_query_only(conn: &Connection) -> Result<()> { Ok(()) } -/// Applies the connection pragmas. A pragma that is not supported is logged and skipped, never -/// fatal. The values actually in effect are logged afterwards. -async fn apply_pragmas(conn: &Connection) { +/// Applies the connection pragmas. A pragma the driver refuses is logged, and the values actually in effect +/// are logged afterwards. `foreign_keys` is read back and must be on: with it off, the cascades that remove a +/// person's sessions, recovery codes and links would silently not run, so the start fails instead. +async fn apply_pragmas(conn: &Connection) -> Result<()> { for sql in [ "PRAGMA journal_mode = WAL", "PRAGMA synchronous = FULL", @@ -244,6 +260,14 @@ async fn apply_pragmas(conn: &Connection) { Err(e) => tracing::warn!(pragma = name, error = %e, "could not read database pragma"), } } + let foreign_keys = + fetch_opt(conn, "PRAGMA foreign_keys", (), |row| col_to_string(row, 0)).await?; + if foreign_keys.as_deref() != Some("1") { + return Err(Error::Database(format!( + "foreign_keys is {foreign_keys:?} after the pragma, expected 1" + ))); + } + Ok(()) } /// Runs a query and maps every row. Returns an empty vector for no rows. diff --git a/crates/im-web/src/api/directory.rs b/crates/im-web/src/api/directory.rs index 1ae4754..454f778 100644 --- a/crates/im-web/src/api/directory.rs +++ b/crates/im-web/src/api/directory.rs @@ -49,31 +49,32 @@ const BATCH: i64 = 200; /// How long a `Retry-After` the refused client is given, in seconds. const RETRY_AFTER_SECS: &str = "5"; -/// The open streams of each client. Shared by every request, so the cap holds across connections. +/// The open streams of each key: a machine client for the directory feed, a user for `/-/alive`. Shared by +/// every request, so each cap holds across connections. #[derive(Default)] pub struct StreamSlots { open: Mutex>, } -/// One open stream of a client. Dropping it frees the slot, so a stream that ends for any reason gives its +/// One open stream of a key. Dropping it frees the slot, so a stream that ends for any reason gives its /// slot back. pub struct SlotGuard { slots: Arc, - client_id: String, + key: String, } impl StreamSlots { - /// Takes a slot for `client_id`, or `None` when the client already holds the maximum. - pub fn acquire(this: &Arc, client_id: &str) -> Option { + /// Takes a slot for `key`, or `None` when the key already holds `max` streams. + pub fn acquire(this: &Arc, key: &str, max: usize) -> Option { let mut open = this.open.lock().unwrap_or_else(PoisonError::into_inner); - let count = open.entry(client_id.to_owned()).or_insert(0); - if *count >= MAX_STREAMS_PER_CLIENT { + let count = open.entry(key.to_owned()).or_insert(0); + if *count >= max { return None; } *count += 1; Some(SlotGuard { slots: Arc::clone(this), - client_id: client_id.to_owned(), + key: key.to_owned(), }) } } @@ -85,10 +86,10 @@ impl Drop for SlotGuard { .open .lock() .unwrap_or_else(PoisonError::into_inner); - if let Some(count) = open.get_mut(&self.client_id) { + if let Some(count) = open.get_mut(&self.key) { *count = count.saturating_sub(1); if *count == 0 { - open.remove(&self.client_id); + open.remove(&self.key); } } } @@ -134,7 +135,11 @@ async fn directory_stream(cx: &Cx) -> Result { Ok(machine) => machine, Err(refusal) => return Ok(refusal), }; - let Some(slot) = StreamSlots::acquire(&app.stream_slots, &machine.client_id) else { + let Some(slot) = StreamSlots::acquire( + &app.stream_slots, + &machine.client_id, + MAX_STREAMS_PER_CLIENT, + ) else { let mut response = api_error( StatusCode::TOO_MANY_REQUESTS, "rate_limited", diff --git a/crates/im-web/src/boot.rs b/crates/im-web/src/boot.rs index 817f414..621efba 100644 --- a/crates/im-web/src/boot.rs +++ b/crates/im-web/src/boot.rs @@ -139,8 +139,16 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result { { std::fs::create_dir_all(parent)?; } - let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; + // The database opens before the key so that a missing key can be checked against it. A key is created + // only for a data directory that holds no sealed rows; otherwise the sealed rows would be unreadable. + let key_path = data_dir.join(KEY_FILE); let store = Store::open(&config.database).await?; + if !key_path.exists() && store.holds_sealed_data().await? { + return Err(im_core::Error::Crypto( + "im.key is missing but im.db holds data sealed with it; restore the key file".into(), + )); + } + let key = secret::load_or_create_key(&key_path)?; let policy = effective_policy(&config, &store).await?; signing::maintain(&store, &key).await?; // im is in its own switcher list. The row follows the configured origin at every boot. @@ -155,6 +163,8 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result { live: Arc::new(LiveHub::default()), throttle: Arc::new(Throttle::default()), photo_uploads: Arc::new(Throttle::photo_uploads()), + email_changes: Arc::new(Throttle::email_changes()), + per_minute: Arc::new(Throttle::per_minute()), stream_slots: Arc::new(StreamSlots::default()), anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), // Replaced by the stop flag of `serve` before any listener starts. The CLI never serves. @@ -195,14 +205,20 @@ pub(crate) fn merge_saved_policy(file: &PolicyConfig, saved: &[(String, String)] /// the CSRF field. The handler enforces the picture limit itself while streaming. const PHOTO_BODY_LIMIT: usize = MAX_UPLOAD_BYTES + 64 * 1024; +/// The request body limit of every other route. A form is a few hundred bytes, so 16 KiB is generous. It +/// replaces the 2 MiB default of the framework, which no form needs. +const FORM_BODY_LIMIT: usize = 16 * 1024; + /// The router of the server: every route and page found by `discover`, the cookie jar, the security -/// headers on every response, the styled 404 for browsers, and the upload limit of the photo route. +/// headers on every response, the styled 404 for browsers, the body limit of forms, and the upload limit +/// of the photo route (which overrides the form limit under its path). pub fn router(state: AppState) -> Router { let security = SecurityHeaders::new(security::headers_for(&state.config.base_url)); Router::builder() .discover() .app_context(state) .cookies() + .layer(BodyLimit::max(FORM_BODY_LIMIT)) .layer(BodyLimit::max(PHOTO_BODY_LIMIT).at(PHOTO_ROUTE)) .layer(security) .layer(NotFoundLayer) @@ -270,6 +286,8 @@ mod tests { live: Arc::new(LiveHub::default()), throttle: Arc::new(Throttle::default()), photo_uploads: Arc::new(Throttle::photo_uploads()), + email_changes: Arc::new(Throttle::email_changes()), + per_minute: Arc::new(Throttle::per_minute()), stream_slots: Arc::new(StreamSlots::default()), anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), stop: watch::channel(false).1, @@ -302,6 +320,25 @@ mod tests { assert_eq!(response.headers()[X_CONTENT_TYPE_OPTIONS], "nosniff"); } + #[tokio::test] + async fn a_missing_key_is_refused_when_the_database_holds_sealed_rows() { + let (dir, state) = test_state().await; + signing::maintain(&state.store, &state.key) + .await + .expect("signing keys"); + drop(state); + std::fs::remove_file(dir.path().join(KEY_FILE)).expect("key removed"); + let text = format!( + "database = \"{}\"\ndata_dir = \"{}\"\nlisten = \"127.0.0.1:7650\"\nbase_url = \"http://127.0.0.1:7650\"\n", + dir.path().join("im.db").display(), + dir.path().display(), + ); + let config = Config::parse(&text).expect("test config"); + let error = open_state(config).await.err().expect("refused"); + assert!(error.to_string().contains("im.key is missing"), "{error}"); + assert!(!dir.path().join(KEY_FILE).exists(), "no key is created"); + } + #[tokio::test] async fn an_unknown_path_for_a_browser_gets_the_styled_404() { let (_dir, state) = test_state().await; diff --git a/crates/im-web/src/i18n/account.rs b/crates/im-web/src/i18n/account.rs index 22350ef..5d1e8ca 100644 --- a/crates/im-web/src/i18n/account.rs +++ b/crates/im-web/src/i18n/account.rs @@ -28,6 +28,8 @@ pub enum Txt { PasswordHint, /// Shown while the throttle holds an account or an address back. ErrThrottled, + /// Shown when the account has asked for too many email changes in the last hour. + ErrEmailChangeLimited, /// The password of the current account is wrong. ErrWrongPassword, /// The two new passwords do not match. @@ -273,6 +275,12 @@ pub fn text(lang: Lang, key: Txt) -> &'static str { (Txt::ErrThrottled, Lang::Tr) => { "Çok fazla deneme yapıldı. Birkaç dakika bekleyip yeniden deneyin." } + (Txt::ErrEmailChangeLimited, Lang::En) => { + "Too many email change requests. Try again in an hour." + } + (Txt::ErrEmailChangeLimited, Lang::Tr) => { + "Çok fazla e-posta değişikliği isteği yapıldı. Bir saat sonra yeniden deneyin." + } (Txt::ErrWrongPassword, Lang::En) => "The password is wrong.", (Txt::ErrWrongPassword, Lang::Tr) => "Parola yanlış.", (Txt::ErrPasswordsDiffer, Lang::En) => "The two new passwords do not match.", diff --git a/crates/im-web/src/live.rs b/crates/im-web/src/live.rs index d3af2da..a101870 100644 --- a/crates/im-web/src/live.rs +++ b/crates/im-web/src/live.rs @@ -28,6 +28,7 @@ use topcoat::router::response::{IntoResponse, Response}; use topcoat::router::{HeaderValue, StatusCode, route}; use crate::api::api_error; +use crate::api::directory::{SlotGuard, StreamSlots}; use crate::auth::current_user; use crate::state::AppState; @@ -47,6 +48,10 @@ pub const RECHECK: Duration = Duration::from_secs(15); /// Anonymous `/-/alive` streams open at once, across the whole process. A further one gets `429`. pub const MAX_ANONYMOUS_STREAMS: usize = 256; +/// Signed-in `/-/alive` streams one user may hold open at once, across all their browsers and tabs. A further +/// one gets `429`. +pub const MAX_ALIVE_STREAMS_PER_USER: usize = 16; + /// What a live page follows. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum Topic { @@ -223,6 +228,8 @@ struct AccountFollow { session_id: String, /// Set after `signed_out` was sent, so the stream ends right after it. done: bool, + /// The user's slot. Held for the life of the stream, so the number of them is capped per user. + _slot: SlotGuard, } /// `GET /-/alive`. Every page holds this stream, so the browser learns when the server stops and @@ -254,6 +261,18 @@ async fn alive(cx: &Cx) -> Result { }); return events_response(cx, events); }; + let Some(slot) = StreamSlots::acquire( + &state.stream_slots, + &format!("user:{}", viewer.user.id), + MAX_ALIVE_STREAMS_PER_USER, + ) else { + return Ok(api_error( + StatusCode::TOO_MANY_REQUESTS, + "rate_limited", + "Too many open streams. Try again shortly.", + None, + )); + }; let follow = AccountFollow { wake: state .live @@ -263,6 +282,7 @@ async fn alive(cx: &Cx) -> Result { store: state.store.clone(), session_id: viewer.session.id.clone(), done: false, + _slot: slot, }; let events = stream::unfold(follow, |mut follow| async move { if follow.done { diff --git a/crates/im-web/src/mail/mod.rs b/crates/im-web/src/mail/mod.rs index c38c231..710d8b8 100644 --- a/crates/im-web/src/mail/mod.rs +++ b/crates/im-web/src/mail/mod.rs @@ -123,7 +123,8 @@ pub fn lang_for(user: &User, request: Lang) -> Lang { } /// Renders `mail` for `to` in `lang`, seals it, and adds it to the outbox. The subject is fixed text; -/// the body (text and HTML, with the recipient's name) is sealed as one JSON document. +/// the body (text and HTML, with the recipient's name) is sealed as one JSON document. A mail that the +/// store drops by its per-address limits is not an error here: the caller answers the same either way. pub async fn queue( store: &Store, key: &[u8; 32], diff --git a/crates/im-web/src/oidc/authorize.rs b/crates/im-web/src/oidc/authorize.rs index 1ae334c..0d85fea 100644 --- a/crates/im-web/src/oidc/authorize.rs +++ b/crates/im-web/src/oidc/authorize.rs @@ -8,6 +8,8 @@ //! A session older than `max_age` (or any session when `prompt=login`) must sign in again first //! (OIDC Core 3.1.2.1). Only the `query` response mode is offered. +use std::time::Instant; + use im_core::model::Client; use im_core::oauth::{MAX_ECHO_BYTES, is_supported_scope, is_user_scope, is_valid_challenge}; use im_core::store::oidc::NewAuthCode; @@ -25,6 +27,7 @@ use crate::auth::{current_user, percent_encode}; use crate::i18n::Lang; use crate::i18n::oidc::{OidcText, text}; use crate::state::AppState; +use crate::throttle::{AUTHORIZE_SESSION_LIMIT, authorize_session_key}; use crate::views::{page_lang, shell}; /// The shortest age, in seconds, that a sign-in is still treated as fresh. A `max_age` below it, and @@ -282,6 +285,24 @@ async fn authorize(cx: &Cx) -> Result { return Err(see_other("/account/security?notice=enrol").into()); } + // Each issue adds a row that lives a day, so a session that repeats the request is limited. The refusal + // goes to the registered redirect URI like the other refusals of this request. + if app + .per_minute + .reserve( + &authorize_session_key(&viewer.session.id), + AUTHORIZE_SESSION_LIMIT, + Instant::now(), + ) + .is_err() + { + let refused = Refused { + code: "temporarily_unavailable", + state: asked.state.clone(), + }; + return Err(refusal_redirect(redirect_uri, issuer, &refused).into()); + } + let code = generate_token(); let expires_at = stamp_after(CODE_TTL); app.store diff --git a/crates/im-web/src/oidc/token.rs b/crates/im-web/src/oidc/token.rs index 2204b06..0f7b47a 100644 --- a/crates/im-web/src/oidc/token.rs +++ b/crates/im-web/src/oidc/token.rs @@ -8,8 +8,10 @@ //! A disabled client fails client authentication, so no grant runs for it: its refresh tokens and its //! machine tokens are refused at once. +use std::time::Instant; + use base64::prelude::{BASE64_STANDARD, Engine as _}; -use http::header::AUTHORIZATION; +use http::header::{AUTHORIZATION, RETRY_AFTER}; use im_core::model::{Client, Session, User, amr}; use im_core::oauth::{is_supported_scope, is_user_scope, is_valid_family_key}; use im_core::oauth::{is_valid_verifier, pkce_s256}; @@ -22,7 +24,7 @@ use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::request::{content_type, headers}; use topcoat::router::response::Response; -use topcoat::router::{Body, StatusCode, route, to_bytes}; +use topcoat::router::{Body, HeaderValue, StatusCode, route, to_bytes}; use super::signing; use super::{ @@ -30,6 +32,7 @@ use super::{ invalid_client, invalid_grant, issuer, json_response, oauth_error, one, parse_pairs, single, }; use crate::state::AppState; +use crate::throttle::{TOKEN_CLIENT_LIMIT, token_client_key}; /// `POST /token`. #[route(POST "/token")] @@ -55,6 +58,19 @@ async fn token_endpoint(cx: &Cx, body: Body) -> Result { Ok(client) => client, Err(response) => return Ok(response), }; + // Counted after the client is authenticated, so a caller without the secret cannot use up a client's + // allowance. Over the limit the answer is a 429 with the wait, in the OAuth error form. + if let Err(wait) = app.per_minute.reserve( + &token_client_key(&client.id), + TOKEN_CLIENT_LIMIT, + Instant::now(), + ) { + let mut response = oauth_error(StatusCode::TOO_MANY_REQUESTS, "invalid_request"); + response + .headers_mut() + .insert(RETRY_AFTER, HeaderValue::from(wait.as_secs().max(1))); + return Ok(response); + } match one(&pairs, "grant_type") { Some("authorization_code") => grant_code(app, &client, &pairs).await, Some("refresh_token") => grant_refresh(app, &client, &pairs).await, diff --git a/crates/im-web/src/pages/email.rs b/crates/im-web/src/pages/email.rs index 3235b7c..e1be687 100644 --- a/crates/im-web/src/pages/email.rs +++ b/crates/im-web/src/pages/email.rs @@ -6,7 +6,7 @@ //! and the store checks the new address is still free at that moment. A link is never used by a GET: the //! confirm and cancel buttons are POSTs with the pre-session token. -use std::time::Duration; +use std::time::{Duration, Instant}; use im_core::model::AuditAction; use im_core::names::parse_email; @@ -32,6 +32,7 @@ use crate::mail::{self, Mail, Recipient}; use crate::pages::path_param; use crate::pages::security::password_problem; use crate::state::AppState; +use crate::throttle::{EMAIL_CHANGE_LIMIT, email_change_key}; use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell}; /// The request form: the new address and the current password. @@ -134,6 +135,20 @@ async fn email_request_submit(cx: &Cx, Form(form): Form) -> Re )); } + // Counted only for a request that would send mail: the two links are the costly part, and a request the + // store would refuse sends nothing. The limit keeps one account from mailing many addresses. + if state + .email_changes + .reserve( + &email_change_key(&viewer.user.id), + EMAIL_CHANGE_LIMIT, + Instant::now(), + ) + .is_err() + { + return Ok(refuse(Txt::ErrEmailChangeLimited)); + } + let hours = state.policy().email_change_hours; let old_token = generate_token(); let new_token = generate_token(); diff --git a/crates/im-web/src/pages/login.rs b/crates/im-web/src/pages/login.rs index 3186ae5..8d69963 100644 --- a/crates/im-web/src/pages/login.rs +++ b/crates/im-web/src/pages/login.rs @@ -32,7 +32,8 @@ use crate::i18n::Lang; use crate::i18n::account::{Txt, text}; use crate::state::AppState; use crate::throttle::{ - LOGIN_IP_LIMIT, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT, ip_key, two_factor_key, user_key, + LOGIN_AUDIT_LIMIT, LOGIN_IP_LIMIT, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT, ip_key, + login_audit_user_key, two_factor_key, user_key, }; use crate::views::{alert, field, page_lang, shell}; @@ -133,15 +134,27 @@ async fn login_submit(cx: &Cx, Form(form): Form) -> Result let target_id = found.as_ref().map(|user| user.id.clone()); // The attempt stays counted on every failure below. let Some(user) = found.filter(|user| password_ok && !user.is_disabled()) else { - let target = target_id.as_deref().map(|id| ("user", id)); - record( - cx, - Actor::Anonymous, - AuditAction::LoginFailed, - target, - json!({ "reason": "credentials" }), - ) - .await; + // One audit row per account, or per client address when the account is unknown, each minute. A + // flood of failures therefore cannot grow the audit log. The throttle above still counts every failure. + let audit_key = match &target_id { + Some(id) => login_audit_user_key(id), + None => ip_key("login-audit-ip", client_ip(cx)), + }; + if state + .per_minute + .reserve(&audit_key, LOGIN_AUDIT_LIMIT, Instant::now()) + .is_ok() + { + let target = target_id.as_deref().map(|id| ("user", id)); + record( + cx, + Actor::Anonymous, + AuditAction::LoginFailed, + target, + json!({ "reason": "credentials" }), + ) + .await; + } let lang = page_lang(cx, None); return Ok(login_view( cx, diff --git a/crates/im-web/src/state.rs b/crates/im-web/src/state.rs index a7e9f09..d032876 100644 --- a/crates/im-web/src/state.rs +++ b/crates/im-web/src/state.rs @@ -29,6 +29,11 @@ pub struct AppState { pub throttle: Arc, /// Profile photo uploads per account, one hour window (see `throttle::PHOTO_UPLOAD_LIMIT`). pub photo_uploads: Arc, + /// Email-change requests per account, one hour window (see `throttle::EMAIL_CHANGE_LIMIT`). + pub email_changes: Arc, + /// Per-minute counters: code issuances per session, token requests per client, and the audit of + /// failed sign-ins (see the limits in `throttle`). + pub per_minute: Arc, /// The open directory streams of each machine client. pub stream_slots: Arc, /// The open anonymous `/-/alive` streams, at most [`MAX_ANONYMOUS_STREAMS`]. diff --git a/crates/im-web/src/sweeper.rs b/crates/im-web/src/sweeper.rs index aa08ec2..c9549c7 100644 --- a/crates/im-web/src/sweeper.rs +++ b/crates/im-web/src/sweeper.rs @@ -7,7 +7,10 @@ //! - revoked access tokens past their expiry (the revocation has done its work by then); //! - directory change rows older than 30 days (a cursor older than the oldest row gets `resync`); //! - account links and invitations past their expiry; -//! - sent mail older than 30 days (its body was blanked when it was sent). +//! - sent mail older than 30 days (its body was blanked when it was sent); +//! - failed and abandoned mail older than 30 days; +//! - back-channel deliveries delivered or given up more than 7 days ago; +//! - audit entries older than a year (`AUDIT_KEEP`). //! //! Each step runs on its own: one failing step is logged and does not stop the others. @@ -26,9 +29,18 @@ const DIRECTORY_KEEP: Duration = Duration::from_secs(30 * 24 * 60 * 60); /// How long an expired authorization code is kept, so a reuse is still seen as reuse. const CODE_KEEP: Duration = Duration::from_secs(24 * 60 * 60); -/// How long a sent mail is kept in the outbox before it is deleted (architecture section 8). +/// How long a sent mail is kept in the outbox before it is deleted (architecture section 8). Failed and +/// abandoned mail are kept as long. const MAIL_KEEP: Duration = Duration::from_secs(30 * 24 * 60 * 60); +/// How long a finished back-channel delivery (sent or given up) is kept. A week is long enough to inspect +/// a failure on the admin pages. +const OUTBOX_KEEP: Duration = Duration::from_secs(7 * 24 * 60 * 60); + +/// How long an audit entry is kept. A fixed year, not a setting: `docs/architecture.md` section 3 lists it with +/// the other retention rules. Entries older than this are removed. +const AUDIT_KEEP: Duration = Duration::from_secs(365 * 24 * 60 * 60); + /// Starts the sweeper. It runs until `stop` is set. pub fn spawn(store: Store, mut stop: watch::Receiver) -> tokio::task::JoinHandle<()> { tokio::spawn(async move { @@ -89,4 +101,22 @@ pub async fn sweep_once(store: &Store) { Ok(count) => tracing::info!(count, "sweeper: sent mail removed"), Err(error) => tracing::error!(error = %error, "sweeper: sent mail"), } + match store.prune_failed_mail(&stamp_before(MAIL_KEEP)).await { + Ok(0) => {} + Ok(count) => tracing::info!(count, "sweeper: failed mail removed"), + Err(error) => tracing::error!(error = %error, "sweeper: failed mail"), + } + match store + .prune_backchannel_outbox(&stamp_before(OUTBOX_KEEP)) + .await + { + Ok(0) => {} + Ok(count) => tracing::info!(count, "sweeper: finished back-channel deliveries removed"), + Err(error) => tracing::error!(error = %error, "sweeper: back-channel deliveries"), + } + match store.prune_audit(&stamp_before(AUDIT_KEEP)).await { + Ok(0) => {} + Ok(count) => tracing::info!(count, "sweeper: old audit entries removed"), + Err(error) => tracing::error!(error = %error, "sweeper: audit entries"), + } } diff --git a/crates/im-web/src/throttle.rs b/crates/im-web/src/throttle.rs index 1845c0f..8d2445c 100644 --- a/crates/im-web/src/throttle.rs +++ b/crates/im-web/src/throttle.rs @@ -13,6 +13,10 @@ //! Email keys are capped too. An address that is too long or not plausible shares one fixed key, so a //! flood of junk addresses cannot grow the map or the key size. //! +//! Each [`Throttle`] has one window for all its keys. The failure counters use [`WINDOW`]; the per-minute +//! and per-hour counters of the OAuth endpoints and the account pages are separate instances, built with +//! [`Throttle::per_minute`] and [`Throttle::email_changes`]. +//! //! The counters live in one process. A restart clears them, and two processes would each count //! their own. `im` runs as one process, so this is the whole picture. @@ -51,6 +55,26 @@ pub const PHOTO_UPLOAD_LIMIT: usize = 10; /// [`Throttle::photo_uploads`]), because a throttle has one window for all its keys. pub const PHOTO_UPLOAD_WINDOW: Duration = Duration::from_secs(60 * 60); +/// Length of the per-minute window of the OAuth endpoints and the audit of failed sign-ins. +pub const MINUTE: Duration = Duration::from_secs(60); + +/// Length of the window of email-change requests: one hour. +pub const EMAIL_CHANGE_WINDOW: Duration = Duration::from_secs(60 * 60); + +/// Email-change requests allowed per account inside [`EMAIL_CHANGE_WINDOW`]. Each one mails two addresses. +pub const EMAIL_CHANGE_LIMIT: usize = 3; + +/// Code issuances allowed per browser session inside [`MINUTE`] at `/authorize`. A refused one is answered +/// with the `temporarily_unavailable` redirect. +pub const AUTHORIZE_SESSION_LIMIT: usize = 60; + +/// Requests allowed per authenticated client inside [`MINUTE`] at `/token`. +pub const TOKEN_CLIENT_LIMIT: usize = 120; + +/// `LoginFailed` audit rows written per account, or per client address when the account is unknown, inside +/// [`MINUTE`]. Failures beyond it are still refused and counted; only their audit rows are skipped. +pub const LOGIN_AUDIT_LIMIT: usize = 1; + /// Maximum number of distinct keys tracked at once. A flood of random keys cannot grow memory past /// this. const MAX_KEYS: usize = 100_000; @@ -93,6 +117,17 @@ impl Throttle { Self::with_limits(PHOTO_UPLOAD_WINDOW, MAX_KEYS) } + /// The per-minute counters: `/authorize` per session, `/token` per client, and the audit of failed + /// sign-ins. One minute window, the same key cap. + pub fn per_minute() -> Self { + Self::with_limits(MINUTE, MAX_KEYS) + } + + /// The counters of email-change requests: one hour window, the same key cap. + pub fn email_changes() -> Self { + Self::with_limits(EMAIL_CHANGE_WINDOW, MAX_KEYS) + } + /// Counters with a custom window and key cap. Tests use short windows. pub fn with_limits(window: Duration, max_keys: usize) -> Self { Self { @@ -283,6 +318,26 @@ pub fn two_factor_key(user_id: &str) -> String { format!("2fa:{user_id}") } +/// Throttle key for the email-change requests of one user, by user id. +pub fn email_change_key(user_id: &str) -> String { + format!("email-change:{user_id}") +} + +/// Throttle key for the code issuances of one browser session, by session id. +pub fn authorize_session_key(session_id: &str) -> String { + format!("authorize:{session_id}") +} + +/// Throttle key for the token requests of one client, by client id. +pub fn token_client_key(client_id: &str) -> String { + format!("token:{client_id}") +} + +/// Throttle key for the `LoginFailed` audit rows of one account, by user id. +pub fn login_audit_user_key(user_id: &str) -> String { + format!("login-audit-user:{user_id}") +} + /// Throttle key for an address under a named scope, such as `login-ip`. pub fn ip_key(scope: &str, ip: IpAddr) -> String { format!("{scope}:{ip}") diff --git a/docs/architecture.md b/docs/architecture.md index 1b37d97..89ac865 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -126,16 +126,22 @@ signed in to: drives back-channel logout and the "connected apps" list. **mail_outbox**: `id` PK, `kind` (invite|reset|email_old|email_new|email_done|notice|test|security), `to_addr`, `subject`, `body_text`, `state` CHECK IN ('pending','sent','failed','abandoned'), `attempts`, -`next_attempt_at`, `last_error`, `created_at`, `sent_at`. Links in bodies are never logged. +`next_attempt_at`, `last_error`, `created_at`, `sent_at`. Links in bodies are never logged. An address holds at +most 10 unsent rows (`pending` or `failed`, `store::mail::PENDING_PER_ADDRESS`), and a reset mail is not queued +again inside 5 minutes of the previous one to the same address (`RESET_COOLDOWN`). A mail over either limit is +dropped without an error. Failed and abandoned rows are deleted 30 days after creation. **backchannel_outbox**: `id` PK, `client_id`, `sid` NULL, `sub`, `reason`, `state`, `attempts`, -`next_attempt_at`, `last_error`, `created_at`, `done_at`. +`next_attempt_at`, `last_error`, `created_at`, `done_at`. `done_at` is set when a row is sent or abandoned; rows +finished more than 7 days ago are deleted. **directory_changes**: `seq` INTEGER PK AUTOINCREMENT, `sub`, `kind` CHECK IN ('member','deleted'), `at`. The cursor of the directory stream is `seq`. Rows older than 30 days are pruned; a cursor older than the oldest row gets `resync`. -**audit_log**: per conventions section 10. +**audit_log**: per conventions section 10. Entries older than 365 days are deleted by the sweeper +(`AUDIT_KEEP` in `sweeper.rs`, a fixed year rather than a setting). A `LoginFailed` row is written at most once per +minute per account, or per client address when the account is unknown; the throttle still counts every failure. **settings**: `key` PK, `value`, `updated_at` (UI overrides and sealed SMTP password). @@ -198,6 +204,10 @@ redirects). Other errors redirect to the client with `error=` and `state`. - Second factor: 6 digits → TOTP with replay guard; `xxxx-xxxx` → recovery code (consumed). Throttled per user. - Session: 30 days idle-extended up to `session_max_days` (policy), cookie `__Host-im_session`. At most `max_sessions` per user: the oldest is ended (with back-channel) when exceeded. +- Limits beyond the failure counters (`throttle.rs`, in memory, refused with `429` or an OAuth error): + `/authorize` issues at most 60 codes a minute per session (over it, `error=temporarily_unavailable` goes to + the redirect URI); `/token` allows 120 requests a minute per authenticated client; an account asks for at most + 3 email changes an hour; each form route reads at most 16 KiB, and the photo route keeps its own limit. - Password change ends every other session; reset ends all. Disable and delete end all and queue back-channel logout by `sub`. - TOTP enroll: secret generated and held sealed in a pending state until a valid code confirms it; enrolling @@ -244,7 +254,8 @@ in the store as single conditional statements so they cannot race. - **keys**: daily; creates the next key 24 h before rotation, retires old keys after 7 days. - **health**: probes services every 60 s (2 s timeout), updates `services`, bumps the admin health topic. - **sweeper**: hourly; deletes expired codes, links, sessions (queuing back-channel), old directory changes, - sent mail older than 30 days. + sent mail older than 30 days, failed and abandoned mail older than 30 days, back-channel deliveries finished + more than 7 days ago, and audit entries older than 365 days. - **backup** (optional, `[backup] dir`): `VACUUM INTO` snapshot + photos + manifest on an interval, keeps N, pings a dead-man URL (`/start`, success, `/fail`). @@ -261,13 +272,10 @@ revoked session leaves at once), `AdminUsers`, `AdminServices`, `AdminMail`, `Ad ## 10. CLI -`im admin create-admin ` (prompts for name and password; `IM_PASSWORD` for scripts), -`im admin reset-2fa `, `im admin disable `, `im admin create-client ` -(prints the secret once), `im admin rotate-key`, `im admin backup --out DIR`, `im admin backup-verify SET`, -`im admin restore --from SET --data-dir NEW`, `im admin audit-purge --older-than-days N`. -The CLI opens the database directly; it refuses to run while the server holds it unless `--online` is given, -in which case it talks to the running server over a unix socket in `data_dir/run/` with a per-boot token -(forge `admin_client.rs` pattern). +The commands are listed in README.md (Command line): `serve`, `client add|list|disable`, `backup now`, +`restore --from SET`, `fsck`, `keys rotate`. Accounts are set up in the browser (`/setup`), not on the CLI. +The CLI opens the database directly and holds the data directory's lock, so it refuses to run beside a +running server. --- diff --git a/docs/conventions.md b/docs/conventions.md index eed1b03..f5869f3 100644 --- a/docs/conventions.md +++ b/docs/conventions.md @@ -132,7 +132,7 @@ unit-tested as a truth table. Append-only `audit_log` (id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data JSON). Written after the change commits; a failed audit write is logged and never fails the request. Never store secrets in -`data`. Admin page with filters and keyset paging. Purge only through `admin audit-purge --older-than-days N`. +`data`. Admin page with filters and keyset paging. Rows older than the retention window are removed by the sweeper; nothing else deletes them. ## 11. i18n