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
+247 -47

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,
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)?;