Reset and email-change links only replaced when their mail is admitted, client sign-out in one step, larger admin message limit, alive stream re-checks, photo limits by decoded size, token throttle per chain, per-address junk keys, reset mail never capped, pending login claimed before the second factor
Browse files at this commitc7a3c1d759c49c46c241a941677e6b727f1a0580Parent: bf598fa- fix
- reset and email-change links only replaced when their mail is admitted, client sign-out in one step, larger admin message limit, alive stream re-checks, photo limits by decoded size, token throttle per chain, per-address junk keys, reset mail never capped, pending login claimed before the second factor
18 changed files +406 -197
- README.md +1 -1
- crates/im-core/src/photo.rs +16 -10
- crates/im-core/src/store/links.rs +49 -12
- crates/im-core/src/store/mail.rs +59 -43
- crates/im-core/src/store/users.rs +14 -0
- crates/im-web/assets/pages.js +12 -4
- crates/im-web/src/boot.rs +4 -2
- crates/im-web/src/i18n/account.rs +3 -3
- crates/im-web/src/live.rs +30 -20
- crates/im-web/src/mail/mod.rs +43 -18
- crates/im-web/src/oidc/logout.rs +8 -4
- crates/im-web/src/oidc/token.rs +31 -11
- crates/im-web/src/pages/admin/message.rs +8 -0
- crates/im-web/src/pages/email.rs +32 -28
- crates/im-web/src/pages/login.rs +19 -12
- crates/im-web/src/pages/reset.rs +34 -19
- crates/im-web/src/throttle.rs +36 -7
- docs/architecture.md +7 -3
README.mdmodified+1 -1
| @@ -115,7 +115,7 @@ im --config /etc/im/im.toml restore --from <set> # verify, then restore | |||
| 115 | the snapshot's integrity and schema. A tampered set is refused. A verified set replaces the database and the | 115 | the snapshot's integrity and schema. A tampered set is refused. A verified set replaces the database and the |
| 116 | photos; the previous database and photos are moved into a `restore-<stamp>` directory inside `data_dir`, so | 116 | photos; the previous database and photos are moved into a `restore-<stamp>` directory inside `data_dir`, so |
| 117 | nothing is lost. `restore` refuses to run while the server (or another `im` command) holds the data directory, | 117 | nothing is lost. `restore` refuses to run while the server (or another `im` command) holds the data directory, |
| 118 | -so stop the service first. | 118 | +so stop the service first. A set written before the manifest MAC was added has no `manifest.mac` and is refused; take a new backup instead. |
| 119 | 119 | ||
| 120 | ## Signing keys | 120 | ## Signing keys |
| 121 | 121 | ||
crates/im-core/src/photo.rsmodified+16 -10
| @@ -28,12 +28,13 @@ pub const MAX_UPLOAD_BYTES: usize = 5 * 1024 * 1024; | |||
| 28 | pub const MAX_SIDE: u32 = 512; | 28 | pub const MAX_SIDE: u32 = 512; |
| 29 | 29 | ||
| 30 | /// Longest side an input may have, in pixels. Larger inputs are refused from the header, before any | 30 | /// Longest side an input may have, in pixels. Larger inputs are refused from the header, before any |
| 31 | -/// pixel is decoded. At this side an RGBA picture is exactly [`MAX_DECODE_ALLOC`]. | 31 | +/// pixel is decoded. |
| 32 | -const MAX_INPUT_SIDE: u32 = 4096; | 32 | +const MAX_INPUT_SIDE: u32 = 8000; |
| 33 | 33 | ||
| 34 | -/// Most memory the decoder may allocate for one input, in bytes (64 MiB). A 4096 x 4096 RGBA picture | 34 | +/// Most memory the decoder may allocate for one input, in bytes (96 MiB). An input is refused from its |
| 35 | -/// fills it exactly, so the side limit and the allocation limit agree. | 35 | +/// header when its pixels as RGBA would need more than this, so a 4096 x 4096 phone picture fits and an |
| 36 | -const MAX_DECODE_ALLOC: u64 = 64 * 1024 * 1024; | 36 | +/// 8000 x 8000 one is refused before any pixel is decoded. |
| 37 | +const MAX_DECODE_ALLOC: u64 = 96 * 1024 * 1024; | ||
| 37 | 38 | ||
| 38 | /// Decodes that may run at once. Each one holds up to [`MAX_DECODE_ALLOC`], so a burst of uploads queues | 39 | /// Decodes that may run at once. Each one holds up to [`MAX_DECODE_ALLOC`], so a burst of uploads queues |
| 39 | /// behind two permits instead of starting one blocking thread and one decode per request. | 40 | /// behind two permits instead of starting one blocking thread and one decode per request. |
| @@ -55,10 +56,11 @@ fn refused() -> Error { | |||
| 55 | 56 | ||
| 56 | /// Turns an upload into the stored picture: a square WebP of at most [`MAX_SIDE`] pixels. | 57 | /// Turns an upload into the stored picture: a square WebP of at most [`MAX_SIDE`] pixels. |
| 57 | /// | 58 | /// |
| 58 | -/// Refuses anything whose bytes are not PNG, JPEG, WebP or GIF, whatever its name says. A picture with a side | 59 | +/// Refuses anything whose bytes are not PNG, JPEG, WebP or GIF, whatever its name says. A picture with a |
| 59 | -/// longer than [`MAX_INPUT_SIDE`] is refused with [`Error::PictureTooLarge`], so the uploader sees the size | 60 | +/// side longer than [`MAX_INPUT_SIDE`], or whose RGBA pixels would need more than [`MAX_DECODE_ALLOC`], is |
| 60 | -/// as the reason. Any other image that is larger than the input limits or cannot be decoded is refused too. | 61 | +/// refused with [`Error::PictureTooLarge`], so the uploader sees the size as the reason. Any other image |
| 61 | -/// Only the first frame of an animated GIF is kept. | 62 | +/// that is larger than the input limits or cannot be decoded is refused too. Only the first frame of an |
| 63 | +/// animated GIF is kept. | ||
| 62 | pub fn normalize_photo(input: &[u8]) -> Result<Vec<u8>> { | 64 | pub fn normalize_photo(input: &[u8]) -> Result<Vec<u8>> { |
| 63 | let format = image::guess_format(input).map_err(|_| refused())?; | 65 | let format = image::guess_format(input).map_err(|_| refused())?; |
| 64 | let accepted = matches!( | 66 | let accepted = matches!( |
| @@ -78,7 +80,11 @@ pub fn normalize_photo(input: &[u8]) -> Result<Vec<u8>> { | |||
| 78 | let (declared_width, declared_height) = ImageReader::with_format(Cursor::new(input), format) | 80 | let (declared_width, declared_height) = ImageReader::with_format(Cursor::new(input), format) |
| 79 | .into_dimensions() | 81 | .into_dimensions() |
| 80 | .map_err(decode_error)?; | 82 | .map_err(decode_error)?; |
| 81 | - if declared_width > MAX_INPUT_SIDE || declared_height > MAX_INPUT_SIDE { | 83 | + let rgba_bytes = u64::from(declared_width) * u64::from(declared_height) * 4; |
| 84 | + if declared_width > MAX_INPUT_SIDE | ||
| 85 | + || declared_height > MAX_INPUT_SIDE | ||
| 86 | + || rgba_bytes > MAX_DECODE_ALLOC | ||
| 87 | + { | ||
| 82 | return Err(Error::PictureTooLarge); | 88 | return Err(Error::PictureTooLarge); |
| 83 | } | 89 | } |
| 84 | let mut reader = ImageReader::with_format(Cursor::new(input), format); | 90 | let mut reader = ImageReader::with_format(Cursor::new(input), format); |
crates/im-core/src/store/links.rsmodified+49 -12
| @@ -13,6 +13,7 @@ use turso::Connection; | |||
| 13 | use crate::error::{Error, Result}; | 13 | use crate::error::{Error, Result}; |
| 14 | use crate::store::backchannel::EndReason; | 14 | use crate::store::backchannel::EndReason; |
| 15 | use crate::store::directory::{ChangeKind, record_change}; | 15 | use crate::store::directory::{ChangeKind, record_change}; |
| 16 | +use crate::store::mail::{NewMail, admitted, insert_mail}; | ||
| 16 | use crate::store::sessions::end_all_sessions; | 17 | use crate::store::sessions::end_all_sessions; |
| 17 | use crate::store::users::insert_error; | 18 | use crate::store::users::insert_error; |
| 18 | use crate::store::{Store, col_opt_text, col_text, db_err, fetch_opt, finish, new_id}; | 19 | use crate::store::{Store, col_opt_text, col_text, db_err, fetch_opt, finish, new_id}; |
| @@ -76,18 +77,25 @@ pub(crate) async fn invalidate_links(conn: &Connection, user_id: &str, now: &str | |||
| 76 | } | 77 | } |
| 77 | 78 | ||
| 78 | impl Store { | 79 | impl Store { |
| 79 | - /// Creates a password-reset link. Older pending reset links of the person stop working. The | 80 | + /// Creates a password-reset link and queues its `mail` in one transaction. The mail is checked first |
| 80 | - /// caller has checked that the person exists and is not disabled. | 81 | + /// (see `store::mail`): when it would be dropped, nothing changes, so an older link that was mailed |
| 82 | + /// keeps working and no new link is made that nobody receives. Otherwise older pending reset links of | ||
| 83 | + /// the person stop working. Returns the outbox id, or `None` when the mail was dropped. The caller has | ||
| 84 | + /// checked that the person exists and is not disabled. | ||
| 81 | pub async fn create_reset_link( | 85 | pub async fn create_reset_link( |
| 82 | &self, | 86 | &self, |
| 83 | user_id: &str, | 87 | user_id: &str, |
| 84 | token_hash: &str, | 88 | token_hash: &str, |
| 85 | expires_at: &str, | 89 | expires_at: &str, |
| 86 | - ) -> Result<()> { | 90 | + mail: &NewMail<'_>, |
| 91 | + ) -> Result<Option<String>> { | ||
| 87 | let now = now_stamp(); | 92 | let now = now_stamp(); |
| 88 | let conn = self.inner.conn.lock().await; | 93 | let conn = self.inner.conn.lock().await; |
| 89 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; | 94 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 90 | - let outcome: Result<()> = async { | 95 | + let outcome: Result<Option<String>> = async { |
| 96 | + if !admitted(&tx, mail).await? { | ||
| 97 | + return Ok(None); | ||
| 98 | + } | ||
| 91 | tx.execute( | 99 | tx.execute( |
| 92 | "UPDATE account_links SET used_at = ?2 \ | 100 | "UPDATE account_links SET used_at = ?2 \ |
| 93 | WHERE user_id = ?1 AND kind = 'reset' AND used_at IS NULL", | 101 | WHERE user_id = ?1 AND kind = 'reset' AND used_at IS NULL", |
| @@ -107,7 +115,7 @@ impl Store { | |||
| 107 | ) | 115 | ) |
| 108 | .await | 116 | .await |
| 109 | .map_err(db_err)?; | 117 | .map_err(db_err)?; |
| 110 | - Ok(()) | 118 | + Ok(Some(insert_mail(&tx, mail).await?)) |
| 111 | } | 119 | } |
| 112 | .await; | 120 | .await; |
| 113 | finish(tx, outcome).await | 121 | finish(tx, outcome).await |
| @@ -197,9 +205,11 @@ impl Store { | |||
| 197 | finish(tx, outcome).await | 205 | finish(tx, outcome).await |
| 198 | } | 206 | } |
| 199 | 207 | ||
| 200 | - /// Starts an email change: two links, one for each address, sharing a pair id. Older pending email | 208 | + /// Starts an email change: two links, one for each address, sharing a pair id, with their two mails |
| 201 | - /// links of the person stop working. Fails with a conflict when `new_email` belongs to an account. | 209 | + /// (`mails[0]` to the current address, `mails[1]` to the new one). Older pending email links of the |
| 202 | - /// `expires_at` is the same for both halves. | 210 | + /// person stop working. Fails with a conflict when `new_email` belongs to an account. When either mail |
| 211 | + /// would be dropped by the limits, nothing changes and the answer is `false`. `expires_at` is the same | ||
| 212 | + /// for both halves. | ||
| 203 | pub async fn start_email_change( | 213 | pub async fn start_email_change( |
| 204 | &self, | 214 | &self, |
| 205 | user_id: &str, | 215 | user_id: &str, |
| @@ -207,12 +217,13 @@ impl Store { | |||
| 207 | old_token_hash: &str, | 217 | old_token_hash: &str, |
| 208 | new_token_hash: &str, | 218 | new_token_hash: &str, |
| 209 | expires_at: &str, | 219 | expires_at: &str, |
| 210 | - ) -> Result<()> { | 220 | + mails: &[NewMail<'_>; 2], |
| 221 | + ) -> Result<bool> { | ||
| 211 | let now = now_stamp(); | 222 | let now = now_stamp(); |
| 212 | let pair = new_id(); | 223 | let pair = new_id(); |
| 213 | let conn = self.inner.conn.lock().await; | 224 | let conn = self.inner.conn.lock().await; |
| 214 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; | 225 | let tx = conn.unchecked_transaction().await.map_err(db_err)?; |
| 215 | - let outcome: Result<()> = async { | 226 | + let outcome: Result<bool> = async { |
| 216 | let taken = fetch_opt( | 227 | let taken = fetch_opt( |
| 217 | &tx, | 228 | &tx, |
| 218 | "SELECT 1 FROM users WHERE email_folded = ?1", | 229 | "SELECT 1 FROM users WHERE email_folded = ?1", |
| @@ -225,6 +236,11 @@ impl Store { | |||
| 225 | "that email address cannot be used".into(), | 236 | "that email address cannot be used".into(), |
| 226 | )); | 237 | )); |
| 227 | } | 238 | } |
| 239 | + for mail in mails { | ||
| 240 | + if !admitted(&tx, mail).await? { | ||
| 241 | + return Ok(false); | ||
| 242 | + } | ||
| 243 | + } | ||
| 228 | invalidate_links_of_kinds(&tx, user_id, &now).await?; | 244 | invalidate_links_of_kinds(&tx, user_id, &now).await?; |
| 229 | for (token_hash, kind) in [(old_token_hash, "email_old"), (new_token_hash, "email_new")] { | 245 | for (token_hash, kind) in [(old_token_hash, "email_old"), (new_token_hash, "email_new")] { |
| 230 | tx.execute( | 246 | tx.execute( |
| @@ -243,7 +259,10 @@ impl Store { | |||
| 243 | .await | 259 | .await |
| 244 | .map_err(db_err)?; | 260 | .map_err(db_err)?; |
| 245 | } | 261 | } |
| 246 | - Ok(()) | 262 | + for mail in mails { |
| 263 | + insert_mail(&tx, mail).await?; | ||
| 264 | + } | ||
| 265 | + Ok(true) | ||
| 247 | } | 266 | } |
| 248 | .await; | 267 | .await; |
| 249 | finish(tx, outcome).await | 268 | finish(tx, outcome).await |
| @@ -383,6 +402,15 @@ mod tests { | |||
| 383 | use crate::time::stamp_after; | 402 | use crate::time::stamp_after; |
| 384 | use std::time::Duration; | 403 | use std::time::Duration; |
| 385 | 404 | ||
| 405 | + fn test_mail(kind: &'static str) -> NewMail<'static> { | ||
| 406 | + NewMail { | ||
| 407 | + kind, | ||
| 408 | + to_addr: "ada@example.com", | ||
| 409 | + subject: "Subject", | ||
| 410 | + sealed_body: "v1:sealed", | ||
| 411 | + } | ||
| 412 | + } | ||
| 413 | + | ||
| 386 | async fn setup() -> (tempfile::TempDir, Store, String) { | 414 | async fn setup() -> (tempfile::TempDir, Store, String) { |
| 387 | let dir = tempfile::tempdir().unwrap(); | 415 | let dir = tempfile::tempdir().unwrap(); |
| 388 | let store = Store::open(&dir.path().join("im.db")).await.unwrap(); | 416 | let store = Store::open(&dir.path().join("im.db")).await.unwrap(); |
| @@ -401,6 +429,7 @@ mod tests { | |||
| 401 | &user_id, | 429 | &user_id, |
| 402 | "reset-hash", | 430 | "reset-hash", |
| 403 | &stamp_after(Duration::from_secs(3600)), | 431 | &stamp_after(Duration::from_secs(3600)), |
| 432 | + &test_mail("reset"), | ||
| 404 | ) | 433 | ) |
| 405 | .await | 434 | .await |
| 406 | .unwrap(); | 435 | .unwrap(); |
| @@ -428,6 +457,7 @@ mod tests { | |||
| 428 | &user_id, | 457 | &user_id, |
| 429 | "reset-hash", | 458 | "reset-hash", |
| 430 | &stamp_after(Duration::from_secs(3600)), | 459 | &stamp_after(Duration::from_secs(3600)), |
| 460 | + &test_mail("reset"), | ||
| 431 | ) | 461 | ) |
| 432 | .await | 462 | .await |
| 433 | .unwrap(); | 463 | .unwrap(); |
| @@ -453,7 +483,14 @@ mod tests { | |||
| 453 | let (_dir, store, user_id) = setup().await; | 483 | let (_dir, store, user_id) = setup().await; |
| 454 | let later = stamp_after(Duration::from_secs(3600)); | 484 | let later = stamp_after(Duration::from_secs(3600)); |
| 455 | store | 485 | store |
| 456 | - .start_email_change(&user_id, "ada.new@example.com", "h-old", "h-new", &later) | 486 | + .start_email_change( |
| 487 | + &user_id, | ||
| 488 | + "ada.new@example.com", | ||
| 489 | + "h-old", | ||
| 490 | + "h-new", | ||
| 491 | + &later, | ||
| 492 | + &[test_mail("email_old"), test_mail("email_new")], | ||
| 493 | + ) | ||
| 457 | .await | 494 | .await |
| 458 | .unwrap(); | 495 | .unwrap(); |
| 459 | // Someone else registers the new address before either half is confirmed. | 496 | // Someone else registers the new address before either half is confirmed. |
crates/im-core/src/store/mail.rsmodified+59 -43
| @@ -6,19 +6,26 @@ | |||
| 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 | //! | 7 | //! |
| 8 | //! Two limits keep one address from being mailed without end. An address may hold at most | 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`]. | 9 | +//! [`PENDING_PER_ADDRESS`] rows that are still `pending`, and a reset mail is not queued again inside |
| 10 | -//! A mail over either limit is dropped without any error, so the answer to the caller never depends on | 10 | +//! [`RESET_COOLDOWN`]. The cap never applies to reset mail, so a person who asks for a reset is always |
| 11 | -//! whether the address has an account. | 11 | +//! sent one (the cooldown still limits how often). A mail over a limit is dropped without any error, so |
| 12 | +//! the answer to the caller never depends on whether the address has an account. | ||
| 13 | +//! | ||
| 14 | +//! The limits are checked by [`admitted`] under the same transaction that creates the links a mail | ||
| 15 | +//! carries (see `store::links`), so a dropped mail never leaves a live link behind. | ||
| 12 | 16 | ||
| 13 | use std::time::Duration; | 17 | use std::time::Duration; |
| 14 | 18 | ||
| 19 | +use turso::Connection; | ||
| 20 | + | ||
| 15 | use crate::error::Result; | 21 | use crate::error::Result; |
| 16 | use crate::store::{ | 22 | use crate::store::{ |
| 17 | Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, missing_row, new_id, | 23 | Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, missing_row, new_id, |
| 18 | }; | 24 | }; |
| 19 | use crate::time::{now_stamp, stamp_before}; | 25 | use crate::time::{now_stamp, stamp_before}; |
| 20 | 26 | ||
| 21 | -/// Most unsent rows (`pending` or `failed`) one recipient address may hold. Mail over it is dropped. | 27 | +/// Most `pending` rows one recipient address may hold. Mail over it is dropped, except reset mail. Rows |
| 28 | +/// that failed are not counted: their retries are already scheduled and they are not new mail. | ||
| 22 | pub const PENDING_PER_ADDRESS: i64 = 10; | 29 | pub const PENDING_PER_ADDRESS: i64 = 10; |
| 23 | 30 | ||
| 24 | /// The least time between two reset mails to one address. A reset mail inside it is dropped. | 31 | /// The least time between two reset mails to one address. A reset mail inside it is dropped. |
| @@ -99,53 +106,62 @@ fn map_job(row: &turso::Row) -> Result<MailJob> { | |||
| 99 | }) | 106 | }) |
| 100 | } | 107 | } |
| 101 | 108 | ||
| 109 | +/// Whether `new` may be queued now: the cooldown for reset mail, and the cap on `pending` rows for any | ||
| 110 | +/// other kind. `conn` is the writer, or a transaction on it, so the answer holds for the insert that follows. | ||
| 111 | +pub(crate) async fn admitted(conn: &Connection, new: &NewMail<'_>) -> Result<bool> { | ||
| 112 | + if new.kind == "reset" { | ||
| 113 | + let recent = fetch_opt( | ||
| 114 | + conn, | ||
| 115 | + "SELECT COUNT(*) FROM mail_outbox WHERE to_addr = ?1 AND kind = 'reset' AND created_at >= ?2", | ||
| 116 | + (new.to_addr.to_string(), stamp_before(RESET_COOLDOWN)), | ||
| 117 | + |row| col_int(row, 0), | ||
| 118 | + ) | ||
| 119 | + .await? | ||
| 120 | + .ok_or_else(missing_row)?; | ||
| 121 | + return Ok(recent == 0); | ||
| 122 | + } | ||
| 123 | + let pending = fetch_opt( | ||
| 124 | + conn, | ||
| 125 | + "SELECT COUNT(*) FROM mail_outbox WHERE to_addr = ?1 AND state = 'pending'", | ||
| 126 | + (new.to_addr.to_string(),), | ||
| 127 | + |row| col_int(row, 0), | ||
| 128 | + ) | ||
| 129 | + .await? | ||
| 130 | + .ok_or_else(missing_row)?; | ||
| 131 | + Ok(pending < PENDING_PER_ADDRESS) | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +/// Inserts one `pending` row for `new` and returns its id. Callers check [`admitted`] first, under the | ||
| 135 | +/// same connection or transaction. | ||
| 136 | +pub(crate) async fn insert_mail(conn: &Connection, new: &NewMail<'_>) -> Result<String> { | ||
| 137 | + let id = new_id(); | ||
| 138 | + conn.execute( | ||
| 139 | + "INSERT INTO mail_outbox (id, kind, to_addr, subject, body_text, state, attempts, \ | ||
| 140 | + next_attempt_at, created_at) VALUES (?1, ?2, ?3, ?4, ?5, 'pending', 0, ?6, ?6)", | ||
| 141 | + ( | ||
| 142 | + id.clone(), | ||
| 143 | + new.kind.to_string(), | ||
| 144 | + new.to_addr.to_string(), | ||
| 145 | + new.subject.to_string(), | ||
| 146 | + new.sealed_body.to_string(), | ||
| 147 | + now_stamp(), | ||
| 148 | + ), | ||
| 149 | + ) | ||
| 150 | + .await | ||
| 151 | + .map_err(db_err)?; | ||
| 152 | + Ok(id) | ||
| 153 | +} | ||
| 154 | + | ||
| 102 | impl Store { | 155 | impl Store { |
| 103 | /// Adds a mail to the outbox, to be sent as soon as the worker looks. Returns its id, or `None` when the | 156 | /// Adds a mail to the outbox, to be sent as soon as the worker looks. Returns its id, or `None` when the |
| 104 | /// mail is dropped by [`PENDING_PER_ADDRESS`] or by [`RESET_COOLDOWN`]. The checks and the insert run | 157 | /// 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. | 158 | /// under the writer, so parallel requests cannot pass a limit together. |
| 106 | pub async fn enqueue_mail(&self, new: &NewMail<'_>) -> Result<Option<String>> { | 159 | pub async fn enqueue_mail(&self, new: &NewMail<'_>) -> Result<Option<String>> { |
| 107 | - let id = new_id(); | ||
| 108 | - let now = now_stamp(); | ||
| 109 | let conn = self.inner.conn.lock().await; | 160 | let conn = self.inner.conn.lock().await; |
| 110 | - let unsent = fetch_opt( | 161 | + if !admitted(&conn, new).await? { |
| 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); | 162 | return Ok(None); |
| 120 | } | 163 | } |
| 121 | - if new.kind == "reset" { | 164 | + Ok(Some(insert_mail(&conn, new).await?)) |
| 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 | - } | ||
| 134 | - conn.execute( | ||
| 135 | - "INSERT INTO mail_outbox (id, kind, to_addr, subject, body_text, state, attempts, \ | ||
| 136 | - next_attempt_at, created_at) VALUES (?1, ?2, ?3, ?4, ?5, 'pending', 0, ?6, ?6)", | ||
| 137 | - ( | ||
| 138 | - id.clone(), | ||
| 139 | - new.kind.to_string(), | ||
| 140 | - new.to_addr.to_string(), | ||
| 141 | - new.subject.to_string(), | ||
| 142 | - new.sealed_body.to_string(), | ||
| 143 | - now, | ||
| 144 | - ), | ||
| 145 | - ) | ||
| 146 | - .await | ||
| 147 | - .map_err(db_err)?; | ||
| 148 | - Ok(Some(id)) | ||
| 149 | } | 165 | } |
| 150 | 166 | ||
| 151 | /// Rows that are due: never tried, or failed and whose retry time has come. Oldest first. | 167 | /// Rows that are due: never tried, or failed and whose retry time has come. Oldest first. |
crates/im-core/src/store/users.rsmodified+14 -0
| @@ -522,6 +522,20 @@ impl Store { | |||
| 522 | Ok(changed == 1) | 522 | Ok(changed == 1) |
| 523 | } | 523 | } |
| 524 | 524 | ||
| 525 | + /// Gives back a nonce that [`Store::consume_pending_login`] claimed, when the second factor was wrong, so | ||
| 526 | + /// the person can try again with the same pending login. Only a claim that did not lead to a sign-in is | ||
| 527 | + /// given back. | ||
| 528 | + pub async fn release_pending_login(&self, nonce: &str) -> Result<()> { | ||
| 529 | + let conn = self.inner.conn.lock().await; | ||
| 530 | + conn.execute( | ||
| 531 | + "DELETE FROM consumed_pending_logins WHERE nonce = ?1", | ||
| 532 | + (nonce.to_string(),), | ||
| 533 | + ) | ||
| 534 | + .await | ||
| 535 | + .map_err(db_err)?; | ||
| 536 | + Ok(()) | ||
| 537 | + } | ||
| 538 | + | ||
| 525 | /// Records `step` as the last accepted TOTP step. Returns true only when that moved the guard | 539 | /// Records `step` as the last accepted TOTP step. Returns true only when that moved the guard |
| 526 | /// forward. A step that is not later than the recorded one, or any step while two-factor is off, | 540 | /// forward. A step that is not later than the recorded one, or any step while two-factor is off, |
| 527 | /// returns false. This is the replay guard: a code is spent by this single statement. | 541 | /// returns false. This is the replay guard: a code is spent by this single statement. |
crates/im-web/assets/pages.jsmodified+12 -4
| @@ -1,9 +1,17 @@ | |||
| 1 | /* | 1 | /* |
| 2 | - * pages.js: small behaviours of individual pages (a dropdown search, a copy button and so on). It | 2 | + * pages.js: small behaviours of individual pages (a dropdown search, a copy button and so on). Each |
| 3 | - * is empty for now. The file exists so the shell can load it and its content hash is already in the | 3 | + * behaviour does nothing unless its own data attribute is on the page. Like nav.js, it is one IIFE |
| 4 | - * page links. Each behaviour, when it is added, does nothing unless its own data attribute is on the | 4 | + * with no globals. |
| 5 | - * page. Like nav.js, it is one IIFE with no globals. | 5 | + * |
| 6 | + * - data-auto-submit="true": such a form is submitted once when the page loads. The | ||
| 7 | + * relying-party sign-out (GET /logout) uses it, so the browser goes back to the client in one | ||
| 8 | + * step. The form has a visible button for pages without JS. The form also carries data-hard, so | ||
| 9 | + * nav.js leaves its submit to the browser. | ||
| 6 | */ | 10 | */ |
| 7 | (function () { | 11 | (function () { |
| 8 | "use strict"; | 12 | "use strict"; |
| 13 | + | ||
| 14 | + document.querySelectorAll("form[data-auto-submit='true']").forEach((form) => { | ||
| 15 | + form.requestSubmit(); | ||
| 16 | + }); | ||
| 9 | })(); | 17 | })(); |
crates/im-web/src/boot.rsmodified+4 -2
| @@ -25,6 +25,7 @@ use crate::backchannel; | |||
| 25 | use crate::live::{LiveHub, MAX_ANONYMOUS_STREAMS}; | 25 | use crate::live::{LiveHub, MAX_ANONYMOUS_STREAMS}; |
| 26 | use crate::mail; | 26 | use crate::mail; |
| 27 | use crate::oidc::signing; | 27 | use crate::oidc::signing; |
| 28 | +use crate::pages::admin::message::{MESSAGE_BODY_LIMIT, MESSAGE_ROUTE}; | ||
| 28 | use crate::pages::not_found::NotFoundLayer; | 29 | use crate::pages::not_found::NotFoundLayer; |
| 29 | use crate::pages::profile::PHOTO_ROUTE; | 30 | use crate::pages::profile::PHOTO_ROUTE; |
| 30 | use crate::security::{self, SecurityHeaders}; | 31 | use crate::security::{self, SecurityHeaders}; |
| @@ -210,8 +211,8 @@ const PHOTO_BODY_LIMIT: usize = MAX_UPLOAD_BYTES + 64 * 1024; | |||
| 210 | const FORM_BODY_LIMIT: usize = 16 * 1024; | 211 | const FORM_BODY_LIMIT: usize = 16 * 1024; |
| 211 | 212 | ||
| 212 | /// The router of the server: every route and page found by `discover`, the cookie jar, the security | 213 | /// The router of the server: every route and page found by `discover`, the cookie jar, the security |
| 213 | -/// headers on every response, the styled 404 for browsers, the body limit of forms, and the upload limit | 214 | +/// headers on every response, the styled 404 for browsers, the body limit of forms, and the larger limits |
| 214 | -/// of the photo route (which overrides the form limit under its path). | 215 | +/// of the photo upload and the admin message (which override the form limit under their paths). |
| 215 | pub fn router(state: AppState) -> Router { | 216 | pub fn router(state: AppState) -> Router { |
| 216 | let security = SecurityHeaders::new(security::headers_for(&state.config.base_url)); | 217 | let security = SecurityHeaders::new(security::headers_for(&state.config.base_url)); |
| 217 | Router::builder() | 218 | Router::builder() |
| @@ -220,6 +221,7 @@ pub fn router(state: AppState) -> Router { | |||
| 220 | .cookies() | 221 | .cookies() |
| 221 | .layer(BodyLimit::max(FORM_BODY_LIMIT)) | 222 | .layer(BodyLimit::max(FORM_BODY_LIMIT)) |
| 222 | .layer(BodyLimit::max(PHOTO_BODY_LIMIT).at(PHOTO_ROUTE)) | 223 | .layer(BodyLimit::max(PHOTO_BODY_LIMIT).at(PHOTO_ROUTE)) |
| 224 | + .layer(BodyLimit::max(MESSAGE_BODY_LIMIT).at(MESSAGE_ROUTE)) | ||
| 223 | .layer(security) | 225 | .layer(security) |
| 224 | .layer(NotFoundLayer) | 226 | .layer(NotFoundLayer) |
| 225 | .build() | 227 | .build() |
crates/im-web/src/i18n/account.rsmodified+3 -3
| @@ -210,7 +210,7 @@ pub enum Txt { | |||
| 210 | ErrPhotoType, | 210 | ErrPhotoType, |
| 211 | /// Shown when the upload is over the size limit. | 211 | /// Shown when the upload is over the size limit. |
| 212 | ErrPhotoTooLarge, | 212 | ErrPhotoTooLarge, |
| 213 | - /// Shown when the picture has a side longer than the decoder accepts (4096 pixels). | 213 | + /// Shown when the picture has a side longer than 8000 pixels, or more than 24 megapixels in all. |
| 214 | ErrPhotoDimensions, | 214 | ErrPhotoDimensions, |
| 215 | /// Shown when the upload form was sent without a file. | 215 | /// Shown when the upload form was sent without a file. |
| 216 | ErrPhotoMissing, | 216 | ErrPhotoMissing, |
| @@ -512,10 +512,10 @@ pub fn text(lang: Lang, key: Txt) -> &'static str { | |||
| 512 | (Txt::ErrPhotoTooLarge, Lang::En) => "The photo is larger than 5 MB.", | 512 | (Txt::ErrPhotoTooLarge, Lang::En) => "The photo is larger than 5 MB.", |
| 513 | (Txt::ErrPhotoTooLarge, Lang::Tr) => "Fotoğraf 5 MB'tan büyük.", | 513 | (Txt::ErrPhotoTooLarge, Lang::Tr) => "Fotoğraf 5 MB'tan büyük.", |
| 514 | (Txt::ErrPhotoDimensions, Lang::En) => { | 514 | (Txt::ErrPhotoDimensions, Lang::En) => { |
| 515 | - "The picture is too large; use one at most 4096 pixels on each side." | 515 | + "The picture is too large; use one at most 8000 pixels on each side and 24 megapixels in all." |
| 516 | } | 516 | } |
| 517 | (Txt::ErrPhotoDimensions, Lang::Tr) => { | 517 | (Txt::ErrPhotoDimensions, Lang::Tr) => { |
| 518 | - "Resim çok büyük; en fazla her kenarı 4096 piksel olan bir resim kullanın." | 518 | + "Resim çok büyük; her kenarı en fazla 8000 piksel, toplamı en fazla 24 megapiksel olan bir resim kullanın." |
| 519 | } | 519 | } |
| 520 | (Txt::ErrPhotoRateLimited, Lang::En) => { | 520 | (Txt::ErrPhotoRateLimited, Lang::En) => { |
| 521 | "Too many photos were uploaded. Try again in an hour." | 521 | "Too many photos were uploaded. Try again in an hour." |
crates/im-web/src/live.rsmodified+30 -20
| @@ -237,7 +237,7 @@ struct AccountFollow { | |||
| 237 | /// | 237 | /// |
| 238 | /// An anonymous viewer gets keep-alives only. A signed-in viewer also gets an `account` event each | 238 | /// An anonymous viewer gets keep-alives only. A signed-in viewer also gets an `account` event each |
| 239 | /// time their account changes (the page then refreshes), and a `signed_out` event when their session | 239 | /// time their account changes (the page then refreshes), and a `signed_out` event when their session |
| 240 | -/// is gone. After `signed_out` the browser goes to the sign-in page, and the stream ends. | 240 | +/// is gone. The session is checked every [`RECHECK`] too, so an idle stream notices an expiry. After `signed_out` the browser goes to the sign-in page, and the stream ends. |
| 241 | #[route(GET "/-/alive")] | 241 | #[route(GET "/-/alive")] |
| 242 | async fn alive(cx: &Cx) -> Result<Response> { | 242 | async fn alive(cx: &Cx) -> Result<Response> { |
| 243 | let state = app_context::<AppState>(cx); | 243 | let state = app_context::<AppState>(cx); |
| @@ -285,26 +285,36 @@ async fn alive(cx: &Cx) -> Result<Response> { | |||
| 285 | _slot: slot, | 285 | _slot: slot, |
| 286 | }; | 286 | }; |
| 287 | let events = stream::unfold(follow, |mut follow| async move { | 287 | let events = stream::unfold(follow, |mut follow| async move { |
| 288 | - if follow.done { | 288 | + loop { |
| 289 | - return None; | 289 | + if follow.done { |
| 290 | - } | 290 | + return None; |
| 291 | - let changed = tokio::select! { | ||
| 292 | - changed = follow.wake.changed() => changed.is_ok(), | ||
| 293 | - () = stopped(&mut follow.stop) => false, | ||
| 294 | - () = tokio::time::sleep_until(follow.until) => false, | ||
| 295 | - }; | ||
| 296 | - if !changed { | ||
| 297 | - return None; | ||
| 298 | - } | ||
| 299 | - match follow.store.session_is_live(&follow.session_id).await { | ||
| 300 | - Ok(true) => Some((Ok(Event::new().event("account").data("1")), follow)), | ||
| 301 | - Ok(false) => { | ||
| 302 | - follow.done = true; | ||
| 303 | - Some((Ok(Event::new().event("signed_out").data("1")), follow)) | ||
| 304 | } | 291 | } |
| 305 | - Err(error) => { | 292 | + // An account change is announced. A recheck tick only looks at the session: a session that |
| 306 | - tracing::error!(error = %error, "alive: could not check the session"); | 293 | + // expired by idle or age policy ends the stream, and a live one sends nothing. |
| 307 | - None | 294 | + let account_changed = tokio::select! { |
| 295 | + changed = follow.wake.changed() => { | ||
| 296 | + if changed.is_err() { | ||
| 297 | + return None; | ||
| 298 | + } | ||
| 299 | + true | ||
| 300 | + } | ||
| 301 | + () = stopped(&mut follow.stop) => return None, | ||
| 302 | + () = tokio::time::sleep_until(follow.until) => return None, | ||
| 303 | + () = tokio::time::sleep(RECHECK) => false, | ||
| 304 | + }; | ||
| 305 | + match follow.store.session_is_live(&follow.session_id).await { | ||
| 306 | + Ok(true) if account_changed => { | ||
| 307 | + return Some((Ok(Event::new().event("account").data("1")), follow)); | ||
| 308 | + } | ||
| 309 | + Ok(true) => {} | ||
| 310 | + Ok(false) => { | ||
| 311 | + follow.done = true; | ||
| 312 | + return Some((Ok(Event::new().event("signed_out").data("1")), follow)); | ||
| 313 | + } | ||
| 314 | + Err(error) => { | ||
| 315 | + tracing::error!(error = %error, "alive: could not check the session"); | ||
| 316 | + return None; | ||
| 317 | + } | ||
| 308 | } | 318 | } |
| 309 | } | 319 | } |
| 310 | }); | 320 | }); |
crates/im-web/src/mail/mod.rsmodified+43 -18
| @@ -122,16 +122,30 @@ pub fn lang_for(user: &User, request: Lang) -> Lang { | |||
| 122 | } | 122 | } |
| 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 | +/// A mail rendered and sealed, not yet in the outbox. Built before any link it carries is created, so the |
| 126 | -/// the body (text and HTML, with the recipient's name) is sealed as one JSON document. A mail that the | 126 | +/// store can check its limits and create the links in one transaction (see `store::links`). |
| 127 | -/// store drops by its per-address limits is not an error here: the caller answers the same either way. | 127 | +pub struct Sealed { |
| 128 | -pub async fn queue( | 128 | + kind: &'static str, |
| 129 | - store: &Store, | 129 | + to_addr: String, |
| 130 | - key: &[u8; 32], | 130 | + subject: String, |
| 131 | - to: &Recipient, | 131 | + sealed_body: String, |
| 132 | - lang: Lang, | 132 | +} |
| 133 | - mail: &Mail<'_>, | 133 | + |
| 134 | -) -> Result<()> { | 134 | +impl Sealed { |
| 135 | + /// The outbox row this mail becomes. | ||
| 136 | + pub fn as_new(&self) -> NewMail<'_> { | ||
| 137 | + NewMail { | ||
| 138 | + kind: self.kind, | ||
| 139 | + to_addr: &self.to_addr, | ||
| 140 | + subject: &self.subject, | ||
| 141 | + sealed_body: &self.sealed_body, | ||
| 142 | + } | ||
| 143 | + } | ||
| 144 | +} | ||
| 145 | + | ||
| 146 | +/// Renders `mail` for `to` in `lang` and seals it under the instance key. The subject is fixed text; the | ||
| 147 | +/// body (text and HTML, with the recipient's name) is sealed as one JSON document. | ||
| 148 | +pub fn seal(key: &[u8; 32], to: &Recipient, lang: Lang, mail: &Mail<'_>) -> Result<Sealed> { | ||
| 135 | let rendered = templates::render(lang, to.name(), mail); | 149 | let rendered = templates::render(lang, to.name(), mail); |
| 136 | let payload = json!({ | 150 | let payload = json!({ |
| 137 | "to_name": to.name(), | 151 | "to_name": to.name(), |
| @@ -140,14 +154,25 @@ pub async fn queue( | |||
| 140 | }) | 154 | }) |
| 141 | .to_string(); | 155 | .to_string(); |
| 142 | let sealed = secret::seal(key, secret::purpose::MAIL_BODY, payload.as_bytes())?; | 156 | let sealed = secret::seal(key, secret::purpose::MAIL_BODY, payload.as_bytes())?; |
| 143 | - store | 157 | + Ok(Sealed { |
| 144 | - .enqueue_mail(&NewMail { | 158 | + kind: mail.kind(), |
| 145 | - kind: mail.kind(), | 159 | + to_addr: to.email().to_string(), |
| 146 | - to_addr: to.email(), | 160 | + subject: rendered.subject, |
| 147 | - subject: &rendered.subject, | 161 | + sealed_body: sealed, |
| 148 | - sealed_body: &sealed, | 162 | + }) |
| 149 | - }) | 163 | +} |
| 150 | - .await?; | 164 | + |
| 165 | +/// Renders `mail` for `to` in `lang`, seals it, and adds it to the outbox. A mail that the store drops by | ||
| 166 | +/// its limits is not an error here: the caller answers the same either way. | ||
| 167 | +pub async fn queue( | ||
| 168 | + store: &Store, | ||
| 169 | + key: &[u8; 32], | ||
| 170 | + to: &Recipient, | ||
| 171 | + lang: Lang, | ||
| 172 | + mail: &Mail<'_>, | ||
| 173 | +) -> Result<()> { | ||
| 174 | + let sealed = seal(key, to, lang, mail)?; | ||
| 175 | + store.enqueue_mail(&sealed.as_new()).await?; | ||
| 151 | Ok(()) | 176 | Ok(()) |
| 152 | } | 177 | } |
| 153 | 178 | ||
crates/im-web/src/oidc/logout.rsmodified+8 -4
| @@ -9,8 +9,12 @@ | |||
| 9 | //! signed-out page, never a redirect. | 9 | //! signed-out page, never a redirect. |
| 10 | //! - `state` is echoed on the redirect only when it is usable (bounded, no control characters). | 10 | //! - `state` is echoed on the redirect only when it is usable (bounded, no control characters). |
| 11 | //! - A `GET` never ends a session: a link or an image on another site must not sign the browser out. A | 11 | //! - A `GET` never ends a session: a link or an image on another site must not sign the browser out. A |
| 12 | -//! `GET` with a session shows a confirmation form, which carries the session's CSRF token. Only the | 12 | +//! `GET` with a session answers with a form that carries the session's CSRF token. When a valid |
| 13 | -//! `POST` ends the session, and it checks that token before anything changes. | 13 | +//! `id_token_hint` came with it (a client's sign-out), the form posts itself (`data-auto-submit`, run by |
| 14 | +//! `assets/pages.js`), so the browser returns to the client without a second click; a bare `GET` waits for | ||
| 15 | +//! the person's click, so a link on another site cannot sign them out. The visible button is the fallback | ||
| 16 | +//! without JS. Only the `POST` ends the session, and it | ||
| 17 | +//! checks that token before anything changes. | ||
| 14 | //! - Ending the session is `im`'s own: the browser session is deleted (and its clients told by | 18 | //! - Ending the session is `im`'s own: the browser session is deleted (and its clients told by |
| 15 | //! back-channel logout, in the store's transaction). When the hint names another session of the same | 19 | //! back-channel logout, in the store's transaction). When the hint names another session of the same |
| 16 | //! person, that one ends too. | 20 | //! person, that one ends too. |
| @@ -221,7 +225,7 @@ async fn logout_post(cx: &Cx, Form(form): Form<LogoutForm>) -> Result<impl View> | |||
| 221 | Ok(logout_view(cx, lang, None)) | 225 | Ok(logout_view(cx, lang, None)) |
| 222 | } | 226 | } |
| 223 | 227 | ||
| 224 | -/// The form that asks for a sign-out (the GET answer when the session is not the hinted one). | 228 | +/// The form that signs the browser out (the GET answer with a session). It posts itself. |
| 225 | struct Confirm { | 229 | struct Confirm { |
| 226 | csrf: String, | 230 | csrf: String, |
| 227 | raw_hint: Option<String>, | 231 | raw_hint: Option<String>, |
| @@ -243,7 +247,7 @@ fn logout_view(cx: &Cx, lang: Lang, confirm: Option<Confirm>) -> impl View { | |||
| 243 | <h1>(title)</h1> | 247 | <h1>(title)</h1> |
| 244 | if let Some(confirm) = confirm { | 248 | if let Some(confirm) = confirm { |
| 245 | <p class="muted">(text(lang, OidcText::ConfirmBody))</p> | 249 | <p class="muted">(text(lang, OidcText::ConfirmBody))</p> |
| 246 | - <form method="post" action="/logout" class="stack"> | 250 | + <form method="post" action="/logout" class="stack" data-hard="true" data-auto-submit=(if confirm.raw_hint.is_some() { "true" } else { "false" })> |
| 247 | <input type="hidden" name="csrf" value=(confirm.csrf)> | 251 | <input type="hidden" name="csrf" value=(confirm.csrf)> |
| 248 | if let Some(hint) = confirm.raw_hint { | 252 | if let Some(hint) = confirm.raw_hint { |
| 249 | <input type="hidden" name="id_token_hint" value=(hint)> | 253 | <input type="hidden" name="id_token_hint" value=(hint)> |
crates/im-web/src/oidc/token.rsmodified+31 -11
| @@ -32,7 +32,9 @@ use super::{ | |||
| 32 | 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, |
| 33 | }; | 33 | }; |
| 34 | use crate::state::AppState; | 34 | use crate::state::AppState; |
| 35 | -use crate::throttle::{TOKEN_CLIENT_LIMIT, token_client_key}; | 35 | +use crate::throttle::{ |
| 36 | + TOKEN_CHAIN_LIMIT, TOKEN_CLIENT_LIMIT, token_client_key, token_code_key, token_family_key, | ||
| 37 | +}; | ||
| 36 | 38 | ||
| 37 | /// `POST /token`. | 39 | /// `POST /token`. |
| 38 | #[route(POST "/token")] | 40 | #[route(POST "/token")] |
| @@ -59,16 +61,9 @@ async fn token_endpoint(cx: &Cx, body: Body) -> Result<Response> { | |||
| 59 | Err(response) => return Ok(response), | 61 | Err(response) => return Ok(response), |
| 60 | }; | 62 | }; |
| 61 | // Counted after the client is authenticated, so a caller without the secret cannot use up a client's | 63 | // 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. | 64 | + // allowance. The client's ceiling applies to every grant; a chain or a code has its own lower limit, |
| 63 | - if let Err(wait) = app.per_minute.reserve( | 65 | + // counted once the grant has found its row (see the grants). |
| 64 | - &token_client_key(&client.id), | 66 | + if let Some(response) = throttled(app, &token_client_key(&client.id), TOKEN_CLIENT_LIMIT) { |
| 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); | 67 | return Ok(response); |
| 73 | } | 68 | } |
| 74 | match one(&pairs, "grant_type") { | 69 | match one(&pairs, "grant_type") { |
| @@ -83,6 +78,17 @@ async fn token_endpoint(cx: &Cx, body: Body) -> Result<Response> { | |||
| 83 | } | 78 | } |
| 84 | } | 79 | } |
| 85 | 80 | ||
| 81 | +/// Counts one request under `key` against `limit` per minute. Over the limit the answer is a 429 with the | ||
| 82 | +/// wait, in the OAuth error form; otherwise `None`. | ||
| 83 | +fn throttled(app: &AppState, key: &str, limit: usize) -> Option<Response> { | ||
| 84 | + let wait = app.per_minute.reserve(key, limit, Instant::now()).err()?; | ||
| 85 | + let mut response = oauth_error(StatusCode::TOO_MANY_REQUESTS, "invalid_request"); | ||
| 86 | + response | ||
| 87 | + .headers_mut() | ||
| 88 | + .insert(RETRY_AFTER, HeaderValue::from(wait.as_secs().max(1))); | ||
| 89 | + Some(response) | ||
| 90 | +} | ||
| 91 | + | ||
| 86 | /// Reads a client-authenticated form for `/revoke` and `/introspect`: the same content type, size and | 92 | /// Reads a client-authenticated form for `/revoke` and `/introspect`: the same content type, size and |
| 87 | /// client authentication as `/token`. The inner `Err` is the refusal to send. | 93 | /// client authentication as `/token`. The inner `Err` is the refusal to send. |
| 88 | pub(super) async fn client_form( | 94 | pub(super) async fn client_form( |
| @@ -203,6 +209,13 @@ async fn grant_code(app: &AppState, client: &Client, pairs: &Pairs) -> Result<Re | |||
| 203 | if row.client_id != client.id { | 209 | if row.client_id != client.id { |
| 204 | return Ok(invalid_grant()); | 210 | return Ok(invalid_grant()); |
| 205 | } | 211 | } |
| 212 | + if let Some(response) = throttled( | ||
| 213 | + app, | ||
| 214 | + &token_code_key(&client.id, &code_hash), | ||
| 215 | + TOKEN_CHAIN_LIMIT, | ||
| 216 | + ) { | ||
| 217 | + return Ok(response); | ||
| 218 | + } | ||
| 206 | if row.used_at.is_some() { | 219 | if row.used_at.is_some() { |
| 207 | // The code was exchanged before. Whoever holds the tokens made from it must lose them. | 220 | // The code was exchanged before. Whoever holds the tokens made from it must lose them. |
| 208 | app.store.revoke_code_refresh_tokens(&code_hash).await?; | 221 | app.store.revoke_code_refresh_tokens(&code_hash).await?; |
| @@ -278,6 +291,13 @@ async fn grant_refresh(app: &AppState, client: &Client, pairs: &Pairs) -> Result | |||
| 278 | if row.client_id != client.id { | 291 | if row.client_id != client.id { |
| 279 | return Ok(invalid_grant()); | 292 | return Ok(invalid_grant()); |
| 280 | } | 293 | } |
| 294 | + if let Some(response) = throttled( | ||
| 295 | + app, | ||
| 296 | + &token_family_key(&client.id, &row.family_id), | ||
| 297 | + TOKEN_CHAIN_LIMIT, | ||
| 298 | + ) { | ||
| 299 | + return Ok(response); | ||
| 300 | + } | ||
| 281 | if row.used_at.is_some() { | 301 | if row.used_at.is_some() { |
| 282 | // A rotated token came back. Either the holder or someone who copied it is replaying it: | 302 | // A rotated token came back. Either the holder or someone who copied it is replaying it: |
| 283 | // the whole chain is revoked, so both lose it. | 303 | // the whole chain is revoked, so both lose it. |
crates/im-web/src/pages/admin/message.rsmodified+8 -0
| @@ -38,6 +38,14 @@ const BODY_MAX: usize = 10_000; | |||
| 38 | /// Sends that the limit allows in one window of the throttle. | 38 | /// Sends that the limit allows in one window of the throttle. |
| 39 | const SENDS_PER_WINDOW: usize = 5; | 39 | const SENDS_PER_WINDOW: usize = 5; |
| 40 | 40 | ||
| 41 | +/// Path of the message form. The router raises the body limit for this path (see `boot.rs`). | ||
| 42 | +pub const MESSAGE_ROUTE: &str = "/admin/message"; | ||
| 43 | + | ||
| 44 | +/// The body limit of the message form: every character of the subject and the body at its longest | ||
| 45 | +/// encoding (4 bytes of UTF-8, 3 bytes each once percent-encoded), plus room for the field names and the | ||
| 46 | +/// CSRF token. Smaller would refuse a long Turkish or CJK message before its own length check runs. | ||
| 47 | +pub const MESSAGE_BODY_LIMIT: usize = (SUBJECT_MAX + BODY_MAX) * 4 * 3 + 4 * 1024; | ||
| 48 | + | ||
| 41 | /// The throttle key of the message form. | 49 | /// The throttle key of the message form. |
| 42 | const THROTTLE_KEY: &str = "admin-message"; | 50 | const THROTTLE_KEY: &str = "admin-message"; |
| 43 | 51 | ||
crates/im-web/src/pages/email.rsmodified+32 -28
| @@ -153,7 +153,30 @@ async fn email_request_submit(cx: &Cx, Form(form): Form<EmailRequestForm>) -> Re | |||
| 153 | let old_token = generate_token(); | 153 | let old_token = generate_token(); |
| 154 | let new_token = generate_token(); | 154 | let new_token = generate_token(); |
| 155 | let expires = stamp_after(Duration::from_secs(u64::from(hours) * 60 * 60)); | 155 | let expires = stamp_after(Duration::from_secs(u64::from(hours) * 60 * 60)); |
| 156 | - match state | 156 | + let old_link = format!("{}/email/{old_token}", state.config.base_url); |
| 157 | + let new_link = format!("{}/email/{new_token}", state.config.base_url); | ||
| 158 | + let user_lang = mail::lang_for(&viewer.user, lang); | ||
| 159 | + // Both mails are sealed before the links exist, so the store can check their limits and create the | ||
| 160 | + // links and the mails in one transaction. | ||
| 161 | + let (Ok(old_to), Ok(new_to)) = ( | ||
| 162 | + Recipient::new(Some(&viewer.user.name), &viewer.user.email), | ||
| 163 | + Recipient::new(None, &new_email), | ||
| 164 | + ) else { | ||
| 165 | + tracing::error!("email change not started: an address is not valid"); | ||
| 166 | + return Ok(refuse(Txt::ErrEmailInvalid)); | ||
| 167 | + }; | ||
| 168 | + let old_mail = Mail::EmailOld { | ||
| 169 | + link: &old_link, | ||
| 170 | + new_email: &new_email, | ||
| 171 | + hours, | ||
| 172 | + }; | ||
| 173 | + let new_mail = Mail::EmailNew { | ||
| 174 | + link: &new_link, | ||
| 175 | + hours, | ||
| 176 | + }; | ||
| 177 | + let old_sealed = mail::seal(&state.key, &old_to, user_lang, &old_mail)?; | ||
| 178 | + let new_sealed = mail::seal(&state.key, &new_to, user_lang, &new_mail)?; | ||
| 179 | + let started = match state | ||
| 157 | .store | 180 | .store |
| 158 | .start_email_change( | 181 | .start_email_change( |
| 159 | &viewer.user.id, | 182 | &viewer.user.id, |
| @@ -161,38 +184,19 @@ async fn email_request_submit(cx: &Cx, Form(form): Form<EmailRequestForm>) -> Re | |||
| 161 | &hash_token(&old_token), | 184 | &hash_token(&old_token), |
| 162 | &hash_token(&new_token), | 185 | &hash_token(&new_token), |
| 163 | &expires, | 186 | &expires, |
| 187 | + &[old_sealed.as_new(), new_sealed.as_new()], | ||
| 164 | ) | 188 | ) |
| 165 | .await | 189 | .await |
| 166 | { | 190 | { |
| 167 | - Ok(()) => {} | 191 | + Ok(started) => started, |
| 168 | Err(im_core::Error::Conflict(_)) => return Ok(refuse(Txt::ErrEmailInvalid)), | 192 | Err(im_core::Error::Conflict(_)) => return Ok(refuse(Txt::ErrEmailInvalid)), |
| 169 | Err(error) => return Err(error.into()), | 193 | Err(error) => return Err(error.into()), |
| 170 | - } | 194 | + }; |
| 171 | - | 195 | + // A change dropped by the limits looks the same to the person as a sent one, as the mail limits |
| 172 | - let old_link = format!("{}/email/{old_token}", state.config.base_url); | 196 | + // always have: the answer does not show the limits. |
| 173 | - let new_link = format!("{}/email/{new_token}", state.config.base_url); | 197 | + if !started { |
| 174 | - let user_lang = mail::lang_for(&viewer.user, lang); | 198 | + tracing::info!("email change dropped by the mail limits; no link created"); |
| 175 | - if let Ok(to) = Recipient::new(Some(&viewer.user.name), &viewer.user.email) { | 199 | + return Err(see_other("/account/email?notice=sent").into()); |
| 176 | - let mail = Mail::EmailOld { | ||
| 177 | - link: &old_link, | ||
| 178 | - new_email: &new_email, | ||
| 179 | - hours, | ||
| 180 | - }; | ||
| 181 | - if let Err(error) = mail::queue(&state.store, &state.key, &to, user_lang, &mail).await { | ||
| 182 | - tracing::error!(error = %error, "email change mail to the old address not queued"); | ||
| 183 | - } | ||
| 184 | - } | ||
| 185 | - match Recipient::new(None, &new_email) { | ||
| 186 | - Ok(to) => { | ||
| 187 | - let mail = Mail::EmailNew { | ||
| 188 | - link: &new_link, | ||
| 189 | - hours, | ||
| 190 | - }; | ||
| 191 | - if let Err(error) = mail::queue(&state.store, &state.key, &to, user_lang, &mail).await { | ||
| 192 | - tracing::error!(error = %error, "email change mail to the new address not queued"); | ||
| 193 | - } | ||
| 194 | - } | ||
| 195 | - Err(error) => tracing::error!(error, "email change mail to the new address not queued"), | ||
| 196 | } | 200 | } |
| 197 | record( | 201 | record( |
| 198 | cx, | 202 | cx, |
crates/im-web/src/pages/login.rsmodified+19 -12
| @@ -221,22 +221,25 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form<TwoFactorForm>) -> Result<i | |||
| 221 | )); | 221 | )); |
| 222 | } | 222 | } |
| 223 | 223 | ||
| 224 | - match check_second_factor(&state.store, &state.key, &user, &form.code).await? { | 224 | + // The pending cookie is good for one sign-in, so its nonce is claimed before any code is checked. A |
| 225 | - Some(method) => { | 225 | + // parallel submission then cannot spend a recovery code for a sign-in that never happens. A wrong code |
| 226 | - // The pending cookie is good for one sign-in. A second use of it is refused like an expired one. | 226 | + // gives the claim back, so a typo does not end the pending login. |
| 227 | - let spent = state | 227 | + let claimed = state |
| 228 | - .store | 228 | + .store |
| 229 | - .consume_pending_login(&pending.nonce, &stamp_after(PENDING_TTL)) | 229 | + .consume_pending_login(&pending.nonce, &stamp_after(PENDING_TTL)) |
| 230 | - .await?; | 230 | + .await?; |
| 231 | - if !spent { | 231 | + if !claimed { |
| 232 | - clear_pending_login(cx); | 232 | + clear_pending_login(cx); |
| 233 | - return Err(see_other("/login").into()); | 233 | + return Err(see_other("/login").into()); |
| 234 | - } | 234 | + } |
| 235 | + match check_second_factor(&state.store, &state.key, &user, &form.code).await { | ||
| 236 | + Ok(Some(method)) => { | ||
| 235 | state.throttle.clear(&limit); | 237 | state.throttle.clear(&limit); |
| 236 | clear_pending_login(cx); | 238 | clear_pending_login(cx); |
| 237 | Err(finish_sign_in(cx, &user, method, &pending.next).await?) | 239 | Err(finish_sign_in(cx, &user, method, &pending.next).await?) |
| 238 | } | 240 | } |
| 239 | - None => { | 241 | + Ok(None) => { |
| 242 | + state.store.release_pending_login(&pending.nonce).await?; | ||
| 240 | record( | 243 | record( |
| 241 | cx, | 244 | cx, |
| 242 | Actor::User(&user.id), | 245 | Actor::User(&user.id), |
| @@ -253,6 +256,10 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form<TwoFactorForm>) -> Result<i | |||
| 253 | false, | 256 | false, |
| 254 | )) | 257 | )) |
| 255 | } | 258 | } |
| 259 | + Err(error) => { | ||
| 260 | + state.store.release_pending_login(&pending.nonce).await?; | ||
| 261 | + Err(error) | ||
| 262 | + } | ||
| 256 | } | 263 | } |
| 257 | } | 264 | } |
| 258 | 265 | ||
crates/im-web/src/pages/reset.rsmodified+34 -19
| @@ -120,8 +120,10 @@ async fn forgot_submit(cx: &Cx, Form(form): Form<ForgotForm>) -> Result<impl Vie | |||
| 120 | Ok(forgot_view(cx, lang, pre_csrf_token(cx), true)) | 120 | Ok(forgot_view(cx, lang, pre_csrf_token(cx), true)) |
| 121 | } | 121 | } |
| 122 | 122 | ||
| 123 | -/// Creates a reset link for `user` and queues its mail, in the background. Failures are logged; the | 123 | +/// Creates a reset link for `user` and queues its mail, in the background. The mail is sealed first and the |
| 124 | -/// person who asked sees the same answer either way. | 124 | +/// store checks its cooldown in the same transaction that creates the link, so a request inside the cooldown |
| 125 | +/// creates no link and leaves the older one working. Failures are logged; the person who asked sees the same | ||
| 126 | +/// answer either way. | ||
| 125 | fn spawn_reset( | 127 | fn spawn_reset( |
| 126 | store: Store, | 128 | store: Store, |
| 127 | key: Arc<[u8; 32]>, | 129 | key: Arc<[u8; 32]>, |
| @@ -134,26 +136,39 @@ fn spawn_reset( | |||
| 134 | tokio::spawn(async move { | 136 | tokio::spawn(async move { |
| 135 | let token = generate_token(); | 137 | let token = generate_token(); |
| 136 | let expires = stamp_after(Duration::from_secs(u64::from(minutes) * 60)); | 138 | let expires = stamp_after(Duration::from_secs(u64::from(minutes) * 60)); |
| 137 | - if let Err(error) = store | ||
| 138 | - .create_reset_link(&user.id, &hash_token(&token), &expires) | ||
| 139 | - .await | ||
| 140 | - { | ||
| 141 | - tracing::error!(error = %error, "reset link not created"); | ||
| 142 | - return; | ||
| 143 | - } | ||
| 144 | let link = format!("{base_url}/reset/{token}"); | 139 | let link = format!("{base_url}/reset/{token}"); |
| 145 | let lang = mail::lang_for(&user, lang); | 140 | let lang = mail::lang_for(&user, lang); |
| 146 | - match Recipient::new(Some(&user.name), &user.email) { | 141 | + let to = match Recipient::new(Some(&user.name), &user.email) { |
| 147 | - Ok(to) => { | 142 | + Ok(to) => to, |
| 148 | - let mail = Mail::Reset { | 143 | + Err(error) => { |
| 149 | - link: &link, | 144 | + tracing::error!(error, "reset mail not queued"); |
| 150 | - minutes, | 145 | + return; |
| 151 | - }; | 146 | + } |
| 152 | - if let Err(error) = mail::queue(&store, &key, &to, lang, &mail).await { | 147 | + }; |
| 153 | - tracing::error!(error = %error, "reset mail not queued"); | 148 | + let mail = Mail::Reset { |
| 154 | - } | 149 | + link: &link, |
| 150 | + minutes, | ||
| 151 | + }; | ||
| 152 | + let sealed = match mail::seal(&key, &to, lang, &mail) { | ||
| 153 | + Ok(sealed) => sealed, | ||
| 154 | + Err(error) => { | ||
| 155 | + tracing::error!(error = %error, "reset mail not queued"); | ||
| 156 | + return; | ||
| 157 | + } | ||
| 158 | + }; | ||
| 159 | + match store | ||
| 160 | + .create_reset_link(&user.id, &hash_token(&token), &expires, &sealed.as_new()) | ||
| 161 | + .await | ||
| 162 | + { | ||
| 163 | + Ok(Some(_)) => {} | ||
| 164 | + Ok(None) => { | ||
| 165 | + tracing::info!("reset mail dropped by the cooldown; no link created"); | ||
| 166 | + return; | ||
| 167 | + } | ||
| 168 | + Err(error) => { | ||
| 169 | + tracing::error!(error = %error, "reset link not created"); | ||
| 170 | + return; | ||
| 155 | } | 171 | } |
| 156 | - Err(error) => tracing::error!(error, "reset mail not queued"), | ||
| 157 | } | 172 | } |
| 158 | let entry = NewAudit { | 173 | let entry = NewAudit { |
| 159 | actor_id: None, | 174 | actor_id: None, |
crates/im-web/src/throttle.rsmodified+36 -7
| @@ -68,8 +68,13 @@ pub const EMAIL_CHANGE_LIMIT: usize = 3; | |||
| 68 | /// with the `temporarily_unavailable` redirect. | 68 | /// with the `temporarily_unavailable` redirect. |
| 69 | pub const AUTHORIZE_SESSION_LIMIT: usize = 60; | 69 | pub const AUTHORIZE_SESSION_LIMIT: usize = 60; |
| 70 | 70 | ||
| 71 | -/// Requests allowed per authenticated client inside [`MINUTE`] at `/token`. | 71 | +/// Requests allowed per authenticated client inside [`MINUTE`] at `/token`, over all its grants together. |
| 72 | -pub const TOKEN_CLIENT_LIMIT: usize = 120; | 72 | +/// A client with many users shares this ceiling, so it is set well above one person's use. |
| 73 | +pub const TOKEN_CLIENT_LIMIT: usize = 1200; | ||
| 74 | + | ||
| 75 | +/// Requests allowed inside [`MINUTE`] for one refresh-token family, or for one authorization code, at | ||
| 76 | +/// `/token`. One person uses one chain or one code, so this is what limits a flood on a single one. | ||
| 77 | +pub const TOKEN_CHAIN_LIMIT: usize = 30; | ||
| 73 | 78 | ||
| 74 | /// `LoginFailed` audit rows written per account, or per client address when the account is unknown, inside | 79 | /// `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. | 80 | /// [`MINUTE`]. Failures beyond it are still refused and counted; only their audit rows are skipped. |
| @@ -82,10 +87,14 @@ const MAX_KEYS: usize = 100_000; | |||
| 82 | /// A full prune runs every this many attempts. | 87 | /// A full prune runs every this many attempts. |
| 83 | const PRUNE_EVERY: u32 = 256; | 88 | const PRUNE_EVERY: u32 = 256; |
| 84 | 89 | ||
| 85 | -/// The part of an email key used for an address that is too long or not plausible. Contains `<`, which | 90 | +/// The part of an email key used for an address that is not plausible. Starts with `<`, which no valid |
| 86 | -/// no valid address contains, so it never collides with a real address. | 91 | +/// address contains, so it never collides with a real address. |
| 87 | const INVALID_ADDRESS: &str = "<invalid>"; | 92 | const INVALID_ADDRESS: &str = "<invalid>"; |
| 88 | 93 | ||
| 94 | +/// The most bytes of a raw, unparseable address that go into its key. Longer input is cut here, so the | ||
| 95 | +/// key stays bounded. | ||
| 96 | +const MAX_RAW_ADDRESS_BYTES: usize = 320; | ||
| 97 | + | ||
| 89 | /// The failure counters of the process. Shared by every request through the app state. | 98 | /// The failure counters of the process. Shared by every request through the app state. |
| 90 | pub struct Throttle { | 99 | pub struct Throttle { |
| 91 | window: Duration, | 100 | window: Duration, |
| @@ -289,12 +298,22 @@ fn wait_for(stamps: &VecDeque<Instant>, limit: usize, window: Duration, now: Ins | |||
| 289 | }) | 298 | }) |
| 290 | } | 299 | } |
| 291 | 300 | ||
| 292 | -/// The part of an email key for `email`: the address itself when it is plausible and short, otherwise | 301 | +/// The part of an email key for `email`: the address itself when it is plausible, otherwise the marker |
| 293 | -/// one fixed sentinel. The sentinel keeps the keys of junk input bounded, and the answer the same. | 302 | +/// and the raw text, trimmed, lowercased and cut to [`MAX_RAW_ADDRESS_BYTES`]. Each junk address gets its |
| 303 | +/// own key, so one junk address cannot lock out a real account whose stored address happens to be | ||
| 304 | +/// unparseable under the current rules. | ||
| 294 | fn address_part(email: &str) -> String { | 305 | fn address_part(email: &str) -> String { |
| 295 | match parse_email(email) { | 306 | match parse_email(email) { |
| 296 | Ok(address) => address, | 307 | Ok(address) => address, |
| 297 | - Err(_) => INVALID_ADDRESS.to_owned(), | 308 | + Err(_) => { |
| 309 | + let raw = email.trim().to_lowercase(); | ||
| 310 | + // Cut on a character boundary at or below the cap. | ||
| 311 | + let cut = (0..=raw.len().min(MAX_RAW_ADDRESS_BYTES)) | ||
| 312 | + .rev() | ||
| 313 | + .find(|&i| raw.is_char_boundary(i)) | ||
| 314 | + .unwrap_or(0); | ||
| 315 | + format!("{INVALID_ADDRESS}{}", &raw[..cut]) | ||
| 316 | + } | ||
| 298 | } | 317 | } |
| 299 | } | 318 | } |
| 300 | 319 | ||
| @@ -333,6 +352,16 @@ pub fn token_client_key(client_id: &str) -> String { | |||
| 333 | format!("token:{client_id}") | 352 | format!("token:{client_id}") |
| 334 | } | 353 | } |
| 335 | 354 | ||
| 355 | +/// Throttle key for the refresh requests of one token family (one chain) of a client. | ||
| 356 | +pub fn token_family_key(client_id: &str, family_id: &str) -> String { | ||
| 357 | + format!("token-family:{client_id}:{family_id}") | ||
| 358 | +} | ||
| 359 | + | ||
| 360 | +/// Throttle key for the code exchanges of one authorization code of a client, by the code's hash. | ||
| 361 | +pub fn token_code_key(client_id: &str, code_hash: &str) -> String { | ||
| 362 | + format!("token-code:{client_id}:{code_hash}") | ||
| 363 | +} | ||
| 364 | + | ||
| 336 | /// Throttle key for the `LoginFailed` audit rows of one account, by user id. | 365 | /// Throttle key for the `LoginFailed` audit rows of one account, by user id. |
| 337 | pub fn login_audit_user_key(user_id: &str) -> String { | 366 | pub fn login_audit_user_key(user_id: &str) -> String { |
| 338 | format!("login-audit-user:{user_id}") | 367 | format!("login-audit-user:{user_id}") |
docs/architecture.mdmodified+7 -3
| @@ -207,8 +207,9 @@ redirects). Other errors redirect to the client with `error=` and `state`. | |||
| 207 | `max_sessions` per user: the oldest is ended (with back-channel) when exceeded. | 207 | `max_sessions` per user: the oldest is ended (with back-channel) when exceeded. |
| 208 | - Limits beyond the failure counters (`throttle.rs`, in memory, refused with `429` or an OAuth error): | 208 | - Limits beyond the failure counters (`throttle.rs`, in memory, refused with `429` or an OAuth error): |
| 209 | `/authorize` issues at most 60 codes a minute per session (over it, `error=temporarily_unavailable` goes to | 209 | `/authorize` issues at most 60 codes a minute per session (over it, `error=temporarily_unavailable` goes to |
| 210 | - the redirect URI); `/token` allows 120 requests a minute per authenticated client; an account asks for at most | 210 | + the redirect URI); `/token` allows 1200 requests a minute per authenticated client, and 30 a minute per |
| 211 | - 3 email changes an hour; each form route reads at most 16 KiB, and the photo route keeps its own limit. | 211 | + refresh-token family or authorization code; an account asks for at most 3 email changes an hour; each form |
| 212 | + route reads at most 16 KiB, and the photo and admin message routes keep their own limits. | ||
| 212 | - Password change ends every other session; reset ends all. Disable and delete end all and queue | 213 | - Password change ends every other session; reset ends all. Disable and delete end all and queue |
| 213 | back-channel logout by `sub`. | 214 | back-channel logout by `sub`. |
| 214 | - TOTP enroll: secret generated and held sealed in a pending state until a valid code confirms it; enrolling | 215 | - TOTP enroll: secret generated and held sealed in a pending state until a valid code confirms it; enrolling |
| @@ -224,7 +225,10 @@ redirects). Other errors redirect to the client with `error=` and `state`. | |||
| 224 | 225 | ||
| 225 | `authz::authorize(actor, action) -> Result<(), Denied>` where `actor` is `Anonymous`, `User { id, is_admin }` | 226 | `authz::authorize(actor, action) -> Result<(), Denied>` where `actor` is `Anonymous`, `User { id, is_admin }` |
| 226 | or `Client { id, scopes, service_key }`, and `action` is an enum (`ViewOwnAccount`, `EditOwnAccount`, | 227 | or `Client { id, scopes, service_key }`, and `action` is an enum (`ViewOwnAccount`, `EditOwnAccount`, |
| 227 | -`ViewPerson`, `Administer`, `ReadDirectory`, `ReadFamily`, ...). Admin pages answer 404 to non-admins. | 228 | +`ViewPerson`, `Administer`, `ReadDirectory`, `ReadFamily`, ...). Admin pages answer 404 to non-admins. An |
| 229 | +admin page with no live session (a visitor, or an administrator whose session expired) also answers 404, not a | ||
| 230 | +redirect to sign-in, so the admin area does not show itself to visitors. The administrator signs in again from | ||
| 231 | +`/login` and opens the page from there. | ||
| 228 | Rules that are not role checks (last admin cannot be demoted or disabled, an admin cannot disable themself) live | 232 | Rules that are not role checks (last admin cannot be demoted or disabled, an admin cannot disable themself) live |
| 229 | in the store as single conditional statements so they cannot race. | 233 | in the store as single conditional statements so they cannot race. |
| 230 | 234 | ||