fix(auth): keep a queued login from passing the cap

A reservation could expire while its request queued, and the guess was then
evaluated anyway. The wait for a hashing permit is now bounded to 30 s, and an
attempt whose reservation is gone is refused at permit time. At the cap, each
failure now reaches the disk, so a restart cannot reopen a slot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-05 07:01:16 -03:00
1 parent 4a48f2bd35
commit 9ef86ac425
5 files changed
+238 -67

No files matched your search

+20 -11
View File
@@ -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<u64>,
}
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<LoginStep> {
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) = &note.write {
@@ -664,6 +665,14 @@ impl AuthService {
password: &str,
now: u64,
) -> Result<LoginStep> {
// 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",
@@ -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());
}
+92 -44
View File
@@ -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<u64>,
/// `(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<String, BudgetEntry>,
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<bool, u64> {
) -> Result<Option<u64>, 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<u64>) {
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<u64>) {
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<u64, u64> {
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);
}