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