From d3228adf9a2558ba097b0ab7c27a596a2c3b4c06 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 15:51:53 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=92=20races:=20sessions=20re-check=20t?= =?UTF-8?q?he=20sign-in=20state,=20single=20TOTP=20enrolment,=20one=20pend?= =?UTF-8?q?ing=20key,=20photo=20lock,=20no=20links=20for=20disabled=20acco?= =?UTF-8?q?unts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/im-core/src/store/backchannel.rs | 4 +- crates/im-core/src/store/keys.rs | 24 ++++-- crates/im-core/src/store/links.rs | 28 ++++-- crates/im-core/src/store/sessions.rs | 109 ++++++++++++++++++++++-- crates/im-core/src/store/users.rs | 47 ++++++++-- crates/im-web/src/auth.rs | 23 +++-- crates/im-web/src/backchannel.rs | 10 ++- crates/im-web/src/boot.rs | 2 + crates/im-web/src/oidc/signing.rs | 25 +++--- crates/im-web/src/oidc/tests.rs | 6 +- crates/im-web/src/pages/admin/tests.rs | 12 ++- crates/im-web/src/pages/invite.rs | 6 +- crates/im-web/src/pages/login.rs | 89 +++++++++++++------ crates/im-web/src/pages/profile.rs | 4 + crates/im-web/src/pages/reset.rs | 12 ++- crates/im-web/src/pages/security.rs | 11 ++- crates/im-web/src/pages/setup.rs | 6 +- crates/im-web/src/pages/tests.rs | 6 +- crates/im-web/src/state.rs | 3 + docs/architecture.md | 9 +- docs/contracts.md | 2 +- 21 files changed, 349 insertions(+), 89 deletions(-) diff --git a/crates/im-core/src/store/backchannel.rs b/crates/im-core/src/store/backchannel.rs index 75633aa..294e929 100644 --- a/crates/im-core/src/store/backchannel.rs +++ b/crates/im-core/src/store/backchannel.rs @@ -316,7 +316,7 @@ mod tests { use crate::model::amr; use crate::store::clients::NewClient; use crate::store::oidc::{NewAuthCode, NewRefreshToken}; - use crate::store::sessions::{NewSession, SESSION_IDLE}; + use crate::store::sessions::{NewSession, SESSION_IDLE, SignInState}; use crate::time::stamp_after; use crate::token::hash_token; @@ -350,6 +350,7 @@ mod tests { .create_session( &NewSession { user_id: &user.id, + decided_on: SignInState::of(&user), token_hash: "session-token", csrf_token: "csrf", amr: amr::PASSWORD, @@ -362,6 +363,7 @@ mod tests { ) .await .expect("session") + .expect("not refused") .session; for client in &clients { store diff --git a/crates/im-core/src/store/keys.rs b/crates/im-core/src/store/keys.rs index 7e46af4..31552a3 100644 --- a/crates/im-core/src/store/keys.rs +++ b/crates/im-core/src/store/keys.rs @@ -8,7 +8,8 @@ use turso::Value; use crate::error::{Error, Result}; use crate::model::KeyRecord; -use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, finish}; +use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish}; +use crate::time::now_stamp; /// The columns of a key row, in the order [`map_key`] reads them. const KEY_COLS: &str = "kid, private_sealed, public_raw, created_at, activates_at, retires_at"; @@ -42,11 +43,24 @@ impl Store { } /// Adds a key. Every key that is not yet retired and activates before it is retired at its - /// activation time, in the same transaction. - pub async fn add_signing_key(&self, key: &KeyRecord) -> Result<()> { + /// activation time, in the same transaction. Returns false, with nothing changed, when another key + /// is still waiting to activate: two pending keys would make the retirement order ambiguous. The + /// check and the insert are one transaction, so parallel rotations cannot both pass it. + pub async fn add_signing_key(&self, key: &KeyRecord) -> 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 { + let pending = fetch_opt( + &tx, + "SELECT 1 FROM signing_keys WHERE retires_at IS NULL AND activates_at > ?1", + (now,), + |row| col_int(row, 0), + ) + .await?; + if pending.is_some() { + return Ok(false); + } tx.execute( "UPDATE signing_keys SET retires_at = ?1 \ WHERE retires_at IS NULL AND activates_at < ?1", @@ -67,7 +81,7 @@ impl Store { ) .await .map_err(db_err)?; - Ok(()) + Ok(true) } .await; finish(tx, outcome).await diff --git a/crates/im-core/src/store/links.rs b/crates/im-core/src/store/links.rs index 8e36217..674010e 100644 --- a/crates/im-core/src/store/links.rs +++ b/crates/im-core/src/store/links.rs @@ -80,8 +80,9 @@ impl Store { /// 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. + /// the person stop working. Returns the outbox id, or `None` when the mail was dropped or the person is + /// disabled or missing (nothing is created then). The check is in the same transaction as the insert, so + /// a link is never made for an account that a parallel disable has just ended. pub async fn create_reset_link( &self, user_id: &str, @@ -93,7 +94,14 @@ impl Store { let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result> = async { - if !admitted(&tx, mail).await? { + let enabled = fetch_opt( + &tx, + "SELECT 1 FROM users WHERE id = ?1 AND disabled_at IS NULL", + (user_id.to_string(),), + |_row| Ok(()), + ) + .await?; + if enabled.is_none() || !admitted(&tx, mail).await? { return Ok(None); } tx.execute( @@ -208,8 +216,8 @@ impl Store { /// 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. + /// would be dropped by the limits, or the person is disabled or missing, 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, @@ -236,6 +244,16 @@ impl Store { "that email address cannot be used".into(), )); } + let enabled = fetch_opt( + &tx, + "SELECT 1 FROM users WHERE id = ?1 AND disabled_at IS NULL", + (user_id.to_string(),), + |_row| Ok(()), + ) + .await?; + if enabled.is_none() { + return Ok(false); + } for mail in mails { if !admitted(&tx, mail).await? { return Ok(false); diff --git a/crates/im-core/src/store/sessions.rs b/crates/im-core/src/store/sessions.rs index 73e462b..3040239 100644 --- a/crates/im-core/src/store/sessions.rs +++ b/crates/im-core/src/store/sessions.rs @@ -14,9 +14,11 @@ use std::time::Duration; use turso::Connection; use crate::error::Result; -use crate::model::Session; +use crate::model::{Session, User}; use crate::store::backchannel::{self, EndReason}; -use crate::store::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; +use crate::store::{ + Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id, +}; use crate::time::{now_stamp, stamp_after, stamp_before}; /// The least time between two writes of `last_seen_at` for one session. Every request reads the @@ -49,12 +51,36 @@ fn map_session(row: &turso::Row) -> Result { }) } +/// The authentication state a sign-in was decided on: the password hash and whether two-factor +/// sign-in was on. A session is created only while the user still has this state (see +/// [`Store::create_session`]), so a password change, reset, enrolment or disable that committed +/// after the sign-in was decided is not undone by it. +#[derive(Debug, Clone, Copy)] +pub struct SignInState<'a> { + /// The argon2id hash the password step was checked against, or the one a reset just set. + pub password_hash: &'a str, + /// Whether two-factor sign-in was on when the sign-in was decided. + pub totp_enabled: bool, +} + +impl<'a> SignInState<'a> { + /// The state of `user` as it was read. + pub fn of(user: &'a User) -> Self { + Self { + password_hash: &user.password_hash, + totp_enabled: user.totp_enabled(), + } + } +} + /// What is needed to create a session. `token_hash` is the hash of the cookie token; the token /// itself never reaches the store. #[derive(Debug, Clone)] pub struct NewSession<'a> { /// Owner of the session. pub user_id: &'a str, + /// The state the sign-in was decided on. Checked again inside the write. + pub decided_on: SignInState<'a>, /// Hex SHA-256 of the token that goes in the cookie. pub token_hash: &'a str, /// The per-session CSRF token. @@ -154,14 +180,18 @@ pub(crate) async fn end_all_sessions( impl Store { /// Creates a session for a user who has just proved who they are. /// - /// In one transaction: if the user already has `max_sessions` live sessions, the oldest ones - /// are ended until there is room for the new one, then the new row is inserted. The check and - /// the insert are in the same transaction, so two parallel sign-ins cannot both exceed the cap. + /// In one transaction: first the user must still be enabled, with the password hash and the + /// two-factor state the sign-in was decided on. Otherwise nothing is written and `None` is + /// returned. Then, if the user already has `max_sessions` live sessions, the oldest ones are + /// ended until there is room for the new one, and the new row is inserted. The check and the + /// insert are in the same transaction, so two parallel sign-ins cannot both exceed the cap, and + /// a concurrent password change or disable either commits first (and this returns `None`) or + /// waits for this session to exist (and then ends it). pub async fn create_session( &self, new: &NewSession<'_>, max_sessions: u32, - ) -> Result { + ) -> Result> { let now = now_stamp(); let hard_expires_at = stamp_after(new.max_age); let idle_expires_at = stamp_after(new.idle); @@ -190,7 +220,22 @@ impl Store { 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 still_decided = fetch_opt( + &tx, + "SELECT 1 FROM users WHERE id = ?1 AND disabled_at IS NULL \ + AND password_hash = ?2 AND (totp_enabled_at IS NOT NULL) = ?3", + ( + new.user_id.to_string(), + new.decided_on.password_hash.to_string(), + i64::from(new.decided_on.totp_enabled), + ), + |row| col_int(row, 0), + ) + .await?; + if still_decided.is_none() { + return Ok(None); + } let live = fetch_all( &tx, "SELECT id FROM sessions WHERE user_id = ?1 AND expires_at > ?2 \ @@ -224,10 +269,10 @@ impl Store { ) .await .map_err(db_err)?; - Ok(CreatedSession { + Ok(Some(CreatedSession { session: session.clone(), ended, - }) + })) } .await; finish(tx, outcome).await @@ -434,6 +479,7 @@ mod tests { .create_session( &NewSession { user_id: &user.id, + decided_on: SignInState::of(&user), token_hash: &token, csrf_token: "csrf", amr: "pwd", @@ -445,6 +491,7 @@ mod tests { 2, ) .await + .unwrap() .unwrap(); if n < 2 { assert!(created.ended.is_empty()); @@ -471,6 +518,48 @@ mod tests { ); } + #[tokio::test] + async fn a_session_is_refused_once_the_decided_state_has_changed() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("im.db")).await.unwrap(); + let user = store + .create_user("ada@example.com", "Ada", "hash", false) + .await + .unwrap(); + let new = |token: &'static str, decided_on| NewSession { + user_id: &user.id, + decided_on, + token_hash: token, + csrf_token: "csrf", + amr: "pwd", + ip: None, + user_agent: None, + idle: SESSION_IDLE, + max_age: Duration::from_secs(3600), + }; + // The password changed after the sign-in was decided on: nothing is created. + let stale = SignInState { + password_hash: "old-hash", + totp_enabled: false, + }; + assert!( + store + .create_session(&new("stale", stale), 10) + .await + .unwrap() + .is_none() + ); + assert!(store.list_sessions(&user.id).await.unwrap().is_empty()); + // The state as decided on still holds: the session is created. + assert!( + store + .create_session(&new("fresh", SignInState::of(&user)), 10) + .await + .unwrap() + .is_some() + ); + } + #[tokio::test] async fn idle_extension_never_passes_the_hard_cap() { let dir = tempfile::tempdir().unwrap(); @@ -484,6 +573,7 @@ mod tests { .create_session( &NewSession { user_id: &user.id, + decided_on: SignInState::of(&user), token_hash: "capped", csrf_token: "csrf", amr: "pwd", @@ -495,6 +585,7 @@ mod tests { 10, ) .await + .unwrap() .unwrap(); let cap = created.session.hard_expires_at.clone(); assert!(created.session.expires_at <= cap); diff --git a/crates/im-core/src/store/users.rs b/crates/im-core/src/store/users.rs index a341f72..77b4567 100644 --- a/crates/im-core/src/store/users.rs +++ b/crates/im-core/src/store/users.rs @@ -358,7 +358,8 @@ impl Store { /// Disables an account. The last enabled administrator cannot be disabled: that is part of the /// same conditional `UPDATE`, so two parallel requests cannot both disable the last two. In one transaction: the account is marked disabled, the directory feed /// records the change, one `sub`-only back-channel logout is queued for every client the person - /// used (contracts.md 2.5), the refresh tokens are revoked and every session is deleted. Returns + /// used (contracts.md 2.5), the refresh tokens are revoked, the pending reset and email-change links are + /// used up, and every session is deleted. Returns /// false, with nothing changed, when the account is missing or already disabled. pub async fn disable_user(&self, user_id: &str) -> Result { let now = now_stamp(); @@ -379,6 +380,8 @@ impl Store { return Ok(false); } record_change(&tx, user_id, ChangeKind::Member).await?; + // A reset or email-change link must not come back to life when the account is enabled again. + invalidate_links(&tx, user_id, &now).await?; // Queued before the sessions go, because the client links are read from them. backchannel::queue_user(&tx, user_id, EndReason::Disabled, &now).await?; tx.execute( @@ -419,7 +422,8 @@ impl Store { /// it as used, replaces the recovery codes with `recovery_hashes` and drops the pending secret. /// Sessions created before it are not second-factor sessions, so in the same transaction every live /// session except `keep_session_id` ends, with its back-channel logouts. `None` ends all of them. - /// One transaction. + /// One transaction. Returns false, with nothing changed, when two-factor sign-in is already on (a + /// parallel confirmation won) or the account is missing. pub async fn enable_totp( &self, user_id: &str, @@ -427,17 +431,20 @@ impl Store { step: u64, recovery_hashes: &[String], keep_session_id: Option<&str>, - ) -> Result<()> { + ) -> Result { let step = i64::try_from(step).map_err(|_| Error::Invalid("totp step out of range".into()))?; 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 { + // Conditional on the state read here: a second confirmation of the same enrolment finds + // two-factor sign-in already on, and changes nothing (its recovery codes are not replaced). let changed = tx .execute( "UPDATE users SET totp_secret_sealed = ?2, totp_enabled_at = ?3, \ - totp_last_step = ?4, updated_at = ?3 WHERE id = ?1", + totp_last_step = ?4, updated_at = ?3 \ + WHERE id = ?1 AND totp_enabled_at IS NULL", ( user_id.to_string(), sealed_secret.to_string(), @@ -447,8 +454,8 @@ impl Store { ) .await .map_err(db_err)?; - if changed == 0 { - return Err(Error::NotFound); + if changed != 1 { + return Ok(false); } replace_codes(&tx, user_id, recovery_hashes).await?; tx.execute( @@ -459,7 +466,7 @@ impl Store { .map_err(db_err)?; let ids = live_session_ids(&tx, user_id, keep_session_id, &now).await?; end_rows(&tx, user_id, &ids, EndReason::Revoked, &now).await?; - Ok(()) + Ok(true) } .await; finish(tx, outcome).await @@ -631,6 +638,30 @@ mod tests { assert_eq!(store.user_count().await.unwrap(), 1); } + #[tokio::test] + async fn a_second_enrolment_confirmation_changes_nothing() { + let (_dir, store) = store().await; + let user = store + .create_user("ada@example.com", "Ada", "hash", false) + .await + .unwrap(); + assert!( + store + .enable_totp(&user.id, "v1:first", 100, &["h1".to_string()], None) + .await + .unwrap() + ); + // A parallel confirmation of the same enrolment: refused, and its recovery codes are not stored. + assert!( + !store + .enable_totp(&user.id, "v1:second", 101, &["h2".to_string()], None) + .await + .unwrap() + ); + let after = store.user_by_id(&user.id).await.unwrap().unwrap(); + assert_eq!(after.totp_last_step, Some(100)); + } + #[tokio::test] async fn a_totp_step_is_accepted_once_and_only_while_enabled() { let (_dir, store) = store().await; diff --git a/crates/im-web/src/auth.rs b/crates/im-web/src/auth.rs index 0836326..7a11940 100644 --- a/crates/im-web/src/auth.rs +++ b/crates/im-web/src/auth.rs @@ -12,7 +12,7 @@ use im_core::model::{Session, User, amr}; use im_core::secret; use im_core::store::Store; use im_core::store::backchannel::EndReason; -use im_core::store::sessions::{NewSession, SESSION_IDLE}; +use im_core::store::sessions::{NewSession, SESSION_IDLE, SignInState}; use im_core::token::{constant_time_eq, generate_token, hash_token}; use im_core::totp; use topcoat::Result; @@ -150,13 +150,20 @@ pub fn check_csrf(session: &Session, submitted: &str) -> bool { && constant_time_eq(session.csrf_token.as_bytes(), submitted.as_bytes()) } -/// Creates a session for `user`, authenticated by `amr`, and sets the cookie. +/// Creates a session for `user`, authenticated by `amr`, and sets the cookie. Returns `false`, with no +/// session and no cookie, when `decided_on` no longer holds for the user (see +/// [`im_core::store::Store::create_session`]). The caller then treats the sign-in as failed. /// /// A session the browser already presented is ended first, whoever it belongs to, so a sign-in always /// rotates the session id and no row is left live with no cookie holding it. The session lives /// [`SESSION_IDLE`] after its last use, up to the policy's `session_max_days` from now; the store keeps /// both limits. The per-person cap of the policy is applied inside the store, in the same write. -pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result { +pub async fn start_session( + cx: &Cx, + user: &User, + amr: &str, + decided_on: SignInState<'_>, +) -> Result { let state = app_context::(cx); let max_age = Duration::from_secs(u64::from(state.policy().session_max_days) * DAY); if let Some(old) = presented_session(cx).await? { @@ -174,11 +181,12 @@ pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result { let csrf = generate_token(); let ip = client_addr(cx).to_string(); let user_agent = user_agent(cx); - let created = state + let Some(_) = state .store .create_session( &NewSession { user_id: &user.id, + decided_on, token_hash: &hash_token(&token), csrf_token: &csrf, amr, @@ -189,7 +197,10 @@ pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result { }, state.policy().max_sessions, ) - .await?; + .await? + else { + return Ok(false); + }; // Sessions ended by the cap were queued for back-channel logout in the store's transaction. state.live.bump(&Topic::Account(user.id.clone())); // The browser keeps the cookie for the hard cap; the server decides the real expiry. @@ -203,7 +214,7 @@ pub async fn start_session(cx: &Cx, user: &User, amr: &str) -> Result { .max_age(cookie_age) .build(), ); - Ok(created.session) + Ok(true) } /// Ends the session of `viewer` (with its back-channel logouts) and clears its cookie. Other sessions of diff --git a/crates/im-web/src/backchannel.rs b/crates/im-web/src/backchannel.rs index 1913230..8ec1d39 100644 --- a/crates/im-web/src/backchannel.rs +++ b/crates/im-web/src/backchannel.rs @@ -130,7 +130,11 @@ pub async fn process_due( "back-channel logout abandoned" ), } - store.record_attempt(&job.id, attempt, &now_stamp()).await?; + // A failed write must not hold up the rows after it: they were already sent, and an unrecorded row + // is sent again on the next pass. The failure is logged and the loop goes on. + if let Err(error) = store.record_attempt(&job.id, attempt, &now_stamp()).await { + tracing::error!(row = %job.id, error = %error, "back-channel attempt could not be recorded"); + } } Ok(due.len()) } @@ -235,7 +239,7 @@ mod tests { use im_core::model::amr; use im_core::store::backchannel::EndReason; use im_core::store::clients::NewClient; - use im_core::store::sessions::{NewSession, SESSION_IDLE}; + use im_core::store::sessions::{NewSession, SESSION_IDLE, SignInState}; use im_core::time::stamp_after; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::{TcpListener, TcpStream}; @@ -316,6 +320,7 @@ mod tests { .create_session( &NewSession { user_id: &user.id, + decided_on: SignInState::of(&user), token_hash: "token", csrf_token: "csrf", amr: amr::PASSWORD, @@ -328,6 +333,7 @@ mod tests { ) .await .expect("session") + .expect("not refused") .session; state .store diff --git a/crates/im-web/src/boot.rs b/crates/im-web/src/boot.rs index f2ac1fb..f23b0c1 100644 --- a/crates/im-web/src/boot.rs +++ b/crates/im-web/src/boot.rs @@ -173,6 +173,7 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result { // Replaced by the stop flag of `serve` before any listener starts. The CLI never serves. stop: watch::channel(false).1, settings_lock: Arc::new(tokio::sync::Mutex::new(())), + photo_lock: Arc::new(tokio::sync::Mutex::new(())), }) } @@ -297,6 +298,7 @@ mod tests { anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), stop: watch::channel(false).1, settings_lock: Arc::new(tokio::sync::Mutex::new(())), + photo_lock: Arc::new(tokio::sync::Mutex::new(())), }; (dir, state) } diff --git a/crates/im-web/src/oidc/signing.rs b/crates/im-web/src/oidc/signing.rs index 1049eac..5792395 100644 --- a/crates/im-web/src/oidc/signing.rs +++ b/crates/im-web/src/oidc/signing.rs @@ -36,8 +36,10 @@ pub async fn maintain(store: &Store, instance_key: &[u8; 32]) -> im_core::Result activates_at: activates_at.clone(), retires_at: None, }; - store.add_signing_key(&record).await?; - tracing::info!(kid = %record.kid, activates_at = %activates_at, "signing key created"); + // A parallel run added the successor first: its key is the pending one, so this one is not needed. + if store.add_signing_key(&record).await? { + tracing::info!(kid = %record.kid, activates_at = %activates_at, "signing key created"); + } } // A key retired by a successor keeps its seed until its retirement time, because it signs until then. let scrubbed = store.scrub_retired_signing_seeds(&now).await?; @@ -78,17 +80,6 @@ pub fn spawn( pub async fn rotate_now(store: &Store, instance_key: &[u8; 32]) -> im_core::Result { let fresh = keys::generate(); let now = now_stamp(); - let pending = store - .signing_keys() - .await? - .iter() - .any(|key| key.retires_at.is_none() && key.activates_at > now); - if pending { - return Err(im_core::Error::Conflict( - "another signing key is still waiting to activate; rotate after it starts signing" - .into(), - )); - } let activates_at = stamp_plus(&now, keys::PUBLISH_LEAD).ok_or_else(|| { im_core::Error::Crypto("the new key's activation time is out of range".into()) })?; @@ -100,7 +91,13 @@ pub async fn rotate_now(store: &Store, instance_key: &[u8; 32]) -> im_core::Resu activates_at, retires_at: None, }; - store.add_signing_key(&record).await?; + // The store refuses while another key is pending, inside the same transaction as the insert. + if !store.add_signing_key(&record).await? { + return Err(im_core::Error::Conflict( + "another signing key is still waiting to activate; rotate after it starts signing" + .into(), + )); + } Ok(fresh.kid) } diff --git a/crates/im-web/src/oidc/tests.rs b/crates/im-web/src/oidc/tests.rs index 13957a9..69ccb31 100644 --- a/crates/im-web/src/oidc/tests.rs +++ b/crates/im-web/src/oidc/tests.rs @@ -10,7 +10,7 @@ use im_core::model::Client; use im_core::oauth::pkce_s256; use im_core::password::hash_password; use im_core::store::clients::NewClient; -use im_core::store::sessions::{NewSession, SESSION_IDLE}; +use im_core::store::sessions::{NewSession, SESSION_IDLE, SignInState}; use im_core::token::{generate_token, hash_token}; use serde_json::Value; use topcoat::router::response::Response; @@ -72,6 +72,7 @@ async fn fixture() -> Fixture { .create_session( &NewSession { user_id: &user.id, + decided_on: SignInState::of(&user), token_hash: &hash_token(&cookie), csrf_token: &generate_token(), amr: "pwd", @@ -83,7 +84,8 @@ async fn fixture() -> Fixture { 10, ) .await - .expect("session"); + .expect("session") + .expect("not refused"); Fixture { _dir: dir, state, diff --git a/crates/im-web/src/pages/admin/tests.rs b/crates/im-web/src/pages/admin/tests.rs index c1962b1..29a9fbd 100644 --- a/crates/im-web/src/pages/admin/tests.rs +++ b/crates/im-web/src/pages/admin/tests.rs @@ -6,7 +6,7 @@ use std::time::Duration; use http::header::{CONTENT_TYPE, COOKIE, LOCATION}; use im_core::password::hash_password; -use im_core::store::sessions::{NewSession, SESSION_IDLE}; +use im_core::store::sessions::{NewSession, SESSION_IDLE, SignInState}; use im_core::token::{generate_token, hash_token}; use topcoat::router::{Body, to_bytes}; @@ -61,11 +61,18 @@ async fn post(state: AppState, path: &str, cookie: &str, form: &str) -> Reply { async fn session_for(state: &AppState, user_id: &str) -> (String, String) { let token = generate_token(); let csrf = generate_token(); + let user = state + .store + .user_by_id(user_id) + .await + .expect("user") + .expect("a user"); state .store .create_session( &NewSession { user_id, + decided_on: SignInState::of(&user), token_hash: &hash_token(&token), csrf_token: &csrf, amr: "pwd", @@ -77,7 +84,8 @@ async fn session_for(state: &AppState, user_id: &str) -> (String, String) { 10, ) .await - .expect("session"); + .expect("session") + .expect("not refused"); (token, csrf) } diff --git a/crates/im-web/src/pages/invite.rs b/crates/im-web/src/pages/invite.rs index 7a8ad86..9fab481 100644 --- a/crates/im-web/src/pages/invite.rs +++ b/crates/im-web/src/pages/invite.rs @@ -10,6 +10,7 @@ use im_core::model::{AuditAction, amr}; use im_core::names::parse_display_name; use im_core::password::{check_policy, hash_password_async}; use im_core::store::invites::AcceptOutcome; +use im_core::store::sessions::SignInState; use im_core::token::hash_token; use serde::Deserialize; use serde_json::json; @@ -104,7 +105,10 @@ async fn invite_submit(cx: &Cx, Form(form): Form) -> Result *user, AcceptOutcome::Refused => return Err(not_found().into()), }; - start_session(cx, &user, amr::PASSWORD).await?; + if !start_session(cx, &user, amr::PASSWORD, SignInState::of(&user)).await? { + clear_pre_csrf(cx); + return Err(see_other("/login").into()); + } clear_pre_csrf(cx); record( cx, diff --git a/crates/im-web/src/pages/login.rs b/crates/im-web/src/pages/login.rs index 8896c1b..3adae1b 100644 --- a/crates/im-web/src/pages/login.rs +++ b/crates/im-web/src/pages/login.rs @@ -11,6 +11,7 @@ use std::time::{Duration, Instant}; use im_core::model::{AuditAction, User, amr}; use im_core::names::normalize_email; use im_core::password::{hash_password_async, verify_password_async}; +use im_core::store::sessions::SignInState; use im_core::time::stamp_after; use serde::Deserialize; use serde_json::{Value, json}; @@ -134,28 +135,9 @@ async fn login_submit(cx: &Cx, Form(form): Form) -> Result let target_id = found.as_ref().map(|user| user.id.clone()); // The attempt stays counted on every failure below. let Some(user) = found.filter(|user| password_ok && !user.is_disabled()) else { - // One audit row per account, or per client address when the account is unknown, each minute. A - // flood of failures therefore cannot grow the audit log. The throttle above still counts every failure. - let audit_key = match &target_id { - Some(id) => login_audit_user_key(id), - None => ip_key("login-audit-ip", client_ip(cx)), - }; - if state - .per_minute - .reserve(&audit_key, LOGIN_AUDIT_LIMIT, Instant::now()) - .is_ok() - { - let target = target_id.as_deref().map(|id| ("user", id)); - record( - cx, - Actor::Anonymous, - AuditAction::LoginFailed, - target, - json!({ "reason": "credentials" }), - ) - .await; - } + audit_failed_sign_in(cx, state, target_id).await; let lang = page_lang(cx, None); + let csrf = pre_csrf_token(cx); return Ok(login_view( cx, lang, @@ -174,7 +156,49 @@ async fn login_submit(cx: &Cx, Form(form): Form) -> Result set_pending_login(cx, &state.key, &user.id, &next)?; return Err(see_other("/login/2fa").into()); } - Err(finish_sign_in(cx, &user, amr::PASSWORD, &next).await?) + match finish_sign_in(cx, &user, amr::PASSWORD, &next).await? { + Some(redirect) => Err(redirect), + // The account changed after the password was checked: the sign-in fails like a wrong password. + None => { + audit_failed_sign_in(cx, state, target_id).await; + let lang = page_lang(cx, None); + let csrf = pre_csrf_token(cx); + Ok(login_view( + cx, + lang, + csrf, + form.email, + next, + Some(Failure::Invalid), + false, + )) + } + } +} + +/// Audits a sign-in that failed after the lookup. The row is per account, or per client address when +/// the account is unknown, and at most one each minute, so a flood of failures cannot grow the audit +/// log. The throttle still counts every failure. +async fn audit_failed_sign_in(cx: &Cx, state: &AppState, target_id: Option) { + let audit_key = match &target_id { + Some(id) => login_audit_user_key(id), + None => ip_key("login-audit-ip", client_ip(cx)), + }; + if state + .per_minute + .reserve(&audit_key, LOGIN_AUDIT_LIMIT, Instant::now()) + .is_ok() + { + let target = target_id.as_deref().map(|id| ("user", id)); + record( + cx, + Actor::Anonymous, + AuditAction::LoginFailed, + target, + json!({ "reason": "credentials" }), + ) + .await; + } } /// `GET /login/2fa`. Needs a pending password step; without one, back to sign-in. @@ -236,7 +260,11 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form) -> Result { state.throttle.clear(&limit); clear_pending_login(cx); - Err(finish_sign_in(cx, &user, method, &pending.next).await?) + match finish_sign_in(cx, &user, method, &pending.next).await? { + Some(redirect) => Err(redirect), + // The account changed since the password step: the pending login is over. + None => Err(see_other("/login").into()), + } } Ok(None) => { state.store.release_pending_login(&pending.nonce).await?; @@ -264,9 +292,18 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form) -> Result Result { +/// Starts the session of a sign-in decided on `user`, records it, and returns the redirect. `None` when +/// the decision no longer holds (see [`start_session`]): nothing was created, and the caller fails the sign-in. +async fn finish_sign_in( + cx: &Cx, + user: &User, + method: &str, + next: &str, +) -> Result> { let state = app_context::(cx); - start_session(cx, user, method).await?; + if !start_session(cx, user, method, SignInState::of(user)).await? { + return Ok(None); + } clear_pre_csrf(cx); record( cx, @@ -276,7 +313,7 @@ async fn finish_sign_in(cx: &Cx, user: &User, method: &str, next: &str) -> Resul json!({ "amr": method }), ) .await; - Ok(see_other(after_sign_in(state, user, next)).into()) + Ok(Some(see_other(after_sign_in(state, user, next)).into())) } /// The hash checked against when the email is unknown or the account disabled. Computed once, so diff --git a/crates/im-web/src/pages/profile.rs b/crates/im-web/src/pages/profile.rs index 717125b..54b0f1c 100644 --- a/crates/im-web/src/pages/profile.rs +++ b/crates/im-web/src/pages/profile.rs @@ -210,6 +210,8 @@ async fn upload_photo(cx: &Cx, mut multipart: Multipart) -> Result { Err(error) => return Err(error.into()), }; + // Held until the row names the new file: a parallel removal cannot delete it in between. + let _photo = state.photo_lock.lock().await; // The file first, then the row: the row only ever names a file that is already in place. let dir = state.config.data_dir.clone(); let user_id = viewer.user.id.clone(); @@ -243,6 +245,8 @@ fn upload_problem(cx: &Cx, lang: Lang, viewer: Viewer, message: &str) -> impl Vi async fn remove_photo(cx: &Cx, Form(form): Form) -> Result { let viewer = require_csrf(cx, &form.csrf).await?; let state = app_context::(cx); + // Held through the file removal, so a parallel upload cannot have its new file deleted here. + let _photo = state.photo_lock.lock().await; if state.store.clear_photo(&viewer.user.id).await? { state.live.bump(&Topic::Account(viewer.user.id.clone())); let dir = state.config.data_dir.clone(); diff --git a/crates/im-web/src/pages/reset.rs b/crates/im-web/src/pages/reset.rs index 2e062b9..8a2c595 100644 --- a/crates/im-web/src/pages/reset.rs +++ b/crates/im-web/src/pages/reset.rs @@ -17,6 +17,7 @@ use im_core::names::{normalize_email, parse_email}; use im_core::password::{check_policy, hash_password_async, verify_password_async}; use im_core::store::Store; use im_core::store::audit::NewAudit; +use im_core::store::sessions::SignInState; use im_core::time::stamp_after; use im_core::token::{generate_token, hash_token}; use serde::Deserialize; @@ -264,7 +265,16 @@ async fn reset_submit(cx: &Cx, Form(form): Form) -> Result clear_pre_csrf(cx); return Err(see_other("/login").into()); } - start_session(cx, &user, amr::PASSWORD).await?; + // The state the reset just set, with no second factor (checked above): a disable that committed + // since then refuses the session. + let decided_on = SignInState { + password_hash: &hash, + totp_enabled: false, + }; + if !start_session(cx, &user, amr::PASSWORD, decided_on).await? { + clear_pre_csrf(cx); + return Err(see_other("/login").into()); + } clear_pre_csrf(cx); Err(see_other(after_sign_in(state, &user, "/")).into()) } diff --git a/crates/im-web/src/pages/security.rs b/crates/im-web/src/pages/security.rs index 120c598..d91ee6b 100644 --- a/crates/im-web/src/pages/security.rs +++ b/crates/im-web/src/pages/security.rs @@ -283,7 +283,7 @@ async fn confirm_enrolment(cx: &Cx, Form(form): Form) -> Result) -> Result) -> Result Err(im_core::Error::Conflict(_)) => return Err(not_found().into()), Err(error) => return Err(error.into()), }; - start_session(cx, &user, amr::PASSWORD).await?; + if !start_session(cx, &user, amr::PASSWORD, SignInState::of(&user)).await? { + clear_pre_csrf(cx); + return Err(see_other("/login").into()); + } clear_pre_csrf(cx); record( cx, diff --git a/crates/im-web/src/pages/tests.rs b/crates/im-web/src/pages/tests.rs index 50761f6..ccf2807 100644 --- a/crates/im-web/src/pages/tests.rs +++ b/crates/im-web/src/pages/tests.rs @@ -5,7 +5,7 @@ use std::time::Duration; use http::header::{CONTENT_TYPE, COOKIE}; use im_core::password::hash_password; -use im_core::store::sessions::{NewSession, SESSION_IDLE}; +use im_core::store::sessions::{NewSession, SESSION_IDLE, SignInState}; use im_core::token::{generate_token, hash_token}; use topcoat::router::{Body, to_bytes}; @@ -45,6 +45,7 @@ async fn signed_in(state: &AppState) -> String { .create_session( &NewSession { user_id: &user.id, + decided_on: SignInState::of(&user), token_hash: &hash_token(&token), csrf_token: &generate_token(), amr: "pwd", @@ -56,7 +57,8 @@ async fn signed_in(state: &AppState) -> String { 10, ) .await - .expect("session"); + .expect("session") + .expect("not refused"); token } diff --git a/crates/im-web/src/state.rs b/crates/im-web/src/state.rs index 8ac2b8f..2e54c08 100644 --- a/crates/im-web/src/state.rs +++ b/crates/im-web/src/state.rs @@ -46,6 +46,9 @@ pub struct AppState { /// Held by every change to the saved policy, from the write to the refresh of `policy_live`. Two saves /// then run one after the other, and the in-memory policy always matches what the database last committed. pub settings_lock: Arc>, + /// Held by every profile photo change, from the row write to the file write or removal, so that a + /// removal cannot delete the file a parallel upload has just put in place. + pub photo_lock: Arc>, } impl AppState { diff --git a/docs/architecture.md b/docs/architecture.md index 9708986..57d6e34 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -146,7 +146,8 @@ minute per account, or per client address when the account is unknown; the throt **settings**: `key` PK, `value`, `updated_at` (UI overrides and sealed SMTP password). -Files beside the DB in `data_dir`: `im.key`, `photos/` (0600, written by temp file + fsync + rename). +Files beside the DB in `data_dir`: `im.key`, `photos/` (0600, written by temp file + fsync + rename). Photo upload and removal run under one +process-wide lock (`photo_lock`), so a removal cannot delete a file a parallel upload has just put in place. --- @@ -212,7 +213,11 @@ redirects). Other errors redirect to the client with `error=` and `state`. 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. Enabling or disabling TOTP ends every other session - (the current one stays). Disable and delete end all and queue back-channel logout by `sub`. + (the current one stays). Disable and delete end all and queue back-channel logout by `sub`. Disable also uses up + the account's pending reset and email-change links, and no new one is made for a disabled account. +- A session is created only in the same write that re-checks the sign-in: the account is still enabled, with the + password hash and two-factor state the sign-in was decided on. If a password change, reset, TOTP change or + disable committed in between, nothing is created and the sign-in fails like a wrong password. - Signing in ends the session the browser presented, whoever it belonged to, so no row is left without its cookie. - TOTP enroll: secret generated and held sealed in a pending state until a valid code confirms it; enrolling again while enabled requires the current code (old defect: re-visiting enroll reset it). Disabling TOTP diff --git a/docs/contracts.md b/docs/contracts.md index 6d8657b..a180cd9 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -60,7 +60,7 @@ Clients fetch discovery once at boot and cache it. They may hard-code the paths the last 7 days, as `{"kty":"OKP","crv":"Ed25519","x":...,"kid":...,"use":"sig","alg":"EdDSA"}`. - `im` rotates the signing key every 90 days and on admin demand. A new key is published 24 hours before it signs anything. -- Clients cache the JWKS for 1 hour, and refetch at most once a minute when a token names an unknown `kid`. +- Clients cache the JWKS for 10 minutes, and refetch at most once a minute when a token names an unknown `kid`. ### 2.3 Sign-in (authorization code + PKCE)