From c7a3c1d759c49c46c241a941677e6b727f1a0580 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 13:27:09 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix:=20reset=20and=20email-chang?= =?UTF-8?q?e=20links=20only=20replaced=20when=20their=20mail=20is=20admitt?= =?UTF-8?q?ed,=20client=20sign-out=20in=20one=20step,=20larger=20admin=20m?= =?UTF-8?q?essage=20limit,=20alive=20stream=20re-checks,=20photo=20limits?= =?UTF-8?q?=20by=20decoded=20size,=20token=20throttle=20per=20chain,=20per?= =?UTF-8?q?-address=20junk=20keys,=20reset=20mail=20never=20capped,=20pend?= =?UTF-8?q?ing=20login=20claimed=20before=20the=20second=20factor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- crates/im-core/src/photo.rs | 26 +++--- crates/im-core/src/store/links.rs | 61 +++++++++++--- crates/im-core/src/store/mail.rs | 102 +++++++++++++---------- crates/im-core/src/store/users.rs | 14 ++++ crates/im-web/assets/pages.js | 16 +++- crates/im-web/src/boot.rs | 6 +- crates/im-web/src/i18n/account.rs | 6 +- crates/im-web/src/live.rs | 50 ++++++----- crates/im-web/src/mail/mod.rs | 61 ++++++++++---- crates/im-web/src/oidc/logout.rs | 12 ++- crates/im-web/src/oidc/token.rs | 42 +++++++--- crates/im-web/src/pages/admin/message.rs | 8 ++ crates/im-web/src/pages/email.rs | 60 ++++++------- crates/im-web/src/pages/login.rs | 31 ++++--- crates/im-web/src/pages/reset.rs | 53 +++++++----- crates/im-web/src/throttle.rs | 43 ++++++++-- docs/architecture.md | 10 ++- 18 files changed, 406 insertions(+), 197 deletions(-) diff --git a/README.md b/README.md index 6491164..06cbbee 100644 --- a/README.md +++ b/README.md @@ -115,7 +115,7 @@ im --config /etc/im/im.toml restore --from # verify, then restore the snapshot's integrity and schema. A tampered set is refused. A verified set replaces the database and the photos; the previous database and photos are moved into a `restore-` directory inside `data_dir`, so nothing is lost. `restore` refuses to run while the server (or another `im` command) holds the data directory, -so stop the service first. +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. ## Signing keys diff --git a/crates/im-core/src/photo.rs b/crates/im-core/src/photo.rs index e18ee94..1c53860 100644 --- a/crates/im-core/src/photo.rs +++ b/crates/im-core/src/photo.rs @@ -28,12 +28,13 @@ pub const MAX_UPLOAD_BYTES: usize = 5 * 1024 * 1024; pub const MAX_SIDE: u32 = 512; /// Longest side an input may have, in pixels. Larger inputs are refused from the header, before any -/// pixel is decoded. At this side an RGBA picture is exactly [`MAX_DECODE_ALLOC`]. -const MAX_INPUT_SIDE: u32 = 4096; +/// pixel is decoded. +const MAX_INPUT_SIDE: u32 = 8000; -/// Most memory the decoder may allocate for one input, in bytes (64 MiB). A 4096 x 4096 RGBA picture -/// fills it exactly, so the side limit and the allocation limit agree. -const MAX_DECODE_ALLOC: u64 = 64 * 1024 * 1024; +/// Most memory the decoder may allocate for one input, in bytes (96 MiB). An input is refused from its +/// header when its pixels as RGBA would need more than this, so a 4096 x 4096 phone picture fits and an +/// 8000 x 8000 one is refused before any pixel is decoded. +const MAX_DECODE_ALLOC: u64 = 96 * 1024 * 1024; /// Decodes that may run at once. Each one holds up to [`MAX_DECODE_ALLOC`], so a burst of uploads queues /// behind two permits instead of starting one blocking thread and one decode per request. @@ -55,10 +56,11 @@ fn refused() -> Error { /// Turns an upload into the stored picture: a square WebP of at most [`MAX_SIDE`] pixels. /// -/// Refuses anything whose bytes are not PNG, JPEG, WebP or GIF, whatever its name says. A picture with a side -/// longer than [`MAX_INPUT_SIDE`] is refused with [`Error::PictureTooLarge`], so the uploader sees the size -/// as the reason. Any other image that is larger than the input limits or cannot be decoded is refused too. -/// Only the first frame of an animated GIF is kept. +/// Refuses anything whose bytes are not PNG, JPEG, WebP or GIF, whatever its name says. A picture with a +/// side longer than [`MAX_INPUT_SIDE`], or whose RGBA pixels would need more than [`MAX_DECODE_ALLOC`], is +/// refused with [`Error::PictureTooLarge`], so the uploader sees the size as the reason. Any other image +/// that is larger than the input limits or cannot be decoded is refused too. Only the first frame of an +/// animated GIF is kept. pub fn normalize_photo(input: &[u8]) -> Result> { let format = image::guess_format(input).map_err(|_| refused())?; let accepted = matches!( @@ -78,7 +80,11 @@ pub fn normalize_photo(input: &[u8]) -> Result> { let (declared_width, declared_height) = ImageReader::with_format(Cursor::new(input), format) .into_dimensions() .map_err(decode_error)?; - if declared_width > MAX_INPUT_SIDE || declared_height > MAX_INPUT_SIDE { + let rgba_bytes = u64::from(declared_width) * u64::from(declared_height) * 4; + if declared_width > MAX_INPUT_SIDE + || declared_height > MAX_INPUT_SIDE + || rgba_bytes > MAX_DECODE_ALLOC + { return Err(Error::PictureTooLarge); } let mut reader = ImageReader::with_format(Cursor::new(input), format); diff --git a/crates/im-core/src/store/links.rs b/crates/im-core/src/store/links.rs index c938c46..8e36217 100644 --- a/crates/im-core/src/store/links.rs +++ b/crates/im-core/src/store/links.rs @@ -13,6 +13,7 @@ use turso::Connection; use crate::error::{Error, Result}; use crate::store::backchannel::EndReason; use crate::store::directory::{ChangeKind, record_change}; +use crate::store::mail::{NewMail, admitted, insert_mail}; use crate::store::sessions::end_all_sessions; use crate::store::users::insert_error; 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 } impl Store { - /// Creates a password-reset link. Older pending reset links of the person stop working. The - /// caller has checked that the person exists and is not disabled. + /// Creates a password-reset link and queues its `mail` in one transaction. The mail is checked first + /// (see `store::mail`): when it would be dropped, nothing changes, so an older link that was mailed + /// keeps working and no new link is made that nobody receives. Otherwise older pending reset links of + /// the person stop working. Returns the outbox id, or `None` when the mail was dropped. The caller has + /// checked that the person exists and is not disabled. pub async fn create_reset_link( &self, user_id: &str, token_hash: &str, expires_at: &str, - ) -> Result<()> { + mail: &NewMail<'_>, + ) -> Result> { let now = now_stamp(); let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; - let outcome: Result<()> = async { + let outcome: Result> = async { + if !admitted(&tx, mail).await? { + return Ok(None); + } tx.execute( "UPDATE account_links SET used_at = ?2 \ WHERE user_id = ?1 AND kind = 'reset' AND used_at IS NULL", @@ -107,7 +115,7 @@ impl Store { ) .await .map_err(db_err)?; - Ok(()) + Ok(Some(insert_mail(&tx, mail).await?)) } .await; finish(tx, outcome).await @@ -197,9 +205,11 @@ impl Store { finish(tx, outcome).await } - /// Starts an email change: two links, one for each address, sharing a pair id. Older pending email - /// links of the person stop working. Fails with a conflict when `new_email` belongs to an account. - /// `expires_at` is the same for both halves. + /// Starts an email change: two links, one for each address, sharing a pair id, with their two mails + /// (`mails[0]` to the current address, `mails[1]` to the new one). Older pending email links of the + /// person stop working. Fails with a conflict when `new_email` belongs to an account. When either mail + /// would be dropped by the limits, nothing changes and the answer is `false`. `expires_at` is the same + /// for both halves. pub async fn start_email_change( &self, user_id: &str, @@ -207,12 +217,13 @@ impl Store { old_token_hash: &str, new_token_hash: &str, expires_at: &str, - ) -> Result<()> { + mails: &[NewMail<'_>; 2], + ) -> Result { let now = now_stamp(); let pair = new_id(); let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; - let outcome: Result<()> = async { + let outcome: Result = async { let taken = fetch_opt( &tx, "SELECT 1 FROM users WHERE email_folded = ?1", @@ -225,6 +236,11 @@ impl Store { "that email address cannot be used".into(), )); } + for mail in mails { + if !admitted(&tx, mail).await? { + return Ok(false); + } + } invalidate_links_of_kinds(&tx, user_id, &now).await?; for (token_hash, kind) in [(old_token_hash, "email_old"), (new_token_hash, "email_new")] { tx.execute( @@ -243,7 +259,10 @@ impl Store { .await .map_err(db_err)?; } - Ok(()) + for mail in mails { + insert_mail(&tx, mail).await?; + } + Ok(true) } .await; finish(tx, outcome).await @@ -383,6 +402,15 @@ mod tests { use crate::time::stamp_after; use std::time::Duration; + fn test_mail(kind: &'static str) -> NewMail<'static> { + NewMail { + kind, + to_addr: "ada@example.com", + subject: "Subject", + sealed_body: "v1:sealed", + } + } + async fn setup() -> (tempfile::TempDir, Store, String) { let dir = tempfile::tempdir().unwrap(); let store = Store::open(&dir.path().join("im.db")).await.unwrap(); @@ -401,6 +429,7 @@ mod tests { &user_id, "reset-hash", &stamp_after(Duration::from_secs(3600)), + &test_mail("reset"), ) .await .unwrap(); @@ -428,6 +457,7 @@ mod tests { &user_id, "reset-hash", &stamp_after(Duration::from_secs(3600)), + &test_mail("reset"), ) .await .unwrap(); @@ -453,7 +483,14 @@ mod tests { let (_dir, store, user_id) = setup().await; let later = stamp_after(Duration::from_secs(3600)); store - .start_email_change(&user_id, "ada.new@example.com", "h-old", "h-new", &later) + .start_email_change( + &user_id, + "ada.new@example.com", + "h-old", + "h-new", + &later, + &[test_mail("email_old"), test_mail("email_new")], + ) .await .unwrap(); // Someone else registers the new address before either half is confirmed. diff --git a/crates/im-core/src/store/mail.rs b/crates/im-core/src/store/mail.rs index 491ed7b..5d48ae8 100644 --- a/crates/im-core/src/store/mail.rs +++ b/crates/im-core/src/store/mail.rs @@ -6,19 +6,26 @@ //! 30 days after they were sent. Nothing here logs a body or a recipient. //! //! Two limits keep one address from being mailed without end. An address may hold at most -//! [`PENDING_PER_ADDRESS`] unsent rows, and a reset mail is not queued again inside [`RESET_COOLDOWN`]. -//! A mail over either limit is dropped without any error, so the answer to the caller never depends on -//! whether the address has an account. +//! [`PENDING_PER_ADDRESS`] rows that are still `pending`, and a reset mail is not queued again inside +//! [`RESET_COOLDOWN`]. The cap never applies to reset mail, so a person who asks for a reset is always +//! sent one (the cooldown still limits how often). A mail over a limit is dropped without any error, so +//! the answer to the caller never depends on whether the address has an account. +//! +//! The limits are checked by [`admitted`] under the same transaction that creates the links a mail +//! carries (see `store::links`), so a dropped mail never leaves a live link behind. use std::time::Duration; +use turso::Connection; + use crate::error::Result; use crate::store::{ Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, missing_row, new_id, }; use crate::time::{now_stamp, stamp_before}; -/// Most unsent rows (`pending` or `failed`) one recipient address may hold. Mail over it is dropped. +/// Most `pending` rows one recipient address may hold. Mail over it is dropped, except reset mail. Rows +/// that failed are not counted: their retries are already scheduled and they are not new mail. pub const PENDING_PER_ADDRESS: i64 = 10; /// 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 { }) } +/// Whether `new` may be queued now: the cooldown for reset mail, and the cap on `pending` rows for any +/// other kind. `conn` is the writer, or a transaction on it, so the answer holds for the insert that follows. +pub(crate) async fn admitted(conn: &Connection, new: &NewMail<'_>) -> Result { + if new.kind == "reset" { + let recent = fetch_opt( + conn, + "SELECT COUNT(*) FROM mail_outbox WHERE to_addr = ?1 AND kind = 'reset' AND created_at >= ?2", + (new.to_addr.to_string(), stamp_before(RESET_COOLDOWN)), + |row| col_int(row, 0), + ) + .await? + .ok_or_else(missing_row)?; + return Ok(recent == 0); + } + let pending = fetch_opt( + conn, + "SELECT COUNT(*) FROM mail_outbox WHERE to_addr = ?1 AND state = 'pending'", + (new.to_addr.to_string(),), + |row| col_int(row, 0), + ) + .await? + .ok_or_else(missing_row)?; + Ok(pending < PENDING_PER_ADDRESS) +} + +/// Inserts one `pending` row for `new` and returns its id. Callers check [`admitted`] first, under the +/// same connection or transaction. +pub(crate) async fn insert_mail(conn: &Connection, new: &NewMail<'_>) -> Result { + let id = new_id(); + conn.execute( + "INSERT INTO mail_outbox (id, kind, to_addr, subject, body_text, state, attempts, \ + next_attempt_at, created_at) VALUES (?1, ?2, ?3, ?4, ?5, 'pending', 0, ?6, ?6)", + ( + id.clone(), + new.kind.to_string(), + new.to_addr.to_string(), + new.subject.to_string(), + new.sealed_body.to_string(), + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + Ok(id) +} + impl Store { /// Adds a mail to the outbox, to be sent as soon as the worker looks. Returns its id, or `None` when the /// mail is dropped by [`PENDING_PER_ADDRESS`] or by [`RESET_COOLDOWN`]. The checks and the insert run /// under the writer, so parallel requests cannot pass a limit together. pub async fn enqueue_mail(&self, new: &NewMail<'_>) -> Result> { - let id = new_id(); - let now = now_stamp(); let conn = self.inner.conn.lock().await; - let unsent = fetch_opt( - &conn, - "SELECT COUNT(*) FROM mail_outbox WHERE to_addr = ?1 AND state IN ('pending', 'failed')", - (new.to_addr.to_string(),), - |row| col_int(row, 0), - ) - .await? - .ok_or_else(missing_row)?; - if unsent >= PENDING_PER_ADDRESS { + if !admitted(&conn, new).await? { return Ok(None); } - if new.kind == "reset" { - let recent = fetch_opt( - &conn, - "SELECT COUNT(*) FROM mail_outbox WHERE to_addr = ?1 AND kind = 'reset' AND created_at >= ?2", - (new.to_addr.to_string(), stamp_before(RESET_COOLDOWN)), - |row| col_int(row, 0), - ) - .await? - .ok_or_else(missing_row)?; - if recent > 0 { - return Ok(None); - } - } - conn.execute( - "INSERT INTO mail_outbox (id, kind, to_addr, subject, body_text, state, attempts, \ - next_attempt_at, created_at) VALUES (?1, ?2, ?3, ?4, ?5, 'pending', 0, ?6, ?6)", - ( - id.clone(), - new.kind.to_string(), - new.to_addr.to_string(), - new.subject.to_string(), - new.sealed_body.to_string(), - now, - ), - ) - .await - .map_err(db_err)?; - Ok(Some(id)) + Ok(Some(insert_mail(&conn, new).await?)) } /// Rows that are due: never tried, or failed and whose retry time has come. Oldest first. diff --git a/crates/im-core/src/store/users.rs b/crates/im-core/src/store/users.rs index 8c94c3e..74c2d50 100644 --- a/crates/im-core/src/store/users.rs +++ b/crates/im-core/src/store/users.rs @@ -522,6 +522,20 @@ impl Store { Ok(changed == 1) } + /// Gives back a nonce that [`Store::consume_pending_login`] claimed, when the second factor was wrong, so + /// the person can try again with the same pending login. Only a claim that did not lead to a sign-in is + /// given back. + pub async fn release_pending_login(&self, nonce: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM consumed_pending_logins WHERE nonce = ?1", + (nonce.to_string(),), + ) + .await + .map_err(db_err)?; + Ok(()) + } + /// Records `step` as the last accepted TOTP step. Returns true only when that moved the guard /// forward. A step that is not later than the recorded one, or any step while two-factor is off, /// returns false. This is the replay guard: a code is spent by this single statement. diff --git a/crates/im-web/assets/pages.js b/crates/im-web/assets/pages.js index faa95d2..3523650 100644 --- a/crates/im-web/assets/pages.js +++ b/crates/im-web/assets/pages.js @@ -1,9 +1,17 @@ /* - * pages.js: small behaviours of individual pages (a dropdown search, a copy button and so on). It - * is empty for now. The file exists so the shell can load it and its content hash is already in the - * page links. Each behaviour, when it is added, does nothing unless its own data attribute is on the - * page. Like nav.js, it is one IIFE with no globals. + * pages.js: small behaviours of individual pages (a dropdown search, a copy button and so on). Each + * behaviour does nothing unless its own data attribute is on the page. Like nav.js, it is one IIFE + * with no globals. + * + * - data-auto-submit="true": such a form is submitted once when the page loads. The + * relying-party sign-out (GET /logout) uses it, so the browser goes back to the client in one + * step. The form has a visible button for pages without JS. The form also carries data-hard, so + * nav.js leaves its submit to the browser. */ (function () { "use strict"; + + document.querySelectorAll("form[data-auto-submit='true']").forEach((form) => { + form.requestSubmit(); + }); })(); diff --git a/crates/im-web/src/boot.rs b/crates/im-web/src/boot.rs index 621efba..bd7a64b 100644 --- a/crates/im-web/src/boot.rs +++ b/crates/im-web/src/boot.rs @@ -25,6 +25,7 @@ use crate::backchannel; use crate::live::{LiveHub, MAX_ANONYMOUS_STREAMS}; use crate::mail; use crate::oidc::signing; +use crate::pages::admin::message::{MESSAGE_BODY_LIMIT, MESSAGE_ROUTE}; use crate::pages::not_found::NotFoundLayer; use crate::pages::profile::PHOTO_ROUTE; use crate::security::{self, SecurityHeaders}; @@ -210,8 +211,8 @@ const PHOTO_BODY_LIMIT: usize = MAX_UPLOAD_BYTES + 64 * 1024; const FORM_BODY_LIMIT: usize = 16 * 1024; /// The router of the server: every route and page found by `discover`, the cookie jar, the security -/// headers on every response, the styled 404 for browsers, the body limit of forms, and the upload limit -/// of the photo route (which overrides the form limit under its path). +/// headers on every response, the styled 404 for browsers, the body limit of forms, and the larger limits +/// of the photo upload and the admin message (which override the form limit under their paths). pub fn router(state: AppState) -> Router { let security = SecurityHeaders::new(security::headers_for(&state.config.base_url)); Router::builder() @@ -220,6 +221,7 @@ pub fn router(state: AppState) -> Router { .cookies() .layer(BodyLimit::max(FORM_BODY_LIMIT)) .layer(BodyLimit::max(PHOTO_BODY_LIMIT).at(PHOTO_ROUTE)) + .layer(BodyLimit::max(MESSAGE_BODY_LIMIT).at(MESSAGE_ROUTE)) .layer(security) .layer(NotFoundLayer) .build() diff --git a/crates/im-web/src/i18n/account.rs b/crates/im-web/src/i18n/account.rs index 5d1e8ca..6201531 100644 --- a/crates/im-web/src/i18n/account.rs +++ b/crates/im-web/src/i18n/account.rs @@ -210,7 +210,7 @@ pub enum Txt { ErrPhotoType, /// Shown when the upload is over the size limit. ErrPhotoTooLarge, - /// Shown when the picture has a side longer than the decoder accepts (4096 pixels). + /// Shown when the picture has a side longer than 8000 pixels, or more than 24 megapixels in all. ErrPhotoDimensions, /// Shown when the upload form was sent without a file. ErrPhotoMissing, @@ -512,10 +512,10 @@ pub fn text(lang: Lang, key: Txt) -> &'static str { (Txt::ErrPhotoTooLarge, Lang::En) => "The photo is larger than 5 MB.", (Txt::ErrPhotoTooLarge, Lang::Tr) => "Fotoğraf 5 MB'tan büyük.", (Txt::ErrPhotoDimensions, Lang::En) => { - "The picture is too large; use one at most 4096 pixels on each side." + "The picture is too large; use one at most 8000 pixels on each side and 24 megapixels in all." } (Txt::ErrPhotoDimensions, Lang::Tr) => { - "Resim çok büyük; en fazla her kenarı 4096 piksel olan bir resim kullanın." + "Resim çok büyük; her kenarı en fazla 8000 piksel, toplamı en fazla 24 megapiksel olan bir resim kullanın." } (Txt::ErrPhotoRateLimited, Lang::En) => { "Too many photos were uploaded. Try again in an hour." diff --git a/crates/im-web/src/live.rs b/crates/im-web/src/live.rs index a101870..cfe6de6 100644 --- a/crates/im-web/src/live.rs +++ b/crates/im-web/src/live.rs @@ -237,7 +237,7 @@ struct AccountFollow { /// /// An anonymous viewer gets keep-alives only. A signed-in viewer also gets an `account` event each /// time their account changes (the page then refreshes), and a `signed_out` event when their session -/// is gone. After `signed_out` the browser goes to the sign-in page, and the stream ends. +/// 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. #[route(GET "/-/alive")] async fn alive(cx: &Cx) -> Result { let state = app_context::(cx); @@ -285,26 +285,36 @@ async fn alive(cx: &Cx) -> Result { _slot: slot, }; let events = stream::unfold(follow, |mut follow| async move { - if follow.done { - return None; - } - let changed = tokio::select! { - changed = follow.wake.changed() => changed.is_ok(), - () = stopped(&mut follow.stop) => false, - () = tokio::time::sleep_until(follow.until) => false, - }; - if !changed { - return None; - } - match follow.store.session_is_live(&follow.session_id).await { - Ok(true) => Some((Ok(Event::new().event("account").data("1")), follow)), - Ok(false) => { - follow.done = true; - Some((Ok(Event::new().event("signed_out").data("1")), follow)) + loop { + if follow.done { + return None; } - Err(error) => { - tracing::error!(error = %error, "alive: could not check the session"); - None + // An account change is announced. A recheck tick only looks at the session: a session that + // expired by idle or age policy ends the stream, and a live one sends nothing. + let account_changed = tokio::select! { + changed = follow.wake.changed() => { + if changed.is_err() { + return None; + } + true + } + () = stopped(&mut follow.stop) => return None, + () = tokio::time::sleep_until(follow.until) => return None, + () = tokio::time::sleep(RECHECK) => false, + }; + match follow.store.session_is_live(&follow.session_id).await { + Ok(true) if account_changed => { + return Some((Ok(Event::new().event("account").data("1")), follow)); + } + Ok(true) => {} + Ok(false) => { + follow.done = true; + return Some((Ok(Event::new().event("signed_out").data("1")), follow)); + } + Err(error) => { + tracing::error!(error = %error, "alive: could not check the session"); + return None; + } } } }); diff --git a/crates/im-web/src/mail/mod.rs b/crates/im-web/src/mail/mod.rs index 5bbd272..6c20e5c 100644 --- a/crates/im-web/src/mail/mod.rs +++ b/crates/im-web/src/mail/mod.rs @@ -122,16 +122,30 @@ pub fn lang_for(user: &User, request: Lang) -> Lang { } } -/// Renders `mail` for `to` in `lang`, seals it, and adds it to the outbox. The subject is fixed text; -/// the body (text and HTML, with the recipient's name) is sealed as one JSON document. A mail that the -/// store drops by its per-address limits is not an error here: the caller answers the same either way. -pub async fn queue( - store: &Store, - key: &[u8; 32], - to: &Recipient, - lang: Lang, - mail: &Mail<'_>, -) -> Result<()> { +/// A mail rendered and sealed, not yet in the outbox. Built before any link it carries is created, so the +/// store can check its limits and create the links in one transaction (see `store::links`). +pub struct Sealed { + kind: &'static str, + to_addr: String, + subject: String, + sealed_body: String, +} + +impl Sealed { + /// The outbox row this mail becomes. + pub fn as_new(&self) -> NewMail<'_> { + NewMail { + kind: self.kind, + to_addr: &self.to_addr, + subject: &self.subject, + sealed_body: &self.sealed_body, + } + } +} + +/// Renders `mail` for `to` in `lang` and seals it under the instance key. The subject is fixed text; the +/// body (text and HTML, with the recipient's name) is sealed as one JSON document. +pub fn seal(key: &[u8; 32], to: &Recipient, lang: Lang, mail: &Mail<'_>) -> Result { let rendered = templates::render(lang, to.name(), mail); let payload = json!({ "to_name": to.name(), @@ -140,14 +154,25 @@ pub async fn queue( }) .to_string(); let sealed = secret::seal(key, secret::purpose::MAIL_BODY, payload.as_bytes())?; - store - .enqueue_mail(&NewMail { - kind: mail.kind(), - to_addr: to.email(), - subject: &rendered.subject, - sealed_body: &sealed, - }) - .await?; + Ok(Sealed { + kind: mail.kind(), + to_addr: to.email().to_string(), + subject: rendered.subject, + sealed_body: sealed, + }) +} + +/// Renders `mail` for `to` in `lang`, seals it, and adds it to the outbox. A mail that the store drops by +/// its limits is not an error here: the caller answers the same either way. +pub async fn queue( + store: &Store, + key: &[u8; 32], + to: &Recipient, + lang: Lang, + mail: &Mail<'_>, +) -> Result<()> { + let sealed = seal(key, to, lang, mail)?; + store.enqueue_mail(&sealed.as_new()).await?; Ok(()) } diff --git a/crates/im-web/src/oidc/logout.rs b/crates/im-web/src/oidc/logout.rs index 13a022c..aa25a96 100644 --- a/crates/im-web/src/oidc/logout.rs +++ b/crates/im-web/src/oidc/logout.rs @@ -9,8 +9,12 @@ //! signed-out page, never a redirect. //! - `state` is echoed on the redirect only when it is usable (bounded, no control characters). //! - A `GET` never ends a session: a link or an image on another site must not sign the browser out. A -//! `GET` with a session shows a confirmation form, which carries the session's CSRF token. Only the -//! `POST` ends the session, and it checks that token before anything changes. +//! `GET` with a session answers with a form that carries the session's CSRF token. When a valid +//! `id_token_hint` came with it (a client's sign-out), the form posts itself (`data-auto-submit`, run by +//! `assets/pages.js`), so the browser returns to the client without a second click; a bare `GET` waits for +//! the person's click, so a link on another site cannot sign them out. The visible button is the fallback +//! without JS. Only the `POST` ends the session, and it +//! checks that token before anything changes. //! - Ending the session is `im`'s own: the browser session is deleted (and its clients told by //! back-channel logout, in the store's transaction). When the hint names another session of the same //! person, that one ends too. @@ -221,7 +225,7 @@ async fn logout_post(cx: &Cx, Form(form): Form) -> Result Ok(logout_view(cx, lang, None)) } -/// The form that asks for a sign-out (the GET answer when the session is not the hinted one). +/// The form that signs the browser out (the GET answer with a session). It posts itself. struct Confirm { csrf: String, raw_hint: Option, @@ -243,7 +247,7 @@ fn logout_view(cx: &Cx, lang: Lang, confirm: Option) -> impl View {

(title)

if let Some(confirm) = confirm {

(text(lang, OidcText::ConfirmBody))

-
+ if let Some(hint) = confirm.raw_hint { diff --git a/crates/im-web/src/oidc/token.rs b/crates/im-web/src/oidc/token.rs index 899167a..58294b4 100644 --- a/crates/im-web/src/oidc/token.rs +++ b/crates/im-web/src/oidc/token.rs @@ -32,7 +32,9 @@ use super::{ invalid_client, invalid_grant, issuer, json_response, oauth_error, one, parse_pairs, single, }; use crate::state::AppState; -use crate::throttle::{TOKEN_CLIENT_LIMIT, token_client_key}; +use crate::throttle::{ + TOKEN_CHAIN_LIMIT, TOKEN_CLIENT_LIMIT, token_client_key, token_code_key, token_family_key, +}; /// `POST /token`. #[route(POST "/token")] @@ -59,16 +61,9 @@ async fn token_endpoint(cx: &Cx, body: Body) -> Result { Err(response) => return Ok(response), }; // Counted after the client is authenticated, so a caller without the secret cannot use up a client's - // allowance. Over the limit the answer is a 429 with the wait, in the OAuth error form. - if let Err(wait) = app.per_minute.reserve( - &token_client_key(&client.id), - TOKEN_CLIENT_LIMIT, - Instant::now(), - ) { - let mut response = oauth_error(StatusCode::TOO_MANY_REQUESTS, "invalid_request"); - response - .headers_mut() - .insert(RETRY_AFTER, HeaderValue::from(wait.as_secs().max(1))); + // allowance. The client's ceiling applies to every grant; a chain or a code has its own lower limit, + // counted once the grant has found its row (see the grants). + if let Some(response) = throttled(app, &token_client_key(&client.id), TOKEN_CLIENT_LIMIT) { return Ok(response); } match one(&pairs, "grant_type") { @@ -83,6 +78,17 @@ async fn token_endpoint(cx: &Cx, body: Body) -> Result { } } +/// Counts one request under `key` against `limit` per minute. Over the limit the answer is a 429 with the +/// wait, in the OAuth error form; otherwise `None`. +fn throttled(app: &AppState, key: &str, limit: usize) -> Option { + let wait = app.per_minute.reserve(key, limit, Instant::now()).err()?; + let mut response = oauth_error(StatusCode::TOO_MANY_REQUESTS, "invalid_request"); + response + .headers_mut() + .insert(RETRY_AFTER, HeaderValue::from(wait.as_secs().max(1))); + Some(response) +} + /// Reads a client-authenticated form for `/revoke` and `/introspect`: the same content type, size and /// client authentication as `/token`. The inner `Err` is the refusal to send. pub(super) async fn client_form( @@ -203,6 +209,13 @@ async fn grant_code(app: &AppState, client: &Client, pairs: &Pairs) -> Result Result if row.client_id != client.id { return Ok(invalid_grant()); } + if let Some(response) = throttled( + app, + &token_family_key(&client.id, &row.family_id), + TOKEN_CHAIN_LIMIT, + ) { + return Ok(response); + } if row.used_at.is_some() { // A rotated token came back. Either the holder or someone who copied it is replaying it: // the whole chain is revoked, so both lose it. diff --git a/crates/im-web/src/pages/admin/message.rs b/crates/im-web/src/pages/admin/message.rs index 20f4849..5f5e822 100644 --- a/crates/im-web/src/pages/admin/message.rs +++ b/crates/im-web/src/pages/admin/message.rs @@ -38,6 +38,14 @@ const BODY_MAX: usize = 10_000; /// Sends that the limit allows in one window of the throttle. const SENDS_PER_WINDOW: usize = 5; +/// Path of the message form. The router raises the body limit for this path (see `boot.rs`). +pub const MESSAGE_ROUTE: &str = "/admin/message"; + +/// The body limit of the message form: every character of the subject and the body at its longest +/// encoding (4 bytes of UTF-8, 3 bytes each once percent-encoded), plus room for the field names and the +/// CSRF token. Smaller would refuse a long Turkish or CJK message before its own length check runs. +pub const MESSAGE_BODY_LIMIT: usize = (SUBJECT_MAX + BODY_MAX) * 4 * 3 + 4 * 1024; + /// The throttle key of the message form. const THROTTLE_KEY: &str = "admin-message"; diff --git a/crates/im-web/src/pages/email.rs b/crates/im-web/src/pages/email.rs index e1be687..85b9a57 100644 --- a/crates/im-web/src/pages/email.rs +++ b/crates/im-web/src/pages/email.rs @@ -153,7 +153,30 @@ async fn email_request_submit(cx: &Cx, Form(form): Form) -> Re let old_token = generate_token(); let new_token = generate_token(); let expires = stamp_after(Duration::from_secs(u64::from(hours) * 60 * 60)); - match state + let old_link = format!("{}/email/{old_token}", state.config.base_url); + let new_link = format!("{}/email/{new_token}", state.config.base_url); + let user_lang = mail::lang_for(&viewer.user, lang); + // Both mails are sealed before the links exist, so the store can check their limits and create the + // links and the mails in one transaction. + let (Ok(old_to), Ok(new_to)) = ( + Recipient::new(Some(&viewer.user.name), &viewer.user.email), + Recipient::new(None, &new_email), + ) else { + tracing::error!("email change not started: an address is not valid"); + return Ok(refuse(Txt::ErrEmailInvalid)); + }; + let old_mail = Mail::EmailOld { + link: &old_link, + new_email: &new_email, + hours, + }; + let new_mail = Mail::EmailNew { + link: &new_link, + hours, + }; + let old_sealed = mail::seal(&state.key, &old_to, user_lang, &old_mail)?; + let new_sealed = mail::seal(&state.key, &new_to, user_lang, &new_mail)?; + let started = match state .store .start_email_change( &viewer.user.id, @@ -161,38 +184,19 @@ async fn email_request_submit(cx: &Cx, Form(form): Form) -> Re &hash_token(&old_token), &hash_token(&new_token), &expires, + &[old_sealed.as_new(), new_sealed.as_new()], ) .await { - Ok(()) => {} + Ok(started) => started, Err(im_core::Error::Conflict(_)) => return Ok(refuse(Txt::ErrEmailInvalid)), Err(error) => return Err(error.into()), - } - - let old_link = format!("{}/email/{old_token}", state.config.base_url); - let new_link = format!("{}/email/{new_token}", state.config.base_url); - let user_lang = mail::lang_for(&viewer.user, lang); - if let Ok(to) = Recipient::new(Some(&viewer.user.name), &viewer.user.email) { - let mail = Mail::EmailOld { - link: &old_link, - new_email: &new_email, - hours, - }; - if let Err(error) = mail::queue(&state.store, &state.key, &to, user_lang, &mail).await { - tracing::error!(error = %error, "email change mail to the old address not queued"); - } - } - match Recipient::new(None, &new_email) { - Ok(to) => { - let mail = Mail::EmailNew { - link: &new_link, - hours, - }; - if let Err(error) = mail::queue(&state.store, &state.key, &to, user_lang, &mail).await { - tracing::error!(error = %error, "email change mail to the new address not queued"); - } - } - Err(error) => tracing::error!(error, "email change mail to the new address not queued"), + }; + // A change dropped by the limits looks the same to the person as a sent one, as the mail limits + // always have: the answer does not show the limits. + if !started { + tracing::info!("email change dropped by the mail limits; no link created"); + return Err(see_other("/account/email?notice=sent").into()); } record( cx, diff --git a/crates/im-web/src/pages/login.rs b/crates/im-web/src/pages/login.rs index 8d69963..8896c1b 100644 --- a/crates/im-web/src/pages/login.rs +++ b/crates/im-web/src/pages/login.rs @@ -221,22 +221,25 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form) -> Result { - // The pending cookie is good for one sign-in. A second use of it is refused like an expired one. - let spent = state - .store - .consume_pending_login(&pending.nonce, &stamp_after(PENDING_TTL)) - .await?; - if !spent { - clear_pending_login(cx); - return Err(see_other("/login").into()); - } + // The pending cookie is good for one sign-in, so its nonce is claimed before any code is checked. A + // parallel submission then cannot spend a recovery code for a sign-in that never happens. A wrong code + // gives the claim back, so a typo does not end the pending login. + let claimed = state + .store + .consume_pending_login(&pending.nonce, &stamp_after(PENDING_TTL)) + .await?; + if !claimed { + clear_pending_login(cx); + return Err(see_other("/login").into()); + } + match check_second_factor(&state.store, &state.key, &user, &form.code).await { + Ok(Some(method)) => { state.throttle.clear(&limit); clear_pending_login(cx); Err(finish_sign_in(cx, &user, method, &pending.next).await?) } - None => { + Ok(None) => { + state.store.release_pending_login(&pending.nonce).await?; record( cx, Actor::User(&user.id), @@ -253,6 +256,10 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form) -> Result { + state.store.release_pending_login(&pending.nonce).await?; + Err(error) + } } } diff --git a/crates/im-web/src/pages/reset.rs b/crates/im-web/src/pages/reset.rs index ca6c542..2e062b9 100644 --- a/crates/im-web/src/pages/reset.rs +++ b/crates/im-web/src/pages/reset.rs @@ -120,8 +120,10 @@ async fn forgot_submit(cx: &Cx, Form(form): Form) -> Result, @@ -134,26 +136,39 @@ fn spawn_reset( tokio::spawn(async move { let token = generate_token(); let expires = stamp_after(Duration::from_secs(u64::from(minutes) * 60)); - if let Err(error) = store - .create_reset_link(&user.id, &hash_token(&token), &expires) - .await - { - tracing::error!(error = %error, "reset link not created"); - return; - } let link = format!("{base_url}/reset/{token}"); let lang = mail::lang_for(&user, lang); - match Recipient::new(Some(&user.name), &user.email) { - Ok(to) => { - let mail = Mail::Reset { - link: &link, - minutes, - }; - if let Err(error) = mail::queue(&store, &key, &to, lang, &mail).await { - tracing::error!(error = %error, "reset mail not queued"); - } + let to = match Recipient::new(Some(&user.name), &user.email) { + Ok(to) => to, + Err(error) => { + tracing::error!(error, "reset mail not queued"); + return; + } + }; + let mail = Mail::Reset { + link: &link, + minutes, + }; + let sealed = match mail::seal(&key, &to, lang, &mail) { + Ok(sealed) => sealed, + Err(error) => { + tracing::error!(error = %error, "reset mail not queued"); + return; + } + }; + match store + .create_reset_link(&user.id, &hash_token(&token), &expires, &sealed.as_new()) + .await + { + Ok(Some(_)) => {} + Ok(None) => { + tracing::info!("reset mail dropped by the cooldown; no link created"); + return; + } + Err(error) => { + tracing::error!(error = %error, "reset link not created"); + return; } - Err(error) => tracing::error!(error, "reset mail not queued"), } let entry = NewAudit { actor_id: None, diff --git a/crates/im-web/src/throttle.rs b/crates/im-web/src/throttle.rs index 8d2445c..741740a 100644 --- a/crates/im-web/src/throttle.rs +++ b/crates/im-web/src/throttle.rs @@ -68,8 +68,13 @@ pub const EMAIL_CHANGE_LIMIT: usize = 3; /// with the `temporarily_unavailable` redirect. pub const AUTHORIZE_SESSION_LIMIT: usize = 60; -/// Requests allowed per authenticated client inside [`MINUTE`] at `/token`. -pub const TOKEN_CLIENT_LIMIT: usize = 120; +/// Requests allowed per authenticated client inside [`MINUTE`] at `/token`, over all its grants together. +/// A client with many users shares this ceiling, so it is set well above one person's use. +pub const TOKEN_CLIENT_LIMIT: usize = 1200; + +/// Requests allowed inside [`MINUTE`] for one refresh-token family, or for one authorization code, at +/// `/token`. One person uses one chain or one code, so this is what limits a flood on a single one. +pub const TOKEN_CHAIN_LIMIT: usize = 30; /// `LoginFailed` audit rows written per account, or per client address when the account is unknown, inside /// [`MINUTE`]. Failures beyond it are still refused and counted; only their audit rows are skipped. @@ -82,10 +87,14 @@ const MAX_KEYS: usize = 100_000; /// A full prune runs every this many attempts. const PRUNE_EVERY: u32 = 256; -/// The part of an email key used for an address that is too long or not plausible. Contains `<`, which -/// no valid address contains, so it never collides with a real address. +/// The part of an email key used for an address that is not plausible. Starts with `<`, which no valid +/// address contains, so it never collides with a real address. const INVALID_ADDRESS: &str = ""; +/// The most bytes of a raw, unparseable address that go into its key. Longer input is cut here, so the +/// key stays bounded. +const MAX_RAW_ADDRESS_BYTES: usize = 320; + /// The failure counters of the process. Shared by every request through the app state. pub struct Throttle { window: Duration, @@ -289,12 +298,22 @@ fn wait_for(stamps: &VecDeque, limit: usize, window: Duration, now: Ins }) } -/// The part of an email key for `email`: the address itself when it is plausible and short, otherwise -/// one fixed sentinel. The sentinel keeps the keys of junk input bounded, and the answer the same. +/// The part of an email key for `email`: the address itself when it is plausible, otherwise the marker +/// and the raw text, trimmed, lowercased and cut to [`MAX_RAW_ADDRESS_BYTES`]. Each junk address gets its +/// own key, so one junk address cannot lock out a real account whose stored address happens to be +/// unparseable under the current rules. fn address_part(email: &str) -> String { match parse_email(email) { Ok(address) => address, - Err(_) => INVALID_ADDRESS.to_owned(), + Err(_) => { + let raw = email.trim().to_lowercase(); + // Cut on a character boundary at or below the cap. + let cut = (0..=raw.len().min(MAX_RAW_ADDRESS_BYTES)) + .rev() + .find(|&i| raw.is_char_boundary(i)) + .unwrap_or(0); + format!("{INVALID_ADDRESS}{}", &raw[..cut]) + } } } @@ -333,6 +352,16 @@ pub fn token_client_key(client_id: &str) -> String { format!("token:{client_id}") } +/// Throttle key for the refresh requests of one token family (one chain) of a client. +pub fn token_family_key(client_id: &str, family_id: &str) -> String { + format!("token-family:{client_id}:{family_id}") +} + +/// Throttle key for the code exchanges of one authorization code of a client, by the code's hash. +pub fn token_code_key(client_id: &str, code_hash: &str) -> String { + format!("token-code:{client_id}:{code_hash}") +} + /// Throttle key for the `LoginFailed` audit rows of one account, by user id. pub fn login_audit_user_key(user_id: &str) -> String { format!("login-audit-user:{user_id}") diff --git a/docs/architecture.md b/docs/architecture.md index fd039a1..b0f679e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -207,8 +207,9 @@ redirects). Other errors redirect to the client with `error=` and `state`. `max_sessions` per user: the oldest is ended (with back-channel) when exceeded. - Limits beyond the failure counters (`throttle.rs`, in memory, refused with `429` or an OAuth error): `/authorize` issues at most 60 codes a minute per session (over it, `error=temporarily_unavailable` goes to - the redirect URI); `/token` allows 120 requests a minute per authenticated client; an account asks for at most - 3 email changes an hour; each form route reads at most 16 KiB, and the photo route keeps its own limit. + the redirect URI); `/token` allows 1200 requests a minute per authenticated client, and 30 a minute per + refresh-token family or authorization code; an account asks for at most 3 email changes an hour; each form + route reads at most 16 KiB, and the photo and admin message routes keep their own limits. - Password change ends every other session; reset ends all. Disable and delete end all and queue back-channel logout by `sub`. - TOTP enroll: secret generated and held sealed in a pending state until a valid code confirms it; enrolling @@ -224,7 +225,10 @@ redirects). Other errors redirect to the client with `error=` and `state`. `authz::authorize(actor, action) -> Result<(), Denied>` where `actor` is `Anonymous`, `User { id, is_admin }` or `Client { id, scopes, service_key }`, and `action` is an enum (`ViewOwnAccount`, `EditOwnAccount`, -`ViewPerson`, `Administer`, `ReadDirectory`, `ReadFamily`, ...). Admin pages answer 404 to non-admins. +`ViewPerson`, `Administer`, `ReadDirectory`, `ReadFamily`, ...). Admin pages answer 404 to non-admins. An +admin page with no live session (a visitor, or an administrator whose session expired) also answers 404, not a +redirect to sign-in, so the admin area does not show itself to visitors. The administrator signs in again from +`/login` and opens the page from there. Rules that are not role checks (last admin cannot be demoted or disabled, an admin cannot disable themself) live in the store as single conditional statements so they cannot race.