diff --git a/crates/acaua-cli/src/auth_http.rs b/crates/acaua-cli/src/auth_http.rs index 2b88070..b262e27 100644 --- a/crates/acaua-cli/src/auth_http.rs +++ b/crates/acaua-cli/src/auth_http.rs @@ -7,8 +7,8 @@ use crate::web::{access_of, is_public, is_public_asset, Access, AppState}; use acaua_core::auth::{ - csrf_matches, csrf_token, AuthService, LoginAttempt, NewSession, PendingMfa, Principal, Role, - Scope, TotpEnrollment, Via, + csrf_matches, csrf_token, AuthService, LoginAttempt, LoginStep, NewSession, PendingMfa, + Principal, Role, Scope, TotpEnrollment, Via, }; use acaua_core::{AcauaError, AuthFailure}; use axum::extract::rejection::JsonRejection; @@ -22,7 +22,7 @@ use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; -use std::time::{SystemTime, UNIX_EPOCH}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; pub const MAX_BODY_BYTES: usize = 64 * 1024; pub const ARGON2_CONCURRENCY: usize = 8; @@ -32,6 +32,8 @@ const PENDING_HEADER: &str = "x-acaua-pending"; const LOGIN_PAGE: &str = "/login.html"; const AUDIT_DEFAULT: usize = 200; const AUDIT_MAX: usize = 1000; +/// The longest a login waits for a hashing permit. +const LOGIN_QUEUE_WAIT: Duration = Duration::from_secs(30); /// A clock before 1970 fails closed: everything looks expired. pub fn unix_now() -> u64 { @@ -551,7 +553,7 @@ pub async fn login( // or a flood of hopeless attempts would stand in front of the owner. let auth = state.auth.clone(); let username = b.username; - let mut queued = blocking(move || { + let queued = blocking(move || { let attempt = auth.login_begin(&username, ip, now)?; Ok(QueuedLogin { auth, @@ -559,23 +561,46 @@ pub async fn login( }) }) .await?; - let password = b.password; - let step = hashing(&state, move || { + let step = finish_queued(&state, queued, b.password, LOGIN_QUEUE_WAIT).await?; + Ok(step_reply(&state, &step)) +} + +/// Evaluates a queued login once a permit is free. Past `wait` it is refused +/// like any other throttled attempt, and gives back what it reserved. +pub(crate) async fn finish_queued( + state: &AppState, + mut queued: QueuedLogin, + password: String, + wait: Duration, +) -> Result { + // Only the queue is timed: once the hash runs, it runs to its answer. Leaving + // here drops `queued`, which gives back what the attempt reserved. + let permit = match tokio::time::timeout(wait, state.argon2.clone().acquire_owned()).await { + Ok(permit) => permit.map_err(|_| internal())?, + Err(_) => { + return Err(AuthFailure::Throttled { + retry_after_secs: wait.as_secs().max(1), + } + .into()) + } + }; + blocking(move || { + let _permit = permit; let attempt = queued .attempt .take() .ok_or(AuthFailure::InvalidCredentials)?; - queued.auth.login_finish(attempt, &password, now) + // The clock now, not at arrival: the queue took time. + queued.auth.login_finish(attempt, &password, unix_now()) }) - .await?; - Ok(step_reply(&state, &step)) + .await } /// A login between its checks and its evaluation. A client that disconnects /// while queued made no guess, so what it reserved goes back. -struct QueuedLogin { - auth: Arc, - attempt: Option, +pub(crate) struct QueuedLogin { + pub(crate) auth: Arc, + pub(crate) attempt: Option, } impl Drop for QueuedLogin { diff --git a/crates/acaua-cli/src/web_tests.rs b/crates/acaua-cli/src/web_tests.rs index c5d86d5..02082e8 100644 --- a/crates/acaua-cli/src/web_tests.rs +++ b/crates/acaua-cli/src/web_tests.rs @@ -1281,3 +1281,50 @@ async fn parallel_requests_stop_at_the_cap() { } assert_eq!((wrong, refused), (4, 12)); } + +#[tokio::test] +async fn a_login_stuck_in_the_queue_is_refused_and_gives_back_its_reservation() { + let (_d, auth, state, _app) = fresh_with_state(Transport::Local); + let code = auth.ensure_bootstrap(now()).unwrap().unwrap(); + auth.complete_bootstrap(&code, "root", PW, peer(), now()) + .unwrap(); + auth.create_user("root", "ana", PW, Role::Analyst, now()) + .unwrap(); + spend_budget(&auth, "ana", 99, now()); + let queued = crate::auth_http::QueuedLogin { + auth: auth.clone(), + attempt: Some(auth.login_begin("ana", v4_peer(700), now()).unwrap()), + }; + assert!( + auth.login_begin("ana", v4_peer(701), now()).is_err(), + "full" + ); + let held = state + .argon2 + .clone() + .acquire_many_owned(crate::auth_http::ARGON2_CONCURRENCY as u32) + .await + .unwrap(); + let done = tokio::time::timeout( + std::time::Duration::from_secs(5), + crate::auth_http::finish_queued( + &state, + queued, + PW.to_string(), + std::time::Duration::from_millis(50), + ), + ) + .await + .expect("the wait is bounded"); + let Err(error) = done else { + panic!("expected a refusal") + }; + let reply = error.into_response(); + assert_eq!(reply.status(), StatusCode::TOO_MANY_REQUESTS); + assert!(reply.headers().contains_key(header::RETRY_AFTER)); + drop(held); + assert!( + auth.login_begin("ana", v4_peer(702), now()).is_ok(), + "returned" + ); +} diff --git a/crates/acaua-core/src/auth/service.rs b/crates/acaua-core/src/auth/service.rs index 11654b4..50eaa03 100644 --- a/crates/acaua-core/src/auth/service.rs +++ b/crates/acaua-core/src/auth/service.rs @@ -34,6 +34,8 @@ const TEMP_PASSWORD_BYTES: usize = 24; /// A completed login makes its address known for this long. const KNOWN_ADDRESS_SECS: u64 = 30 * 86_400; const KNOWN_ADDRESS_MAX: usize = 10; +/// Retry-After for an attempt that lost its place under the budget. +const RESERVATION_LOST_RETRY_SECS: u64 = 30; /// A session just created. The token exists only here; the store has its hash. pub struct NewSession { @@ -118,8 +120,8 @@ pub struct LoginAttempt { ip: IpAddr, /// Hash that makes `ip` known to this account once the login completes. address: String, - /// The reservation was charged to the budget. - budgeted: bool, + /// The attempt's place under the budget, if it was charged. + reservation: Option, } impl std::fmt::Debug for LoginAttempt { @@ -586,8 +588,8 @@ impl AuthService { }; // The hash keeps a password typed into the wrong field out of memory. let throttle_key = hash_token(&key); - let budgeted = match self.logins.acquire(&throttle_key, ip, known, stored, now) { - Ok(budgeted) => budgeted, + let reservation = match self.logins.acquire(&throttle_key, ip, known, stored, now) { + Ok(reservation) => reservation, Err(left) => { self.ips.release(ip); return Err(throttled(left)); @@ -598,7 +600,7 @@ impl AuthService { account, ip, address, - budgeted, + reservation, }) } @@ -606,15 +608,14 @@ impl AuthService { pub fn login_abandon(&self, attempt: LoginAttempt) { self.ips.release(attempt.ip); self.logins - .abandon(&attempt.throttle_key, attempt.ip, attempt.budgeted); + .abandon(&attempt.throttle_key, attempt.ip, attempt.reservation); } /// Records an evaluated failure and returns its refusal. pub fn login_failed(&self, attempt: LoginAttempt, now: u64) -> Result { - let note = if attempt.budgeted { - self.logins.failed(&attempt.throttle_key, now) - } else { - Default::default() + let note = match attempt.reservation { + Some(id) => self.logins.failed(&attempt.throttle_key, id, now), + None => Default::default(), }; let id = attempt.account.as_ref().map(|k| k.id.as_str()); if let Some(state) = ¬e.write { @@ -664,6 +665,14 @@ impl AuthService { password: &str, now: u64, ) -> Result { + // A reservation can be swept or evicted while its request waits. Its place + // may be taken by now, so evaluating this guess could pass the cap. + if let Some(id) = attempt.reservation { + if !self.logins.renew(&attempt.throttle_key, id, now) { + self.login_abandon(attempt); + return Err(throttled(RESERVATION_LOST_RETRY_SECS)); + } + } let Some(known) = &attempt.account else { verify_password(None, password); return self.login_failed(attempt, now); @@ -720,7 +729,7 @@ impl AuthService { }; self.ips.release(attempt.ip); self.logins - .right_password(&attempt.throttle_key, attempt.ip, attempt.budgeted); + .right_password(&attempt.throttle_key, attempt.ip, attempt.reservation); let detail = match step { LoginStep::Session(_) => "session", LoginStep::MfaRequired(_) => "mfa required", diff --git a/crates/acaua-core/src/auth/service_tests.rs b/crates/acaua-core/src/auth/service_tests.rs index d16dd07..4226aa0 100644 --- a/crates/acaua-core/src/auth/service_tests.rs +++ b/crates/acaua-core/src/auth/service_tests.rs @@ -1717,3 +1717,45 @@ fn mfa_changes_kill_stale_pending_tokens() { s.disable_mfa("ana", &id, None, None, T0 + 120).unwrap(); assert_ne!(user_of(&s, &id).auth_epoch, before); } + +#[test] +fn an_expired_reservation_is_refused_and_the_cap_holds() { + let (_d, s) = svc(); + admin(&s); + let id = analyst(&s, "ana"); + let held: Vec<_> = (0..100u32) + .map(|i| s.login_begin("ana", v4(i), T0).unwrap()) + .collect(); + // The sweep takes them, and their places go to fresh failures. + let later = T0 + 3601; + assert_eq!(burn(&s, "ana", 100, 1000, later), 100); + let lines = s.audit_tail(100_000).unwrap().len(); + for a in held { + assert!(matches!( + failure(s.login_finish(a, WRONG, later)), + AuthFailure::Throttled { .. } + )); + } + assert_eq!(s.audit_tail(100_000).unwrap().len(), lines, "not evaluated"); + assert_eq!(user_of(&s, &id).budget_times.len(), 100); + assert!(s.login_begin("ana", v4(5000), later).is_err()); +} + +#[test] +fn a_failure_at_the_cap_survives_a_restart() { + let (d, s) = svc(); + admin(&s); + let id = analyst(&s, "ana"); + burn(&s, "ana", 1, 0, T0); + burn(&s, "ana", 1, 1, T0 + 10); + burn(&s, "ana", 98, 2, T0 + 1000); + // Two slots open ten seconds apart, inside one write interval. + assert_eq!(burn(&s, "ana", 1, 200, T0 + DAY), 1); + assert_eq!(burn(&s, "ana", 1, 201, T0 + DAY + 10), 1); + assert_eq!( + user_of(&s, &id).budget_times.iter().max(), + Some(&(T0 + DAY + 10)) + ); + let s = AuthService::open(d.path(), None).unwrap(); + assert!(s.login_begin("ana", v4(300), T0 + DAY + 11).is_err()); +} diff --git a/crates/acaua-core/src/auth/throttle.rs b/crates/acaua-core/src/auth/throttle.rs index 5ce5b0d..5c69c7d 100644 --- a/crates/acaua-core/src/auth/throttle.rs +++ b/crates/acaua-core/src/auth/throttle.rs @@ -25,7 +25,8 @@ pub const BUDGET_MAX_FAILURES: usize = 100; pub const BUDGET_WINDOW_SECS: u64 = 86_400; /// A budget is written to disk at most this often, bar crossing the cap. pub const BUDGET_WRITE_SECS: u64 = 60; -/// A reservation older than this lost its request, whatever happened to it. +/// Only a sweep for reservations whose request died unseen: an attempt whose +/// reservation is gone is refused, see `renew`. const RESERVATION_SECS: u64 = 3600; const IP_TABLE_CAPACITY: usize = 100_000; const PAIR_TABLE_CAPACITY: usize = 100_000; @@ -186,11 +187,13 @@ pub struct BudgetState { #[derive(Debug, Clone, Default)] struct BudgetEntry { state: BudgetState, - /// Instants of attempts between their checks and their evaluation. They - /// hold a place under the cap but are not failures yet. - reserved: Vec, + /// `(id, instant)` of attempts between their checks and their evaluation. + /// They hold a place under the cap but are not failures yet. + reserved: Vec<(u64, u64)>, written_at: u64, written_count: usize, + /// Newest failure the disk holds. + written_newest: u64, } impl BudgetEntry { @@ -199,7 +202,7 @@ impl BudgetEntry { .times .retain(|t| now.saturating_sub(*t) < BUDGET_WINDOW_SECS); self.reserved - .retain(|t| now.saturating_sub(*t) < RESERVATION_SECS); + .retain(|(_, t)| now.saturating_sub(*t) < RESERVATION_SECS); } fn weight(&self, now: u64) -> usize { @@ -231,6 +234,7 @@ pub struct FailureNote { struct LoginTables { pairs: HashMap<(String, IpAddr), PairEntry>, budgets: HashMap, + next_reservation: u64, } /// Failure counts for login attempts, known username or not. In memory and @@ -260,8 +264,8 @@ impl LoginThrottle { /// Reserves the attempt before Argon2 runs, in one step under one lock, so /// parallel guesses cannot pass the cap. `right_password` or `abandon` undoes - /// it; `failed` makes it a failure. `Ok` says whether the budget was charged; - /// `Err` carries the seconds to wait, and a refusal changes no count. + /// it; `failed` makes it a failure. `Ok` holds the budget reservation, if one + /// was taken; `Err` carries the seconds to wait, and a refusal changes no count. pub fn acquire( &self, account: &str, @@ -269,7 +273,7 @@ impl LoginThrottle { known: bool, stored: BudgetState, now: u64, - ) -> Result { + ) -> Result, u64> { let pair_key = (account.to_string(), address_key(ip)); let generation = stored.generation; let mut guard = guard(&self.tables); @@ -295,9 +299,11 @@ impl LoginThrottle { } let mut budget = t.budgets.get(account).cloned().unwrap_or_else(|| { let written_count = stored.times.len(); + let written_newest = stored.times.iter().max().copied().unwrap_or(0); BudgetEntry { state: stored, written_count, + written_newest, ..Default::default() } }); @@ -317,27 +323,52 @@ impl LoginThrottle { pair.last = if pair_failures == 0 { now } else { pair_last }; pair.locked_until = lock_until(pair.failures, now); - if !known { - budget.reserved.push(now); - } + let reservation = (!known).then(|| { + t.next_reservation = t.next_reservation.wrapping_add(1); + budget.reserved.push((t.next_reservation, now)); + t.next_reservation + }); if !t.budgets.contains_key(account) && t.budgets.len() >= self.budget_capacity { evict_budget(&mut t.budgets, self.budget_capacity, now); } t.budgets.insert(account.to_string(), budget); - Ok(!known) + Ok(reservation) + } + + /// Called with a permit in hand, just before Argon2. `false`: the reservation + /// is gone, its place may belong to someone else, and the attempt must not be + /// evaluated. `true` restarts its clock, so it cannot expire during the hash. + pub fn renew(&self, account: &str, reservation: u64, now: u64) -> bool { + let mut t = guard(&self.tables); + let Some(e) = t.budgets.get_mut(account) else { + return false; + }; + e.prune(now); + match e.reserved.iter_mut().find(|(id, _)| *id == reservation) { + Some(held) => { + held.1 = now; + true + } + None => false, + } } /// A reservation was evaluated and failed. Says what the caller must write /// and audit, once the throttle's lock is gone. - pub fn failed(&self, account: &str, now: u64) -> FailureNote { + pub fn failed(&self, account: &str, reservation: u64, now: u64) -> FailureNote { let mut t = guard(&self.tables); let Some(e) = t.budgets.get_mut(account) else { return FailureNote::default(); }; - e.reserved.pop(); + let held = take_reservation(e, reservation); e.prune(now); - e.state.times.push(now); + // Without its reservation (evicted during the hash) it counts only if + // that keeps the cap. + if held || e.weight(now) < BUDGET_MAX_FAILURES { + e.state.times.push(now); + } let count = e.state.times.len(); + let newest = e.state.times.iter().max().copied().unwrap_or(0); let over = count >= BUDGET_MAX_FAILURES; let audit = over && (e.state.audited_at == 0 @@ -346,11 +377,14 @@ impl LoginThrottle { e.state.audited_at = now; } let due = e.written_at == 0 || now.saturating_sub(e.written_at) >= BUDGET_WRITE_SECS; - // Once over the cap nothing is evaluated, so a later write would not come. - let crossing = over && e.written_count < BUDGET_MAX_FAILURES; - let write = (due || crossing || audit).then(|| { + // At the cap no further failure may come to carry this one to disk, and + // the older instants on disk may have left the window by a restart, so + // the disk must hold the newest one. + let at_cap = over && (e.written_count < BUDGET_MAX_FAILURES || e.written_newest < newest); + let write = (due || at_cap || audit).then(|| { e.written_at = now; e.written_count = count; + e.written_newest = newest; e.state.clone() }); FailureNote { write, audit } @@ -359,19 +393,21 @@ impl LoginThrottle { /// The password was right: this address is clear, and the reservation goes /// back. Other failures stay, or each login by the owner would hand a /// distributed attacker a fresh budget. - pub fn right_password(&self, account: &str, ip: IpAddr, budgeted: bool) { + pub fn right_password(&self, account: &str, ip: IpAddr, reservation: Option) { let mut t = guard(&self.tables); if let Some(pair) = t.pairs.get_mut(&(account.to_string(), address_key(ip))) { pair.failures = 0; pair.locked_until = 0; } - if budgeted { - release_reservation(&mut t, account); + if let Some(id) = reservation { + if let Some(e) = t.budgets.get_mut(account) { + take_reservation(e, id); + } } } /// The attempt was never evaluated: it gives back what it reserved. - pub fn abandon(&self, account: &str, ip: IpAddr, budgeted: bool) { + pub fn abandon(&self, account: &str, ip: IpAddr, reservation: Option) { let mut t = guard(&self.tables); if let Some(pair) = t.pairs.get_mut(&(account.to_string(), address_key(ip))) { pair.failures = pair.failures.saturating_sub(1); @@ -379,8 +415,10 @@ impl LoginThrottle { pair.locked_until = 0; } } - if budgeted { - release_reservation(&mut t, account); + if let Some(id) = reservation { + if let Some(e) = t.budgets.get_mut(account) { + take_reservation(e, id); + } } } @@ -391,10 +429,10 @@ impl LoginThrottle { } } -fn release_reservation(t: &mut LoginTables, account: &str) { - if let Some(e) = t.budgets.get_mut(account) { - e.reserved.pop(); - } +fn take_reservation(e: &mut BudgetEntry, id: u64) -> bool { + let before = e.reserved.len(); + e.reserved.retain(|(held, _)| *held != id); + e.reserved.len() != before } /// Drops what no longer matters; if that frees no room, the entry with the @@ -482,6 +520,10 @@ mod tests { fn addr(n: u8) -> IpAddr { IpAddr::from([198, 51, 100, n]) } + fn reserve(t: &LoginThrottle, account: &str, ip: IpAddr, now: u64) -> Result { + t.acquire(account, ip, false, BudgetState::default(), now) + .map(|id| id.expect("an unknown address is charged")) + } /// An attempt from an address the account does not know. fn pair(t: &LoginThrottle, account: &str, ip: IpAddr, now: u64) -> Result<(), u64> { t.acquire(account, ip, false, BudgetState::default(), now) @@ -526,9 +568,9 @@ mod tests { let mut through = 0; for i in 0..n { let ip = IpAddr::V4(Ipv4Addr::from(0x0a00_0000 + first + i)); - if pair(t, account, ip, now).is_ok() { + if let Ok(id) = reserve(t, account, ip, now) { through += 1; - t.failed(account, now); + t.failed(account, id, now); } } through @@ -547,7 +589,10 @@ mod tests { fn a_known_address_skips_the_budget_but_not_the_pair() { let t = LoginThrottle::default(); spend(&t, "k", 100, 0, 1000); - let known = |now| t.acquire("k", addr(1), true, BudgetState::default(), now); + let known = |now| { + t.acquire("k", addr(1), true, BudgetState::default(), now) + .map(|id| id.is_some()) + }; for _ in 0..5 { assert_eq!(known(1000), Ok(false)); } @@ -557,14 +602,14 @@ mod tests { fn a_right_password_returns_only_a_reservation() { let t = LoginThrottle::default(); spend(&t, "k", 99, 0, 1000); - pair(&t, "k", addr(2), 1000).unwrap(); + let id = reserve(&t, "k", addr(2), 1000).unwrap(); assert!(pair(&t, "k", addr(1), 1000).is_err(), "reserved counts"); - t.right_password("k", addr(2), false); + t.right_password("k", addr(2), None); assert!(pair(&t, "k", addr(1), 1000).is_err(), "not charged"); - t.right_password("k", addr(2), true); - pair(&t, "k", addr(1), 1000).unwrap(); - t.failed("k", 1000); - t.right_password("k", addr(1), true); + t.right_password("k", addr(2), Some(id)); + let id = reserve(&t, "k", addr(1), 1000).unwrap(); + t.failed("k", id, 1000); + t.right_password("k", addr(1), Some(id)); assert!(pair(&t, "k", addr(3), 1000).is_err(), "failures stay"); } #[test] @@ -605,7 +650,8 @@ mod tests { ..Default::default() }; assert_eq!( - t.acquire("k", addr(1), false, reset.clone(), 1000), + t.acquire("k", addr(1), false, reset.clone(), 1000) + .map(|id| id.is_some()), Ok(true) ); } @@ -621,7 +667,8 @@ mod tests { ..Default::default() }; assert_eq!( - t.acquire("k", addr(1), false, reset.clone(), 1000), + t.acquire("k", addr(1), false, reset.clone(), 1000) + .map(|id| id.is_some()), Ok(true) ); // Pairs too, even for an account seen only from a known address. @@ -631,7 +678,8 @@ mod tests { .unwrap(); } assert_eq!( - t.acquire("k", addr(1), true, reset.clone(), 1000), + t.acquire("k", addr(1), true, reset.clone(), 1000) + .map(|id| id.is_some()), Ok(false) ); } @@ -673,15 +721,15 @@ mod tests { fn a_failure_asks_for_a_write_per_minute_and_at_the_crossing() { let t = LoginThrottle::default(); let note = |now| { - pair(&t, "k", addr(9), now).ok(); - t.failed("k", now) + let id = reserve(&t, "k", addr(9), now).unwrap(); + t.failed("k", id, now) }; assert!(note(1000).write.is_some()); assert!(note(1000).write.is_none()); assert!(note(1000 + BUDGET_WRITE_SECS).write.is_some()); spend(&t, "x", 99, 0, 1000); - pair(&t, "x", addr(8), 1000).unwrap(); - let crossing = t.failed("x", 1000); + let id = reserve(&t, "x", addr(8), 1000).unwrap(); + let crossing = t.failed("x", id, 1000); assert_eq!(crossing.write.map(|s| s.times.len()), Some(100)); assert!(crossing.audit); }