From adfb39f6647f7634fbff1e8151d09fab6d644f62 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 11:36:53 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=92=20fix:=20atomic=20throttle=20reser?= =?UTF-8?q?vations,=20bounded=20argon2=20with=20length=20cap,=20password?= =?UTF-8?q?=20before=202FA=20enrolment,=20single-use=20pending=202FA,=20lo?= =?UTF-8?q?gout=20only=20on=20POST,=20atomic=20password=20change,=20HMAC?= =?UTF-8?q?=20recovery=20codes,=20admin=20404=20for=20anonymous,=20live=20?= =?UTF-8?q?stream=20re-checks=20and=20caps,=20admin=202FA=20policy=20on=20?= =?UTF-8?q?refresh?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0003_consumed_pending_logins.sql | 10 + crates/im-core/src/password.rs | 42 +++- crates/im-core/src/store/migrate.rs | 4 + crates/im-core/src/store/mod.rs | 2 +- crates/im-core/src/store/sessions.rs | 2 +- crates/im-core/src/store/users.rs | 79 ++++-- crates/im-core/src/totp.rs | 33 ++- crates/im-web/src/auth.rs | 31 ++- crates/im-web/src/boot.rs | 6 +- crates/im-web/src/live.rs | 50 +++- crates/im-web/src/oidc/logout.rs | 22 +- crates/im-web/src/oidc/tests.rs | 33 ++- crates/im-web/src/oidc/token.rs | 5 + crates/im-web/src/pages/admin/message.rs | 8 +- crates/im-web/src/pages/admin/mod.rs | 25 +- crates/im-web/src/pages/admin/users.rs | 2 +- crates/im-web/src/pages/email.rs | 9 +- crates/im-web/src/pages/login.rs | 40 +-- crates/im-web/src/pages/reset.rs | 19 +- crates/im-web/src/pages/security.rs | 148 +++++------ crates/im-web/src/state.rs | 4 +- crates/im-web/src/throttle.rs | 230 ++++++++++++++---- 22 files changed, 553 insertions(+), 251 deletions(-) create mode 100644 crates/im-core/migrations/0003_consumed_pending_logins.sql diff --git a/crates/im-core/migrations/0003_consumed_pending_logins.sql b/crates/im-core/migrations/0003_consumed_pending_logins.sql new file mode 100644 index 0000000..0bab181 --- /dev/null +++ b/crates/im-core/migrations/0003_consumed_pending_logins.sql @@ -0,0 +1,10 @@ +-- 0003: the pending-login nonces that a second factor has spent. A password-verified sign-in may be +-- completed once; its nonce is kept until the pending cookie would have expired, so a restart does not +-- reopen a spent cookie. Rows past expires_at are removed by the next spend. + +CREATE TABLE consumed_pending_logins ( + nonce TEXT PRIMARY KEY NOT NULL, + expires_at TEXT NOT NULL +); + +CREATE INDEX consumed_pending_logins_expires ON consumed_pending_logins (expires_at); diff --git a/crates/im-core/src/password.rs b/crates/im-core/src/password.rs index 3e2e0bf..b08e5a8 100644 --- a/crates/im-core/src/password.rs +++ b/crates/im-core/src/password.rs @@ -7,6 +7,7 @@ use argon2::Argon2; use argon2::password_hash::phc::PasswordHash; use argon2::password_hash::{PasswordHasher, PasswordVerifier}; +use tokio::sync::{Semaphore, SemaphorePermit}; use crate::error::{Error, Result}; @@ -18,12 +19,28 @@ pub const MIN_PASSWORD_CHARS: usize = 10; /// per request. pub const MAX_PASSWORD_CHARS: usize = 256; +/// Most argon2 operations running at once. Each one takes tens of megabytes, so a burst of requests +/// queues here instead of starting one blocking thread and one hash per request. +const HASH_PERMITS: usize = 4; + +/// The gate of every async hash and verify. +static HASHING: Semaphore = Semaphore::const_new(HASH_PERMITS); + +/// True for a password longer than [`MAX_PASSWORD_CHARS`]. Such a password is never hashed or verified. +fn too_long(pw: &str) -> bool { + pw.chars().count() > MAX_PASSWORD_CHARS +} + /// Shortest word of the name or email local part that a password may not contain, in characters. /// Shorter words are too common to forbid: a two-letter word would reject many good passwords. pub const MIN_FORBIDDEN_WORD_CHARS: usize = 4; -/// Hashes `pw` with argon2id (default parameters) and a fresh random salt. Returns a PHC string. +/// Hashes `pw` with argon2id (default parameters) and a fresh random salt. Returns a PHC string. A +/// password over [`MAX_PASSWORD_CHARS`] is refused before any hashing. pub fn hash_password(pw: &str) -> Result { + if too_long(pw) { + return Err(Error::Invalid("the password is too long".into())); + } Argon2::default() .hash_password(pw.as_bytes()) .map(|h| h.to_string()) @@ -31,8 +48,11 @@ pub fn hash_password(pw: &str) -> Result { } /// Returns true only if `pw` matches the PHC string `hash`. A malformed hash gives false, never -/// a panic. +/// a panic. A password over [`MAX_PASSWORD_CHARS`] gives false without any hashing. pub fn verify_password(pw: &str, hash: &str) -> bool { + if too_long(pw) { + return false; + } let Ok(parsed) = PasswordHash::new(hash) else { return false; }; @@ -41,15 +61,29 @@ pub fn verify_password(pw: &str, hash: &str) -> bool { .is_ok() } -/// [`hash_password`] on the blocking thread pool. +/// Takes one of the [`HASH_PERMITS`] slots. Held until the blocking work ends. +async fn gate() -> Result> { + HASHING + .acquire() + .await + .map_err(|e| Error::Crypto(format!("hashing gate closed: {e}"))) +} + +/// [`hash_password`] on the blocking thread pool, behind the hashing gate. pub async fn hash_password_async(pw: String) -> Result { + let _permit = gate().await?; tokio::task::spawn_blocking(move || hash_password(&pw)) .await .map_err(|e| Error::Crypto(format!("hashing task failed: {e}")))? } -/// [`verify_password`] on the blocking thread pool. +/// [`verify_password`] on the blocking thread pool, behind the hashing gate. An over-long password is +/// answered without taking a slot. pub async fn verify_password_async(pw: String, hash: String) -> Result { + if too_long(&pw) { + return Ok(false); + } + let _permit = gate().await?; tokio::task::spawn_blocking(move || verify_password(&pw, &hash)) .await .map_err(|e| Error::Crypto(format!("verify task failed: {e}"))) diff --git a/crates/im-core/src/store/migrate.rs b/crates/im-core/src/store/migrate.rs index 01fc518..c6162a1 100644 --- a/crates/im-core/src/store/migrate.rs +++ b/crates/im-core/src/store/migrate.rs @@ -16,6 +16,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ 2, include_str!("../../migrations/0002_sessions_cap_and_language.sql"), ), + ( + 3, + include_str!("../../migrations/0003_consumed_pending_logins.sql"), + ), ]; fn migration_err(e: turso::Error) -> Error { diff --git a/crates/im-core/src/store/mod.rs b/crates/im-core/src/store/mod.rs index 43c9503..81e5599 100644 --- a/crates/im-core/src/store/mod.rs +++ b/crates/im-core/src/store/mod.rs @@ -335,6 +335,6 @@ mod tests { }) .await .unwrap(); - assert_eq!(applied, vec![1, 2]); + assert_eq!(applied, vec![1, 2, 3]); } } diff --git a/crates/im-core/src/store/sessions.rs b/crates/im-core/src/store/sessions.rs index b1a9195..73e462b 100644 --- a/crates/im-core/src/store/sessions.rs +++ b/crates/im-core/src/store/sessions.rs @@ -83,7 +83,7 @@ pub struct CreatedSession { /// The ids of the live sessions of `user_id` except `keep` (none keeps nothing), oldest first. /// Only sessions that are still live count; expired rows are removed by the sweeper. -async fn live_session_ids( +pub(crate) async fn live_session_ids( conn: &Connection, user_id: &str, keep: Option<&str>, diff --git a/crates/im-core/src/store/users.rs b/crates/im-core/src/store/users.rs index bcda7cd..195a780 100644 --- a/crates/im-core/src/store/users.rs +++ b/crates/im-core/src/store/users.rs @@ -18,6 +18,7 @@ use crate::error::{Error, Result}; use crate::model::User; use crate::store::backchannel::{self, EndReason}; use crate::store::directory::{ChangeKind, record_change}; +use crate::store::sessions::{end_rows, live_session_ids}; use crate::store::{ Store, col_int, col_opt_int, col_opt_text, col_text, db_err, fetch_opt, finish, new_id, }; @@ -318,20 +319,36 @@ impl Store { result } - /// Stores a new argon2id hash. The caller has checked the policy and the current password. - pub async fn set_password_hash(&self, id: &str, password_hash: &str) -> Result<()> { + /// Stores a new argon2id hash and ends every live session of the person except `keep_session_id`, + /// with their back-channel logouts. One transaction: the old password never stays in force for a + /// session that the new one has ended, and nothing changes unless both happen. The caller has checked + /// the policy and the current password. Returns the ids of the sessions ended. + pub async fn change_password( + &self, + id: &str, + password_hash: &str, + keep_session_id: &str, + ) -> Result> { + let now = now_stamp(); let conn = self.inner.conn.lock().await; - let changed = conn - .execute( - "UPDATE users SET password_hash = ?2, updated_at = ?3 WHERE id = ?1", - (id.to_string(), password_hash.to_string(), now_stamp()), - ) - .await - .map_err(db_err)?; - if changed == 0 { - return Err(Error::NotFound); + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result> = async { + let changed = tx + .execute( + "UPDATE users SET password_hash = ?2, updated_at = ?3 WHERE id = ?1", + (id.to_string(), password_hash.to_string(), now.clone()), + ) + .await + .map_err(db_err)?; + if changed == 0 { + return Err(Error::NotFound); + } + let ids = live_session_ids(&tx, id, Some(keep_session_id), &now).await?; + end_rows(&tx, id, &ids, EndReason::PasswordChanged, &now).await?; + Ok(ids) } - Ok(()) + .await; + finish(tx, outcome).await } /// Disables an account. The last enabled administrator cannot be disabled: that is part of the @@ -435,8 +452,11 @@ impl Store { } /// Turns two-factor sign-in off: clears the secret, the step and the recovery codes, and drops - /// any pending enrolment. One transaction. - pub async fn disable_totp(&self, user_id: &str) -> Result<()> { + /// any pending enrolment. Two-factor sign-in was the policy's guard for the session, so in the same + /// transaction the person's refresh tokens are revoked and every live session except `keep_session_id` + /// ends, with its back-channel logouts. `None` ends all of them. + pub async fn disable_totp(&self, user_id: &str, keep_session_id: Option<&str>) -> 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 { @@ -444,7 +464,7 @@ impl Store { .execute( "UPDATE users SET totp_secret_sealed = NULL, totp_enabled_at = NULL, \ totp_last_step = NULL, updated_at = ?2 WHERE id = ?1", - (user_id.to_string(), now_stamp()), + (user_id.to_string(), now.clone()), ) .await .map_err(db_err)?; @@ -463,12 +483,41 @@ impl Store { ) .await .map_err(db_err)?; + tx.execute( + "UPDATE refresh_tokens SET revoked_at = ?2 WHERE user_id = ?1 AND revoked_at IS NULL", + (user_id.to_string(), now.clone()), + ) + .await + .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(()) } .await; finish(tx, outcome).await } + /// Spends the pending-login nonce of a password-verified sign-in that has just passed its second + /// factor. Returns true only for the first spend. `keep_until` is when the nonce may be forgotten: + /// after the pending cookie expired, it could not be used anyway. Expired nonces are removed here. + pub async fn consume_pending_login(&self, nonce: &str, keep_until: &str) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM consumed_pending_logins WHERE expires_at <= ?1", + (now_stamp(),), + ) + .await + .map_err(db_err)?; + let changed = conn + .execute( + "INSERT OR IGNORE INTO consumed_pending_logins (nonce, expires_at) VALUES (?1, ?2)", + (nonce.to_string(), keep_until.to_string()), + ) + .await + .map_err(db_err)?; + Ok(changed == 1) + } + /// 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-core/src/totp.rs b/crates/im-core/src/totp.rs index 743d8b2..31f7363 100644 --- a/crates/im-core/src/totp.rs +++ b/crates/im-core/src/totp.rs @@ -9,7 +9,7 @@ use hmac::{Hmac, KeyInit, Mac}; use sha1::Sha1; -use sha2::{Digest, Sha256}; +use sha2::Sha256; use crate::token::{constant_time_eq, random_readable}; @@ -32,6 +32,12 @@ const BASE32_ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; type HmacSha1 = Hmac; +type HmacSha256 = Hmac; + +/// What a recovery-code subkey is derived for. The subkey is HMAC of this label under the instance key, +/// so the instance key itself keys only that derivation. +const RECOVERY_SUBKEY_LABEL: &[u8] = b"im recovery code key v1"; + /// A fresh random secret of [`SECRET_LEN`] bytes. pub fn new_secret() -> [u8; SECRET_LEN] { let mut secret = [0u8; SECRET_LEN]; @@ -144,16 +150,26 @@ pub fn new_recovery_code() -> String { format!("{}-{}", &raw[..4], &raw[4..]) } -/// Hex SHA-256 of a recovery code after normalisation: lowercase, without dashes and spaces. The -/// stored hash and the checked input go through the same normalisation, so how the person types -/// the code does not matter. -pub fn recovery_code_hash(code: &str) -> String { +/// Hex HMAC-SHA256 of a recovery code after normalisation: lowercase, without dashes and spaces. The +/// key is a subkey of the instance key `key`, so a copy of the database alone cannot be checked against +/// guesses: the codes are random, but a fast unkeyed hash would still allow an offline search. The stored +/// hash and the checked input go through the same normalisation, so how the person types the code does +/// not matter. +pub fn recovery_code_hash(key: &[u8; 32], code: &str) -> String { let normalized: String = code .chars() .filter(|c| !c.is_whitespace() && *c != '-') .map(|c| c.to_ascii_lowercase()) .collect(); - hex::encode(Sha256::digest(normalized.as_bytes())) + // HMAC accepts a key of any length, so construction cannot fail. + let mut derive = + ::new_from_slice(key).expect("HMAC takes any key length"); + derive.update(RECOVERY_SUBKEY_LABEL); + let subkey = derive.finalize().into_bytes(); + let mut mac = + ::new_from_slice(&subkey).expect("HMAC takes any key length"); + mac.update(normalized.as_bytes()); + hex::encode(mac.finalize().into_bytes()) } #[cfg(test)] @@ -220,9 +236,10 @@ mod tests { let code = new_recovery_code(); assert_eq!(code.len(), 9); assert_eq!(code.as_bytes()[4], b'-'); + let key = [7u8; 32]; assert_eq!( - recovery_code_hash(&code), - recovery_code_hash(&code.to_uppercase().replace('-', " ")) + recovery_code_hash(&key, &code), + recovery_code_hash(&key, &code.to_uppercase().replace('-', " ")) ); } } diff --git a/crates/im-web/src/auth.rs b/crates/im-web/src/auth.rs index d09e99a..27bcf42 100644 --- a/crates/im-web/src/auth.rs +++ b/crates/im-web/src/auth.rs @@ -102,11 +102,15 @@ pub async fn require_user(cx: &Cx) -> Result { } } -/// The signed-in administrator. A person who is not an administrator gets 404, the same answer as a -/// page that does not exist. An administrator without two-factor sign-in, while the policy requires +/// The signed-in administrator. A visitor without a session, and a person who is not an administrator, +/// get 404, the same answer as a page that does not exist. An administrator without two-factor sign-in, while the policy requires /// it, is sent to the security page instead. pub async fn require_admin(cx: &Cx) -> Result { - let viewer = require_user(cx).await?; + // Anyone without a live session gets 404 too: an admin page does not redirect to sign-in, so its + // existence is not revealed to visitors. + let Some(viewer) = current_user(cx).await? else { + return Err(not_found().into()); + }; if !viewer.user.is_admin { return Err(not_found().into()); } @@ -256,6 +260,8 @@ fn pre_csrf_cookie(token: String) -> Cookie<'static> { /// A password-verified sign-in that waits for its second factor. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Pending { + /// Random id of this pending sign-in. The second factor spends it once (`Store::consume_pending_login`). + pub nonce: String, /// The person who passed the password step. pub user_id: String, /// The authentication method so far. Always the password. @@ -265,10 +271,12 @@ pub struct Pending { } /// Parks a password-verified sign-in in the pending cookie. The payload is sealed with the instance -/// key, so the browser can neither change the person nor extend the expiry. +/// key, so the browser can neither change the person nor extend the expiry. It carries a random nonce, +/// which a successful second factor spends, so the same cookie cannot sign in twice. pub fn set_pending_login(cx: &Cx, key: &[u8; 32], user_id: &str, next: &str) -> Result<()> { let expires = unix_now() + PENDING_TTL.as_secs(); - let payload = format!("{user_id}|{expires}|{}|{next}", amr::PASSWORD); + let nonce = generate_token(); + let payload = format!("{user_id}|{expires}|{}|{nonce}|{next}", amr::PASSWORD); let sealed = secret::seal(key, payload.as_bytes())?; let max_age = time::Duration::seconds(i64::try_from(PENDING_TTL.as_secs()).unwrap_or(0)); jar(cx).add( @@ -290,15 +298,17 @@ pub fn pending_login(cx: &Cx, key: &[u8; 32]) -> Option { let plain = secret::open(key, cookie.value()).ok()?; let text = String::from_utf8(plain).ok()?; // `next` comes last, so a `|` inside it cannot shift the other fields. - let mut parts = text.splitn(4, '|'); + let mut parts = text.splitn(5, '|'); let user_id = parts.next()?; let expires: u64 = parts.next()?.parse().ok()?; let amr = parts.next()?; + let nonce = parts.next()?; let next = parts.next()?; if unix_now() >= expires { return None; } Some(Pending { + nonce: nonce.to_owned(), user_id: user_id.to_owned(), amr: amr.to_owned(), next: next.to_owned(), @@ -346,7 +356,7 @@ pub async fn check_second_factor( return Ok(None); } let spent = store - .consume_recovery_code(&user.id, &totp::recovery_code_hash(input)) + .consume_recovery_code(&user.id, &totp::recovery_code_hash(key, input)) .await?; Ok(spent.then_some(amr::PASSWORD_RECOVERY)) } @@ -466,7 +476,12 @@ mod tests { let code = totp::new_recovery_code(); state .store - .enable_totp(&user.id, &sealed, 1, &[totp::recovery_code_hash(&code)]) + .enable_totp( + &user.id, + &sealed, + 1, + &[totp::recovery_code_hash(&state.key, &code)], + ) .await .expect("enable"); let user = state diff --git a/crates/im-web/src/boot.rs b/crates/im-web/src/boot.rs index ece966d..c19aa52 100644 --- a/crates/im-web/src/boot.rs +++ b/crates/im-web/src/boot.rs @@ -16,13 +16,13 @@ use im_core::secret; use im_core::store::Store; use tokio::net::TcpListener; use tokio::signal::unix::{SignalKind, signal}; -use tokio::sync::watch; +use tokio::sync::{Semaphore, watch}; use topcoat::cookie::RouterBuilderCookieExt; use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService}; use crate::api::directory::StreamSlots; use crate::backchannel; -use crate::live::LiveHub; +use crate::live::{LiveHub, MAX_ANONYMOUS_STREAMS}; use crate::mail; use crate::oidc::signing; use crate::pages::not_found::NotFoundLayer; @@ -152,6 +152,7 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result { live: Arc::new(LiveHub::default()), throttle: Arc::new(Throttle::default()), stream_slots: Arc::new(StreamSlots::default()), + anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), // Replaced by the stop flag of `serve` before any listener starts. The CLI never serves. stop: watch::channel(false).1, }) @@ -256,6 +257,7 @@ mod tests { live: Arc::new(LiveHub::default()), throttle: Arc::new(Throttle::default()), stream_slots: Arc::new(StreamSlots::default()), + anonymous_streams: Arc::new(Semaphore::new(MAX_ANONYMOUS_STREAMS)), stop: watch::channel(false).1, }; (dir, state) diff --git a/crates/im-web/src/live.rs b/crates/im-web/src/live.rs index fdd3f47..8497d5e 100644 --- a/crates/im-web/src/live.rs +++ b/crates/im-web/src/live.rs @@ -10,22 +10,24 @@ //! authenticates and authorises first, then calls [`stream_changes`]. //! //! Every stream ends when the process stops (the stop flag in [`AppState`]), so a shutdown does not wait -//! for a browser to close its connection. +//! for a browser to close its connection. No stream lives longer than [`MAX_STREAM_LIFE`]: the browser +//! reconnects, and each new connection authenticates again. use std::collections::HashMap; use std::future::Future; -use std::sync::{Mutex, MutexGuard, PoisonError}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use std::time::Duration; use futures_util::{Stream, StreamExt, future::select_all, stream}; use im_core::store::Store; -use tokio::sync::watch; +use tokio::sync::{OwnedSemaphorePermit, watch}; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::sse::{Event, KeepAlive, Sse}; use topcoat::router::response::{IntoResponse, Response}; -use topcoat::router::{HeaderValue, route}; +use topcoat::router::{HeaderValue, StatusCode, route}; +use crate::api::api_error; use crate::auth::current_user; use crate::state::AppState; @@ -35,6 +37,13 @@ pub const STREAM_RETRY: Duration = Duration::from_millis(1000); /// Silence after which the server sends a keep-alive comment, so proxies keep the stream open. pub const KEEP_ALIVE: Duration = Duration::from_secs(30); +/// Longest a stream lives, whatever happens on it. The browser reconnects after it, and a reconnect +/// authenticates and authorises again, so a session that ended or lost its role is not kept by a stream. +pub const MAX_STREAM_LIFE: Duration = Duration::from_secs(60 * 60); + +/// Anonymous `/-/alive` streams open at once, across the whole process. A further one gets `429`. +pub const MAX_ANONYMOUS_STREAMS: usize = 256; + /// What a live page follows. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum Topic { @@ -96,6 +105,8 @@ impl LiveHub { struct Follow { wakes: Vec>, stop: watch::Receiver, + /// When the stream ends, whatever else happened ([`MAX_STREAM_LIFE`]). + until: tokio::time::Instant, fingerprint: F, last: String, } @@ -104,8 +115,9 @@ struct Follow { /// differs from the value it last sent, so a bump that changes nothing the viewer sees sends /// nothing. Nothing is sent on connect: the page already shows the state that `fingerprint` read. /// -/// `fingerprint` must be cheap and must describe everything the page shows. A read that fails ends -/// the stream, and the browser reconnects. +/// `fingerprint` must be cheap and must describe everything the page shows. It runs on every wake, before +/// anything is sent, so it is also the place to check the viewer again: an error (a read that fails, or a +/// viewer who may no longer see the page) ends the stream, and the browser reconnects and is refused. pub async fn stream_changes( cx: &Cx, hub: &LiveHub, @@ -123,6 +135,7 @@ where let follow = Follow { wakes, stop: app_context::(cx).stop.clone(), + until: tokio::time::Instant::now() + MAX_STREAM_LIFE, fingerprint, last, }; @@ -131,6 +144,7 @@ where let woke = tokio::select! { woke = wait_any(&mut follow.wakes) => woke, () = stopped(&mut follow.stop) => false, + () = tokio::time::sleep_until(follow.until) => false, }; if !woke { return None; @@ -197,6 +211,8 @@ struct AccountFollow { wake: watch::Receiver, /// Set when the process stops. The stream then ends. stop: watch::Receiver, + /// When the stream ends, whatever else happened ([`MAX_STREAM_LIFE`]). + until: tokio::time::Instant, /// Checks that the session of this stream still exists. store: Store, /// The session the stream was opened with. @@ -215,10 +231,22 @@ struct AccountFollow { async fn alive(cx: &Cx) -> Result { let state = app_context::(cx); let Some(viewer) = current_user(cx).await? else { - // Anonymous: no events, but the stream still ends when the process stops. - let events = stream::unfold(state.stop.clone(), |mut stop| async move { - stopped(&mut stop).await; - None::<(Result, watch::Receiver)> + // Anonymous: no events, but the stream still ends when the process stops or its time is up. The + // slot is held for the life of the stream, so the number of these is capped for the process. + let Ok(slot) = Arc::clone(&state.anonymous_streams).try_acquire_owned() else { + return Ok(api_error( + StatusCode::TOO_MANY_REQUESTS, + "rate_limited", + "Too many open streams. Try again shortly.", + None, + )); + }; + let events = stream::unfold((state.stop.clone(), slot), |(mut stop, _slot)| async move { + tokio::select! { + () = stopped(&mut stop) => {} + () = tokio::time::sleep(MAX_STREAM_LIFE) => {} + } + None::<(Result, (watch::Receiver, OwnedSemaphorePermit))> }); return events_response(cx, events); }; @@ -227,6 +255,7 @@ async fn alive(cx: &Cx) -> Result { .live .subscribe(&Topic::Account(viewer.user.id.clone())), stop: state.stop.clone(), + until: tokio::time::Instant::now() + MAX_STREAM_LIFE, store: state.store.clone(), session_id: viewer.session.id.clone(), done: false, @@ -238,6 +267,7 @@ async fn alive(cx: &Cx) -> Result { 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; diff --git a/crates/im-web/src/oidc/logout.rs b/crates/im-web/src/oidc/logout.rs index 8a33ca9..7c48ad9 100644 --- a/crates/im-web/src/oidc/logout.rs +++ b/crates/im-web/src/oidc/logout.rs @@ -8,9 +8,9 @@ //! `post_logout_redirect_uri` equals one of its registered URIs exactly. Otherwise the answer is the //! signed-out page, never a redirect. //! - `state` is echoed on the redirect only when it is usable (bounded, no control characters). -//! - A `GET` ends a session only when the hint's `sid` is the browser's own session: an attacker's -//! link cannot know that. Any other `GET` shows a confirmation form, which carries the session's CSRF -//! token. A `POST` checks that token before anything changes. +//! - 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. //! - 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. @@ -173,28 +173,14 @@ async fn sign_out(cx: &Cx, viewer: &Viewer, hint_sid: Option<&str>) -> Result<() Ok(()) } -/// `GET /logout`. +/// `GET /logout`. Never ends a session: with one, it shows the confirmation form. #[page(GET "/logout")] async fn logout_get(cx: &Cx, Form(form): Form) -> Result { let app = app_context::(cx); let asked = read(app, &form).await?; let viewer = current_user(cx).await?; let lang = page_lang(cx, viewer.as_ref()); - let own_session = viewer.as_ref().is_some_and(|viewer| { - asked - .hint - .as_ref() - .and_then(|hint| hint.sid.as_deref()) - .is_some_and(|sid| sid == viewer.session.id) - }); match viewer { - Some(viewer) if own_session => { - sign_out(cx, &viewer, None).await?; - if let Some(target) = redirect_target(&asked) { - return Err(see_other(target).into()); - } - Ok(logout_view(cx, lang, None)) - } Some(viewer) => { let confirm = Confirm { csrf: viewer.session.csrf_token.clone(), diff --git a/crates/im-web/src/oidc/tests.rs b/crates/im-web/src/oidc/tests.rs index 36e58fc..e520ebb 100644 --- a/crates/im-web/src/oidc/tests.rs +++ b/crates/im-web/src/oidc/tests.rs @@ -425,16 +425,30 @@ async fn id_token_of(f: &Fixture) -> String { tokens["id_token"].as_str().expect("id_token").to_owned() } +/// The CSRF token of the fixture's browser session. +async fn csrf_of(f: &Fixture) -> String { + f.state + .store + .session_by_token_hash(&hash_token(&f.cookie)) + .await + .expect("lookup") + .expect("session") + .csrf_token +} + #[tokio::test] async fn logout_redirects_only_to_the_registered_post_logout_uri() { let f = fixture().await; let hint = encode_value(&id_token_of(&f).await); let unregistered = encode_value("http://127.0.0.1:17651/elsewhere"); - let path = - format!("/logout?id_token_hint={hint}&post_logout_redirect_uri={unregistered}&state=abc"); - let request = http::Request::get(path) + let body = format!( + "csrf={}&id_token_hint={hint}&post_logout_redirect_uri={unregistered}&state=abc", + csrf_of(&f).await + ); + let request = http::Request::post("/logout") .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie)) - .body(Body::empty()) + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") + .body(Body::from(body)) .expect("request"); let (status, headers, body) = send(&f.state, request).await; assert_eq!(status, StatusCode::OK, "{body}"); @@ -457,11 +471,14 @@ async fn logout_with_the_registered_uri_redirects_and_carries_the_state() { let f = fixture().await; let hint = encode_value(&id_token_of(&f).await); let registered = encode_value(POST_LOGOUT); - let path = - format!("/logout?id_token_hint={hint}&post_logout_redirect_uri={registered}&state=abc"); - let request = http::Request::get(path) + let body = format!( + "csrf={}&id_token_hint={hint}&post_logout_redirect_uri={registered}&state=abc", + csrf_of(&f).await + ); + let request = http::Request::post("/logout") .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie)) - .body(Body::empty()) + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") + .body(Body::from(body)) .expect("request"); let (status, headers, _) = send(&f.state, request).await; assert_eq!(status, StatusCode::SEE_OTHER); diff --git a/crates/im-web/src/oidc/token.rs b/crates/im-web/src/oidc/token.rs index 6ebd6c3..2204b06 100644 --- a/crates/im-web/src/oidc/token.rs +++ b/crates/im-web/src/oidc/token.rs @@ -283,6 +283,11 @@ async fn grant_refresh(app: &AppState, client: &Client, pairs: &Pairs) -> Result else { return Ok(invalid_grant()); }; + // The administrator policy holds for refresh too: an administrator without two-factor sign-in gets no + // more tokens, the same as the admin pages refuse them. + if user.is_admin && app.policy().require_2fa_for_admins && !user.totp_enabled() { + return Ok(invalid_grant()); + } let refresh = generate_token(); let refresh_id = new_id(); diff --git a/crates/im-web/src/pages/admin/message.rs b/crates/im-web/src/pages/admin/message.rs index a661760..20f4849 100644 --- a/crates/im-web/src/pages/admin/message.rs +++ b/crates/im-web/src/pages/admin/message.rs @@ -84,11 +84,12 @@ async fn send_message(cx: &Cx, Form(form): Form) -> Result BODY_MAX { return Ok(refused("/admin/message", "message-body")); } - let now = Instant::now(); + // Counted before the sends, so parallel submits cannot all pass the limit. A send is what is limited, so + // the count stays whatever the outcome. if state .throttle - .check(THROTTLE_KEY, SENDS_PER_WINDOW, now) - .is_some() + .reserve(THROTTLE_KEY, SENDS_PER_WINDOW, Instant::now()) + .is_err() { return Ok(refused("/admin/message", "rate-limited")); } @@ -105,7 +106,6 @@ async fn send_message(cx: &Cx, Form(form): Form) -> Result Result { /// `GET /admin/events`: the live stream of the admin pages. It sends one `changed` event for each admin /// write, and the page fetches itself again. Non-administrators get 404. +/// +/// The session and the administrator role are checked again on every wake, before an event is sent. A +/// session that ended, or an account that lost the role or was disabled, ends the stream. #[route(GET "/admin/events")] async fn admin_events(cx: &Cx) -> Result { - require_admin(cx).await?; + let viewer = require_admin(cx).await?; let state = app_context::(cx); let live = state.live.clone(); + let store = state.store.clone(); + let session_id = viewer.session.id.clone(); + let user_id = viewer.user.id.clone(); stream_changes(cx, &state.live, &[Topic::Admin], move || { let live = live.clone(); - async move { Ok(live.generation(&Topic::Admin).to_string()) } + let store = store.clone(); + let session_id = session_id.clone(); + let user_id = user_id.clone(); + async move { + let session_live = store.session_is_live(&session_id).await?; + let admin = store + .user_by_id(&user_id) + .await? + .is_some_and(|user| user.is_admin && !user.is_disabled()); + if !(session_live && admin) { + return Err(topcoat::Error::msg( + "the administrator stream is no longer allowed", + )); + } + Ok(live.generation(&Topic::Admin).to_string()) + } }) .await } diff --git a/crates/im-web/src/pages/admin/users.rs b/crates/im-web/src/pages/admin/users.rs index dcc03ea..cea33d9 100644 --- a/crates/im-web/src/pages/admin/users.rs +++ b/crates/im-web/src/pages/admin/users.rs @@ -423,7 +423,7 @@ async fn reset_two_factor(cx: &Cx, Form(form): Form) -> Result(cx); - state.store.disable_totp(&user.id).await?; + state.store.disable_totp(&user.id, None).await?; state.live.bump(&Topic::Account(user.id.clone())); changed(&state.live); let request_lang = page_lang(cx, Some(&viewer)); diff --git a/crates/im-web/src/pages/email.rs b/crates/im-web/src/pages/email.rs index e0e76e0..3235b7c 100644 --- a/crates/im-web/src/pages/email.rs +++ b/crates/im-web/src/pages/email.rs @@ -30,7 +30,7 @@ use crate::i18n::flows::{Flow, email_link_summary, text as flow_text}; use crate::live::Topic; use crate::mail::{self, Mail, Recipient}; use crate::pages::path_param; -use crate::pages::security::{password_locked, password_matches}; +use crate::pages::security::password_problem; use crate::state::AppState; use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell}; @@ -97,11 +97,8 @@ async fn email_request_submit(cx: &Cx, Form(form): Form) -> Re ) }; - if password_locked(state, &viewer) { - return Ok(refuse(Txt::ErrThrottled)); - } - if !password_matches(state, &viewer, &form.current_password).await? { - return Ok(refuse(Txt::ErrWrongPassword)); + if let Some(problem) = password_problem(state, &viewer, &form.current_password).await? { + return Ok(refuse(problem)); } let new_email = match parse_email(&form.new_email) { Ok(email) => email, diff --git a/crates/im-web/src/pages/login.rs b/crates/im-web/src/pages/login.rs index 72ea1f1..3186ae5 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::time::stamp_after; use serde::Deserialize; use serde_json::{Value, json}; use topcoat::Result; @@ -23,8 +24,8 @@ use topcoat::view::{View, view}; use crate::audit::{Actor, record}; use crate::auth::{ - after_sign_in, check_pre_csrf, check_second_factor, clear_pending_login, clear_pre_csrf, - pending_login, pre_csrf_token, safe_next, set_pending_login, start_session, + PENDING_TTL, after_sign_in, check_pre_csrf, check_second_factor, clear_pending_login, + clear_pre_csrf, pending_login, pre_csrf_token, safe_next, set_pending_login, start_session, }; use crate::client_ip::client_ip; use crate::i18n::Lang; @@ -102,14 +103,14 @@ async fn login_submit(cx: &Cx, Form(form): Form) -> Result let email = normalize_email(&form.email); let user_limit = user_key(&email); let ip_limit = ip_key("login-ip", client_ip(cx)); - let now = Instant::now(); - // A key over its limit answers with the throttle message and a Retry-After, before any lookup. - let wait = [(&user_limit, LOGIN_USER_LIMIT), (&ip_limit, LOGIN_IP_LIMIT)] - .iter() - .filter_map(|(key, limit)| state.throttle.check(key, *limit, now)) - .max(); - if let Some(wait) = wait { + // Both keys are counted before the lookup, as one step. A key over its limit answers with the throttle + // message and a Retry-After, and nothing is counted against the other key either. + let reserved = state.throttle.reserve_all( + &[(&user_limit, LOGIN_USER_LIMIT), (&ip_limit, LOGIN_IP_LIMIT)], + Instant::now(), + ); + if let Err(wait) = reserved { retry_after(cx, wait); let lang = page_lang(cx, None); return Ok(login_view( @@ -130,9 +131,8 @@ async fn login_submit(cx: &Cx, Form(form): Form) -> Result }; let password_ok = verify_password_async(form.password.clone(), hash).await?; 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 { - state.throttle.record_failure(&user_limit, now); - state.throttle.record_failure(&ip_limit, now); let target = target_id.as_deref().map(|id| ("user", id)); record( cx, @@ -154,7 +154,9 @@ async fn login_submit(cx: &Cx, Form(form): Form) -> Result )); }; + // A success forgets the account's earlier failures, and gives this address's attempt back. state.throttle.clear(&user_limit); + state.throttle.refund(&ip_limit); if user.totp_enabled() { set_pending_login(cx, &state.key, &user.id, &next)?; return Err(see_other("/login/2fa").into()); @@ -192,8 +194,10 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form) -> Result) -> 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()); + } state.throttle.clear(&limit); clear_pending_login(cx); Err(finish_sign_in(cx, &user, method, &pending.next).await?) } None => { - state.throttle.record_failure(&limit, now); record( cx, Actor::User(&user.id), diff --git a/crates/im-web/src/pages/reset.rs b/crates/im-web/src/pages/reset.rs index d7b7be1..ca6c542 100644 --- a/crates/im-web/src/pages/reset.rs +++ b/crates/im-web/src/pages/reset.rs @@ -84,21 +84,22 @@ async fn forgot_submit(cx: &Cx, Form(form): Form) -> Result(cx); let lang = page_lang(cx, None); - let now = Instant::now(); let email = normalize_email(&form.email); let client = client_ip(cx); let email_limit = forgot_email_key(&email); let client_limit = ip_key("forgot-ip", client); + // Counted only while neither key is limited: a request refused by the limit is not counted again, so + // the mail of a flood is capped at the limit's worth per window. let limited = state .throttle - .check(&email_limit, FORGOT_EMAIL_LIMIT, now) - .is_some() - || state - .throttle - .check(&client_limit, FORGOT_IP_LIMIT, now) - .is_some(); - state.throttle.record_failure(&email_limit, now); - state.throttle.record_failure(&client_limit, now); + .reserve_all( + &[ + (&email_limit, FORGOT_EMAIL_LIMIT), + (&client_limit, FORGOT_IP_LIMIT), + ], + Instant::now(), + ) + .is_err(); // The same lookup for a known and an unknown address; only a known, enabled one gets a link. if !limited diff --git a/crates/im-web/src/pages/security.rs b/crates/im-web/src/pages/security.rs index 83aa644..f486850 100644 --- a/crates/im-web/src/pages/security.rs +++ b/crates/im-web/src/pages/security.rs @@ -9,7 +9,6 @@ use base64::engine::general_purpose::STANDARD as BASE64; use im_core::model::AuditAction; use im_core::password::{check_policy, hash_password_async, verify_password_async}; use im_core::secret; -use im_core::store::backchannel::EndReason; use im_core::totp; use serde::Deserialize; use serde_json::json; @@ -62,6 +61,17 @@ struct CodeForm { code: String, } +/// The enrolment form: the current password when two-factor sign-in is off, a code when it is on. +#[derive(Deserialize, Default)] +struct StartForm { + #[serde(default)] + csrf: String, + #[serde(default)] + current_password: String, + #[serde(default)] + code: String, +} + /// The turn-off form: the password and a second factor. #[derive(Deserialize, Default)] struct DisableForm { @@ -131,21 +141,8 @@ async fn change_password(cx: &Cx, Form(form): Form) -> Result(cx); let lang = page_lang(cx, Some(&viewer)); - if password_locked(state, &viewer) { - return render_security( - cx, - viewer.clone(), - Flash::alert(text(lang, Txt::ErrThrottled)), - ) - .await; - } - if !password_matches(state, &viewer, &form.current_password).await? { - return render_security( - cx, - viewer.clone(), - Flash::alert(text(lang, Txt::ErrWrongPassword)), - ) - .await; + if let Some(problem) = password_problem(state, &viewer, &form.current_password).await? { + return render_security(cx, viewer.clone(), Flash::alert(text(lang, problem))).await; } if form.new_password != form.new_password_again { return render_security( @@ -170,18 +167,11 @@ async fn change_password(cx: &Cx, Form(form): Form) -> Result) -> Result) -> Result { +async fn start_enrolment(cx: &Cx, Form(form): Form) -> Result { let viewer = require_csrf(cx, &form.csrf).await?; let state = app_context::(cx); let lang = page_lang(cx, Some(&viewer)); @@ -220,11 +210,10 @@ async fn start_enrolment(cx: &Cx, Form(form): Form) -> Result) -> Result) -> Result) -> Result = codes .iter() - .map(|code| totp::recovery_code_hash(code)) + .map(|code| totp::recovery_code_hash(&state.key, code)) .collect(); state .store @@ -335,28 +327,22 @@ async fn disable_two_factor(cx: &Cx, Form(form): Form) -> Result) -> Result) -> Result) -> Result< if !viewer.user.totp_enabled() { return Err(see_other("/account/security").into()); } - if password_locked(state, &viewer) { - return render_security( - cx, - viewer.clone(), - Flash::alert(text(lang, Txt::ErrThrottled)), - ) - .await; - } - if !password_matches(state, &viewer, &form.current_password).await? { - return render_security( - cx, - viewer.clone(), - Flash::alert(text(lang, Txt::ErrWrongPassword)), - ) - .await; + if let Some(problem) = password_problem(state, &viewer, &form.current_password).await? { + return render_security(cx, viewer.clone(), Flash::alert(text(lang, problem))).await; } let codes = issue_codes(); let hashes: Vec = codes .iter() - .map(|code| totp::recovery_code_hash(code)) + .map(|code| totp::recovery_code_hash(&state.key, code)) .collect(); state .store @@ -473,29 +441,28 @@ fn issue_codes() -> Vec { .collect() } -/// True while the password counters hold the account. Wrong passwords on this page count toward -/// the same limit as sign-in. -pub fn password_locked(state: &AppState, viewer: &Viewer) -> bool { - state - .throttle - .check( - &user_key(&viewer.user.email), - LOGIN_USER_LIMIT, - Instant::now(), - ) - .is_some() -} - -/// Checks the password of the signed-in person and records the outcome in the throttle. -pub async fn password_matches(state: &AppState, viewer: &Viewer, given: &str) -> Result { - let ok = verify_password_async(given.to_owned(), viewer.user.password_hash.clone()).await?; +/// Checks the password of the signed-in person, counted against the same limit as sign-in. The attempt is +/// counted before the check, so parallel guesses cannot all pass. `None` when the password is right; +/// otherwise the message to show: the throttle's, or the wrong-password one. Wrong passwords on this page +/// count toward the sign-in limit, so guessing here locks sign-in too. +pub async fn password_problem( + state: &AppState, + viewer: &Viewer, + given: &str, +) -> Result> { let limit = user_key(&viewer.user.email); - if ok { + if state + .throttle + .reserve(&limit, LOGIN_USER_LIMIT, Instant::now()) + .is_err() + { + return Ok(Some(Txt::ErrThrottled)); + } + if verify_password_async(given.to_owned(), viewer.user.password_hash.clone()).await? { state.throttle.clear(&limit); - } else { - state.throttle.record_failure(&limit, Instant::now()); + return Ok(None); } - Ok(ok) + Ok(Some(Txt::ErrWrongPassword)) } /// Tells the open account pages that the person's security changed. @@ -629,6 +596,7 @@ fn security_view( } else if !has_pending {
+ field(label: text(lang, Txt::CurrentPassword), name: "current_password", kind: "password", autocomplete: "current-password", value: String::new())
} diff --git a/crates/im-web/src/state.rs b/crates/im-web/src/state.rs index 23e8923..18383e8 100644 --- a/crates/im-web/src/state.rs +++ b/crates/im-web/src/state.rs @@ -4,7 +4,7 @@ use std::sync::{Arc, PoisonError, RwLock}; use im_core::config::{Config, PolicyConfig}; use im_core::store::Store; -use tokio::sync::watch; +use tokio::sync::{Semaphore, watch}; use crate::api::directory::StreamSlots; use crate::live::LiveHub; @@ -29,6 +29,8 @@ pub struct AppState { pub throttle: Arc, /// The open directory streams of each machine client. pub stream_slots: Arc, + /// The open anonymous `/-/alive` streams, at most [`MAX_ANONYMOUS_STREAMS`]. + pub anonymous_streams: Arc, /// Set when the process is stopping. Long-lived streams end when it is, so the server can drain. pub stop: watch::Receiver, } diff --git a/crates/im-web/src/throttle.rs b/crates/im-web/src/throttle.rs index 00e7cde..1955c69 100644 --- a/crates/im-web/src/throttle.rs +++ b/crates/im-web/src/throttle.rs @@ -1,9 +1,17 @@ //! In-memory sliding-window failure counters that slow down password guessing. //! //! Each key keeps the instants of its recent failures, and is limited while it has `limit` of them -//! inside [`WINDOW`]. Only rejected attempts are recorded, so a locked key stops growing. Memory is -//! bounded: expired instants and empty keys are pruned every few hundred failures, and at the key -//! cap the key whose latest failure is oldest is evicted. +//! inside [`WINDOW`]. An attempt first asks [`Throttle::reserve`], which counts it before the work +//! is done and answers with the wait when the key is already limited. A success gives the count back +//! with [`Throttle::refund`] (or drops the key with [`Throttle::clear`] where the old failures go too). +//! Check and count are one step under one lock, so parallel attempts cannot all pass together. +//! +//! Memory is bounded. Expired instants and empty keys are pruned every few hundred attempts. At the key +//! cap, expired keys go first; then the key whose latest failure is oldest is evicted, but never a key +//! that is limited right now. When every key is limited, a new key is refused: fail closed. +//! +//! Email keys are capped too. An address that is too long or not plausible shares one fixed key, so a +//! flood of junk addresses cannot grow the map or the key size. //! //! The counters live in one process. A restart clears them, and two processes would each count //! their own. `im` runs as one process, so this is the whole picture. @@ -13,6 +21,8 @@ use std::net::IpAddr; use std::sync::{Mutex, MutexGuard}; use std::time::{Duration, Instant}; +use im_core::names::parse_email; + /// Length of the failure window. pub const WINDOW: Duration = Duration::from_secs(15 * 60); @@ -37,9 +47,13 @@ pub const FORGOT_IP_LIMIT: usize = 20; /// this. const MAX_KEYS: usize = 100_000; -/// A full prune runs every this many recorded failures. +/// 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. +const INVALID_ADDRESS: &str = ""; + /// The failure counters of the process. Shared by every request through the app state. pub struct Throttle { window: Duration, @@ -49,8 +63,14 @@ pub struct Throttle { #[derive(Default)] struct State { - failures: HashMap>, - recorded: u32, + failures: HashMap, + attempts: u32, +} + +/// The failures of one key, and the limit they were counted against. +struct Entry { + stamps: VecDeque, + limit: usize, } impl Default for Throttle { @@ -69,33 +89,43 @@ impl Throttle { } } - /// How long until `key` drops below `limit` failures, or `None` when it is not limited. - pub fn check(&self, key: &str, limit: usize, now: Instant) -> Option { - let mut state = self.lock(); - let timestamps = state.failures.get_mut(key)?; - drop_expired(timestamps, self.window, now); - if timestamps.len() < limit { - return None; - } - // The failure at this index leaves the window first, and that brings the count below limit. - let index = timestamps.len().checked_sub(limit)?; - let oldest = *timestamps.get(index)?; - Some((oldest + self.window).saturating_duration_since(now)) + /// Counts one attempt of `key` now, before the work is done. When the key already has `limit` + /// failures inside the window, nothing is counted and the wait until it may try again comes back + /// (at least one second when it is the key cap that refuses a new key). + pub fn reserve(&self, key: &str, limit: usize, now: Instant) -> Result<(), Duration> { + self.reserve_all(&[(key, limit)], now) } - /// Records one rejected attempt for `key` at `now`. - pub fn record_failure(&self, key: &str, now: Instant) { + /// Counts one attempt against every key, or against none. All keys are checked under one lock. When + /// one of them refuses, the keys already counted are given back, and the longest wait comes back. + pub fn reserve_all(&self, keys: &[(&str, usize)], now: Instant) -> Result<(), Duration> { let mut state = self.lock(); - state.recorded = state.recorded.wrapping_add(1); - if state.recorded.is_multiple_of(PRUNE_EVERY) { + state.attempts = state.attempts.wrapping_add(1); + if state.attempts.is_multiple_of(PRUNE_EVERY) { self.prune_locked(&mut state, now); } - if !state.failures.contains_key(key) && state.failures.len() >= self.max_keys { - self.evict_oldest_locked(&mut state); + let mut admitted = Vec::with_capacity(keys.len()); + let mut wait: Option = None; + for &(key, limit) in keys { + match self.reserve_locked(&mut state, key, limit, now) { + Ok(()) => admitted.push(key), + Err(due) => wait = Some(wait.map_or(due, |longest| longest.max(due))), + } + } + match wait { + None => Ok(()), + Some(due) => { + for key in admitted { + self.refund_locked(&mut state, key); + } + Err(due) + } } - let timestamps = state.failures.entry(key.to_owned()).or_default(); - drop_expired(timestamps, self.window, now); - timestamps.push_back(now); + } + + /// Takes back the newest counted attempt of `key`, for an attempt that succeeded. + pub fn refund(&self, key: &str) { + self.refund_locked(&mut self.lock(), key); } /// Forgets the failures of `key`, after a success. @@ -103,28 +133,87 @@ impl Throttle { self.lock().failures.remove(key); } - /// Drops expired failures and the keys left empty. - fn prune_locked(&self, state: &mut State, now: Instant) { - let window = self.window; - state.failures.retain(|_, timestamps| { - drop_expired(timestamps, window, now); - !timestamps.is_empty() - }); + /// Counts one attempt of `key` under `limit`, with the lock already held. + fn reserve_locked( + &self, + state: &mut State, + key: &str, + limit: usize, + now: Instant, + ) -> Result<(), Duration> { + if !state.failures.contains_key(key) + && state.failures.len() >= self.max_keys + && !self.make_room_locked(state, now) + { + // Every key is limited right now: the new one is refused, which is the fail-closed answer. + return Err(self.window); + } + let entry = state + .failures + .entry(key.to_owned()) + .or_insert_with(|| Entry { + stamps: VecDeque::new(), + limit, + }); + entry.limit = limit; + drop_expired(&mut entry.stamps, self.window, now); + if entry.stamps.len() >= limit { + return Err(wait_for(&entry.stamps, limit, self.window, now)); + } + entry.stamps.push_back(now); + Ok(()) + } + + /// Gives back the newest failure of `key`, and drops the key when nothing is left. + fn refund_locked(&self, state: &mut State, key: &str) { + let emptied = match state.failures.get_mut(key) { + Some(entry) => { + entry.stamps.pop_back(); + entry.stamps.is_empty() + } + None => false, + }; + if emptied { + state.failures.remove(key); + } } - /// Removes the key whose latest failure is the oldest. Runs only when the cap is reached. - fn evict_oldest_locked(&self, state: &mut State) { + /// Frees one slot for a new key. Expired failures go first. Then the key whose latest failure is the + /// oldest is removed, but only among keys that are not limited now. Returns false when every key is + /// limited, so nothing can be removed. + fn make_room_locked(&self, state: &mut State, now: Instant) -> bool { + let window = self.window; + state.failures.retain(|_, entry| { + drop_expired(&mut entry.stamps, window, now); + !entry.stamps.is_empty() + }); + if state.failures.len() < self.max_keys { + return true; + } let victim = state .failures .iter() - .filter_map(|(key, timestamps)| timestamps.back().map(|last| (key, *last))) - .min_by_key(|(_, last)| *last) + .filter(|(_, entry)| entry.stamps.len() < entry.limit) + .min_by_key(|(_, entry)| entry.stamps.back().copied()) .map(|(key, _)| key.clone()); - if let Some(key) = victim { - state.failures.remove(&key); + match victim { + Some(key) => { + state.failures.remove(&key); + true + } + None => false, } } + /// Drops expired failures and the keys left empty. + fn prune_locked(&self, state: &mut State, now: Instant) { + let window = self.window; + state.failures.retain(|_, entry| { + drop_expired(&mut entry.stamps, window, now); + !entry.stamps.is_empty() + }); + } + fn lock(&self) -> MutexGuard<'_, State> { // A poisoned lock still holds consistent counters, so the next caller uses it as it is. self.state.lock().unwrap_or_else(|e| e.into_inner()) @@ -141,14 +230,34 @@ fn drop_expired(timestamps: &mut VecDeque, window: Duration, now: Insta } } +/// The wait until `stamps` drops below `limit` failures: the failure at this index is the last one to +/// leave the window before the count does. +fn wait_for(stamps: &VecDeque, limit: usize, window: Duration, now: Instant) -> Duration { + let Some(index) = stamps.len().checked_sub(limit) else { + return Duration::ZERO; + }; + stamps.get(index).map_or(Duration::ZERO, |oldest| { + (*oldest + window).saturating_duration_since(now) + }) +} + +/// 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. +fn address_part(email: &str) -> String { + match parse_email(email) { + Ok(address) => address, + Err(_) => INVALID_ADDRESS.to_owned(), + } +} + /// Throttle key for a normalised email address. pub fn user_key(email: &str) -> String { - format!("user:{email}") + format!("user:{}", address_part(email)) } /// Throttle key for the reset-link requests of one normalised address. pub fn forgot_email_key(email: &str) -> String { - format!("forgot:{email}") + format!("forgot:{}", address_part(email)) } /// Throttle key for the second factor of one user, by user id. @@ -164,6 +273,7 @@ pub fn ip_key(scope: &str, ip: IpAddr) -> String { #[cfg(test)] mod tests { use super::*; + use std::sync::Arc; #[test] fn a_key_is_limited_at_the_threshold_and_free_when_the_window_passes() { @@ -171,26 +281,48 @@ mod tests { let t0 = Instant::now(); for i in 0..3 { let at = t0 + Duration::from_secs(i); - assert!(throttle.check("k", 3, at).is_none()); - throttle.record_failure("k", at); + assert!(throttle.reserve("k", 3, at).is_ok()); } let retry = throttle - .check("k", 3, t0 + Duration::from_secs(10)) - .expect("limited"); + .reserve("k", 3, t0 + Duration::from_secs(10)) + .expect_err("limited"); assert_eq!(retry, Duration::from_secs(50)); assert!( throttle - .check("k", 3, t0 + Duration::from_secs(60)) - .is_none() + .reserve("k", 3, t0 + Duration::from_secs(60)) + .is_ok() ); } + /// Twenty parallel wrong-password attempts against one key: only the limit's worth is counted and + /// admitted, and the rest are refused. Check and count are one step, so none can slip past. + #[test] + fn parallel_reservations_admit_no_more_than_the_limit() { + let throttle = Arc::new(Throttle::with_limits(WINDOW, MAX_KEYS)); + let handles: Vec<_> = (0..20) + .map(|_| { + let throttle = Arc::clone(&throttle); + std::thread::spawn(move || { + throttle + .reserve("login", LOGIN_USER_LIMIT, Instant::now()) + .is_ok() + }) + }) + .collect(); + let admitted = handles + .into_iter() + .map(|handle| handle.join().expect("attempt thread")) + .filter(|ok| *ok) + .count(); + assert_eq!(admitted, LOGIN_USER_LIMIT); + } + #[test] fn the_key_count_stays_at_the_cap() { let throttle = Throttle::with_limits(Duration::from_secs(10), 8); let t0 = Instant::now(); for i in 0..1000u64 { - throttle.record_failure(&format!("key-{i}"), t0 + Duration::from_millis(i)); + let _ = throttle.reserve(&format!("key-{i}"), 2, t0 + Duration::from_millis(i)); assert!(throttle.lock().failures.len() <= 8); } }