From c2d352ae302559dd4940f51c79bd67cd9b8528b5 Mon Sep 17 00:00:00 2001 From: Lucas Rayan Date: Wed, 4 Nov 2026 19:34:37 -0300 Subject: [PATCH] feat(auth): sessions and scoped API tokens Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/acaua-core/Cargo.toml | 1 + crates/acaua-core/src/auth/mod.rs | 4 +- crates/acaua-core/src/auth/service.rs | 22 +- crates/acaua-core/src/auth/store.rs | 19 +- crates/acaua-core/src/auth/tokens.rs | 891 ++++++++++++++++++++++++++ crates/acaua-core/src/error.rs | 6 + 7 files changed, 931 insertions(+), 13 deletions(-) create mode 100644 crates/acaua-core/src/auth/tokens.rs diff --git a/Cargo.lock b/Cargo.lock index eb90507..c3d5f51 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -32,6 +32,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.10.9", + "subtle", "tempfile", "thiserror", "time", diff --git a/crates/acaua-core/Cargo.toml b/crates/acaua-core/Cargo.toml index 3f12029..846d519 100644 --- a/crates/acaua-core/Cargo.toml +++ b/crates/acaua-core/Cargo.toml @@ -25,6 +25,7 @@ fs2 = "0.4" argon2 = "0.6.0" totp-rs = { version = "6.0.0", features = ["qr", "otpauth"] } unicode-normalization = "0.1" +subtle = "2" [dev-dependencies] tempfile = "3" diff --git a/crates/acaua-core/src/auth/mod.rs b/crates/acaua-core/src/auth/mod.rs index 6e5a8be..927ee12 100644 --- a/crates/acaua-core/src/auth/mod.rs +++ b/crates/acaua-core/src/auth/mod.rs @@ -8,11 +8,13 @@ pub mod secrets; pub mod service; pub mod store; pub mod throttle; +pub mod tokens; pub use audit::{AuditEntry, AuditEvent, AuditLog}; pub use secrets::{hash_token, random_token, Secrets}; pub use service::{AuthService, LoginStep, NewSession, PendingMfa, TotpEnrollment}; -pub use store::{ApiToken, AuthState, AuthStore, Bootstrap, Role, Session, User}; +pub use store::{ApiToken, AuthState, AuthStore, Bootstrap, Role, Scope, Session, User}; +pub use tokens::{NewToken, Principal, SessionView, TokenView, Via}; use crate::error::Result; use fs2::FileExt; diff --git a/crates/acaua-core/src/auth/service.rs b/crates/acaua-core/src/auth/service.rs index 3ec0567..acca880 100644 --- a/crates/acaua-core/src/auth/service.rs +++ b/crates/acaua-core/src/auth/service.rs @@ -98,18 +98,18 @@ struct PendingClaims { pub struct AuthService { pub(super) store: AuthStore, pub(super) secrets: Secrets, - audit: AuditLog, + pub(super) audit: AuditLog, pub(super) ips: IpLimiter, unknown: UnknownAccounts, #[cfg_attr(not(test), allow(dead_code))] pub(super) auth_dir: PathBuf, } -fn throttled(retry_after_secs: u64) -> AcauaError { +pub(super) fn throttled(retry_after_secs: u64) -> AcauaError { AuthFailure::Throttled { retry_after_secs }.into() } -fn invalid() -> AcauaError { +pub(super) fn invalid() -> AcauaError { AuthFailure::InvalidCredentials.into() } @@ -145,20 +145,20 @@ fn has_admin(st: &AuthState) -> bool { st.users.iter().any(|u| u.role == Role::Admin) } -fn user_mut<'a>(st: &'a mut AuthState, id: &str) -> Option<&'a mut User> { +pub(super) fn user_mut<'a>(st: &'a mut AuthState, id: &str) -> Option<&'a mut User> { st.users.iter_mut().find(|u| u.id == id) } -fn user_or_missing<'a>(st: &'a mut AuthState, id: &str) -> Result<&'a mut User> { +pub(super) fn user_or_missing<'a>(st: &'a mut AuthState, id: &str) -> Result<&'a mut User> { user_mut(st, id).ok_or_else(|| AuthFailure::UserNotFound.into()) } -fn count_failure(u: &mut User, now: u64) { +pub(super) fn count_failure(u: &mut User, now: u64) { u.failed_attempts = u.failed_attempts.saturating_add(1); u.locked_until = lock_until(u.failed_attempts, now); } -fn check_lock(u: &User, now: u64) -> std::result::Result<(), u64> { +pub(super) fn check_lock(u: &User, now: u64) -> std::result::Result<(), u64> { if u.locked_until > now { Err(u.locked_until - now) } else { @@ -168,7 +168,7 @@ fn check_lock(u: &User, now: u64) -> std::result::Result<(), u64> { /// Counts the attempt as failed before Argon2 runs, so parallel guesses /// cannot all pass the check. `refund_attempt` undoes it on a right password. -fn reserve_attempt(u: &mut User, now: u64) -> std::result::Result<(), u64> { +pub(super) fn reserve_attempt(u: &mut User, now: u64) -> std::result::Result<(), u64> { check_lock(u, now)?; count_failure(u, now); Ok(()) @@ -176,7 +176,7 @@ fn reserve_attempt(u: &mut User, now: u64) -> std::result::Result<(), u64> { /// The password was right: this attempt was no failure. Earlier failures stay, /// because they may be MFA guesses; only a completed login clears them. -fn refund_attempt(u: &mut User) { +pub(super) fn refund_attempt(u: &mut User) { u.failed_attempts = u.failed_attempts.saturating_sub(1); u.locked_until = 0; } @@ -250,7 +250,7 @@ impl AuthService { }) } - fn log( + pub(super) fn log( &self, action: &str, actor: Option<&str>, @@ -686,6 +686,7 @@ impl AuthService { let name = u.username.clone(); st.users.retain(|u| u.id != user_id); end_sessions(st, user_id, None); + st.tokens.retain(|t| t.user_id != user_id); Ok(name) }); self.log_admin_result("user.delete", actor, &result)?; @@ -829,6 +830,7 @@ impl AuthService { u.auth_epoch = u.auth_epoch.wrapping_add(1); let (id, name) = (u.id.clone(), u.username.clone()); end_sessions(st, &id, None); + st.tokens.retain(|t| t.user_id != id); Ok(Some(name)) })?; let Some(name) = target else { diff --git a/crates/acaua-core/src/auth/store.rs b/crates/acaua-core/src/auth/store.rs index c3393c9..195adfc 100644 --- a/crates/acaua-core/src/auth/store.rs +++ b/crates/acaua-core/src/auth/store.rs @@ -46,6 +46,8 @@ 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 { @@ -81,15 +83,28 @@ impl std::fmt::Debug for Session { } } +/// How much an API token may do. `Read` < `Admin`. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Scope { + #[default] + Read, + Admin, +} + #[derive(Clone, Default, Serialize, Deserialize)] #[serde(default)] pub struct ApiToken { pub id: String, + pub user_id: String, pub name: String, /// SHA-256 hex of the token; the token itself is never stored. pub token_hash: String, - pub created_at: String, - pub expires_at: Option, + pub scope: Scope, + /// Unix seconds. + pub created_at: u64, + /// Unix seconds; every token expires. + pub expires_at: u64, } impl std::fmt::Debug for ApiToken { diff --git a/crates/acaua-core/src/auth/tokens.rs b/crates/acaua-core/src/auth/tokens.rs new file mode 100644 index 0000000..d5e9add --- /dev/null +++ b/crates/acaua-core/src/auth/tokens.rs @@ -0,0 +1,891 @@ +//! 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, + /// The user passed `reauthenticate` within the last 10 minutes. + pub recent_auth: bool, +} + +/// 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, +} + +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(u: &User, now: u64) -> bool { + u.last_reauth != 0 && now >= u.last_reauth && now - u.last_reauth <= RECENT_AUTH_SECS +} + +fn principal(u: &User, via: Via, scope: Scope, recent_auth: bool) -> Principal { + Principal { + user_id: u.id.clone(), + username: u.username.clone(), + role: u.role, + via, + scope, + recent_auth, + } +} + +/// An admin may act on anyone's sessions and tokens; others only their own. +fn may_manage(actor: &Principal, owner: &str) -> bool { + 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 { + 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(u, now)), + 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, + 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> { + 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. Throttled like + /// login; a code is never accepted twice. + pub fn reauthenticate( + &self, + user_id: &str, + password: &str, + code: Option<&str>, + now: u64, + ) -> Result<()> { + let (name, hash) = self.store.update(|st| { + 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 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); + return Ok(false); + } + } + u.last_reauth = now; + Ok(true) + })?; + 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 { + 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 { + 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)?; + if !is_recent(u, now) { + 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 { + 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, + )) + })? + } + + /// Unexpired tokens of one user. + pub fn list_tokens(&self, user_id: &str, now: u64) -> Result> { + 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, + 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(r: Result) -> 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, 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, 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, _) = analyst_session(&s, "ana", T0); + for i in 0..20 { + let r = s.reauthenticate(&id, "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, PW, None, T0 + 100).is_err()); + assert!(s.reauthenticate(&id, 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(); + 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()); + } + + #[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, 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, 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, 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, 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, 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, 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, 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)); + 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, 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()); + } +} diff --git a/crates/acaua-core/src/error.rs b/crates/acaua-core/src/error.rs index a3e677e..e69c432 100644 --- a/crates/acaua-core/src/error.rs +++ b/crates/acaua-core/src/error.rs @@ -60,6 +60,12 @@ pub enum AuthFailure { UsernameTaken, #[error("user not found")] UserNotFound, + #[error("recent authentication is required")] + ReauthRequired, + #[error("not permitted for this role or scope")] + Forbidden, + #[error("not found")] + NotFound, } pub type Result = std::result::Result;