Files
acaua/crates/acaua-core/src/auth/service_tests.rs
T
Lucas RayanandClaude Opus 5.5 348e61ca95 fix(auth): close unauthenticated lockout and tighten the daemon's edges
Key login failures by username and client address with decay, plus a loose
per-username limit that delays every address by a bounded time. Refused
attempts write nothing. Unknown usernames share the code path. MFA and session
password checks keep a persistent user-bound count that needs a password or a
session to reach.

Also: local mode refuses a non-loopback bind outside a container; security
headers on every response; the Argon2 permit lives as long as the blocking
task; a required password change rechecks role, MFA and epoch; auth reset
works for any user; mfa_enabled in /api/auth/state; disabling MFA that is off
is refused with no side effects; StateCorrupt keeps only line and column.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 21:03:27 -03:00

1215 lines
38 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, 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, 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.
assert_eq!(
failure(s.confirm_mfa(&p.token, &pending_code, T0)),
AuthFailure::InvalidCredentials
);
let next = code_at(&s, &id, T0 + 60);
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, 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, 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.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
// account-wide limit.
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, 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: 60
}
);
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 wrong_passwords_and_refusals_write_no_state() {
let (_d, s) = svc();
admin(&s);
analyst(&s, "ana");
let state = s.auth_dir.join(crate::auth::STATE_FILE);
let before = std::fs::read(&state).unwrap();
let modified = std::fs::metadata(&state).unwrap().modified().unwrap();
for _ in 0..8 {
let _ = s.login("ana", WRONG, ip(), T0);
let _ = s.login("ghost", WRONG, ip(), T0);
}
assert_eq!(std::fs::read(&state).unwrap(), before);
assert_eq!(
std::fs::metadata(&state).unwrap().modified().unwrap(),
modified
);
// Refusals do not reach the audit log either.
let lines = s.audit_tail(1000).unwrap().len();
let _ = s.login("ana", WRONG, ip(), T0);
assert_eq!(s.audit_tail(1000).unwrap().len(), lines);
}
#[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, 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), 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), T0)),
AuthFailure::InvalidCredentials
);
assert_eq!(sessions(&s, &id), 2);
assert!(matches!(
s.change_password(&id, PW, "short", Some(&keep.token), T0)
.unwrap_err(),
AcauaError::InvalidInput(_)
));
s.change_password(&id, PW, PW2, Some(&keep.token), 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), 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, 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, 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,
T0
)
.unwrap_err(),
AcauaError::InvalidInput(_)
));
s.change_password(&id, &temp, PW2, 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", ""));
}