From a90ff81650474a140f66ec23f8065e05ad9463a2 Mon Sep 17 00:00:00 2001 From: Lucas Rayan Date: Wed, 4 Nov 2026 19:40:08 -0300 Subject: [PATCH] fix(auth): per-session reauth and admin token lifecycle Co-Authored-By: Claude Opus 5.5 --- crates/acaua-core/src/auth/service.rs | 20 +- crates/acaua-core/src/auth/store.rs | 4 +- crates/acaua-core/src/auth/tokens.rs | 270 +++++++++++++++++++++----- 3 files changed, 247 insertions(+), 47 deletions(-) diff --git a/crates/acaua-core/src/auth/service.rs b/crates/acaua-core/src/auth/service.rs index acca880..e2256f9 100644 --- a/crates/acaua-core/src/auth/service.rs +++ b/crates/acaua-core/src/auth/service.rs @@ -10,7 +10,7 @@ use super::credentials::{ hash_password, hash_recovery_code, new_recovery_codes, new_totp_secret, normalize, totp_uri_and_qr, validate_password, verify_password, verify_totp, }; -use super::store::{AuthState, AuthStore, Bootstrap, Role, Session, User}; +use super::store::{AuthState, AuthStore, Bootstrap, Role, Scope, Session, User}; use super::throttle::{lock_until, IpLimiter, UnknownAccounts}; use super::{hash_token, random_token, AuditEntry, AuditEvent, AuditLog, Secrets}; use crate::error::{AcauaError, AuthFailure, Result}; @@ -188,6 +188,13 @@ fn end_sessions(st: &mut AuthState, user_id: &str, keep_token: Option<&str>) { .retain(|s| s.user_id != user_id || keep.as_deref() == Some(s.token_hash.as_str())); } +/// A password or MFA change is the usual answer to a compromise: admin-scope +/// tokens die with it, read tokens keep automation alive. +pub(super) fn drop_admin_tokens(st: &mut AuthState, user_id: &str) { + st.tokens + .retain(|t| t.user_id != user_id || t.scope != Scope::Admin); +} + fn issue_session(st: &mut AuthState, user_id: &str, now: u64) -> NewSession { st.sessions.retain(|s| s.expires_at > now); let token = random_token(SESSION_TOKEN_BYTES); @@ -200,6 +207,7 @@ fn issue_session(st: &mut AuthState, user_id: &str, now: u64) -> NewSession { created_at: now, last_seen: now, expires_at, + last_reauth: 0, }); NewSession { id, @@ -608,6 +616,7 @@ impl AuthService { u.totp_last_step = Some(step); u.recovery_hashes = hashes; end_sessions(st, user_id, None); + drop_admin_tokens(st, user_id); Ok((name, true)) })?; self.log("mfa.enroll.confirm", Some(&name), None, accepted, None)?; @@ -666,9 +675,16 @@ impl AuthService { let changed = u.role != role; let name = u.username.clone(); if changed { + let leaving_admin = u.role == Role::Admin && role != Role::Admin; u.role = role; u.auth_epoch = u.auth_epoch.wrapping_add(1); end_sessions(st, user_id, None); + if leaving_admin { + // Permanent: a later re-promotion must not revive them. + for t in st.tokens.iter_mut().filter(|t| t.user_id == user_id) { + t.scope = Scope::Read; + } + } } Ok(name) }); @@ -741,6 +757,7 @@ impl AuthService { u.must_change_password = false; u.auth_epoch = u.auth_epoch.wrapping_add(1); end_sessions(st, user_id, keep_session_token); + drop_admin_tokens(st, user_id); Ok(true) })?; self.log("password.change", Some(&name), None, changed, None)?; @@ -797,6 +814,7 @@ impl AuthService { u.totp_last_step = None; u.recovery_hashes.clear(); end_sessions(st, user_id, keep_session_token); + drop_admin_tokens(st, user_id); Ok(name) }); self.log_admin_result("mfa.disable", actor, &result)?; diff --git a/crates/acaua-core/src/auth/store.rs b/crates/acaua-core/src/auth/store.rs index 195adfc..cff01b2 100644 --- a/crates/acaua-core/src/auth/store.rs +++ b/crates/acaua-core/src/auth/store.rs @@ -46,8 +46,6 @@ pub struct User { pub auth_epoch: u64, /// Set by `reset_admin`: no ordinary session until the password changes. pub must_change_password: bool, - /// Unix seconds of the last `reauthenticate`; 0 if never. - pub last_reauth: u64, } impl std::fmt::Debug for User { @@ -71,6 +69,8 @@ pub struct Session { pub created_at: u64, pub last_seen: u64, pub expires_at: u64, + /// Unix seconds of the last `reauthenticate` of this session; 0 if never. + pub last_reauth: u64, } impl std::fmt::Debug for Session { diff --git a/crates/acaua-core/src/auth/tokens.rs b/crates/acaua-core/src/auth/tokens.rs index d5e9add..ba023d1 100644 --- a/crates/acaua-core/src/auth/tokens.rs +++ b/crates/acaua-core/src/auth/tokens.rs @@ -40,8 +40,10 @@ pub struct Principal { pub role: Role, pub via: Via, pub scope: Scope, - /// The user passed `reauthenticate` within the last 10 minutes. + /// This session passed `reauthenticate` within the last 10 minutes. pub recent_auth: bool, + /// Id of the session behind a `Via::Session` principal. + pub session_id: Option, } /// A token just created. The secret exists only here. @@ -105,11 +107,17 @@ fn role_scope(role: Role) -> Scope { } } -fn is_recent(u: &User, now: u64) -> bool { - u.last_reauth != 0 && now >= u.last_reauth && now - u.last_reauth <= RECENT_AUTH_SECS +fn is_recent(last_reauth: u64, now: u64) -> bool { + last_reauth != 0 && now >= last_reauth && now - last_reauth <= RECENT_AUTH_SECS } -fn principal(u: &User, via: Via, scope: Scope, recent_auth: bool) -> Principal { +fn principal( + u: &User, + via: Via, + scope: Scope, + recent_auth: bool, + session_id: Option, +) -> Principal { Principal { user_id: u.id.clone(), username: u.username.clone(), @@ -117,11 +125,16 @@ fn principal(u: &User, via: Via, scope: Scope, recent_auth: bool) -> Principal { via, scope, recent_auth, + session_id, } } /// An admin may act on anyone's sessions and tokens; others only their own. +/// A read-scope token manages nothing. fn may_manage(actor: &Principal, owner: &str) -> bool { + if actor.via != Via::Session && actor.scope != Scope::Admin { + return false; + } actor.user_id == owner || (actor.role == Role::Admin && actor.scope == Scope::Admin) } @@ -153,7 +166,13 @@ impl AuthService { .ok_or_else(invalid)?; let touch = now.saturating_sub(s.last_seen) >= LAST_SEEN_WRITE_SECS; Ok(( - principal(u, Via::Session, role_scope(u.role), is_recent(u, now)), + principal( + u, + Via::Session, + role_scope(u.role), + is_recent(s.last_reauth, now), + Some(s.id.clone()), + ), touch, )) })??; @@ -186,7 +205,7 @@ impl AuthService { Some(&actor.username), None, removed, - Some(session_id), + removed.then_some(session_id), )?; if removed { Ok(()) @@ -237,16 +256,27 @@ impl AuthService { } /// Proves the password (and the code, when the account has MFA) again, - /// which opens a 10-minute window for sensitive actions. Throttled like - /// login; a code is never accepted twice. + /// which opens a 10-minute window for sensitive actions in the session + /// holding `session_token` only. Throttled like login; a code is never + /// accepted twice. pub fn reauthenticate( &self, user_id: &str, + session_token: &str, password: &str, code: Option<&str>, now: u64, ) -> Result<()> { + let session_hash = hash_token(session_token); let (name, hash) = self.store.update(|st| { + let live = find_hash(&st.sessions, &session_hash, |s| &s.token_hash).is_some_and(|s| { + s.user_id == user_id + && now <= s.expires_at + && now.saturating_sub(s.last_seen) <= SESSION_IDLE_SECS + }); + if !live { + return Err(invalid()); + } let u = user_or_missing(st, user_id)?; reserve_attempt(u, now).map_err(throttled)?; Ok((u.username.clone(), u.password_hash.clone())) @@ -263,28 +293,49 @@ impl AuthService { } let recovery_hash = code.map(hash_recovery_code); let ok = self.store.update(|st| { - let Some(u) = user_mut(st, user_id).filter(|u| u.password_hash == hash) else { - return Ok(false); - }; - refund_attempt(u); - if let Some(sealed) = u.totp_sealed.clone() { - let secret = self.secrets.open_sealed(&sealed)?; - let step = code.and_then(|c| verify_totp(&secret, c, now, u.totp_last_step)); - if let Some(step) = step { - u.totp_last_step = Some(step); - } else if let Some(i) = recovery_hash - .as_ref() - .and_then(|h| u.recovery_hashes.iter().position(|x| x == h)) - { - u.recovery_hashes.remove(i); - } else { - // Persisted: a wrong or missing code counts as a failure. - count_failure(u, now); + let passed = { + let Some(u) = user_mut(st, user_id).filter(|u| u.password_hash == hash) else { return Ok(false); + }; + refund_attempt(u); + match u.totp_sealed.clone() { + None => true, + Some(sealed) => { + let secret = self.secrets.open_sealed(&sealed)?; + let step = + code.and_then(|c| verify_totp(&secret, c, now, u.totp_last_step)); + if let Some(step) = step { + u.totp_last_step = Some(step); + true + } else if let Some(i) = recovery_hash + .as_ref() + .and_then(|h| u.recovery_hashes.iter().position(|x| x == h)) + { + u.recovery_hashes.remove(i); + true + } else { + // Persisted: a wrong or missing code is a failure. + count_failure(u, now); + false + } + } } + }; + if !passed { + return Ok(false); + } + // The session may have ended while Argon2 ran. + match st + .sessions + .iter_mut() + .find(|s| ct_eq(&s.token_hash, &session_hash) && s.user_id == user_id) + { + Some(s) => { + s.last_reauth = now; + Ok(true) + } + None => Ok(false), } - u.last_reauth = now; - Ok(true) })?; self.log( "reauth", @@ -344,6 +395,9 @@ impl AuthService { expires_at: u64, now: u64, ) -> Result { + let Some(session_id) = principal.session_id.as_deref() else { + return Err(AuthFailure::ReauthRequired.into()); + }; if principal.via != Via::Session || !principal.recent_auth { return Err(AuthFailure::ReauthRequired.into()); } @@ -361,7 +415,13 @@ impl AuthService { .iter() .find(|u| u.id == principal.user_id && !u.must_change_password) .ok_or_else(invalid)?; - if !is_recent(u, now) { + let recent = st.sessions.iter().any(|s| { + s.id == session_id + && s.user_id == u.id + && now <= s.expires_at + && is_recent(s.last_reauth, now) + }); + if !recent { return Err(AuthFailure::ReauthRequired.into()); } if scope > role_scope(u.role) { @@ -420,6 +480,7 @@ impl AuthService { Via::Token, t.scope.min(role_scope(u.role)), false, + None, )) })? } @@ -457,7 +518,7 @@ impl AuthService { Some(&actor.username), None, removed, - Some(token_id), + removed.then_some(token_id), )?; if removed { Ok(()) @@ -648,7 +709,7 @@ mod tests { root(&s); let (id, tok) = analyst_session(&s, "ana", T0); assert!(!s.authenticate_session(&tok, T0 + 1).unwrap().recent_auth); - s.reauthenticate(&id, PW, None, T0 + 10).unwrap(); + s.reauthenticate(&id, &tok, PW, None, T0 + 10).unwrap(); assert!(s.authenticate_session(&tok, T0 + 610).unwrap().recent_auth); assert!(!s.authenticate_session(&tok, T0 + 611).unwrap().recent_auth); } @@ -657,9 +718,9 @@ mod tests { fn reauthenticate_uses_password_throttle_and_requires_code_with_mfa() { let (_d, s) = svc(); root(&s); - let (id, _) = analyst_session(&s, "ana", T0); + let (id, tok) = analyst_session(&s, "ana", T0); for i in 0..20 { - let r = s.reauthenticate(&id, "wrong password here", None, T0 + 1 + i); + let r = s.reauthenticate(&id, &tok, "wrong password here", None, T0 + 1 + i); if matches!(r, Err(AcauaError::Auth(AuthFailure::Throttled { .. }))) { return assert!(i >= 3, "throttled too early"); } @@ -672,15 +733,17 @@ mod tests { let (_d, s) = svc(); root(&s); let (id, tok) = admin_session(&s, "adm", T0); - assert!(s.reauthenticate(&id, PW, None, T0 + 100).is_err()); - assert!(s.reauthenticate(&id, PW, Some("000000"), T0 + 200).is_err()); + assert!(s.reauthenticate(&id, &tok, PW, None, T0 + 100).is_err()); + assert!(s + .reauthenticate(&id, &tok, PW, Some("000000"), T0 + 200) + .is_err()); // Within the idle window, past any throttle; use a fresh TOTP step. let t = T0 + 1000; let code = code_at(&s, &id, t); - s.reauthenticate(&id, PW, Some(&code), t).unwrap(); + s.reauthenticate(&id, &tok, PW, Some(&code), t).unwrap(); assert!(s.authenticate_session(&tok, t).unwrap().recent_auth); // The same code is not accepted twice. - assert!(s.reauthenticate(&id, PW, Some(&code), t + 1).is_err()); + assert!(s.reauthenticate(&id, &tok, PW, Some(&code), t + 1).is_err()); } #[test] @@ -694,7 +757,7 @@ mod tests { failure(s.create_api_token(&p, "ci", Scope::Read, exp, T0 + 1)), AuthFailure::ReauthRequired ); - s.reauthenticate(&id, PW, None, T0 + 2).unwrap(); + s.reauthenticate(&id, &tok, PW, None, T0 + 2).unwrap(); let p = s.authenticate_session(&tok, T0 + 3).unwrap(); assert!(p.recent_auth); // Expiry is mandatory, in the future, and at most 365 days. @@ -733,7 +796,7 @@ mod tests { let (_d, s) = svc(); root(&s); let (id, tok) = analyst_session(&s, "ana", T0); - s.reauthenticate(&id, PW, None, T0 + 1).unwrap(); + s.reauthenticate(&id, &tok, PW, None, T0 + 1).unwrap(); let p = s.authenticate_session(&tok, T0 + 2).unwrap(); let t = s .create_api_token(&p, "ci", Scope::Read, T0 + 1000, T0 + 2) @@ -755,7 +818,7 @@ mod tests { let (_d, s) = svc(); root(&s); let (id, tok) = analyst_session(&s, "ana", T0); - s.reauthenticate(&id, PW, None, T0 + 1).unwrap(); + s.reauthenticate(&id, &tok, PW, None, T0 + 1).unwrap(); let p = s.authenticate_session(&tok, T0 + 2).unwrap(); assert_eq!( failure(s.create_api_token(&p, "x", Scope::Admin, T0 + 1000, T0 + 2)), @@ -776,7 +839,7 @@ mod tests { let (_d, s) = svc(); root(&s); let (id, tok) = analyst_session(&s, "ana", T0); - s.reauthenticate(&id, PW, None, T0 + 1).unwrap(); + s.reauthenticate(&id, &tok, PW, None, T0 + 1).unwrap(); let p = s.authenticate_session(&tok, T0 + 2).unwrap(); let t = s .create_api_token(&p, "ci", Scope::Read, T0 + 1000, T0 + 2) @@ -793,7 +856,7 @@ mod tests { let (_d, s) = svc(); root(&s); let (id, tok) = analyst_session(&s, "ana", T0); - s.reauthenticate(&id, PW, None, T0 + 1).unwrap(); + s.reauthenticate(&id, &tok, PW, None, T0 + 1).unwrap(); let p = s.authenticate_session(&tok, T0 + 2).unwrap(); let a = s .create_api_token(&p, "a", Scope::Read, T0 + 1000, T0 + 2) @@ -823,7 +886,7 @@ mod tests { root(&s); let (id, tok) = admin_session(&s, "adm", T0); let t = T0 + 1000; - s.reauthenticate(&id, PW, Some(&code_at(&s, &id, t)), t) + s.reauthenticate(&id, &tok, PW, Some(&code_at(&s, &id, t)), t) .unwrap(); let p = s.authenticate_session(&tok, t).unwrap(); assert_eq!(p.scope, Scope::Admin); @@ -850,7 +913,7 @@ mod tests { root(&s); let (id, tok) = admin_session(&s, "adm", T0); let t = T0 + 1000; - s.reauthenticate(&id, PW, Some(&code_at(&s, &id, t)), t) + s.reauthenticate(&id, &tok, PW, Some(&code_at(&s, &id, t)), t) .unwrap(); let p = s.authenticate_session(&tok, t).unwrap(); let a = s @@ -859,6 +922,10 @@ mod tests { s.set_role("root", &id, Role::Analyst, t + 1).unwrap(); let dp = s.authenticate_token(&a.token, t + 2).unwrap(); assert_eq!((dp.scope, dp.role), (Scope::Read, Role::Analyst)); + // Re-promotion must not revive the admin token. + s.set_role("root", &id, Role::Admin, t + 2).unwrap(); + let rp = s.authenticate_token(&a.token, t + 3).unwrap(); + assert_eq!((rp.scope, rp.role), (Scope::Read, Role::Admin)); s.delete_user("root", &id, t + 3).unwrap(); assert!(s.authenticate_token(&a.token, t + 4).is_err()); assert!(!state_json(&s).contains(&hash_token(&a.token))); @@ -876,7 +943,7 @@ mod tests { }; (id2, n.token) }; - s.reauthenticate(&id, PW, None, T0 + 1).unwrap(); + s.reauthenticate(&id, &tok, PW, None, T0 + 1).unwrap(); let p = s.authenticate_session(&tok, T0 + 2).unwrap(); let t = s .create_api_token(&p, "a", Scope::Read, T0 + 1000, T0 + 2) @@ -888,4 +955,119 @@ mod tests { ); assert!(s.authenticate_token(&t.token, T0 + 4).is_ok()); } + + /// Admin `adm` with a live session and one admin and one read token. + /// Returns (id, session token, admin token, read token, time). + fn admin_with_tokens(s: &AuthService) -> (String, String, NewToken, NewToken, u64) { + let (id, tok) = admin_session(s, "adm", T0); + let t = T0 + 1000; + s.reauthenticate(&id, &tok, PW, Some(&code_at(s, &id, t)), t) + .unwrap(); + let p = s.authenticate_session(&tok, t).unwrap(); + let a = s + .create_api_token(&p, "a", Scope::Admin, t + 5000, t) + .unwrap(); + let r = s + .create_api_token(&p, "r", Scope::Read, t + 5000, t) + .unwrap(); + (id, tok, a, r, t) + } + + #[test] + fn reauthenticating_one_session_leaves_another_not_recent() { + let (_d, s) = svc(); + root(&s); + let (id, tok_a) = analyst_session(&s, "ana", T0); + let LoginStep::Session(b) = s.login("ana", PW, ip(), T0 + 1).unwrap() else { + panic!() + }; + s.reauthenticate(&id, &tok_a, PW, None, T0 + 2).unwrap(); + assert!(s.authenticate_session(&tok_a, T0 + 3).unwrap().recent_auth); + let pb = s.authenticate_session(&b.token, T0 + 3).unwrap(); + assert!(!pb.recent_auth); + assert_eq!( + failure(s.create_api_token(&pb, "x", Scope::Read, T0 + 1000, T0 + 3)), + AuthFailure::ReauthRequired + ); + // A forged claim for session B is checked against B's own record. + let mut forged = pb.clone(); + forged.recent_auth = true; + assert_eq!( + failure(s.create_api_token(&forged, "x", Scope::Read, T0 + 1000, T0 + 3)), + AuthFailure::ReauthRequired + ); + // Another user's session cannot be elevated with this user's password. + assert!(s + .reauthenticate(&id, "not-a-session", PW, None, T0 + 4) + .is_err()); + } + + #[test] + fn password_change_drops_admin_tokens_keeps_read() { + let (_d, s) = svc(); + root(&s); + let (id, _tok, a, r, t) = admin_with_tokens(&s); + s.change_password(&id, PW, "another long enough passphrase", None, t + 1) + .unwrap(); + assert!(s.authenticate_token(&a.token, t + 2).is_err()); + assert!(s.authenticate_token(&r.token, t + 2).is_ok()); + } + + #[test] + fn mfa_change_drops_admin_tokens_keeps_read() { + let (_d, s) = svc(); + root(&s); + let (id, _tok, a, r, t) = admin_with_tokens(&s); + s.start_enrollment(&id, t + 100).unwrap(); + let sealed = s + .store + .read(|st| { + let u = st.users.iter().find(|u| u.id == id).unwrap(); + u.totp_pending_sealed.clone().unwrap() + }) + .unwrap(); + let secret = s.secrets.open_sealed(&sealed).unwrap(); + let code = build_totp(&secret, "x") + .unwrap() + .generate(t + 100) + .to_string(); + s.confirm_enrollment(&id, &code, t + 100).unwrap(); + assert!(s.authenticate_token(&a.token, t + 101).is_err()); + assert!(s.authenticate_token(&r.token, t + 101).is_ok()); + } + + #[test] + fn read_token_cannot_revoke_but_admin_token_can() { + let (_d, s) = svc(); + root(&s); + let (id, _tok, a, r, t) = admin_with_tokens(&s); + let rp = s.authenticate_token(&r.token, t + 1).unwrap(); + assert_eq!( + failure(s.revoke_token(&rp, &a.id, t + 2)), + AuthFailure::NotFound + ); + assert_eq!( + failure(s.revoke_token(&rp, &r.id, t + 2)), + AuthFailure::NotFound + ); + assert!(s.authenticate_token(&r.token, t + 3).is_ok()); + let ap = s.authenticate_token(&a.token, t + 3).unwrap(); + s.revoke_token(&ap, &r.id, t + 4).unwrap(); + assert!(s.list_tokens(&id, t + 5).unwrap().len() == 1); + } + + #[test] + fn failed_revocation_logs_no_caller_supplied_id() { + let (_d, s) = svc(); + root(&s); + let (id, tok) = analyst_session(&s, "ana", T0); + let p = s.authenticate_session(&tok, T0 + 1).unwrap(); + let hostile = "attacker-supplied-id\u{1b}[31m"; + assert!(s.revoke_token(&p, hostile, T0 + 2).is_err()); + assert!(s.revoke_session(&p, hostile, T0 + 2).is_err()); + let raw = std::fs::read_to_string(s.auth_dir.join("audit.jsonl")).unwrap(); + assert!(!raw.contains("attacker-supplied-id")); + assert!(s.audit_tail(2).unwrap().iter().all(|e| !e.event.ok)); + let _ = id; + } }