fix(auth): per-session reauth and admin token lifecycle

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:40:08 -03:00
1 parent c2d352ae30
commit a90ff81650
3 files changed
+233 -33

No files matched your search

+19 -1
View File
@@ -10,7 +10,7 @@ use super::credentials::{
hash_password, hash_recovery_code, new_recovery_codes, new_totp_secret, normalize, hash_password, hash_recovery_code, new_recovery_codes, new_totp_secret, normalize,
totp_uri_and_qr, validate_password, verify_password, verify_totp, 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::throttle::{lock_until, IpLimiter, UnknownAccounts};
use super::{hash_token, random_token, AuditEntry, AuditEvent, AuditLog, Secrets}; use super::{hash_token, random_token, AuditEntry, AuditEvent, AuditLog, Secrets};
use crate::error::{AcauaError, AuthFailure, Result}; 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())); .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 { fn issue_session(st: &mut AuthState, user_id: &str, now: u64) -> NewSession {
st.sessions.retain(|s| s.expires_at > now); st.sessions.retain(|s| s.expires_at > now);
let token = random_token(SESSION_TOKEN_BYTES); 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, created_at: now,
last_seen: now, last_seen: now,
expires_at, expires_at,
last_reauth: 0,
}); });
NewSession { NewSession {
id, id,
@@ -608,6 +616,7 @@ impl AuthService {
u.totp_last_step = Some(step); u.totp_last_step = Some(step);
u.recovery_hashes = hashes; u.recovery_hashes = hashes;
end_sessions(st, user_id, None); end_sessions(st, user_id, None);
drop_admin_tokens(st, user_id);
Ok((name, true)) Ok((name, true))
})?; })?;
self.log("mfa.enroll.confirm", Some(&name), None, accepted, None)?; self.log("mfa.enroll.confirm", Some(&name), None, accepted, None)?;
@@ -666,9 +675,16 @@ impl AuthService {
let changed = u.role != role; let changed = u.role != role;
let name = u.username.clone(); let name = u.username.clone();
if changed { if changed {
let leaving_admin = u.role == Role::Admin && role != Role::Admin;
u.role = role; u.role = role;
u.auth_epoch = u.auth_epoch.wrapping_add(1); u.auth_epoch = u.auth_epoch.wrapping_add(1);
end_sessions(st, user_id, None); 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) Ok(name)
}); });
@@ -741,6 +757,7 @@ impl AuthService {
u.must_change_password = false; u.must_change_password = false;
u.auth_epoch = u.auth_epoch.wrapping_add(1); u.auth_epoch = u.auth_epoch.wrapping_add(1);
end_sessions(st, user_id, keep_session_token); end_sessions(st, user_id, keep_session_token);
drop_admin_tokens(st, user_id);
Ok(true) Ok(true)
})?; })?;
self.log("password.change", Some(&name), None, changed, None)?; self.log("password.change", Some(&name), None, changed, None)?;
@@ -797,6 +814,7 @@ impl AuthService {
u.totp_last_step = None; u.totp_last_step = None;
u.recovery_hashes.clear(); u.recovery_hashes.clear();
end_sessions(st, user_id, keep_session_token); end_sessions(st, user_id, keep_session_token);
drop_admin_tokens(st, user_id);
Ok(name) Ok(name)
}); });
self.log_admin_result("mfa.disable", actor, &result)?; self.log_admin_result("mfa.disable", actor, &result)?;
+2 -2
View File
@@ -46,8 +46,6 @@ pub struct User {
pub auth_epoch: u64, pub auth_epoch: u64,
/// Set by `reset_admin`: no ordinary session until the password changes. /// Set by `reset_admin`: no ordinary session until the password changes.
pub must_change_password: bool, pub must_change_password: bool,
/// Unix seconds of the last `reauthenticate`; 0 if never.
pub last_reauth: u64,
} }
impl std::fmt::Debug for User { impl std::fmt::Debug for User {
@@ -71,6 +69,8 @@ pub struct Session {
pub created_at: u64, pub created_at: u64,
pub last_seen: u64, pub last_seen: u64,
pub expires_at: 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 { impl std::fmt::Debug for Session {
+212 -30
View File
@@ -40,8 +40,10 @@ pub struct Principal {
pub role: Role, pub role: Role,
pub via: Via, pub via: Via,
pub scope: Scope, 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, pub recent_auth: bool,
/// Id of the session behind a `Via::Session` principal.
pub session_id: Option<String>,
} }
/// A token just created. The secret exists only here. /// 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 { fn is_recent(last_reauth: u64, now: u64) -> bool {
u.last_reauth != 0 && now >= u.last_reauth && now - u.last_reauth <= RECENT_AUTH_SECS 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<String>,
) -> Principal {
Principal { Principal {
user_id: u.id.clone(), user_id: u.id.clone(),
username: u.username.clone(), username: u.username.clone(),
@@ -117,11 +125,16 @@ fn principal(u: &User, via: Via, scope: Scope, recent_auth: bool) -> Principal {
via, via,
scope, scope,
recent_auth, recent_auth,
session_id,
} }
} }
/// An admin may act on anyone's sessions and tokens; others only their own. /// 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 { 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) actor.user_id == owner || (actor.role == Role::Admin && actor.scope == Scope::Admin)
} }
@@ -153,7 +166,13 @@ impl AuthService {
.ok_or_else(invalid)?; .ok_or_else(invalid)?;
let touch = now.saturating_sub(s.last_seen) >= LAST_SEEN_WRITE_SECS; let touch = now.saturating_sub(s.last_seen) >= LAST_SEEN_WRITE_SECS;
Ok(( 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, touch,
)) ))
})??; })??;
@@ -186,7 +205,7 @@ impl AuthService {
Some(&actor.username), Some(&actor.username),
None, None,
removed, removed,
Some(session_id), removed.then_some(session_id),
)?; )?;
if removed { if removed {
Ok(()) Ok(())
@@ -237,16 +256,27 @@ impl AuthService {
} }
/// Proves the password (and the code, when the account has MFA) again, /// Proves the password (and the code, when the account has MFA) again,
/// which opens a 10-minute window for sensitive actions. Throttled like /// which opens a 10-minute window for sensitive actions in the session
/// login; a code is never accepted twice. /// holding `session_token` only. Throttled like login; a code is never
/// accepted twice.
pub fn reauthenticate( pub fn reauthenticate(
&self, &self,
user_id: &str, user_id: &str,
session_token: &str,
password: &str, password: &str,
code: Option<&str>, code: Option<&str>,
now: u64, now: u64,
) -> Result<()> { ) -> Result<()> {
let session_hash = hash_token(session_token);
let (name, hash) = self.store.update(|st| { 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)?; let u = user_or_missing(st, user_id)?;
reserve_attempt(u, now).map_err(throttled)?; reserve_attempt(u, now).map_err(throttled)?;
Ok((u.username.clone(), u.password_hash.clone())) Ok((u.username.clone(), u.password_hash.clone()))
@@ -263,28 +293,49 @@ impl AuthService {
} }
let recovery_hash = code.map(hash_recovery_code); let recovery_hash = code.map(hash_recovery_code);
let ok = self.store.update(|st| { let ok = self.store.update(|st| {
let passed = {
let Some(u) = user_mut(st, user_id).filter(|u| u.password_hash == hash) else { let Some(u) = user_mut(st, user_id).filter(|u| u.password_hash == hash) else {
return Ok(false); return Ok(false);
}; };
refund_attempt(u); refund_attempt(u);
if let Some(sealed) = u.totp_sealed.clone() { match u.totp_sealed.clone() {
None => true,
Some(sealed) => {
let secret = self.secrets.open_sealed(&sealed)?; let secret = self.secrets.open_sealed(&sealed)?;
let step = code.and_then(|c| verify_totp(&secret, c, now, u.totp_last_step)); let step =
code.and_then(|c| verify_totp(&secret, c, now, u.totp_last_step));
if let Some(step) = step { if let Some(step) = step {
u.totp_last_step = Some(step); u.totp_last_step = Some(step);
true
} else if let Some(i) = recovery_hash } else if let Some(i) = recovery_hash
.as_ref() .as_ref()
.and_then(|h| u.recovery_hashes.iter().position(|x| x == h)) .and_then(|h| u.recovery_hashes.iter().position(|x| x == h))
{ {
u.recovery_hashes.remove(i); u.recovery_hashes.remove(i);
true
} else { } else {
// Persisted: a wrong or missing code counts as a failure. // Persisted: a wrong or missing code is a failure.
count_failure(u, now); count_failure(u, now);
false
}
}
}
};
if !passed {
return Ok(false); return Ok(false);
} }
} // The session may have ended while Argon2 ran.
u.last_reauth = now; 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) Ok(true)
}
None => Ok(false),
}
})?; })?;
self.log( self.log(
"reauth", "reauth",
@@ -344,6 +395,9 @@ impl AuthService {
expires_at: u64, expires_at: u64,
now: u64, now: u64,
) -> Result<NewToken> { ) -> Result<NewToken> {
let Some(session_id) = principal.session_id.as_deref() else {
return Err(AuthFailure::ReauthRequired.into());
};
if principal.via != Via::Session || !principal.recent_auth { if principal.via != Via::Session || !principal.recent_auth {
return Err(AuthFailure::ReauthRequired.into()); return Err(AuthFailure::ReauthRequired.into());
} }
@@ -361,7 +415,13 @@ impl AuthService {
.iter() .iter()
.find(|u| u.id == principal.user_id && !u.must_change_password) .find(|u| u.id == principal.user_id && !u.must_change_password)
.ok_or_else(invalid)?; .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()); return Err(AuthFailure::ReauthRequired.into());
} }
if scope > role_scope(u.role) { if scope > role_scope(u.role) {
@@ -420,6 +480,7 @@ impl AuthService {
Via::Token, Via::Token,
t.scope.min(role_scope(u.role)), t.scope.min(role_scope(u.role)),
false, false,
None,
)) ))
})? })?
} }
@@ -457,7 +518,7 @@ impl AuthService {
Some(&actor.username), Some(&actor.username),
None, None,
removed, removed,
Some(token_id), removed.then_some(token_id),
)?; )?;
if removed { if removed {
Ok(()) Ok(())
@@ -648,7 +709,7 @@ mod tests {
root(&s); root(&s);
let (id, tok) = analyst_session(&s, "ana", T0); let (id, tok) = analyst_session(&s, "ana", T0);
assert!(!s.authenticate_session(&tok, T0 + 1).unwrap().recent_auth); 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 + 610).unwrap().recent_auth);
assert!(!s.authenticate_session(&tok, T0 + 611).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() { fn reauthenticate_uses_password_throttle_and_requires_code_with_mfa() {
let (_d, s) = svc(); let (_d, s) = svc();
root(&s); root(&s);
let (id, _) = analyst_session(&s, "ana", T0); let (id, tok) = analyst_session(&s, "ana", T0);
for i in 0..20 { 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 { .. }))) { if matches!(r, Err(AcauaError::Auth(AuthFailure::Throttled { .. }))) {
return assert!(i >= 3, "throttled too early"); return assert!(i >= 3, "throttled too early");
} }
@@ -672,15 +733,17 @@ mod tests {
let (_d, s) = svc(); let (_d, s) = svc();
root(&s); root(&s);
let (id, tok) = admin_session(&s, "adm", T0); let (id, tok) = admin_session(&s, "adm", T0);
assert!(s.reauthenticate(&id, PW, None, T0 + 100).is_err()); assert!(s.reauthenticate(&id, &tok, PW, None, T0 + 100).is_err());
assert!(s.reauthenticate(&id, PW, Some("000000"), T0 + 200).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. // Within the idle window, past any throttle; use a fresh TOTP step.
let t = T0 + 1000; let t = T0 + 1000;
let code = code_at(&s, &id, t); 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); assert!(s.authenticate_session(&tok, t).unwrap().recent_auth);
// The same code is not accepted twice. // 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] #[test]
@@ -694,7 +757,7 @@ mod tests {
failure(s.create_api_token(&p, "ci", Scope::Read, exp, T0 + 1)), failure(s.create_api_token(&p, "ci", Scope::Read, exp, T0 + 1)),
AuthFailure::ReauthRequired 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(); let p = s.authenticate_session(&tok, T0 + 3).unwrap();
assert!(p.recent_auth); assert!(p.recent_auth);
// Expiry is mandatory, in the future, and at most 365 days. // Expiry is mandatory, in the future, and at most 365 days.
@@ -733,7 +796,7 @@ mod tests {
let (_d, s) = svc(); let (_d, s) = svc();
root(&s); root(&s);
let (id, tok) = analyst_session(&s, "ana", T0); 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 p = s.authenticate_session(&tok, T0 + 2).unwrap();
let t = s let t = s
.create_api_token(&p, "ci", Scope::Read, T0 + 1000, T0 + 2) .create_api_token(&p, "ci", Scope::Read, T0 + 1000, T0 + 2)
@@ -755,7 +818,7 @@ mod tests {
let (_d, s) = svc(); let (_d, s) = svc();
root(&s); root(&s);
let (id, tok) = analyst_session(&s, "ana", T0); 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 p = s.authenticate_session(&tok, T0 + 2).unwrap();
assert_eq!( assert_eq!(
failure(s.create_api_token(&p, "x", Scope::Admin, T0 + 1000, T0 + 2)), failure(s.create_api_token(&p, "x", Scope::Admin, T0 + 1000, T0 + 2)),
@@ -776,7 +839,7 @@ mod tests {
let (_d, s) = svc(); let (_d, s) = svc();
root(&s); root(&s);
let (id, tok) = analyst_session(&s, "ana", T0); 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 p = s.authenticate_session(&tok, T0 + 2).unwrap();
let t = s let t = s
.create_api_token(&p, "ci", Scope::Read, T0 + 1000, T0 + 2) .create_api_token(&p, "ci", Scope::Read, T0 + 1000, T0 + 2)
@@ -793,7 +856,7 @@ mod tests {
let (_d, s) = svc(); let (_d, s) = svc();
root(&s); root(&s);
let (id, tok) = analyst_session(&s, "ana", T0); 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 p = s.authenticate_session(&tok, T0 + 2).unwrap();
let a = s let a = s
.create_api_token(&p, "a", Scope::Read, T0 + 1000, T0 + 2) .create_api_token(&p, "a", Scope::Read, T0 + 1000, T0 + 2)
@@ -823,7 +886,7 @@ mod tests {
root(&s); root(&s);
let (id, tok) = admin_session(&s, "adm", T0); let (id, tok) = admin_session(&s, "adm", T0);
let t = T0 + 1000; 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(); .unwrap();
let p = s.authenticate_session(&tok, t).unwrap(); let p = s.authenticate_session(&tok, t).unwrap();
assert_eq!(p.scope, Scope::Admin); assert_eq!(p.scope, Scope::Admin);
@@ -850,7 +913,7 @@ mod tests {
root(&s); root(&s);
let (id, tok) = admin_session(&s, "adm", T0); let (id, tok) = admin_session(&s, "adm", T0);
let t = T0 + 1000; 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(); .unwrap();
let p = s.authenticate_session(&tok, t).unwrap(); let p = s.authenticate_session(&tok, t).unwrap();
let a = s let a = s
@@ -859,6 +922,10 @@ mod tests {
s.set_role("root", &id, Role::Analyst, t + 1).unwrap(); s.set_role("root", &id, Role::Analyst, t + 1).unwrap();
let dp = s.authenticate_token(&a.token, t + 2).unwrap(); let dp = s.authenticate_token(&a.token, t + 2).unwrap();
assert_eq!((dp.scope, dp.role), (Scope::Read, Role::Analyst)); 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(); s.delete_user("root", &id, t + 3).unwrap();
assert!(s.authenticate_token(&a.token, t + 4).is_err()); assert!(s.authenticate_token(&a.token, t + 4).is_err());
assert!(!state_json(&s).contains(&hash_token(&a.token))); assert!(!state_json(&s).contains(&hash_token(&a.token)));
@@ -876,7 +943,7 @@ mod tests {
}; };
(id2, n.token) (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 p = s.authenticate_session(&tok, T0 + 2).unwrap();
let t = s let t = s
.create_api_token(&p, "a", Scope::Read, T0 + 1000, T0 + 2) .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()); 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;
}
} }