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
+396 -150

No files matched your search

+7 -3
View File
@@ -675,12 +675,13 @@ pub async fn change_password(
State(state): State<AppState>,
Auth(p): Auth,
Extension(SessionToken(token)): Extension<SessionToken>,
Extension(ClientIp(ip)): Extension<ClientIp>,
JsonBody(b): JsonBody<PasswordBody>,
) -> Result<Response, ApiError> {
let auth = state.auth.clone();
let now = unix_now();
hashing(&state, move || {
auth.change_password(&p.user_id, &b.current, &b.new, Some(&token), now)
auth.change_password(&p.user_id, &b.current, &b.new, Some(&token), Some(ip), now)
})
.await?;
Ok(ok_reply())
@@ -750,6 +751,7 @@ pub struct CodeBody {
pub async fn enroll_confirm(
State(state): State<AppState>,
Extension(ClientIp(ip)): Extension<ClientIp>,
actor: EnrollActor,
JsonBody(b): JsonBody<CodeBody>,
) -> Result<Response, ApiError> {
@@ -758,7 +760,7 @@ pub async fn enroll_confirm(
let from_session = matches!(actor, EnrollActor::Session(_));
let codes = blocking(move || match actor {
EnrollActor::Pending(token) => auth.confirm_enrollment_pending(&token, &b.code, now),
EnrollActor::Session(p) => auth.confirm_enrollment(&p.user_id, &b.code, now),
EnrollActor::Session(p) => auth.confirm_enrollment(&p.user_id, &b.code, Some(ip), now),
})
.await?;
let reply = Json(serde_json::json!({ "recovery_codes": codes })).into_response();
@@ -774,13 +776,15 @@ pub async fn mfa_disable(
State(state): State<AppState>,
Auth(p): Auth,
Extension(SessionToken(token)): Extension<SessionToken>,
Extension(ClientIp(ip)): Extension<ClientIp>,
) -> Result<Response, ApiError> {
if !p.recent_auth {
return Err(AuthFailure::ReauthRequired.into());
}
let auth = state.auth.clone();
let now = unix_now();
blocking(move || auth.disable_mfa(&p.username, &p.user_id, Some(&token), now)).await?;
blocking(move || auth.disable_mfa(&p.username, &p.user_id, Some(&token), Some(ip), now))
.await?;
Ok(ok_reply())
}
+57 -18
View File
@@ -310,13 +310,24 @@ fn remember_address(u: &mut User, hash: &str, now: u64) {
fn stored_budget(u: &User) -> BudgetState {
BudgetState {
failures: u.budget_failures,
last: u.budget_at,
times: u.budget_times.clone(),
audited_at: u.budget_audited_at,
generation: u.budget_generation,
}
}
/// A credential changed: the old addresses no longer vouch for anyone. A change
/// made from a live session proved the password and a recent reauthentication,
/// so its own address stays known; a change made with a pending ticket passes
/// `None`, and its address is recorded when the login completes.
fn replace_known_addresses(u: &mut User, acting: Option<IpAddr>, now: u64) {
u.known_addresses.clear();
if let Some(ip) = acting {
let hash = address_hash(&u.id, ip);
remember_address(u, &hash, now);
}
}
/// Clears the throttle, voids outstanding pending tokens and opens a session.
/// `address` is where the login came from, the only thing that makes one known.
fn complete_login(
@@ -606,7 +617,7 @@ impl AuthService {
Default::default()
};
let id = attempt.account.as_ref().map(|k| k.id.as_str());
if let Some(state) = note.write {
if let Some(state) = &note.write {
// A name with no account writes too, with nothing to store: a real
// name must not answer slower once a minute.
self.store.update(|st| {
@@ -614,8 +625,7 @@ impl AuthService {
.and_then(|id| user_mut(st, id))
.filter(|u| u.budget_generation == state.generation)
{
u.budget_failures = state.failures;
u.budget_at = state.last;
u.budget_times = state.times.clone();
u.budget_audited_at = state.audited_at;
}
Ok(())
@@ -631,10 +641,12 @@ impl AuthService {
false,
Some("invalid credentials"),
)?;
if note.audit {
// Only a real account has anything to report: a name with no account
// may be a password, and its failures are already in the log.
if let Some(name) = name.as_deref().filter(|_| note.audit) {
self.log(
"login.budget_exhausted",
name.as_deref(),
Some(name),
None,
false,
Some(&format!(
@@ -695,7 +707,14 @@ impl AuthService {
LoginStep::Session(complete_login(st, &id, Some(address), now)?)
};
Ok(Some(step))
})?;
});
let step = match step {
Ok(step) => step,
Err(e) => {
self.login_abandon(attempt);
return Err(e);
}
};
let Some(step) = step else {
return self.login_failed(attempt, now);
};
@@ -852,8 +871,14 @@ impl AuthService {
/// here. The accepted step is spent, so finishing a login needs a later
/// code. Ends every session of the user. A pending token goes through
/// `confirm_enrollment_pending`.
pub fn confirm_enrollment(&self, user_id: &str, code: &str, now: u64) -> Result<Vec<String>> {
self.confirm_enrollment_guarded(user_id, None, code, now)
pub fn confirm_enrollment(
&self,
user_id: &str,
code: &str,
acting: Option<IpAddr>,
now: u64,
) -> Result<Vec<String>> {
self.confirm_enrollment_guarded(user_id, None, code, acting, now)
}
/// As `start_enrollment_pending`: two racing requests get one activation,
@@ -865,7 +890,7 @@ impl AuthService {
now: u64,
) -> Result<Vec<String>> {
let claims = self.open_pending(pending, PENDING_PURPOSE, now)?;
self.confirm_enrollment_guarded(&claims.user_id, Some(claims.epoch), code, now)
self.confirm_enrollment_guarded(&claims.user_id, Some(claims.epoch), code, None, now)
}
fn confirm_enrollment_guarded(
@@ -873,6 +898,7 @@ impl AuthService {
user_id: &str,
pending_epoch: Option<u64>,
code: &str,
acting: Option<IpAddr>,
now: u64,
) -> Result<Vec<String>> {
let (texts, hashes) = new_recovery_codes();
@@ -897,7 +923,13 @@ impl AuthService {
u.totp_pending_sealed = None;
u.totp_last_step = Some(step);
u.recovery_hashes = hashes;
u.known_addresses.clear();
replace_known_addresses(u, acting, now);
// Voids pending tokens issued before the new factor. A pending
// enrollment is the exception: its own token goes on to finish that
// first login, under the new factor.
if pending_epoch.is_none() {
u.auth_epoch = u.auth_epoch.wrapping_add(1);
}
end_sessions(st, user_id, None);
drop_admin_tokens(st, user_id);
Ok((name, true))
@@ -985,6 +1017,11 @@ impl AuthService {
let name = u.username.clone();
if changed {
let leaving_admin = u.role == Role::Admin && role != Role::Admin;
if role == Role::Admin {
// An address trusted for an analyst has not earned the
// exception for an administrator.
u.known_addresses.clear();
}
u.role = role;
u.auth_epoch = u.auth_epoch.wrapping_add(1);
end_sessions(st, user_id, None);
@@ -1038,6 +1075,7 @@ impl AuthService {
current: &str,
new: &str,
keep_session_token: Option<&str>,
acting: Option<IpAddr>,
now: u64,
) -> Result<()> {
validate_password(new)?;
@@ -1064,7 +1102,7 @@ impl AuthService {
refund_attempt(u);
u.password_hash = new_hash;
u.must_change_password = false;
u.known_addresses.clear();
replace_known_addresses(u, acting, now);
u.auth_epoch = u.auth_epoch.wrapping_add(1);
end_sessions(st, user_id, keep_session_token);
drop_admin_tokens(st, user_id);
@@ -1095,7 +1133,7 @@ impl AuthService {
if !live {
return Err(invalid());
}
self.change_password(&claims.user_id, current, new, None, now)?;
self.change_password(&claims.user_id, current, new, None, None, now)?;
self.store.update(|st| {
finish_required_change(
st,
@@ -1114,7 +1152,8 @@ impl AuthService {
actor: &str,
user_id: &str,
keep_session_token: Option<&str>,
_now: u64,
acting: Option<IpAddr>,
now: u64,
) -> Result<()> {
let result = self.store.update(|st| {
let u = user_or_missing(st, user_id)?;
@@ -1129,7 +1168,8 @@ impl AuthService {
u.totp_pending_sealed = None;
u.totp_last_step = None;
u.recovery_hashes.clear();
u.known_addresses.clear();
replace_known_addresses(u, acting, now);
u.auth_epoch = u.auth_epoch.wrapping_add(1);
end_sessions(st, user_id, keep_session_token);
drop_admin_tokens(st, user_id);
Ok(name)
@@ -1167,8 +1207,7 @@ impl AuthService {
u.failed_attempts = 0;
u.locked_until = 0;
u.known_addresses.clear();
u.budget_failures = 0;
u.budget_at = 0;
u.budget_times.clear();
u.budget_audited_at = 0;
u.budget_generation = u.budget_generation.wrapping_add(1);
u.auth_epoch = u.auth_epoch.wrapping_add(1);
+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);
}
+3 -5
View File
@@ -53,11 +53,9 @@ pub struct User {
/// Addresses of recent completed logins, for `throttle`'s budget exception.
/// Hashes only: never a raw address.
pub known_addresses: Vec<KnownAddress>,
/// Login failures from unknown addresses, as last written. The daemon's
/// memory leads this by at most a minute.
pub budget_failures: u32,
/// Start of the current decay period of `budget_failures`.
pub budget_at: u64,
/// Instants of evaluated login failures from unknown addresses in the last
/// 24 hours, at most 100. The daemon's memory leads this by at most a minute.
pub budget_times: Vec<u64>,
/// When `login.budget_exhausted` was last audited for this account.
pub budget_audited_at: u64,
/// Moved by `reset_account`, which may run in another process: the daemon
+158 -83
View File
@@ -20,14 +20,13 @@ const ACCOUNT_FREE_FAILURES: u32 = 5;
const ACCOUNT_DELAY_BASE_SECS: u64 = 30;
/// One failure is forgotten per this many seconds without another.
pub const DECAY_SECS: u64 = 900;
/// Failures from unknown addresses that one username can take in a rolling day.
pub const BUDGET_MAX_FAILURES: u32 = 100;
/// Failures from unknown addresses that one username can take in any 24 hours.
pub const BUDGET_MAX_FAILURES: usize = 100;
pub const BUDGET_WINDOW_SECS: u64 = 86_400;
/// One budget failure is forgotten per this many seconds, so the window holds
/// the whole budget.
pub const BUDGET_DECAY_SECS: u64 = BUDGET_WINDOW_SECS / BUDGET_MAX_FAILURES as u64;
/// 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.
const RESERVATION_SECS: u64 = 3600;
const IP_TABLE_CAPACITY: usize = 100_000;
const PAIR_TABLE_CAPACITY: usize = 100_000;
const ACCOUNT_TABLE_CAPACITY: usize = 10_000;
@@ -55,16 +54,12 @@ pub(super) fn lock_until(failures: u32, now: u64) -> u64 {
/// `(failures, last)` after forgiving one failure per `DECAY_SECS` elapsed.
pub(super) fn decayed(failures: u32, last: u64, now: u64) -> (u32, u64) {
decayed_by(failures, last, now, DECAY_SECS)
}
fn decayed_by(failures: u32, last: u64, now: u64, period: u64) -> (u32, u64) {
let steps = now.saturating_sub(last) / period;
let steps = now.saturating_sub(last) / DECAY_SECS;
if steps >= u64::from(failures) {
return (0, now);
}
// `steps` is below `failures`, so it fits in u32.
(failures - steps as u32, last + steps * period)
(failures - steps as u32, last + steps * DECAY_SECS)
}
fn guard<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
@@ -174,27 +169,57 @@ struct PairEntry {
failures: u32,
last: u64,
locked_until: u64,
/// The account's `budget_generation` these counts belong to.
generation: u64,
}
/// A budget as the store holds it, for an account the daemon has not met yet.
/// A username with no account starts from the default.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BudgetState {
pub failures: u32,
pub last: u64,
/// Instants of evaluated failures inside the window; never reservations.
pub times: Vec<u64>,
pub audited_at: u64,
pub generation: u64,
}
#[derive(Debug, Clone, Copy, Default)]
#[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>,
written_at: u64,
written_failures: u32,
written_count: usize,
}
impl BudgetEntry {
fn prune(&mut self, now: u64) {
self.state
.times
.retain(|t| now.saturating_sub(*t) < BUDGET_WINDOW_SECS);
self.reserved
.retain(|t| now.saturating_sub(*t) < RESERVATION_SECS);
}
fn weight(&self, now: u64) -> usize {
let live = |t: &&u64| now.saturating_sub(**t) < BUDGET_WINDOW_SECS;
self.state.times.iter().filter(live).count() + self.reserved.len()
}
/// Seconds until the oldest failure leaves the window.
fn wait(&self, now: u64) -> u64 {
self.state
.times
.iter()
.min()
.map_or(1, |t| (t + BUDGET_WINDOW_SECS).saturating_sub(now))
.max(1)
}
}
/// What an evaluated failure asks of the caller, outside the throttle's lock.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FailureNote {
/// The state to persist, when a write is due.
pub write: Option<BudgetState>,
@@ -233,10 +258,10 @@ impl LoginThrottle {
}
}
/// Counts the attempt as failed before Argon2 runs, in one step under one
/// lock, so parallel guesses cannot pass the cap. `right_password` or
/// `abandon` undoes it. `Ok` says whether the budget was charged; `Err`
/// carries the seconds to wait, and a refused attempt changes no count.
/// 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.
pub fn acquire(
&self,
account: &str,
@@ -246,47 +271,54 @@ impl LoginThrottle {
now: u64,
) -> Result<bool, u64> {
let pair_key = (account.to_string(), address_key(ip));
let generation = stored.generation;
let mut guard = guard(&self.tables);
let t = &mut *guard;
// A reset, possibly from another process, starts this account over.
// A reset, possibly from another process, starts this account over. Each
// table checks for itself: either entry may have been evicted.
if t.budgets
.get(account)
.is_some_and(|e| e.state.generation != stored.generation)
.is_some_and(|e| e.state.generation != generation)
{
t.budgets.remove(account);
t.pairs.retain(|k, _| k.0 != account);
}
let known_pair = t.pairs.get(&pair_key).copied();
let known_pair = t
.pairs
.get(&pair_key)
.copied()
.filter(|e| e.generation == generation);
if let Some(left) = known_pair
.map(|e| e.locked_until.saturating_sub(now))
.filter(|left| *left > 0)
{
return Err(left);
}
let mut budget = t.budgets.get(account).copied().unwrap_or(BudgetEntry {
let mut budget = t.budgets.get(account).cloned().unwrap_or_else(|| {
let written_count = stored.times.len();
BudgetEntry {
state: stored,
written_at: 0,
written_failures: stored.failures,
written_count,
..Default::default()
}
});
let (failures, last) = budget_now(&budget.state, now);
if !known && failures >= BUDGET_MAX_FAILURES {
return Err((last + BUDGET_DECAY_SECS).saturating_sub(now).max(1));
budget.prune(now);
if !known && budget.weight(now) >= BUDGET_MAX_FAILURES {
return Err(budget.wait(now));
}
if known_pair.is_none() && t.pairs.len() >= self.pair_capacity {
if !t.pairs.contains_key(&pair_key) && t.pairs.len() >= self.pair_capacity {
evict_pair(&mut t.pairs, self.pair_capacity, now);
}
let pair = t.pairs.entry(pair_key).or_default();
let (pair_failures, pair_last) = decayed(pair.failures, pair.last, now);
let current = known_pair.unwrap_or_default();
let (pair_failures, pair_last) = decayed(current.failures, current.last, now);
pair.generation = generation;
pair.failures = pair_failures.saturating_add(1);
pair.last = if pair_failures == 0 { now } else { pair_last };
pair.locked_until = lock_until(pair.failures, now);
// A known address charges nothing, but the entry carries the generation
// that a later reset is noticed by.
if !known {
budget.state.failures = failures.saturating_add(1);
budget.state.last = if failures == 0 { now } else { last };
budget.reserved.push(now);
}
if !t.budgets.contains_key(account) && t.budgets.len() >= self.budget_capacity {
evict_budget(&mut t.budgets, self.budget_capacity, now);
@@ -295,17 +327,18 @@ impl LoginThrottle {
Ok(!known)
}
/// An attempt charged to the budget was evaluated and failed. Says what the
/// caller must write and audit, once the throttle's lock is gone.
/// 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 {
let mut t = guard(&self.tables);
let Some(e) = t.budgets.get_mut(account) else {
return FailureNote::default();
};
let (failures, last) = budget_now(&e.state, now);
e.state.failures = failures;
e.state.last = last;
let over = failures >= BUDGET_MAX_FAILURES;
e.reserved.pop();
e.prune(now);
e.state.times.push(now);
let count = e.state.times.len();
let over = count >= BUDGET_MAX_FAILURES;
let audit = over
&& (e.state.audited_at == 0
|| now.saturating_sub(e.state.audited_at) >= BUDGET_WINDOW_SECS);
@@ -314,18 +347,18 @@ impl LoginThrottle {
}
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_failures < BUDGET_MAX_FAILURES;
let crossing = over && e.written_count < BUDGET_MAX_FAILURES;
let write = (due || crossing || audit).then(|| {
e.written_at = now;
e.written_failures = failures;
e.state
e.written_count = count;
e.state.clone()
});
FailureNote { write, audit }
}
/// The password was right: this address is clear, and the reserved failure
/// leaves the budget. The rest of the budget stays spent, or each login by
/// the owner would hand a distributed attacker a fresh one.
/// 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) {
let mut t = guard(&self.tables);
if let Some(pair) = t.pairs.get_mut(&(account.to_string(), address_key(ip))) {
@@ -333,7 +366,7 @@ impl LoginThrottle {
pair.locked_until = 0;
}
if budgeted {
refund_budget(&mut t, account);
release_reservation(&mut t, account);
}
}
@@ -347,7 +380,7 @@ impl LoginThrottle {
}
}
if budgeted {
refund_budget(&mut t, account);
release_reservation(&mut t, account);
}
}
@@ -358,13 +391,9 @@ impl LoginThrottle {
}
}
fn budget_now(state: &BudgetState, now: u64) -> (u32, u64) {
decayed_by(state.failures, state.last, now, BUDGET_DECAY_SECS)
}
fn refund_budget(t: &mut LoginTables, account: &str) {
fn release_reservation(t: &mut LoginTables, account: &str) {
if let Some(e) = t.budgets.get_mut(account) {
e.state.failures = e.state.failures.saturating_sub(1);
e.reserved.pop();
}
}
@@ -386,13 +415,13 @@ fn evict_pair(pairs: &mut HashMap<(String, IpAddr), PairEntry>, capacity: usize,
}
fn evict_budget(budgets: &mut HashMap<String, BudgetEntry>, capacity: usize, now: u64) {
budgets.retain(|_, e| budget_now(&e.state, now).0 > 0);
budgets.retain(|_, e| e.weight(now) > 0);
if budgets.len() < capacity {
return;
}
let least = budgets
.iter()
.min_by_key(|(_, e)| (budget_now(&e.state, now).0, e.state.last))
.min_by_key(|(_, e)| (e.weight(now), e.state.times.iter().max().copied()))
.map(|(k, _)| k.clone());
if let Some(k) = least {
budgets.remove(&k);
@@ -505,19 +534,14 @@ mod tests {
through
}
#[test]
fn the_budget_is_a_cap_that_fades_one_per_slot() {
fn the_budget_is_a_cap_over_a_rolling_day() {
let t = LoginThrottle::default();
assert_eq!(spend(&t, "k", 150, 0, 1000), 100);
assert_eq!(
pair(&t, "k", addr(1), 1000),
Err(BUDGET_DECAY_SECS),
"seconds until the next slot"
);
assert_eq!(
pair(&t, "k", addr(1), 1000 + 800),
Err(BUDGET_DECAY_SECS - 800)
);
assert_eq!(spend(&t, "k", 5, 200, 1000 + BUDGET_DECAY_SECS), 1);
assert_eq!(pair(&t, "k", addr(1), 1800), Err(BUDGET_WINDOW_SECS - 800));
// Nothing opens before the oldest failure is a day old, then all at once:
// these 100 all happened at the same instant.
assert_eq!(spend(&t, "k", 5, 200, 1000 + BUDGET_WINDOW_SECS - 1), 0);
assert_eq!(spend(&t, "k", 150, 300, 1000 + BUDGET_WINDOW_SECS), 100);
}
#[test]
fn a_known_address_skips_the_budget_but_not_the_pair() {
@@ -530,14 +554,60 @@ mod tests {
assert_eq!(known(1000), Err(30));
}
#[test]
fn a_right_password_refunds_only_its_own_reservation() {
fn a_right_password_returns_only_a_reservation() {
let t = LoginThrottle::default();
spend(&t, "k", 100, 0, 1000);
assert!(pair(&t, "k", addr(1), 1000).is_err());
spend(&t, "k", 99, 0, 1000);
pair(&t, "k", addr(2), 1000).unwrap();
assert!(pair(&t, "k", addr(1), 1000).is_err(), "reserved counts");
t.right_password("k", addr(2), false);
assert!(pair(&t, "k", addr(1), 1000).is_err());
assert!(pair(&t, "k", addr(1), 1000).is_err(), "not charged");
t.right_password("k", addr(2), true);
assert!(pair(&t, "k", addr(1), 1000).is_ok());
pair(&t, "k", addr(1), 1000).unwrap();
t.failed("k", 1000);
t.right_password("k", addr(1), true);
assert!(pair(&t, "k", addr(3), 1000).is_err(), "failures stay");
}
#[test]
fn taking_every_opening_slot_never_passes_the_rolling_cap() {
let t = LoginThrottle::default();
let start = 10_000u64;
let mut taken: Vec<u64> = Vec::new();
let mut first = 0;
for minute in 0..(3 * 1440u64) {
let now = start + minute * 60;
// Fresh addresses: only the budget can refuse.
for _ in 0..3 {
first += 1;
if spend(&t, "k", 1, first, now) == 1 {
taken.push(now);
}
}
}
assert!(taken.len() >= 200, "the window reopens: {}", taken.len());
for (i, a) in taken.iter().enumerate() {
let inside = taken[i..]
.iter()
.take_while(|b| **b < a + BUDGET_WINDOW_SECS)
.count();
assert!(inside <= 100, "{inside} failures in the day from {a}");
}
}
#[test]
fn a_reset_frees_a_pair_even_after_its_budget_was_evicted() {
let t = LoginThrottle::with_capacity(1000, 1);
for _ in 0..5 {
pair(&t, "k", addr(1), 1000).unwrap();
}
pair(&t, "other", addr(2), 1000).unwrap();
pair(&t, "other2", addr(2), 1000).unwrap();
let reset = BudgetState {
generation: 1,
..Default::default()
};
assert_eq!(
t.acquire("k", addr(1), false, reset.clone(), 1000),
Ok(true)
);
}
#[test]
fn a_new_generation_starts_the_account_over() {
@@ -550,21 +620,26 @@ mod tests {
generation: 1,
..Default::default()
};
assert_eq!(t.acquire("k", addr(1), false, reset, 1000), Ok(true));
assert_eq!(
t.acquire("k", addr(1), false, reset.clone(), 1000),
Ok(true)
);
// Pairs too, even for an account seen only from a known address.
let t = LoginThrottle::default();
for _ in 0..5 {
t.acquire("k", addr(1), true, BudgetState::default(), 1000)
.unwrap();
}
assert_eq!(t.acquire("k", addr(1), true, reset, 1000), Ok(false));
assert_eq!(
t.acquire("k", addr(1), true, reset.clone(), 1000),
Ok(false)
);
}
#[test]
fn a_stored_budget_is_where_an_unmet_account_starts() {
let t = LoginThrottle::default();
let stored = BudgetState {
failures: 100,
last: 1000,
times: vec![1000; BUDGET_MAX_FAILURES],
..Default::default()
};
assert!(t.acquire("k", addr(1), false, stored, 1000).is_err());
@@ -574,10 +649,10 @@ mod tests {
fn eviction_takes_the_faded_then_the_least_counted() {
let t = LoginThrottle::with_capacity(1000, 3);
spend(&t, "faded", 1, 0, 1000);
spend(&t, "busy", 50, 10, 1000 + BUDGET_DECAY_SECS);
spend(&t, "small", 2, 100, 1000 + BUDGET_DECAY_SECS);
spend(&t, "busy", 50, 10, 1000);
spend(&t, "small", 2, 100, 1000);
// Newer than all of them, and each new name pushes out the last.
let now = 1001 + BUDGET_DECAY_SECS;
let now = 1001;
for i in 0..50 {
spend(&t, &format!("junk{i}"), 1, 200 + i, now);
}
@@ -607,7 +682,7 @@ mod tests {
spend(&t, "x", 99, 0, 1000);
pair(&t, "x", addr(8), 1000).unwrap();
let crossing = t.failed("x", 1000);
assert_eq!(crossing.write.map(|s| s.failures), Some(100));
assert_eq!(crossing.write.map(|s| s.times.len()), Some(100));
assert!(crossing.audit);
}
#[test]
+3 -3
View File
@@ -601,7 +601,7 @@ mod tests {
fn enroll(s: &AuthService, id: &str, now: u64) {
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();
}
/// Bootstraps `root` (admin, MFA enrolled).
@@ -1018,7 +1018,7 @@ mod tests {
let (_d, s) = svc();
root(&s);
let (id, _tok, a, r, t) = admin_with_tokens(&s);
s.change_password(&id, PW, "another long enough passphrase", None, t + 1)
s.change_password(&id, PW, "another long enough passphrase", None, None, t + 1)
.unwrap();
assert!(s.authenticate_token(&a.token, t + 2).is_err());
assert!(s.authenticate_token(&r.token, t + 2).is_ok());
@@ -1042,7 +1042,7 @@ mod tests {
.unwrap()
.generate(t + 100)
.to_string();
s.confirm_enrollment(&id, &code, t + 100).unwrap();
s.confirm_enrollment(&id, &code, None, t + 100).unwrap();
assert!(s.authenticate_token(&a.token, t + 101).is_err());
assert!(s.authenticate_token(&r.token, t + 101).is_ok());
}