fix(auth): make the login budget a true rolling cap

The leaky bucket allowed about 199 failures in a day; persisted timestamps now
hold it to 100 in any 24 hours, and only evaluated failures reach the disk. A
credential change from a live session keeps its own address as known. Promotion
clears the list, session MFA changes void stale pending tokens, reset frees pairs
whose budget was evicted, and only real accounts audit exhaustion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-05 06:48:59 -03:00
1 parent b7fd1b7c8a
commit b384ed91c3
6 files changed
+397 -151

No files matched your search

+168 -38
View File
@@ -63,7 +63,7 @@ fn code_at(s: &AuthService, id: &str, unix: u64) -> String {
fn enroll(s: &AuthService, id: &str, now: u64) -> Vec<String> {
s.start_enrollment(id, now).unwrap();
let code = code_at(s, id, now);
s.confirm_enrollment(id, &code, now).unwrap()
s.confirm_enrollment(id, &code, None, now).unwrap()
}
/// First admin, enrolled. Returns its id.
@@ -186,15 +186,16 @@ fn admin_cannot_finish_login_without_mfa() {
);
assert_eq!(sessions(&s, &id), 0);
let codes = s.confirm_enrollment(&id, &pending_code, T0).unwrap();
let codes = s.confirm_enrollment(&id, &pending_code, None, T0).unwrap();
assert_eq!(codes.len(), 10);
assert_eq!(sessions(&s, &id), 0, "enrolling is not logging in");
// The enrollment step cannot be replayed; the next one finishes the login.
// Tokens from before the activation die with it, even with a good code.
let next = code_at(&s, &id, T0 + 60);
assert_eq!(
failure(s.confirm_mfa(&p.token, &pending_code, T0)),
failure(s.confirm_mfa(&p.token, &next, T0 + 60)),
AuthFailure::InvalidCredentials
);
let next = code_at(&s, &id, T0 + 60);
let p = pending_of(s.login("root", PW, ip(), T0 + 60).unwrap());
let session = session_of(s.confirm_mfa(&p.token, &next, T0 + 60).unwrap());
assert_eq!(session.user_id, id);
assert_eq!(sessions(&s, &id), 1);
@@ -297,7 +298,8 @@ fn pending_token_is_void_after_password_change() {
let id = analyst(&s, "ana");
enroll(&s, &id, T0);
let p = pending_of(s.login("ana", PW, ip(), T0 + 60).unwrap());
s.change_password(&id, PW, PW2, None, T0 + 60).unwrap();
s.change_password(&id, PW, PW2, None, None, T0 + 60)
.unwrap();
let code = code_at_active(&s, &id, T0 + 60);
assert_eq!(
failure(s.confirm_mfa(&p.token, &code, T0 + 60)),
@@ -334,14 +336,14 @@ fn cannot_remove_last_admin() {
AuthFailure::LastAdmin
);
assert_eq!(
failure(s.disable_mfa("root", &root, None, T0)),
failure(s.disable_mfa("root", &root, None, None, T0)),
AuthFailure::MfaMandatory
);
// With a second admin the first may go.
s.create_user("root", "second", PW, Role::Admin, T0)
.unwrap();
s.set_role("root", &root, Role::Analyst, T0).unwrap();
s.disable_mfa("root", &root, None, T0).unwrap();
s.disable_mfa("root", &root, None, None, T0).unwrap();
s.delete_user("second", &root, T0).unwrap();
assert_eq!(
failure(s.delete_user("x", "no-such-id", T0)),
@@ -409,7 +411,7 @@ fn same_error_for_unknown_user_and_bad_password() {
assert_eq!(
unknown,
AuthFailure::Throttled {
retry_after_secs: crate::auth::throttle::BUDGET_DECAY_SECS
retry_after_secs: crate::auth::throttle::BUDGET_WINDOW_SECS
}
);
assert_eq!(unknown, bad);
@@ -553,7 +555,7 @@ fn refusals_write_nothing_and_failures_store_only_the_budget() {
let _ = s.login("ana", WRONG, ip(), T0);
}
let u = user_of(&s, &id);
assert_eq!((u.budget_failures, u.budget_at), (1, T0), "written once");
assert_eq!(u.budget_times, vec![T0], "written once");
assert_eq!(u.failed_attempts, 0);
// Refusals reach neither the state nor the audit log.
let before = std::fs::read(&state).unwrap();
@@ -645,7 +647,7 @@ fn disabling_mfa_that_is_off_changes_nothing() {
let before = std::fs::read(&state).unwrap();
let lines = s.audit_tail(1000).unwrap().len();
assert_eq!(
failure(s.disable_mfa("ana", &id, Some(&session.token), T0)),
failure(s.disable_mfa("ana", &id, Some(&session.token), None, T0)),
AuthFailure::MfaNotEnabled
);
assert_eq!(std::fs::read(&state).unwrap(), before);
@@ -765,16 +767,16 @@ fn password_or_mfa_change_ends_other_sessions() {
assert_eq!(sessions(&s, &id), 2);
assert_eq!(
failure(s.change_password(&id, WRONG, PW2, Some(&keep.token), T0)),
failure(s.change_password(&id, WRONG, PW2, Some(&keep.token), None, T0)),
AuthFailure::InvalidCredentials
);
assert_eq!(sessions(&s, &id), 2);
assert!(matches!(
s.change_password(&id, PW, "short", Some(&keep.token), T0)
s.change_password(&id, PW, "short", Some(&keep.token), None, T0)
.unwrap_err(),
AcauaError::InvalidInput(_)
));
s.change_password(&id, PW, PW2, Some(&keep.token), T0)
s.change_password(&id, PW, PW2, Some(&keep.token), None, T0)
.unwrap();
let left = s
.store
@@ -807,7 +809,8 @@ fn password_or_mfa_change_ends_other_sessions() {
s.confirm_mfa(&p.token, &code_at_active(&s, &id, T0 + 90), T0 + 90)
.unwrap();
assert_eq!(sessions(&s, &id), 2);
s.disable_mfa("ana", &id, Some(&a.token), T0 + 90).unwrap();
s.disable_mfa("ana", &id, Some(&a.token), None, T0 + 90)
.unwrap();
assert_eq!(sessions(&s, &id), 1);
session_of(s.login("ana", PW2, ip(), T0 + 90).unwrap());
}
@@ -907,7 +910,7 @@ fn audit_records_operations_without_secrets() {
let p = s.create_user("root", "ana", PW, Role::Analyst, T0).unwrap();
s.set_role("root", &p, Role::Admin, T0).unwrap();
s.set_role("root", &p, Role::Analyst, T0).unwrap();
s.change_password(&p, PW, PW2, None, T0).unwrap();
s.change_password(&p, PW, PW2, None, None, T0).unwrap();
s.delete_user("root", &p, T0).unwrap();
let actions: Vec<String> = s
@@ -1092,7 +1095,7 @@ fn change_password_clears_flag_and_refuses_the_same_password() {
let (id, temp) = reset_and_enroll(&s);
// Same password, also in another Unicode form: refused, nothing counted.
assert!(matches!(
s.change_password(&id, &temp, &temp, None, T0 + 300)
s.change_password(&id, &temp, &temp, None, None, T0 + 300)
.unwrap_err(),
AcauaError::InvalidInput(_)
));
@@ -1113,12 +1116,14 @@ fn change_password_clears_flag_and_refuses_the_same_password() {
"maçã açaí pitanga",
"mac\u{0327}a\u{0303} ac\u{0327}ai\u{0301} pitanga",
None,
None,
T0
)
.unwrap_err(),
AcauaError::InvalidInput(_)
));
s.change_password(&id, &temp, PW2, None, T0 + 300).unwrap();
s.change_password(&id, &temp, PW2, None, None, T0 + 300)
.unwrap();
let flag = s
.store
.read(|st| {
@@ -1399,11 +1404,9 @@ fn the_budget_decays_and_survives_reopening() {
let reopened = AuthService::open(d.path(), None).unwrap();
let fresh: IpAddr = "198.51.100.200".parse().unwrap();
assert!(reopened.login_begin("ana", fresh, T0 + 1).is_err());
// One failure fades per 864 s, so one guess fits and no more.
let later = T0 + 864;
assert_eq!(burn(&reopened, "ana", 5, 500, later), 1);
// A day later the budget is back.
assert_eq!(burn(&reopened, "ana", 100, 600, later + DAY), 100);
// Nothing opens until those failures are a day old.
assert_eq!(burn(&reopened, "ana", 5, 500, T0 + DAY - 1), 0);
assert_eq!(burn(&reopened, "ana", 100, 600, T0 + DAY), 100);
}
#[test]
@@ -1412,15 +1415,23 @@ fn budget_writes_are_coalesced_and_a_refusal_writes_nothing() {
admin(&s);
let id = analyst(&s, "ana");
burn(&s, "ana", 3, 0, T0);
assert_eq!(user_of(&s, &id).budget_failures, 1, "first failure writes");
assert_eq!(
user_of(&s, &id).budget_times.len(),
1,
"first failure writes"
);
burn(&s, "ana", 1, 10, T0 + 59);
assert_eq!(user_of(&s, &id).budget_failures, 1, "within the minute");
assert_eq!(user_of(&s, &id).budget_times.len(), 1, "within the minute");
burn(&s, "ana", 1, 20, T0 + 60);
assert_eq!(user_of(&s, &id).budget_failures, 5);
assert_eq!(user_of(&s, &id).budget_times.len(), 5);
burn(&s, "ana", 95, 100, T0 + 120);
let path = d.path().join("auth/state.json");
let before = std::fs::read(&path).unwrap();
assert_eq!(user_of(&s, &id).budget_failures, 100, "the crossing writes");
assert_eq!(
user_of(&s, &id).budget_times.len(),
100,
"the crossing writes"
);
assert_eq!(burn(&s, "ana", 10, 300, T0 + 121), 0);
assert_eq!(std::fs::read(&path).unwrap(), before);
}
@@ -1456,7 +1467,7 @@ fn an_unknown_username_exhausts_like_a_real_one() {
}
#[test]
fn exhaustion_is_audited_once_per_window_without_a_guessed_name() {
fn exhaustion_is_audited_once_per_window() {
let (d, s) = svc();
admin(&s);
analyst(&s, "ana");
@@ -1472,13 +1483,6 @@ fn exhaustion_is_audited_once_per_window_without_a_guessed_name() {
// Still under attack a day later: one more.
burn(&s, "ana", 100, 500, T0 + DAY + 1);
assert_eq!(exhausted_events(&s).len(), 2);
burn(&s, "secret-typed-in-wrong-field", 100, 700, T0);
let events = exhausted_events(&s);
assert_eq!(events.len(), 3);
let last = serde_json::to_string(events.last().unwrap()).unwrap();
assert!(!last.contains("secret-typed"), "{last}");
assert_eq!(events[2].event.actor, None);
}
#[test]
@@ -1489,7 +1493,7 @@ fn credential_changes_clear_known_addresses_and_reset_reopens_login() {
let owner: IpAddr = OWNER.parse().unwrap();
let live = session_of(s.login("ana", PW, owner, T0).unwrap());
assert_eq!(user_of(&s, &id).known_addresses.len(), 1);
s.change_password(&id, PW, PW2, Some(&live.token), T0)
s.change_password(&id, PW, PW2, Some(&live.token), None, T0)
.unwrap();
assert!(user_of(&s, &id).known_addresses.is_empty(), "password");
@@ -1500,7 +1504,7 @@ fn credential_changes_clear_known_addresses_and_reset_reopens_login() {
let code = code_at(&s, &id, T0 + 60);
session_of(s.confirm_mfa(&p.token, &code, T0 + 60).unwrap());
assert_eq!(user_of(&s, &id).known_addresses.len(), 1);
s.disable_mfa("ana", &id, None, T0 + 60).unwrap();
s.disable_mfa("ana", &id, None, None, T0 + 60).unwrap();
assert!(user_of(&s, &id).known_addresses.is_empty(), "disabling");
session_of(s.login("ana", PW2, owner, T0 + 60).unwrap());
@@ -1512,7 +1516,7 @@ fn credential_changes_clear_known_addresses_and_reset_reopens_login() {
let temp = cli.reset_account("ana", T0 + 61).unwrap();
let u = user_of(&s, &id);
assert!(u.known_addresses.is_empty());
assert_eq!(u.budget_failures, 0);
assert!(u.budget_times.is_empty());
assert!(matches!(
s.login("ana", &temp, stranger, T0 + 62).unwrap(),
LoginStep::PasswordChangeRequired(_)
@@ -1587,3 +1591,129 @@ fn an_abandoned_attempt_returns_its_reservations() {
}
assert_eq!(burn(&s, "ana", 100, 600, T0), 100);
}
#[test]
fn a_credential_change_from_a_session_keeps_only_the_acting_address() {
for change in ["enroll", "password", "disable"] {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
let acting: IpAddr = OWNER.parse().unwrap();
let old: IpAddr = "203.0.113.77".parse().unwrap();
let t = T0 + 60;
session_of(s.login("ana", PW, old, T0).unwrap());
let mut pw = PW;
match change {
"enroll" => {
s.start_enrollment(&id, t).unwrap();
let code = code_at(&s, &id, t);
s.confirm_enrollment(&id, &code, Some(acting), t).unwrap();
}
"password" => {
s.change_password(&id, PW, PW2, None, Some(acting), t)
.unwrap();
pw = PW2;
}
_ => {
enroll(&s, &id, T0);
s.disable_mfa("ana", &id, None, Some(acting), t).unwrap();
}
}
burn(&s, "ana", 100, 0, t);
assert!(matches!(
failure(s.login("ana", pw, old, t + 90)),
AuthFailure::Throttled { .. }
));
match s.login("ana", pw, acting, t + 90).unwrap() {
LoginStep::MfaRequired(_) => assert_eq!(change, "enroll"),
LoginStep::Session(_) => assert_ne!(change, "enroll"),
other => panic!("{change}: {other:?}"),
}
}
}
#[test]
fn an_enrollment_with_a_pending_token_records_nothing_until_login() {
let (_d, s) = svc();
let code = s.ensure_bootstrap(T0).unwrap().unwrap();
let p = s.complete_bootstrap(&code, "root", PW, ip(), T0).unwrap();
let e = s.start_enrollment_pending(&p.token, T0).unwrap();
let _ = e;
let id = uid(&s, "root");
let code = code_at(&s, &id, T0);
s.confirm_enrollment_pending(&p.token, &code, T0).unwrap();
assert!(user_of(&s, &id).known_addresses.is_empty());
}
#[test]
fn only_a_real_account_audits_exhaustion() {
let (_d, s) = svc();
admin(&s);
burn(&s, "nobody", 150, 0, T0);
assert!(exhausted_events(&s).is_empty());
}
#[test]
fn a_reservation_never_reaches_the_disk() {
let (d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
let held: Vec<_> = (0..5u32)
.map(|i| s.login_begin("ana", v4(i), T0).unwrap())
.collect();
let one = s.login_begin("ana", v4(50), T0).unwrap();
let _ = s.login_failed(one, T0);
assert_eq!(user_of(&s, &id).budget_times, vec![T0]);
for a in held {
s.login_abandon(a);
}
drop(s);
let s = AuthService::open(d.path(), None).unwrap();
assert_eq!(burn(&s, "ana", 120, 100, T0), 99);
}
#[test]
fn promotion_clears_known_addresses() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
session_of(s.login("ana", PW, ip(), T0).unwrap());
s.set_role("root", &id, Role::Admin, T0).unwrap();
assert!(user_of(&s, &id).known_addresses.is_empty());
}
#[test]
fn mfa_changes_kill_stale_pending_tokens() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
enroll(&s, &id, T0);
let p = pending_of(s.login("ana", PW, ip(), T0 + 60).unwrap());
s.start_enrollment(&id, T0 + 60).unwrap();
let code = code_at(&s, &id, T0 + 60);
let pending = s.store.read(|st| {
st.users
.iter()
.find(|u| u.id == id)
.unwrap()
.totp_pending_sealed
.clone()
});
assert!(pending.unwrap().is_some());
let _ = code;
let sealed = user_of(&s, &id).totp_pending_sealed.unwrap();
let secret = s.secrets.open_sealed(&sealed).unwrap();
let new = build_totp(&secret, "x")
.unwrap()
.generate(T0 + 60)
.to_string();
s.confirm_enrollment(&id, &new, None, T0 + 60).unwrap();
let next = code_at_active(&s, &id, T0 + 120);
assert_eq!(
failure(s.confirm_mfa(&p.token, &next, T0 + 120)),
AuthFailure::InvalidCredentials
);
let before = user_of(&s, &id).auth_epoch;
s.disable_mfa("ana", &id, None, None, T0 + 120).unwrap();
assert_ne!(user_of(&s, &id).auth_epoch, before);
}