feat(auth): accounts, first-run setup and MFA login flow

Adds AuthService with single-use setup code, password login, TOTP and
recovery codes, enrollment, account management and local admin reset.
Attempts are reserved before Argon2 so parallel guesses cannot outrun the
per-account delay or the IP limit, and unknown usernames follow the same
schedule as real accounts. Passwords are NFC-normalized; repeated-character
and all-digit passwords are refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-04 19:24:46 -03:00
1 parent deea3e245b
commit 2b71ae41c0
9 files changed
+1998 -10

No files matched your search

+795
View File
@@ -0,0 +1,795 @@
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, 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, T0)),
AuthFailure::BootstrapInvalid
);
assert_eq!(
failure(s.complete_bootstrap(&code, "root", PW, T0 + 3601)),
AuthFailure::BootstrapInvalid
);
// A weak password does not burn the code.
assert!(matches!(
s.complete_bootstrap(&code, "root", "short", 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, T0 + 10)),
AuthFailure::BootstrapInvalid
);
s.complete_bootstrap(&renewed, "root", PW, T0 + 3610)
.unwrap();
assert_eq!(
failure(s.complete_bootstrap(&renewed, "other", PW, 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, 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, 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 = 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.
for _ in 0..4 {
let _ = s.login("ghost", PW, "192.0.2.2".parse().unwrap(), T0);
let _ = s.login("ana", WRONG, "192.0.2.2".parse().unwrap(), T0);
}
let unknown = failure(s.login("ghost", PW, "192.0.2.3".parse().unwrap(), T0));
let bad = failure(s.login("ana", WRONG, "192.0.2.3".parse().unwrap(), T0));
assert_eq!(
unknown,
AuthFailure::Throttled {
retry_after_secs: 30
}
);
assert_eq!(unknown, bad);
}
#[test]
fn account_throttle_delay_grows_capped() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
let mut now = T0;
for _ in 0..4 {
assert_eq!(
failure(s.login("ana", WRONG, ip(), now)),
AuthFailure::InvalidCredentials
);
}
assert_eq!(
failure(s.login("ana", WRONG, ip(), now)),
AuthFailure::InvalidCredentials
);
// Locked: even the right password is not evaluated.
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
}
);
// Survives a restart and is capped.
s.store
.update(|st| {
st.users
.iter_mut()
.find(|u| u.id == id)
.unwrap()
.failed_attempts = 50;
Ok(())
})
.unwrap();
let dir = s.auth_dir.parent().unwrap().to_path_buf();
let s2 = AuthService::open(&dir, None).unwrap();
now += 61;
assert_eq!(
failure(s2.login("ana", WRONG, ip(), now)),
AuthFailure::InvalidCredentials
);
assert_eq!(
failure(s2.login("ana", PW, ip(), now)),
AuthFailure::Throttled {
retry_after_secs: 900
}
);
now += 901;
session_of(s2.login("ana", PW, ip(), now).unwrap());
let (f, l) = s2
.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), "success clears the counter");
}
#[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_account_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 addr = IpAddr::from([192, 0, 2, 100 + i]);
s.login("ana", WRONG, addr, 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 = 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_admin("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_admin("ghost", T0)),
AuthFailure::UserNotFound
);
analyst(&s, "ana");
assert_eq!(failure(s.reset_admin("ana", T0)), AuthFailure::UserNotFound);
let log = s.audit_tail(100).unwrap();
assert!(log
.iter()
.any(|e| e.event.action == "admin.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, 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);
}