Files
acaua/crates/acaua-core/src/auth/service_tests.rs
T
Lucas RayanandClaude Opus 5.5 9ef86ac425 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>
2026-11-05 07:01:16 -03:00

1762 lines
56 KiB
Rust

use super::*;
use crate::auth::credentials::build_totp;
use crate::error::{AcauaError, AuthFailure};
use tempfile::TempDir;
const T0: u64 = 1_800_000_000;
const PW: &str = "correct horse battery staple";
const PW2: &str = "another long enough passphrase";
const WRONG: &str = "definitely not the passphrase";
fn ip() -> IpAddr {
"192.0.2.1".parse().unwrap()
}
fn svc() -> (TempDir, AuthService) {
let dir = tempfile::tempdir().unwrap();
let s = AuthService::open(dir.path(), None).unwrap();
(dir, s)
}
fn failure<T: std::fmt::Debug>(r: Result<T>) -> AuthFailure {
match r.unwrap_err() {
AcauaError::Auth(f) => f,
other => panic!("expected auth failure, got {other}"),
}
}
fn uid(s: &AuthService, name: &str) -> String {
s.store
.read(|st| {
st.users
.iter()
.find(|u| u.username == name)
.unwrap()
.id
.clone()
})
.unwrap()
}
fn sessions(s: &AuthService, id: &str) -> usize {
s.store
.read(|st| st.sessions.iter().filter(|x| x.user_id == id).count())
.unwrap()
}
fn code_at(s: &AuthService, id: &str, unix: u64) -> String {
let sealed = s
.store
.read(|st| {
let u = st.users.iter().find(|u| u.id == id).unwrap();
u.totp_sealed
.clone()
.or(u.totp_pending_sealed.clone())
.unwrap()
})
.unwrap();
let secret = s.secrets.open_sealed(&sealed).unwrap();
build_totp(&secret, "x").unwrap().generate(unix).to_string()
}
/// Enrolls `id`; returns recovery codes.
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, None, now).unwrap()
}
/// First admin, enrolled. Returns its id.
fn admin(s: &AuthService) -> String {
let code = s.ensure_bootstrap(T0).unwrap().unwrap();
s.complete_bootstrap(&code, "root", PW, ip(), T0).unwrap();
let id = uid(s, "root");
enroll(s, &id, T0);
id
}
fn analyst(s: &AuthService, name: &str) -> String {
s.create_user("root", name, PW, Role::Analyst, T0).unwrap()
}
fn session_of(step: LoginStep) -> NewSession {
match step {
LoginStep::Session(x) => x,
other => panic!("expected session, got {other:?}"),
}
}
fn pending_of(step: LoginStep) -> PendingMfa {
match step {
LoginStep::MfaRequired(p) => p,
other => panic!("expected MfaRequired, got {other:?}"),
}
}
#[test]
fn bootstrap_code_single_use_and_expires() {
let (_d, s) = svc();
let code = s.ensure_bootstrap(T0).unwrap().unwrap();
assert_eq!(hash_token(&code).len(), 64);
// 128 bits in URL-safe base64.
assert_eq!(code.len(), 22);
assert_eq!(
failure(s.login("root", PW, ip(), T0)),
AuthFailure::SetupRequired
);
assert_eq!(
failure(s.complete_bootstrap("wrong", "root", PW, ip(), T0)),
AuthFailure::BootstrapInvalid
);
assert_eq!(
failure(s.complete_bootstrap(&code, "root", PW, ip(), T0 + 3601)),
AuthFailure::BootstrapInvalid
);
// A weak password does not burn the code.
assert!(matches!(
s.complete_bootstrap(&code, "root", "short", ip(), T0)
.unwrap_err(),
AcauaError::InvalidInput(_)
));
// Restart renews: the old code dies, the new one works.
let renewed = s.ensure_bootstrap(T0 + 10).unwrap().unwrap();
assert_ne!(renewed, code);
assert_eq!(
failure(s.complete_bootstrap(&code, "root", PW, ip(), T0 + 10)),
AuthFailure::BootstrapInvalid
);
s.complete_bootstrap(&renewed, "root", PW, ip(), T0 + 3610)
.unwrap();
assert_eq!(
failure(s.complete_bootstrap(&renewed, "other", PW, ip(), T0 + 3610)),
AuthFailure::BootstrapInvalid
);
assert_eq!(s.ensure_bootstrap(T0 + 3620).unwrap(), None);
assert!(s.has_admin().unwrap());
}
#[test]
fn bootstrap_code_is_consumed_once_under_concurrency() {
let (_d, s) = svc();
let code = s.ensure_bootstrap(T0).unwrap().unwrap();
let wins = std::thread::scope(|sc| {
let hs: Vec<_> = (0..4)
.map(|i| {
let (s, code) = (&s, &code);
sc.spawn(move || {
s.complete_bootstrap(code, &format!("adm{i}"), PW, ip(), T0)
.is_ok()
})
})
.collect();
hs.into_iter()
.map(|h| h.join().unwrap())
.filter(|ok| *ok)
.count()
});
assert_eq!(wins, 1);
assert_eq!(s.store.read(|st| st.users.len()).unwrap(), 1);
}
#[test]
fn admin_cannot_finish_login_without_mfa() {
let (_d, s) = svc();
let code = s.ensure_bootstrap(T0).unwrap().unwrap();
let boot = s.complete_bootstrap(&code, "root", PW, ip(), T0).unwrap();
let id = uid(&s, "root");
let LoginStep::MfaEnrollRequired(p) = s.login("root", PW, ip(), T0).unwrap() else {
panic!("admin must enroll");
};
assert_eq!(s.pending_user(&p.token, T0).unwrap(), id);
assert_eq!(s.pending_user(&boot.token, T0).unwrap(), id);
// No code can finish it before enrollment, not even with a started one.
assert_eq!(
failure(s.confirm_mfa(&p.token, "000000", T0)),
AuthFailure::InvalidCredentials
);
let e = s.start_enrollment(&id, T0).unwrap();
assert!(e.uri.starts_with("otpauth://totp/"));
assert!(!e.manual_key.is_empty() && e.uri.contains(&e.manual_key));
assert!(!e.qr_png_base64.is_empty());
let pending_code = code_at(&s, &id, T0);
assert_eq!(
failure(s.confirm_mfa(&p.token, &pending_code, T0)),
AuthFailure::InvalidCredentials
);
assert_eq!(sessions(&s, &id), 0);
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");
// 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, &next, T0 + 60)),
AuthFailure::InvalidCredentials
);
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);
// Once MFA is active a pending token gives no enrollment access.
assert_eq!(
failure(s.pending_user(&boot.token, T0 + 60)),
AuthFailure::InvalidCredentials
);
}
#[test]
fn analyst_without_mfa_gets_session_with_password() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
let n = session_of(s.login("ana", PW, ip(), T0).unwrap());
assert_eq!(n.user_id, id);
assert_eq!(n.expires_at, T0 + 43_200);
assert_eq!(n.token.len(), 43);
let raw = std::fs::read_to_string(s.auth_dir.join("state.json")).unwrap();
assert!(!raw.contains(&n.token));
assert!(raw.contains(&hash_token(&n.token)));
assert!(!format!("{n:?}").contains(&n.token));
}
#[test]
fn analyst_with_mfa_needs_code() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
enroll(&s, &id, T0);
let raw = std::fs::read_to_string(s.auth_dir.join("state.json")).unwrap();
let seed = s
.secrets
.open_sealed(
&s.store
.read(|st| st.users[1].totp_sealed.clone().unwrap())
.unwrap(),
)
.unwrap();
let b32 = s.start_enrollment(&id, T0).unwrap().manual_key;
assert!(!raw.contains(&b32) && !seed.is_empty());
let p = pending_of(s.login("ana", PW, ip(), T0 + 60).unwrap());
assert_eq!(p.expires_at, T0 + 60 + 300);
assert_eq!(sessions(&s, &id), 0);
assert_eq!(
failure(s.confirm_mfa(&p.token, "000000", T0 + 60)),
AuthFailure::InvalidCredentials
);
assert_eq!(
failure(s.confirm_mfa("garbage", "000000", T0 + 60)),
AuthFailure::InvalidCredentials
);
let good = code_at_active(&s, &id, T0 + 60);
// Expired pending token, even with a valid code for that moment.
let late = code_at_active(&s, &id, T0 + 361);
assert_eq!(
failure(s.confirm_mfa(&p.token, &late, T0 + 361)),
AuthFailure::InvalidCredentials
);
s.confirm_mfa(&p.token, &good, T0 + 60).unwrap();
assert_eq!(sessions(&s, &id), 1);
// Single use, and the same TOTP step cannot serve a second login.
let p2 = pending_of(s.login("ana", PW, ip(), T0 + 60).unwrap());
assert_eq!(
failure(s.confirm_mfa(&p2.token, &good, T0 + 60)),
AuthFailure::InvalidCredentials
);
let next = code_at_active(&s, &id, T0 + 90);
assert_eq!(
failure(s.confirm_mfa(&p.token, &next, T0 + 90)),
AuthFailure::InvalidCredentials,
"used pending token"
);
s.confirm_mfa(&p2.token, &next, T0 + 90).unwrap();
}
fn code_at_active(s: &AuthService, id: &str, unix: u64) -> String {
let sealed = s
.store
.read(|st| {
st.users
.iter()
.find(|u| u.id == id)
.unwrap()
.totp_sealed
.clone()
.unwrap()
})
.unwrap();
let secret = s.secrets.open_sealed(&sealed).unwrap();
build_totp(&secret, "x").unwrap().generate(unix).to_string()
}
#[test]
fn pending_token_is_void_after_password_change() {
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.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)),
AuthFailure::InvalidCredentials
);
}
#[test]
fn promotion_requires_enrollment() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
session_of(s.login("ana", PW, ip(), T0).unwrap());
assert_eq!(sessions(&s, &id), 1);
s.set_role("root", &id, Role::Admin, T0).unwrap();
assert_eq!(sessions(&s, &id), 0);
assert!(matches!(
s.login("ana", PW, ip(), T0).unwrap(),
LoginStep::MfaEnrollRequired(_)
));
assert_eq!(sessions(&s, &id), 0);
}
#[test]
fn cannot_remove_last_admin() {
let (_d, s) = svc();
let root = admin(&s);
assert_eq!(
failure(s.delete_user("root", &root, T0)),
AuthFailure::LastAdmin
);
assert_eq!(
failure(s.set_role("root", &root, Role::Analyst, T0)),
AuthFailure::LastAdmin
);
assert_eq!(
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, None, T0).unwrap();
s.delete_user("second", &root, T0).unwrap();
assert_eq!(
failure(s.delete_user("x", "no-such-id", T0)),
AuthFailure::UserNotFound
);
}
#[test]
fn recovery_code_replaces_totp_once() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
let codes = enroll(&s, &id, T0);
let raw = std::fs::read_to_string(s.auth_dir.join("state.json")).unwrap();
assert!(codes.iter().all(|c| !raw.contains(c.as_str())));
let p = pending_of(s.login("ana", PW, ip(), T0).unwrap());
// Canonicalized input is accepted.
s.confirm_mfa(&p.token, &codes[0].replace('-', " ").to_uppercase(), T0)
.unwrap();
let p = pending_of(s.login("ana", PW, ip(), T0).unwrap());
assert_eq!(
failure(s.confirm_mfa(&p.token, &codes[0], T0)),
AuthFailure::InvalidCredentials
);
s.confirm_mfa(&p.token, &codes[1], T0).unwrap();
}
#[test]
fn same_error_for_unknown_user_and_bad_password() {
let (_d, s) = svc();
admin(&s);
analyst(&s, "ana");
let unknown = failure(s.login("ghost", PW, ip(), T0));
let bad = failure(s.login("ana", WRONG, ip(), T0));
assert_eq!(unknown, AuthFailure::InvalidCredentials);
assert_eq!(unknown, bad);
assert_eq!(unknown.to_string(), bad.to_string());
// The throttle must not tell them apart either, per address or past the
// failure budget.
let spent: IpAddr = "192.0.2.2".parse().unwrap();
for _ in 0..5 {
let _ = s.login("ghost", PW, spent, T0);
let _ = s.login("ana", WRONG, spent, T0);
}
let unknown = failure(s.login("ghost", PW, spent, T0));
let bad = failure(s.login("ana", WRONG, spent, T0));
assert_eq!(
unknown,
AuthFailure::Throttled {
retry_after_secs: 30
}
);
assert_eq!(unknown, bad);
for name in ["ghost", "ana"] {
for i in 0..100u32 {
let addr = IpAddr::V4(std::net::Ipv4Addr::from(0x0a00_0000 + i));
let _ = s
.logins
.acquire(&hash_token(name), addr, false, Default::default(), T0);
}
}
let fresh: IpAddr = "192.0.2.3".parse().unwrap();
let unknown = failure(s.login("ghost", PW, fresh, T0));
let bad = failure(s.login("ana", WRONG, fresh, T0));
assert_eq!(
unknown,
AuthFailure::Throttled {
retry_after_secs: crate::auth::throttle::BUDGET_WINDOW_SECS
}
);
assert_eq!(unknown, bad);
}
#[test]
fn login_delay_grows_per_address() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
let mut now = T0;
for _ in 0..5 {
assert_eq!(
failure(s.login("ana", WRONG, ip(), now)),
AuthFailure::InvalidCredentials
);
}
// Locked: even the right password is not evaluated from this address.
assert_eq!(
failure(s.login("ana", PW, ip(), now)),
AuthFailure::Throttled {
retry_after_secs: 30
}
);
now += 31;
assert_eq!(
failure(s.login("ana", WRONG, ip(), now)),
AuthFailure::InvalidCredentials
);
assert_eq!(
failure(s.login("ana", WRONG, ip(), now)),
AuthFailure::Throttled {
retry_after_secs: 60
}
);
now += 61;
session_of(s.login("ana", PW, ip(), now).unwrap());
// None of it touched the user-bound counter.
let (f, l) = s
.store
.read(|st| {
let u = st.users.iter().find(|u| u.id == id).unwrap();
(u.failed_attempts, u.locked_until)
})
.unwrap();
assert_eq!((f, l), (0, 0));
// A right password clears the address.
for _ in 0..4 {
let _ = s.login("ana", WRONG, ip(), now);
}
assert_eq!(
failure(s.login("ana", WRONG, ip(), now)),
AuthFailure::InvalidCredentials
);
}
#[test]
fn right_password_from_another_ip_still_gets_in_while_an_attacker_keeps_failing() {
let (_d, s) = svc();
admin(&s);
analyst(&s, "ana");
let attacker: IpAddr = "203.0.113.9".parse().unwrap();
let owner: IpAddr = "198.51.100.1".parse().unwrap();
let mut now = T0;
for _ in 0..6 {
let _ = s.login("ana", WRONG, attacker, now);
}
// The cadence of the proof of concept: a failure each time the lock lapses,
// for a day, with the owner trying a second later.
for _ in 0..96 {
now += 901;
assert_eq!(
failure(s.login("ana", WRONG, attacker, now)),
AuthFailure::InvalidCredentials
);
session_of(s.login("ana", PW, owner, now + 1).unwrap());
}
assert!(matches!(
failure(s.login("ana", PW, attacker, now + 1)),
AuthFailure::Throttled { .. }
));
}
#[test]
fn login_counts_decay_over_time() {
let (_d, s) = svc();
admin(&s);
analyst(&s, "ana");
for _ in 0..5 {
let _ = s.login("ana", WRONG, ip(), T0);
}
// Long after, four failures are free again: the count was forgotten.
let later = T0 + 5 * 900;
for _ in 0..4 {
assert_eq!(
failure(s.login("ana", WRONG, ip(), later)),
AuthFailure::InvalidCredentials
);
}
session_of(s.login("ana", PW, ip(), later).unwrap());
}
#[test]
fn user_bound_failures_decay_over_time() {
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());
for _ in 0..4 {
let _ = s.confirm_mfa(&p.token, "000000", T0 + 60);
}
let p = pending_of(s.login("ana", PW, ip(), T0 + 1920).unwrap());
let _ = s.confirm_mfa(&p.token, "000000", T0 + 1920);
let failures = s
.store
.read(|st| {
st.users
.iter()
.find(|u| u.id == id)
.unwrap()
.failed_attempts
})
.unwrap();
assert_eq!(failures, 3, "two windows forgot two of four, then one more");
}
#[test]
fn refusals_write_nothing_and_failures_store_only_the_budget() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
let state = s.auth_dir.join(crate::auth::STATE_FILE);
let before = std::fs::read(&state).unwrap();
// A name with no account leaves no trace in the state.
for _ in 0..8 {
let _ = s.login("ghost", WRONG, ip(), T0);
}
assert_eq!(std::fs::read(&state).unwrap(), before);
for _ in 0..8 {
let _ = s.login("ana", WRONG, ip(), T0);
}
let u = user_of(&s, &id);
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();
let modified = std::fs::metadata(&state).unwrap().modified().unwrap();
let lines = s.audit_tail(1000).unwrap().len();
let _ = s.login("ana", WRONG, ip(), T0);
assert_eq!(s.audit_tail(1000).unwrap().len(), lines);
assert_eq!(std::fs::read(&state).unwrap(), before);
assert_eq!(
std::fs::metadata(&state).unwrap().modified().unwrap(),
modified
);
}
#[test]
fn a_stranger_cannot_trigger_the_user_bound_throttle() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
enroll(&s, &id, T0);
let attacker: IpAddr = "203.0.113.9".parse().unwrap();
for _ in 0..8 {
let _ = s.login("ana", WRONG, attacker, T0 + 60);
}
let p = pending_of(s.login("ana", PW, ip(), T0 + 60).unwrap());
let good = code_at_active(&s, &id, T0 + 60);
session_of(s.confirm_mfa(&p.token, &good, T0 + 60).unwrap());
}
#[test]
fn required_change_final_step_refuses_a_changed_account() {
let (_d, s) = svc();
let root = admin(&s);
let ana = analyst(&s, "ana");
let finish = |id: &str, epoch: u64| {
s.store
.update(|st| finish_required_change(st, id, epoch, None, T0))
};
// An administrator without MFA, as after a promotion in between.
let epoch = s
.store
.update(|st| {
let u = user_mut(st, &root).unwrap();
u.totp_sealed = None;
Ok(u.auth_epoch)
})
.unwrap();
assert_eq!(
failure(finish(&root, epoch.wrapping_sub(1))),
AuthFailure::InvalidCredentials
);
// The wrong epoch.
let epoch = s
.store
.read(|st| st.users.iter().find(|u| u.id == ana).unwrap().auth_epoch)
.unwrap();
assert_eq!(
failure(finish(&ana, epoch)),
AuthFailure::InvalidCredentials
);
// The expected epoch opens the session.
finish(&ana, epoch.wrapping_sub(1)).unwrap();
}
#[test]
fn an_analyst_who_lost_mfa_can_be_reset() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
enroll(&s, &id, T0);
let temp = s.reset_account("ana", T0 + 100).unwrap();
assert!(!s.mfa_enabled(&id).unwrap());
let LoginStep::PasswordChangeRequired(ticket) = s.login("ana", &temp, ip(), T0 + 200).unwrap()
else {
panic!("expected the password step");
};
s.change_required_password(&ticket.token, &temp, PW2, T0 + 200)
.unwrap();
session_of(s.login("ana", PW2, ip(), T0 + 300).unwrap());
}
#[test]
fn disabling_mfa_that_is_off_changes_nothing() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
let session = session_of(s.login("ana", PW, ip(), T0).unwrap());
let state = s.auth_dir.join(crate::auth::STATE_FILE);
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), None, T0)),
AuthFailure::MfaNotEnabled
);
assert_eq!(std::fs::read(&state).unwrap(), before);
assert_eq!(s.audit_tail(1000).unwrap().len(), lines);
assert_eq!(sessions(&s, &id), 1);
}
#[test]
fn bad_codes_count_towards_the_account_throttle() {
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());
for _ in 0..5 {
assert_eq!(
failure(s.confirm_mfa(&p.token, "000000", T0 + 60)),
AuthFailure::InvalidCredentials
);
}
let good = code_at_active(&s, &id, T0 + 60);
assert_eq!(
failure(s.confirm_mfa(&p.token, &good, T0 + 60)),
AuthFailure::Throttled {
retry_after_secs: 30
}
);
// A correct password alone does not wipe the MFA failures.
let f = |s: &AuthService| {
s.store
.read(|st| {
st.users
.iter()
.find(|u| u.id == id)
.unwrap()
.failed_attempts
})
.unwrap()
};
let p = pending_of(s.login("ana", PW, ip(), T0 + 91).unwrap());
assert_eq!(f(&s), 5);
let good = code_at_active(&s, &id, T0 + 91);
s.confirm_mfa(&p.token, &good, T0 + 91).unwrap();
assert_eq!(f(&s), 0);
}
#[test]
fn concurrent_guesses_cannot_outrun_the_address_throttle() {
let (_d, s) = svc();
admin(&s);
analyst(&s, "ana");
let evaluated = std::thread::scope(|sc| {
let hs: Vec<_> = (0..16u8)
.map(|i| {
let s = &s;
sc.spawn(move || {
let _ = i;
s.login("ana", WRONG, ip(), T0)
})
})
.collect();
hs.into_iter()
.map(|h| failure(h.join().unwrap()))
.filter(|f| *f == AuthFailure::InvalidCredentials)
.count()
});
assert_eq!(evaluated, 5);
}
#[test]
fn ip_throttle_blocks_after_20() {
let (_d, s) = svc();
admin(&s);
for _ in 0..19 {
s.ips.acquire(ip(), T0).unwrap();
}
assert_eq!(
failure(s.login("ghost1", WRONG, ip(), T0)),
AuthFailure::InvalidCredentials
);
assert_eq!(
failure(s.login("ghost2", WRONG, ip(), T0)),
AuthFailure::Throttled {
retry_after_secs: 900
}
);
let other: IpAddr = "192.0.2.9".parse().unwrap();
assert_eq!(
failure(s.login("ghost3", WRONG, other, T0)),
AuthFailure::InvalidCredentials
);
assert_eq!(
failure(s.login("ghost4", WRONG, ip(), T0 + 901)),
AuthFailure::InvalidCredentials
);
}
#[test]
fn successful_login_does_not_consume_ip_budget() {
let (_d, s) = svc();
admin(&s);
analyst(&s, "ana");
for _ in 0..19 {
s.ips.acquire(ip(), T0).unwrap();
}
session_of(s.login("ana", PW, ip(), T0).unwrap());
session_of(s.login("ana", PW, ip(), T0).unwrap());
}
#[test]
fn password_or_mfa_change_ends_other_sessions() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
let keep = session_of(s.login("ana", PW, ip(), T0).unwrap());
session_of(s.login("ana", PW, ip(), T0).unwrap());
assert_eq!(sessions(&s, &id), 2);
assert_eq!(
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), None, T0)
.unwrap_err(),
AcauaError::InvalidInput(_)
));
s.change_password(&id, PW, PW2, Some(&keep.token), None, T0)
.unwrap();
let left = s
.store
.read(|st| {
st.sessions
.iter()
.filter(|x| x.user_id == id)
.map(|x| x.id.clone())
.collect::<Vec<_>>()
})
.unwrap();
assert_eq!(left, std::slice::from_ref(&keep.id));
assert_eq!(
failure(s.login("ana", PW, ip(), T0)),
AuthFailure::InvalidCredentials
);
// Enrolling ends every session: its signature has none to keep.
session_of(s.login("ana", PW2, ip(), T0).unwrap());
enroll(&s, &id, T0);
assert_eq!(sessions(&s, &id), 0);
// Disabling MFA keeps only the named session.
let p = pending_of(s.login("ana", PW2, ip(), T0 + 60).unwrap());
let a = session_of(
s.confirm_mfa(&p.token, &code_at_active(&s, &id, T0 + 60), T0 + 60)
.unwrap(),
);
let p = pending_of(s.login("ana", PW2, ip(), T0 + 90).unwrap());
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), None, T0 + 90)
.unwrap();
assert_eq!(sessions(&s, &id), 1);
session_of(s.login("ana", PW2, ip(), T0 + 90).unwrap());
}
#[test]
fn usernames_are_validated_and_unique() {
let (_d, s) = svc();
admin(&s);
for bad in [
"",
"a:b",
"tab\tname",
"nul\0",
"line\nbreak",
" pad",
"pad ",
&"x".repeat(65),
] {
assert!(
matches!(
s.create_user("root", bad, PW, Role::Analyst, T0)
.unwrap_err(),
AcauaError::InvalidInput(_)
),
"{bad:?}"
);
}
let code_user = "joão.silva";
let id = analyst(&s, code_user);
s.start_enrollment(&id, T0).unwrap();
assert_eq!(
failure(s.create_user("root", "JOÃO.SILVA", PW, Role::Analyst, T0)),
AuthFailure::UsernameTaken
);
assert!(matches!(
s.create_user("root", "bob", "short", Role::Analyst, T0)
.unwrap_err(),
AcauaError::InvalidInput(_)
));
}
#[test]
fn login_accepts_any_unicode_form_and_case_of_username() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "joão");
assert_eq!(
session_of(s.login("JOA\u{0303}O", PW, ip(), T0).unwrap()).user_id,
id
);
}
#[test]
fn reset_admin_is_audited_and_forces_enrollment() {
let (_d, s) = svc();
let root = admin(&s);
session_of_any(&s, &root);
let temp = s.reset_account("root", T0 + 200).unwrap();
assert_eq!(sessions(&s, &root), 0);
assert!(temp.len() >= 24);
assert_eq!(
failure(s.login("root", PW, ip(), T0 + 200)),
AuthFailure::InvalidCredentials
);
assert!(matches!(
s.login("root", &temp, ip(), T0 + 200).unwrap(),
LoginStep::MfaEnrollRequired(_)
));
assert_eq!(
failure(s.reset_account("ghost", T0)),
AuthFailure::UserNotFound
);
let log = s.audit_tail(100).unwrap();
assert!(log
.iter()
.any(|e| e.event.action == "auth.reset" && e.event.ok));
let raw = std::fs::read_to_string(s.auth_dir.join("audit.jsonl")).unwrap();
assert!(!raw.contains(&temp));
}
fn session_of_any(s: &AuthService, id: &str) {
let p = pending_of(s.login("root", PW, ip(), T0 + 100).unwrap());
s.confirm_mfa(&p.token, &code_at_active(s, id, T0 + 100), T0 + 100)
.unwrap();
}
#[test]
fn audit_records_operations_without_secrets() {
let (_d, s) = svc();
let code = s.ensure_bootstrap(T0).unwrap().unwrap();
s.complete_bootstrap(&code, "root", PW, ip(), T0).unwrap();
let id = uid(&s, "root");
let codes = enroll(&s, &id, T0);
// A password typed into the username field must not reach the log.
let _ = s.login("my-secret-typed-as-name", WRONG, ip(), T0);
let _ = s.login("root", WRONG, ip(), T0);
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, None, T0).unwrap();
s.delete_user("root", &p, T0).unwrap();
let actions: Vec<String> = s
.audit_tail(100)
.unwrap()
.into_iter()
.map(|e| e.event.action)
.collect();
for want in [
"bootstrap.complete",
"mfa.enroll.start",
"mfa.enroll.confirm",
"login",
"user.create",
"user.role",
"password.change",
"user.delete",
] {
assert!(
actions.iter().any(|a| a == want),
"missing {want}: {actions:?}"
);
}
let raw = std::fs::read_to_string(s.auth_dir.join("audit.jsonl")).unwrap();
for secret in [
PW,
PW2,
WRONG,
code.as_str(),
codes[0].as_str(),
"my-secret-typed-as-name",
] {
assert!(!raw.contains(secret), "audit leaked {secret}");
}
}
#[test]
fn state_and_debug_hold_no_clear_secrets() {
let (_d, s) = svc();
admin(&s);
let u = s.store.read(|st| st.users[0].clone()).unwrap();
let dbg = format!("{u:?}");
assert!(!dbg.contains(&u.password_hash));
assert!(!dbg.contains(u.totp_sealed.as_deref().unwrap()));
let e = s.start_enrollment(&u.id, T0).unwrap();
let dbg = format!("{e:?}");
assert!(!dbg.contains(&e.manual_key) && !dbg.contains(&e.uri));
let raw = std::fs::read_to_string(s.auth_dir.join("state.json")).unwrap();
assert!(!raw.contains(&e.manual_key));
let p = s.login("root", PW, ip(), T0).unwrap();
let LoginStep::MfaRequired(p) = p else {
panic!()
};
assert!(!format!("{p:?}").contains(&p.token));
}
#[test]
fn open_fails_on_missing_key_without_touching_state() {
let dir = tempfile::tempdir().unwrap();
{
let s = AuthService::open(dir.path(), None).unwrap();
s.ensure_bootstrap(T0).unwrap();
}
let auth = dir.path().join("auth");
std::fs::remove_file(auth.join("secret.key")).unwrap();
let before = std::fs::read(auth.join("state.json")).unwrap();
assert_eq!(
failure(AuthService::open(dir.path(), None).map(|_| ())),
AuthFailure::KeyMissing
);
assert_eq!(std::fs::read(auth.join("state.json")).unwrap(), before);
}
/// Admin after `reset_account`, enrolled again. Returns (id, temp password).
fn reset_and_enroll(s: &AuthService) -> (String, String) {
let id = admin(s);
let temp = s.reset_account("root", T0 + 200).unwrap();
enroll(s, &id, T0 + 200);
(id, temp)
}
fn change_ticket(step: LoginStep) -> PendingMfa {
match step {
LoginStep::PasswordChangeRequired(p) => p,
other => panic!("expected PasswordChangeRequired, got {other:?}"),
}
}
#[test]
fn must_change_password_survives_enrollment_and_reopen() {
let (d, s) = svc();
let (id, temp) = reset_and_enroll(&s);
drop(s);
let s = AuthService::open(d.path(), None).unwrap();
let flag = s
.store
.read(|st| {
st.users
.iter()
.find(|u| u.id == id)
.unwrap()
.must_change_password
})
.unwrap();
assert!(flag);
let p = pending_of(s.login("root", &temp, ip(), T0 + 300).unwrap());
let code = code_at_active(&s, &id, T0 + 300);
change_ticket(s.confirm_mfa(&p.token, &code, T0 + 300).unwrap());
}
#[test]
fn no_ordinary_session_while_password_change_is_required() {
let (_d, s) = svc();
let (id, temp) = reset_and_enroll(&s);
let p = pending_of(s.login("root", &temp, ip(), T0 + 300).unwrap());
let code = code_at_active(&s, &id, T0 + 300);
let ticket = change_ticket(s.confirm_mfa(&p.token, &code, T0 + 300).unwrap());
assert_eq!(sessions(&s, &id), 0);
// The ticket is good for nothing else, and a pending token is no ticket.
assert_eq!(
failure(s.pending_user(&ticket.token, T0 + 300)),
AuthFailure::InvalidCredentials
);
let next = code_at_active(&s, &id, T0 + 330);
assert_eq!(
failure(s.confirm_mfa(&ticket.token, &next, T0 + 330)),
AuthFailure::InvalidCredentials
);
let p2 = pending_of(s.login("root", &temp, ip(), T0 + 330).unwrap());
assert_eq!(
failure(s.change_required_password(&p2.token, &temp, PW2, T0 + 330)),
AuthFailure::InvalidCredentials
);
// Expired ticket.
let t2 = change_ticket(s.confirm_mfa(&p2.token, &next, T0 + 330).unwrap());
assert_eq!(
failure(s.change_required_password(&t2.token, &temp, PW2, T0 + 631)),
AuthFailure::InvalidCredentials
);
assert_eq!(sessions(&s, &id), 0);
let n = s
.change_required_password(&t2.token, &temp, PW2, T0 + 330)
.unwrap();
assert_eq!(n.user_id, id);
assert_eq!(sessions(&s, &id), 1);
// Single use, the flag is gone, the temporary password is dead.
assert_eq!(
failure(s.change_required_password(&t2.token, PW2, PW, T0 + 330)),
AuthFailure::InvalidCredentials
);
assert_eq!(
failure(s.login("root", &temp, ip(), T0 + 360)),
AuthFailure::InvalidCredentials
);
let p = pending_of(s.login("root", PW2, ip(), T0 + 360).unwrap());
let code = code_at_active(&s, &id, T0 + 360);
session_of(s.confirm_mfa(&p.token, &code, T0 + 360).unwrap());
}
#[test]
fn flag_also_blocks_password_only_login() {
// A reset admin later demoted, without MFA, reaches the password-only path.
let (_d, s) = svc();
let root = admin(&s);
s.create_user("root", "second", PW, Role::Admin, T0)
.unwrap();
let second = uid(&s, "second");
let temp = s.reset_account("second", T0).unwrap();
s.set_role("root", &second, Role::Analyst, T0).unwrap();
let t = change_ticket(s.login("second", &temp, ip(), T0).unwrap());
assert_eq!(sessions(&s, &second), 0);
s.change_required_password(&t.token, &temp, PW2, T0)
.unwrap();
session_of(s.login("second", PW2, ip(), T0).unwrap());
assert_eq!(sessions(&s, &root), 0);
}
#[test]
fn change_password_clears_flag_and_refuses_the_same_password() {
let (_d, s) = svc();
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, None, T0 + 300)
.unwrap_err(),
AcauaError::InvalidInput(_)
));
assert_eq!(
s.store
.read(|st| st
.users
.iter()
.find(|u| u.id == id)
.unwrap()
.failed_attempts)
.unwrap(),
0
);
assert!(matches!(
s.change_password(
&id,
"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, None, T0 + 300)
.unwrap();
let flag = s
.store
.read(|st| {
st.users
.iter()
.find(|u| u.id == id)
.unwrap()
.must_change_password
})
.unwrap();
assert!(!flag);
}
// ---- Enrollment through a pending token: re-checked inside the update ----
fn first_admin(s: &AuthService) -> PendingMfa {
let code = s.ensure_bootstrap(T0).unwrap().unwrap();
s.complete_bootstrap(&code, "root", PW, ip(), T0).unwrap()
}
fn root_id(s: &AuthService) -> String {
s.store
.read(|st| {
st.users
.iter()
.find(|u| u.username == "root")
.unwrap()
.id
.clone()
})
.unwrap()
}
fn code_from_uri(uri: &str, unix: u64) -> String {
totp_rs::Totp::from_url(uri)
.unwrap()
.generate(unix)
.to_string()
}
#[test]
fn pending_enrollment_activates_mfa_and_then_refuses_the_token() {
let dir = tempfile::tempdir().unwrap();
let s = AuthService::open(dir.path(), None).unwrap();
let pending = first_admin(&s);
let e = s.start_enrollment_pending(&pending.token, T0).unwrap();
let codes = s
.confirm_enrollment_pending(&pending.token, &code_from_uri(&e.uri, T0), T0)
.unwrap();
assert!(!codes.is_empty());
// A password alone can never replace a second factor that is now active.
assert!(s.start_enrollment_pending(&pending.token, T0).is_err());
assert!(s
.confirm_enrollment_pending(&pending.token, &code_from_uri(&e.uri, T0 + 30), T0 + 30)
.is_err());
// The same token still finishes the login, with a later code.
let step = s
.confirm_mfa(&pending.token, &code_from_uri(&e.uri, T0 + 30), T0 + 30)
.unwrap();
assert!(matches!(step, LoginStep::Session(_)));
}
#[test]
fn pending_enrollment_refuses_a_stale_epoch_and_other_purposes() {
let dir = tempfile::tempdir().unwrap();
let s = AuthService::open(dir.path(), None).unwrap();
let pending = first_admin(&s);
let e = s.start_enrollment_pending(&pending.token, T0).unwrap();
let id = root_id(&s);
s.store
.update(|st| {
st.users.iter_mut().find(|u| u.id == id).unwrap().auth_epoch += 1;
Ok(())
})
.unwrap();
assert!(s.start_enrollment_pending(&pending.token, T0).is_err());
assert!(s
.confirm_enrollment_pending(&pending.token, &code_from_uri(&e.uri, T0), T0)
.is_err());
assert!(s.start_enrollment_pending("forged", T0).is_err());
}
#[test]
fn list_users_exposes_no_secret_material() {
let dir = tempfile::tempdir().unwrap();
let s = AuthService::open(dir.path(), None).unwrap();
first_admin(&s);
let json = serde_json::to_string(&s.list_users().unwrap()).unwrap();
assert!(json.contains("root"));
for leak in ["password_hash", "recovery", "totp_", "$argon2"] {
assert!(!json.contains(leak), "{leak} in {json}");
}
}
#[test]
fn csrf_value_is_bound_to_the_session_and_is_not_its_token_hash() {
let a = crate::auth::tokens::csrf_token("session-a");
assert_ne!(a, crate::auth::tokens::csrf_token("session-b"));
assert_ne!(a, hash_token("session-a"));
assert!(crate::auth::tokens::csrf_matches("session-a", &a));
assert!(!crate::auth::tokens::csrf_matches("session-b", &a));
assert!(!crate::auth::tokens::csrf_matches("session-a", ""));
}
// ---- Failure budget --------------------------------------------------------
const DAY: u64 = 86_400;
fn v4(i: u32) -> IpAddr {
IpAddr::V4(std::net::Ipv4Addr::from(0x0a00_0000 + i))
}
/// Spends `n` failures from distinct addresses, without the cost of Argon2;
/// `login_failed` is what a wrong password ends in.
fn burn(s: &AuthService, name: &str, n: u32, first: u32, now: u64) -> u32 {
let mut evaluated = 0;
for i in 0..n {
if let Ok(a) = s.login_begin(name, v4(first + i), now) {
evaluated += 1;
let _ = s.login_failed(a, now);
}
}
evaluated
}
fn user_of(s: &AuthService, id: &str) -> User {
s.store
.read(|st| st.users.iter().find(|u| u.id == id).unwrap().clone())
.unwrap()
}
fn exhausted_events(s: &AuthService) -> Vec<AuditEntry> {
s.audit_tail(100_000)
.unwrap()
.into_iter()
.filter(|e| e.event.action == "login.budget_exhausted")
.collect()
}
const OWNER: &str = "203.0.113.50";
#[test]
fn budget_stops_a_distributed_guesser_before_argon2() {
let (_d, s) = svc();
admin(&s);
analyst(&s, "ana");
assert_eq!(burn(&s, "ana", 1000, 0, T0), 100);
let fresh: IpAddr = "198.51.100.200".parse().unwrap();
// `login_begin` is all that runs before Argon2.
assert!(matches!(
failure(s.login_begin("ana", fresh, T0)),
AuthFailure::Throttled { retry_after_secs } if retry_after_secs > 0
));
assert!(matches!(
failure(s.login("ana", PW, fresh, T0)),
AuthFailure::Throttled { .. }
));
// A cap, not a delay: waiting a minute or an hour gets no guess through.
assert!(s.login_begin("ana", fresh, T0 + 61).is_err());
assert!(s.login_begin("ana", fresh, T0 + 800).is_err());
}
#[test]
fn a_known_address_logs_in_during_exhaustion_and_a_session_survives() {
let (_d, s) = svc();
admin(&s);
analyst(&s, "ana");
let owner: IpAddr = OWNER.parse().unwrap();
let live = session_of(s.login("ana", PW, owner, T0).unwrap());
burn(&s, "ana", 100, 0, T0 + 1);
session_of(s.login("ana", PW, owner, T0 + 1).unwrap());
assert!(s.authenticate_session(&live.token, T0 + 1).is_ok());
let stranger: IpAddr = "198.51.100.200".parse().unwrap();
assert!(matches!(
failure(s.login("ana", PW, stranger, T0 + 1)),
AuthFailure::Throttled { .. }
));
// Still under the pair throttle.
for _ in 0..5 {
assert_eq!(
failure(s.login("ana", WRONG, owner, T0 + 2)),
AuthFailure::InvalidCredentials
);
}
assert!(matches!(
failure(s.login("ana", PW, owner, T0 + 2)),
AuthFailure::Throttled { .. }
));
}
#[test]
fn a_known_address_requires_the_full_login_and_expires() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
enroll(&s, &id, T0);
let owner: IpAddr = OWNER.parse().unwrap();
let p = pending_of(s.login("ana", PW, owner, T0 + 60).unwrap());
assert!(
user_of(&s, &id).known_addresses.is_empty(),
"password alone"
);
let _ = s.confirm_mfa(&p.token, "000000", T0 + 60);
assert!(user_of(&s, &id).known_addresses.is_empty(), "wrong code");
let code = code_at(&s, &id, T0 + 90);
session_of(s.confirm_mfa(&p.token, &code, T0 + 90).unwrap());
assert_eq!(user_of(&s, &id).known_addresses.len(), 1);
burn(&s, "ana", 100, 0, T0 + 100);
assert!(s.login_begin("ana", owner, T0 + 100).is_ok());
// Past 30 days the entry is worth nothing, while a new attack exhausts.
let later = T0 + 31 * DAY;
burn(&s, "ana", 100, 1000, later);
assert!(s.login_begin("ana", owner, later).is_err());
}
#[test]
fn the_known_list_is_bounded_and_holds_no_raw_address() {
let (d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
for i in 0..12u32 {
session_of(s.login("ana", PW, v4(i), T0 + u64::from(i)).unwrap());
}
let known = user_of(&s, &id).known_addresses;
assert_eq!(known.len(), 10);
assert_eq!(known.iter().map(|k| k.last_seen).min(), Some(T0 + 2));
let state = std::fs::read_to_string(d.path().join("auth/state.json")).unwrap();
assert!(!state.contains("10.0.0."), "raw address stored");
}
#[test]
fn a_48_counts_as_one_address() {
let (_d, s) = svc();
admin(&s);
analyst(&s, "ana");
for i in 0..5 {
let ip: IpAddr = format!("2001:db8:1:{i:x}::1").parse().unwrap();
assert_eq!(
failure(s.login("ana", WRONG, ip, T0)),
AuthFailure::InvalidCredentials
);
}
let same: IpAddr = "2001:db8:1:ffff::2".parse().unwrap();
assert!(matches!(
failure(s.login("ana", PW, same, T0)),
AuthFailure::Throttled { .. }
));
// Known by prefix too, and a mapped IPv4 is the IPv4.
let (_d, s) = svc();
admin(&s);
analyst(&s, "ana");
session_of(
s.login("ana", PW, "2001:db8:2:1::1".parse().unwrap(), T0)
.unwrap(),
);
session_of(
s.login("ana", PW, "203.0.113.9".parse().unwrap(), T0)
.unwrap(),
);
burn(&s, "ana", 100, 0, T0);
assert!(s
.login_begin("ana", "2001:db8:2:ffff::9".parse().unwrap(), T0)
.is_ok());
assert!(s
.login_begin("ana", "::ffff:203.0.113.9".parse().unwrap(), T0)
.is_ok());
assert!(s
.login_begin("ana", "2001:db8:3::1".parse().unwrap(), T0)
.is_err());
}
#[test]
fn the_budget_decays_and_survives_reopening() {
let (d, s) = svc();
admin(&s);
analyst(&s, "ana");
burn(&s, "ana", 100, 0, T0);
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());
// 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]
fn budget_writes_are_coalesced_and_a_refusal_writes_nothing() {
let (d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
burn(&s, "ana", 3, 0, T0);
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_times.len(), 1, "within the minute");
burn(&s, "ana", 1, 20, T0 + 60);
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_times.len(),
100,
"the crossing writes"
);
assert_eq!(burn(&s, "ana", 10, 300, T0 + 121), 0);
assert_eq!(std::fs::read(&path).unwrap(), before);
}
#[test]
fn an_unknown_username_exhausts_like_a_real_one() {
let (_d, s) = svc();
admin(&s);
analyst(&s, "ana");
let run = |name: &str| -> Vec<std::result::Result<(), u64>> {
let mut seen = Vec::new();
for (step, now) in [(90u32, T0), (20, T0 + 100), (3, T0 + 864), (3, T0 + 2000)] {
for i in 0..step {
seen.push(match s.login_begin(name, v4(10_000 + i), now) {
Ok(a) => {
let _ = s.login_failed(a, now);
Ok(())
}
Err(AcauaError::Auth(AuthFailure::Throttled { retry_after_secs })) => {
Err(retry_after_secs)
}
Err(other) => panic!("{other}"),
});
}
}
seen
};
// Pairs differ per name, so both use the same addresses in order.
let real = run("ana");
let ghost = run("nobody");
assert_eq!(real, ghost);
assert!(real.iter().any(|r| r.is_err()));
}
#[test]
fn exhaustion_is_audited_once_per_window() {
let (d, s) = svc();
admin(&s);
analyst(&s, "ana");
burn(&s, "ana", 300, 0, T0);
let events = exhausted_events(&s);
assert_eq!(events.len(), 1);
assert_eq!(events[0].event.actor.as_deref(), Some("ana"));
assert!(events[0].event.detail.as_deref().unwrap().contains("100"));
// Hovering at the cap, reopened or not, stays quiet inside the window.
let s = AuthService::open(d.path(), None).unwrap();
burn(&s, "ana", 5, 400, T0 + 864);
assert_eq!(exhausted_events(&s).len(), 1);
// Still under attack a day later: one more.
burn(&s, "ana", 100, 500, T0 + DAY + 1);
assert_eq!(exhausted_events(&s).len(), 2);
}
#[test]
fn credential_changes_clear_known_addresses_and_reset_reopens_login() {
let (d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
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), None, T0)
.unwrap();
assert!(user_of(&s, &id).known_addresses.is_empty(), "password");
session_of(s.login("ana", PW2, owner, T0).unwrap());
enroll(&s, &id, T0);
assert!(user_of(&s, &id).known_addresses.is_empty(), "enrolling");
let p = pending_of(s.login("ana", PW2, owner, T0 + 60).unwrap());
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, None, T0 + 60).unwrap();
assert!(user_of(&s, &id).known_addresses.is_empty(), "disabling");
session_of(s.login("ana", PW2, owner, T0 + 60).unwrap());
burn(&s, "ana", 100, 0, T0 + 60);
// A locked owner on a new address. The CLI is another process.
let stranger: IpAddr = "198.51.100.200".parse().unwrap();
assert!(s.login_begin("ana", stranger, T0 + 61).is_err());
let cli = AuthService::open(d.path(), None).unwrap();
let temp = cli.reset_account("ana", T0 + 61).unwrap();
let u = user_of(&s, &id);
assert!(u.known_addresses.is_empty());
assert!(u.budget_times.is_empty());
assert!(matches!(
s.login("ana", &temp, stranger, T0 + 62).unwrap(),
LoginStep::PasswordChangeRequired(_)
));
}
#[test]
fn a_required_password_change_makes_the_address_known() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
let temp = s.reset_account("ana", T0).unwrap();
let owner: IpAddr = OWNER.parse().unwrap();
let LoginStep::PasswordChangeRequired(t) = s.login("ana", &temp, owner, T0).unwrap() else {
panic!("expected a ticket");
};
assert!(user_of(&s, &id).known_addresses.is_empty());
s.change_required_password(&t.token, &temp, PW2, T0)
.unwrap();
assert_eq!(user_of(&s, &id).known_addresses.len(), 1);
}
#[test]
fn a_flood_of_junk_usernames_keeps_a_real_budget() {
let (_d, mut s) = svc();
s.logins = LoginThrottle::with_capacity(64, 16);
admin(&s);
analyst(&s, "ana");
assert_eq!(burn(&s, "ana", 50, 0, T0), 50);
for i in 0..200 {
// Newer than the real entry, which is what an oldest-first eviction drops.
burn(&s, &format!("junk{i}"), 1, 1000 + i, T0 + 1);
}
assert_eq!(
burn(&s, "ana", 60, 2000, T0 + 1),
50,
"the budget stayed spent"
);
}
#[test]
fn parallel_attempts_cannot_overrun_the_cap() {
let (_d, s) = svc();
admin(&s);
analyst(&s, "ana");
let s = std::sync::Arc::new(s);
let handles: Vec<_> = (0..8u32)
.map(|t| {
let s = s.clone();
std::thread::spawn(move || {
(0..50u32)
.filter(|i| s.login_begin("ana", v4(t * 100 + i), T0).is_ok())
.count()
})
})
.collect();
let through: usize = handles.into_iter().map(|h| h.join().unwrap()).sum();
assert_eq!(through, 100);
}
#[test]
fn an_abandoned_attempt_returns_its_reservations() {
let (_d, s) = svc();
admin(&s);
analyst(&s, "ana");
let held: Vec<_> = (0..100u32)
.map(|i| s.login_begin("ana", v4(i), T0).unwrap())
.collect();
assert!(s.login_begin("ana", v4(500), T0).is_err());
for a in held {
s.login_abandon(a);
}
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);
}
#[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());
}