Files
acaua/crates/acaua-core/src/auth/tokens.rs
T
Lucas RayanandClaude Opus 5.5 5ad89d5be5 fix(auth): throttle bootstrap and require reauth for user changes
Bootstrap takes the client IP, is limited per IP, and writes no audit line
once an admin exists. Creating, changing the role of or deleting a user now
needs a session with recent reauthentication; API tokens are refused.
/api/analyze and /api/update return fixed messages and log the detail.

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

1085 lines
38 KiB
Rust

//! Sessions and scoped API tokens. Only SHA-256 digests are stored; a digest
//! is compared in constant time. Role and scope are recomputed from the
//! current user on every authentication, so a demotion takes effect at once.
//!
//! As in `service`, never touch the audit log or call `store.read` inside an
//! `update` closure: audit after the update returns.
use super::credentials::{hash_recovery_code, verify_password, verify_totp};
use super::service::{
count_failure, invalid, refund_attempt, reserve_attempt, throttled, user_mut, user_or_missing,
AuthService,
};
use super::store::{ApiToken, AuthState, Role, Scope, User};
use super::{hash_token, random_token};
use crate::error::{AcauaError, AuthFailure, Result};
use serde::Serialize;
use subtle::ConstantTimeEq;
pub const SESSION_IDLE_SECS: u64 = 1800;
pub const RECENT_AUTH_SECS: u64 = 600;
pub const MAX_TOKEN_LIFETIME_SECS: u64 = 365 * 86_400;
const LAST_SEEN_WRITE_SECS: u64 = 60;
const TOKEN_PREFIX: &str = "acaua_";
const TOKEN_BYTES: usize = 32; // 256 bits
const TOKEN_NAME_MAX_CHARS: usize = 64;
const MAX_TOKENS_PER_USER: usize = 100;
const ID_BYTES: usize = 16;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Via {
Session,
Token,
}
/// Who is acting, as recomputed from the stored user at authentication time.
#[derive(Debug, Clone)]
pub struct Principal {
pub user_id: String,
pub username: String,
pub role: Role,
pub via: Via,
pub scope: Scope,
/// 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<String>,
}
/// A token just created. The secret exists only here.
pub struct NewToken {
pub id: String,
pub name: String,
pub token: String,
pub scope: Scope,
pub expires_at: u64,
}
impl std::fmt::Debug for NewToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("NewToken")
.field("id", &self.id)
.field("name", &self.name)
.field("scope", &self.scope)
.field("expires_at", &self.expires_at)
.finish_non_exhaustive()
}
}
/// Listing view: no hash, no secret.
#[derive(Debug, Clone, Serialize)]
pub struct SessionView {
pub id: String,
pub created_at: u64,
pub last_seen: u64,
pub expires_at: u64,
}
/// Listing view: no hash, no secret.
#[derive(Debug, Clone, Serialize)]
pub struct TokenView {
pub id: String,
pub name: String,
pub scope: Scope,
pub created_at: u64,
pub expires_at: u64,
}
/// The anti-CSRF value of a session. Derived from the session token with a
/// domain prefix, so it needs no storage, dies with the session, and differs
/// from the digest kept in the store.
pub fn csrf_token(session_token: &str) -> String {
hash_token(&format!("acaua-csrf:{session_token}"))
}
pub fn csrf_matches(session_token: &str, candidate: &str) -> bool {
ct_eq(&csrf_token(session_token), candidate)
}
fn ct_eq(a: &str, b: &str) -> bool {
a.as_bytes().ct_eq(b.as_bytes()).into()
}
/// Scans every entry (no early exit) so timing does not reveal a match.
fn find_hash<'a, T>(items: &'a [T], hash: &str, of: impl Fn(&T) -> &str) -> Option<&'a T> {
let mut found = None;
for item in items {
if ct_eq(of(item), hash) {
found = Some(item);
}
}
found
}
fn role_scope(role: Role) -> Scope {
match role {
Role::Admin => Scope::Admin,
Role::Analyst => Scope::Read,
}
}
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,
session_id: Option<String>,
) -> Principal {
Principal {
user_id: u.id.clone(),
username: u.username.clone(),
role: u.role,
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)
}
fn validate_token_name(name: &str) -> Result<()> {
let n = name.chars().count();
if n == 0 || n > TOKEN_NAME_MAX_CHARS || name.chars().any(char::is_control) {
return Err(AcauaError::InvalidInput(format!(
"token name must have 1 to {TOKEN_NAME_MAX_CHARS} characters, without control characters"
)));
}
Ok(())
}
impl AuthService {
/// Validates a session token. `last_seen` is written at most every 60 s,
/// so the effective idle limit is between 1740 and 1800 s.
pub fn authenticate_session(&self, token: &str, now: u64) -> Result<Principal> {
let hash = hash_token(token);
let (principal, touch) = self.store.read(|st| {
let s = find_hash(&st.sessions, &hash, |s| &s.token_hash).ok_or_else(invalid)?;
if now > s.expires_at || now.saturating_sub(s.last_seen) > SESSION_IDLE_SECS {
return Err(invalid());
}
let u = st
.users
.iter()
.find(|u| u.id == s.user_id)
.filter(|u| !u.must_change_password)
.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(s.last_reauth, now),
Some(s.id.clone()),
),
touch,
))
})??;
if touch {
self.store.update(|st| {
if let Some(s) = st.sessions.iter_mut().find(|s| ct_eq(&s.token_hash, &hash)) {
s.last_seen = s.last_seen.max(now);
}
Ok(())
})?;
}
Ok(principal)
}
/// Ends one session by its id (not its token). Refused as `NotFound` when
/// the session belongs to someone the actor may not manage.
pub fn revoke_session(&self, actor: &Principal, session_id: &str, _now: u64) -> Result<()> {
let removed = self.store.update(|st| {
let Some(i) = st.sessions.iter().position(|s| s.id == session_id) else {
return Ok(false);
};
if !may_manage(actor, &st.sessions[i].user_id) {
return Ok(false);
}
st.sessions.remove(i);
Ok(true)
})?;
self.log(
"session.revoke",
Some(&actor.username),
None,
removed,
removed.then_some(session_id),
)?;
if removed {
Ok(())
} else {
Err(AuthFailure::NotFound.into())
}
}
/// Ends the session holding `token`.
pub fn logout(&self, token: &str, _now: u64) -> Result<()> {
let hash = hash_token(token);
let name = self.store.update(|st| {
let Some(s) = find_hash(&st.sessions, &hash, |s| &s.token_hash) else {
return Ok(None);
};
let user = s.user_id.clone();
st.sessions.retain(|s| !ct_eq(&s.token_hash, &hash));
Ok(st
.users
.iter()
.find(|u| u.id == user)
.map(|u| u.username.clone()))
})?;
match name {
Some(n) => self.log("logout", Some(&n), None, true, None),
None => Ok(()),
}
}
/// Live sessions of one user.
pub fn list_sessions(&self, user_id: &str, now: u64) -> Result<Vec<SessionView>> {
self.store.read(|st| {
st.sessions
.iter()
.filter(|s| {
s.user_id == user_id
&& now <= s.expires_at
&& now.saturating_sub(s.last_seen) <= SESSION_IDLE_SECS
})
.map(|s| SessionView {
id: s.id.clone(),
created_at: s.created_at,
last_seen: s.last_seen,
expires_at: s.expires_at,
})
.collect()
})
}
/// Proves the password (and the code, when the account has MFA) again,
/// 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()))
})?;
if !verify_password(Some(&hash), password) {
self.log(
"reauth",
Some(&name),
None,
false,
Some("invalid credentials"),
)?;
return Err(invalid());
}
let recovery_hash = code.map(hash_recovery_code);
let ok = self.store.update(|st| {
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),
}
})?;
self.log(
"reauth",
Some(&name),
None,
ok,
if ok {
None
} else {
Some("invalid credentials")
},
)?;
if ok {
Ok(())
} else {
Err(invalid())
}
}
/// Creates a token for the principal's own account. Needs a session (a
/// token cannot mint tokens), a reauthentication in the last 10 minutes,
/// and an expiry within 365 days; the scope may not exceed the role.
pub fn create_api_token(
&self,
principal: &Principal,
name: &str,
scope: Scope,
expires_at: u64,
now: u64,
) -> Result<NewToken> {
let result = self.create_token_inner(principal, name, scope, expires_at, now);
match &result {
Ok(t) => self.log(
"token.create",
Some(&principal.username),
None,
true,
Some(&format!("id {} scope {:?}", t.id, t.scope)),
)?,
Err(AcauaError::Auth(f)) => self.log(
"token.create",
Some(&principal.username),
None,
false,
Some(&f.to_string()),
)?,
Err(_) => {}
}
result
}
fn create_token_inner(
&self,
principal: &Principal,
name: &str,
scope: Scope,
expires_at: u64,
now: u64,
) -> 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 {
return Err(AuthFailure::ReauthRequired.into());
}
validate_token_name(name)?;
if expires_at <= now || expires_at - now > MAX_TOKEN_LIFETIME_SECS {
return Err(AcauaError::InvalidInput(
"token expiry must be in the future and within 365 days".to_string(),
));
}
let token = format!("{TOKEN_PREFIX}{}", random_token(TOKEN_BYTES));
let id = random_token(ID_BYTES);
self.store.update(|st| {
let u = st
.users
.iter()
.find(|u| u.id == principal.user_id && !u.must_change_password)
.ok_or_else(invalid)?;
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) {
return Err(AuthFailure::Forbidden.into());
}
prune_tokens(st, now);
if st
.tokens
.iter()
.filter(|t| t.user_id == principal.user_id)
.count()
>= MAX_TOKENS_PER_USER
{
return Err(AcauaError::InvalidInput("too many API tokens".to_string()));
}
st.tokens.push(ApiToken {
id: id.clone(),
user_id: principal.user_id.clone(),
name: name.to_string(),
token_hash: hash_token(&token),
scope,
created_at: now,
expires_at,
});
Ok(())
})?;
Ok(NewToken {
id,
name: name.to_string(),
token,
scope,
expires_at,
})
}
/// Validates an API token. The effective scope is the lesser of the
/// token's scope and what the user's current role allows.
pub fn authenticate_token(&self, token: &str, now: u64) -> Result<Principal> {
if !token.starts_with(TOKEN_PREFIX) {
return Err(invalid());
}
let hash = hash_token(token);
self.store.read(|st| {
let t = find_hash(&st.tokens, &hash, |t| &t.token_hash).ok_or_else(invalid)?;
if now > t.expires_at {
return Err(invalid());
}
let u = st
.users
.iter()
.find(|u| u.id == t.user_id)
.filter(|u| !u.must_change_password)
.ok_or_else(invalid)?;
Ok(principal(
u,
Via::Token,
t.scope.min(role_scope(u.role)),
false,
None,
))
})?
}
/// Unexpired tokens of one user.
pub fn list_tokens(&self, user_id: &str, now: u64) -> Result<Vec<TokenView>> {
self.store.read(|st| {
st.tokens
.iter()
.filter(|t| t.user_id == user_id && now <= t.expires_at)
.map(|t| TokenView {
id: t.id.clone(),
name: t.name.clone(),
scope: t.scope,
created_at: t.created_at,
expires_at: t.expires_at,
})
.collect()
})
}
pub fn revoke_token(&self, actor: &Principal, token_id: &str, _now: u64) -> Result<()> {
let removed = self.store.update(|st| {
let Some(i) = st.tokens.iter().position(|t| t.id == token_id) else {
return Ok(false);
};
if !may_manage(actor, &st.tokens[i].user_id) {
return Ok(false);
}
st.tokens.remove(i);
Ok(true)
})?;
self.log(
"token.revoke",
Some(&actor.username),
None,
removed,
removed.then_some(token_id),
)?;
if removed {
Ok(())
} else {
Err(AuthFailure::NotFound.into())
}
}
}
fn prune_tokens(st: &mut AuthState, now: u64) {
st.tokens.retain(|t| t.expires_at >= now);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::auth::credentials::build_totp;
use crate::auth::service::LoginStep;
use std::net::IpAddr;
const T0: u64 = 1_800_000_000;
const PW: &str = "correct horse battery staple";
fn ip() -> IpAddr {
"192.0.2.1".parse().unwrap()
}
fn svc() -> (tempfile::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 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()
}
fn enroll(s: &AuthService, id: &str, now: u64) {
s.start_enrollment(id, now).unwrap();
let code = code_at(s, id, now);
s.confirm_enrollment(id, &code, now).unwrap();
}
/// Bootstraps `root` (admin, MFA enrolled).
fn root(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
}
/// Analyst without MFA, logged in at `now`.
fn analyst_session(s: &AuthService, name: &str, now: u64) -> (String, String) {
let id = s.create_user("root", name, PW, Role::Analyst, T0).unwrap();
match s.login(name, PW, ip(), now).unwrap() {
LoginStep::Session(n) => (id, n.token),
other => panic!("unexpected {other:?}"),
}
}
/// Second admin with MFA, logged in at `now`; returns (id, session token).
fn admin_session(s: &AuthService, name: &str, now: u64) -> (String, String) {
let id = s.create_user("root", name, PW, Role::Admin, T0).unwrap();
enroll(s, &id, T0);
let LoginStep::MfaRequired(p) = s.login(name, PW, ip(), now).unwrap() else {
panic!("mfa expected");
};
let code = code_at(s, &id, now + 60);
match s.confirm_mfa(&p.token, &code, now + 60).unwrap() {
LoginStep::Session(n) => (id, n.token),
other => panic!("unexpected {other:?}"),
}
}
fn state_json(s: &AuthService) -> String {
std::fs::read_to_string(s.auth_dir.join("state.json")).unwrap()
}
#[test]
fn session_idle_and_absolute_expiry() {
let (_d, s) = svc();
root(&s);
let (_, tok) = analyst_session(&s, "ana", T0);
assert!(s.authenticate_session(&tok, T0 + 1800).is_ok());
let (_, idle) = analyst_session(&s, "bob", T0);
assert!(s.authenticate_session(&idle, T0 + 1801).is_err());
// Constant use keeps it alive until the absolute limit.
let mut t = T0;
while t + 1000 <= T0 + 43_200 {
t += 1000;
s.authenticate_session(&tok, t).unwrap();
}
s.authenticate_session(&tok, T0 + 43_200).unwrap();
assert!(s.authenticate_session(&tok, T0 + 43_201).is_err());
}
#[test]
fn last_seen_written_at_most_every_60_seconds() {
let (_d, s) = svc();
root(&s);
let (_, tok) = analyst_session(&s, "ana", T0);
let seen = |s: &AuthService| s.store.read(|st| st.sessions[0].last_seen).unwrap();
s.authenticate_session(&tok, T0 + 59).unwrap();
assert_eq!(seen(&s), T0);
s.authenticate_session(&tok, T0 + 60).unwrap();
assert_eq!(seen(&s), T0 + 60);
}
#[test]
fn session_token_not_stored_in_clear() {
let (_d, s) = svc();
root(&s);
let (_, tok) = analyst_session(&s, "ana", T0);
assert!(tok.len() >= 43, "256 bits");
assert!(!state_json(&s).contains(&tok));
assert!(state_json(&s).contains(&hash_token(&tok)));
let dbg = s.store.read(|st| format!("{:?}", st.sessions)).unwrap();
assert!(!dbg.contains(&tok) && !dbg.contains(&hash_token(&tok)));
}
#[test]
fn logout_and_revoke_end_the_session() {
let (_d, s) = svc();
root(&s);
let (_, tok) = analyst_session(&s, "ana", T0);
s.logout(&tok, T0 + 1).unwrap();
assert!(s.authenticate_session(&tok, T0 + 2).is_err());
let LoginStep::Session(n) = s.login("ana", PW, ip(), T0 + 3).unwrap() else {
panic!()
};
let p = s.authenticate_session(&n.token, T0 + 4).unwrap();
s.revoke_session(&p, &n.id, T0 + 5).unwrap();
assert!(s.authenticate_session(&n.token, T0 + 6).is_err());
assert_eq!(
failure(s.revoke_session(&p, &n.id, T0 + 7)),
AuthFailure::NotFound
);
}
#[test]
fn session_listing_has_no_hashes_and_is_per_user() {
let (_d, s) = svc();
root(&s);
let (a, tok) = analyst_session(&s, "ana", T0);
analyst_session(&s, "bob", T0);
let list = s.list_sessions(&a, T0 + 1).unwrap();
assert_eq!(list.len(), 1);
let json = serde_json::to_string(&list).unwrap();
assert!(!json.contains(&hash_token(&tok)) && !json.contains(&tok));
assert!(!json.contains("hash"));
}
#[test]
fn reauthenticate_sets_recent_auth_for_ten_minutes() {
let (_d, s) = svc();
root(&s);
let (id, tok) = analyst_session(&s, "ana", T0);
assert!(!s.authenticate_session(&tok, T0 + 1).unwrap().recent_auth);
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);
}
#[test]
fn reauthenticate_uses_password_throttle_and_requires_code_with_mfa() {
let (_d, s) = svc();
root(&s);
let (id, tok) = analyst_session(&s, "ana", T0);
for i in 0..20 {
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");
}
}
panic!("never throttled");
}
#[test]
fn reauthenticate_with_mfa_needs_a_valid_code() {
let (_d, s) = svc();
root(&s);
let (id, tok) = admin_session(&s, "adm", T0);
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, &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, &tok, PW, Some(&code), t + 1).is_err());
}
#[test]
fn token_requires_recent_auth_and_expiry() {
let (_d, s) = svc();
root(&s);
let (id, tok) = analyst_session(&s, "ana", T0);
let p = s.authenticate_session(&tok, T0 + 1).unwrap();
let exp = T0 + 86_400;
assert_eq!(
failure(s.create_api_token(&p, "ci", Scope::Read, exp, T0 + 1)),
AuthFailure::ReauthRequired
);
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.
assert!(s
.create_api_token(&p, "ci", Scope::Read, 0, T0 + 3)
.is_err());
assert!(s
.create_api_token(&p, "ci", Scope::Read, T0 + 3, T0 + 3)
.is_err());
let max = T0 + 3 + 365 * 86_400;
assert!(s
.create_api_token(&p, "ci", Scope::Read, max + 1, T0 + 3)
.is_err());
let ok = s
.create_api_token(&p, "ci", Scope::Read, max, T0 + 3)
.unwrap();
assert!(ok.token.starts_with("acaua_"));
assert!(ok.token.len() >= "acaua_".len() + 43);
// After 600 s the same principal is no longer recent.
let stale = s.authenticate_session(&tok, T0 + 700).unwrap();
assert_eq!(
failure(s.create_api_token(&stale, "ci2", Scope::Read, exp, T0 + 700)),
AuthFailure::ReauthRequired
);
// A stale `recent_auth: true` claim is checked against the store.
let mut forged = stale.clone();
forged.recent_auth = true;
assert_eq!(
failure(s.create_api_token(&forged, "ci2", Scope::Read, exp, T0 + 700)),
AuthFailure::ReauthRequired
);
}
#[test]
fn token_not_stored_in_clear_and_listing_has_no_hashes() {
let (_d, s) = svc();
root(&s);
let (id, tok) = analyst_session(&s, "ana", T0);
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)
.unwrap();
assert!(!state_json(&s).contains(&t.token));
assert!(state_json(&s).contains(&hash_token(&t.token)));
assert!(!format!("{t:?}").contains(&t.token));
let list = s.list_tokens(&id, T0 + 3).unwrap();
assert_eq!(list.len(), 1);
let json = serde_json::to_string(&list).unwrap();
assert!(!json.contains(&t.token) && !json.contains(&hash_token(&t.token)));
assert!(!json.contains("hash"));
let dbg = s.store.read(|st| format!("{:?}", st.tokens)).unwrap();
assert!(!dbg.contains(&hash_token(&t.token)));
}
#[test]
fn analyst_cannot_create_admin_token() {
let (_d, s) = svc();
root(&s);
let (id, tok) = analyst_session(&s, "ana", T0);
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)),
AuthFailure::Forbidden
);
// Not fooled by a principal that claims more than the stored role.
let mut forged = p.clone();
forged.role = Role::Admin;
forged.scope = Scope::Admin;
assert_eq!(
failure(s.create_api_token(&forged, "x", Scope::Admin, T0 + 1000, T0 + 2)),
AuthFailure::Forbidden
);
}
#[test]
fn token_cannot_mint_tokens() {
let (_d, s) = svc();
root(&s);
let (id, tok) = analyst_session(&s, "ana", T0);
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)
.unwrap();
let tp = s.authenticate_token(&t.token, T0 + 3).unwrap();
assert!(!tp.recent_auth);
assert!(s
.create_api_token(&tp, "n", Scope::Read, T0 + 1000, T0 + 3)
.is_err());
}
#[test]
fn revoked_expired_token_rejected() {
let (_d, s) = svc();
root(&s);
let (id, tok) = analyst_session(&s, "ana", T0);
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)
.unwrap();
let b = s
.create_api_token(&p, "b", Scope::Read, T0 + 5000, T0 + 2)
.unwrap();
assert!(s.authenticate_token(&a.token, T0 + 1000).is_ok());
assert!(s.authenticate_token(&a.token, T0 + 1001).is_err());
assert!(s.authenticate_token("acaua_nope", T0 + 5).is_err());
assert!(
s.authenticate_token(&tok, T0 + 5).is_err(),
"session token is no API token"
);
s.revoke_token(&p, &b.id, T0 + 10).unwrap();
assert!(s.authenticate_token(&b.token, T0 + 11).is_err());
assert!(s
.list_tokens(&id, T0 + 11)
.unwrap()
.iter()
.all(|t| t.id != b.id));
}
#[test]
fn read_token_scope_is_read() {
let (_d, s) = svc();
root(&s);
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();
assert_eq!(p.scope, Scope::Admin);
let r = s
.create_api_token(&p, "r", Scope::Read, t + 1000, t)
.unwrap();
let a = s
.create_api_token(&p, "a", Scope::Admin, t + 1000, t)
.unwrap();
let rp = s.authenticate_token(&r.token, t + 1).unwrap();
assert_eq!(
(rp.scope, rp.role, rp.via),
(Scope::Read, Role::Admin, Via::Token)
);
assert_eq!(
s.authenticate_token(&a.token, t + 1).unwrap().scope,
Scope::Admin
);
}
#[test]
fn demotion_or_deletion_invalidates_tokens() {
let (_d, s) = svc();
root(&s);
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 + 1000, t)
.unwrap();
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)));
}
#[test]
fn revoking_someone_elses_token_is_refused() {
let (_d, s) = svc();
root(&s);
let (id, tok) = analyst_session(&s, "ana", T0);
let (_, tok2) = {
let id2 = s.create_user("root", "bob", PW, Role::Analyst, T0).unwrap();
let LoginStep::Session(n) = s.login("bob", PW, ip(), T0).unwrap() else {
panic!()
};
(id2, n.token)
};
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)
.unwrap();
let other = s.authenticate_session(&tok2, T0 + 2).unwrap();
assert_eq!(
failure(s.revoke_token(&other, &t.id, T0 + 3)),
AuthFailure::NotFound
);
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;
}
}