//! Accounts, first-run setup and the MFA login flow. No HTTP here: `now` is //! always a parameter and callers decide who may call what. //! //! The store and the audit log share one flock, and flock conflicts between //! descriptors of one process: never touch either inside an `update` closure. //! Argon2 runs outside the lock, with the state re-checked afterwards. A //! failed attempt must return `Ok` from its closure, or its count is discarded. 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, 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}; use serde::{Deserialize, Serialize}; use std::net::IpAddr; use std::path::{Path, PathBuf}; use unicode_normalization::UnicodeNormalization; const BOOTSTRAP_CODE_BYTES: usize = 16; // 128 bits const BOOTSTRAP_TTL_SECS: u64 = 3600; const PENDING_TTL_SECS: u64 = 300; const PENDING_PURPOSE: &str = "pending_mfa"; const PASSWORD_CHANGE_PURPOSE: &str = "password_change"; const SESSION_TOKEN_BYTES: usize = 32; // 256 bits const SESSION_ABSOLUTE_SECS: u64 = 43_200; const USERNAME_MAX_CHARS: usize = 64; const ID_BYTES: usize = 16; const TEMP_PASSWORD_BYTES: usize = 24; /// A session just created. The token exists only here; the store has its hash. pub struct NewSession { pub id: String, pub user_id: String, pub token: String, pub expires_at: u64, } impl std::fmt::Debug for NewSession { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("NewSession") .field("id", &self.id) .field("user_id", &self.user_id) .field("expires_at", &self.expires_at) .finish_non_exhaustive() } } /// Proof that the password step passed. Encrypted, short-lived, and grants no /// access to data: it only unlocks the MFA step. pub struct PendingMfa { pub token: String, pub expires_at: u64, } impl std::fmt::Debug for PendingMfa { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("PendingMfa") .field("expires_at", &self.expires_at) .finish_non_exhaustive() } } #[derive(Debug)] pub enum LoginStep { Session(NewSession), MfaRequired(PendingMfa), MfaEnrollRequired(PendingMfa), /// All factors passed, but the token only allows /// `change_required_password`. It is not a session. PasswordChangeRequired(PendingMfa), } /// What the user needs to add the account to an authenticator app. pub struct TotpEnrollment { pub uri: String, pub qr_png_base64: String, /// Base32 secret for manual entry. pub manual_key: String, } impl std::fmt::Debug for TotpEnrollment { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("TotpEnrollment()") } } /// Listing view of an account: no hash, no secret. #[derive(Debug, Clone, Serialize)] pub struct UserView { pub id: String, pub username: String, pub role: Role, pub created_at: u64, pub mfa_enabled: bool, pub must_change_password: bool, } #[derive(Serialize, Deserialize)] struct PendingClaims { purpose: String, user_id: String, epoch: u64, exp: u64, } pub struct AuthService { pub(super) store: AuthStore, pub(super) secrets: Secrets, pub(super) audit: AuditLog, pub(super) ips: IpLimiter, unknown: UnknownAccounts, #[cfg_attr(not(test), allow(dead_code))] pub(super) auth_dir: PathBuf, } pub(super) fn throttled(retry_after_secs: u64) -> AcauaError { AuthFailure::Throttled { retry_after_secs }.into() } pub(super) fn invalid() -> AcauaError { AuthFailure::InvalidCredentials.into() } /// Comparison form: the same name in any Unicode form or case is one account. fn username_key(username: &str) -> String { username.nfc().collect::().to_lowercase() } /// Returns the NFC form to store. `:` is refused because TOTP enrollment /// refuses it; surrounding spaces would make look-alike accounts. fn validate_username(username: &str) -> Result { let name: String = username.nfc().collect(); let count = name.chars().count(); if count == 0 || count > USERNAME_MAX_CHARS { return Err(AcauaError::InvalidInput(format!( "username must have 1 to {USERNAME_MAX_CHARS} characters" ))); } if name.chars().any(|c| c == ':' || c.is_control()) { return Err(AcauaError::InvalidInput( "username must not contain ':' or control characters".to_string(), )); } if name.trim() != name { return Err(AcauaError::InvalidInput( "username must not start or end with a space".to_string(), )); } Ok(name) } /// With a pending token's epoch: the account must still be the one the token /// was issued for, and must still have no active second factor. fn check_pending_epoch(u: &User, pending_epoch: Option) -> Result<()> { match pending_epoch { Some(epoch) if u.auth_epoch != epoch || u.totp_sealed.is_some() => Err(invalid()), _ => Ok(()), } } fn has_admin(st: &AuthState) -> bool { st.users.iter().any(|u| u.role == Role::Admin) } 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) } 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()) } 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); } pub(super) fn check_lock(u: &User, now: u64) -> std::result::Result<(), u64> { if u.locked_until > now { Err(u.locked_until - now) } else { Ok(()) } } /// Counts the attempt as failed before Argon2 runs, so parallel guesses /// cannot all pass the check. `refund_attempt` undoes it on a right password. pub(super) fn reserve_attempt(u: &mut User, now: u64) -> std::result::Result<(), u64> { check_lock(u, now)?; count_failure(u, now); Ok(()) } /// The password was right: this attempt was no failure. Earlier failures stay, /// because they may be MFA guesses; only a completed login clears them. pub(super) fn refund_attempt(u: &mut User) { u.failed_attempts = u.failed_attempts.saturating_sub(1); u.locked_until = 0; } /// Drops the user's sessions, except the one holding `keep_token`. fn end_sessions(st: &mut AuthState, user_id: &str, keep_token: Option<&str>) { let keep = keep_token.map(hash_token); st.sessions .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); let id = random_token(ID_BYTES); let expires_at = now.saturating_add(SESSION_ABSOLUTE_SECS); st.sessions.push(Session { id: id.clone(), user_id: user_id.to_string(), token_hash: hash_token(&token), created_at: now, last_seen: now, expires_at, last_reauth: 0, }); NewSession { id, user_id: user_id.to_string(), token, expires_at, } } /// Clears the throttle, voids outstanding pending tokens and opens a session. fn complete_login(st: &mut AuthState, user_id: &str, now: u64) -> Result { let u = user_or_missing(st, user_id)?; u.failed_attempts = 0; u.locked_until = 0; u.auth_epoch = u.auth_epoch.wrapping_add(1); Ok(issue_session(st, user_id, now)) } fn bootstrap_valid(st: &AuthState, code_hash: &str, now: u64) -> bool { !has_admin(st) && st.bootstrap.as_ref().is_some_and(|b| { b.token_hash == code_hash && now.saturating_sub(b.created_at) <= BOOTSTRAP_TTL_SECS }) } fn manual_key(uri: &str) -> Option { let query = uri.split_once('?')?.1; query .split('&') .find_map(|kv| kv.strip_prefix("secret=")) .map(str::to_string) } impl AuthService { /// Opens `/auth`. The key comes first: state without a key could /// never be read again. pub fn open(data_dir: &Path, key_file: Option<&Path>) -> Result { let auth_dir = data_dir.join("auth"); let secrets = Secrets::open(&auth_dir, key_file)?; let store = AuthStore::open(&auth_dir)?; Ok(AuthService { store, secrets, audit: AuditLog::open(&auth_dir), ips: IpLimiter::default(), unknown: UnknownAccounts::default(), auth_dir, }) } pub(super) fn log( &self, action: &str, actor: Option<&str>, ip: Option, ok: bool, detail: Option<&str>, ) -> Result<()> { self.audit.record(AuditEvent { action: action.to_string(), actor: actor.map(str::to_string), ip: ip.map(|i| i.to_string()), ok, detail: detail.map(str::to_string), }) } pub fn has_admin(&self) -> Result { self.store.read(has_admin) } pub fn audit_tail(&self, limit: usize) -> Result> { self.audit.tail(limit) } /// With no admin yet, replaces the setup code and returns it for printing. /// With an admin, removes any leftover code and returns `None`. pub fn ensure_bootstrap(&self, now: u64) -> Result> { let code = self.store.update(|st| { if has_admin(st) { st.bootstrap = None; return Ok(None); } let code = random_token(BOOTSTRAP_CODE_BYTES); st.bootstrap = Some(Bootstrap { token_hash: hash_token(&code), created_at: now, }); Ok(Some(code)) })?; if code.is_some() { self.log("bootstrap.code", None, None, true, None)?; } Ok(code) } /// Creates the first admin. Bad input does not burn the code. The result /// is an enrollment-stage pending token: there is no session until MFA. /// /// Anyone can call this, so it must not let them grow the audit log: once /// an admin exists the refusal writes nothing, and before that wrong codes /// are limited per IP. pub fn complete_bootstrap( &self, code: &str, username: &str, password: &str, ip: IpAddr, now: u64, ) -> Result { if self.has_admin()? { return Err(AuthFailure::BootstrapInvalid.into()); } let name = validate_username(username)?; validate_password(password)?; self.ips.acquire(ip, now).map_err(throttled)?; let code_hash = hash_token(code); // Checked first so a wrong code costs no Argon2 work. if !self.store.read(|st| bootstrap_valid(st, &code_hash, now))? { return self.refuse_bootstrap(ip); } let password_hash = hash_password(password)?; // Checked and consumed in one closure: concurrent requests get one win. let done = self.store.update(|st| { if !bootstrap_valid(st, &code_hash, now) { return Ok(None); } st.bootstrap = None; let id = random_token(ID_BYTES); st.users.push(User { id: id.clone(), username: name.clone(), created_at: now, role: Role::Admin, password_hash: password_hash.clone(), ..Default::default() }); Ok(Some(self.seal_pending(&id, 0, PENDING_PURPOSE, now)?)) })?; let Some(pending) = done else { return self.refuse_bootstrap(ip); }; self.ips.release(ip); self.log("bootstrap.complete", Some(&name), Some(ip), true, None)?; Ok(pending) } /// Losing a race to the first admin is not worth an audit line either. fn refuse_bootstrap(&self, ip: IpAddr) -> Result { if !self.has_admin()? { self.log("bootstrap.complete", None, Some(ip), false, None)?; } Err(AuthFailure::BootstrapInvalid.into()) } fn seal_pending( &self, user_id: &str, epoch: u64, purpose: &str, now: u64, ) -> Result { let exp = now.saturating_add(PENDING_TTL_SECS); let claims = PendingClaims { purpose: purpose.to_string(), user_id: user_id.to_string(), epoch, exp, }; Ok(PendingMfa { token: self.secrets.seal(&serde_json::to_vec(&claims)?)?, expires_at: exp, }) } /// Any defect is the same refusal: forged, expired, or for another purpose. fn open_pending(&self, token: &str, purpose: &str, now: u64) -> Result { let raw = self.secrets.open_sealed(token).map_err(|_| invalid())?; let claims: PendingClaims = serde_json::from_slice(&raw).map_err(|_| invalid())?; if claims.purpose != purpose || now > claims.exp { return Err(invalid()); } Ok(claims) } /// First factor. Unknown user and wrong password are indistinguishable: /// same error, same Argon2 cost, same store write, same throttle schedule. pub fn login(&self, username: &str, password: &str, ip: IpAddr, now: u64) -> Result { enum Gate { NoAdmin, Unknown, Locked(u64), Known { id: String, name: String, hash: String, }, } self.ips.acquire(ip, now).map_err(throttled)?; let key = username_key(username); let gate = self.store.update(|st| { if !has_admin(st) { return Ok(Gate::NoAdmin); } let Some(u) = st .users .iter_mut() .find(|u| username_key(&u.username) == key) else { return Ok(Gate::Unknown); }; Ok(match reserve_attempt(u, now) { Err(left) => Gate::Locked(left), Ok(()) => Gate::Known { id: u.id.clone(), name: u.username.clone(), hash: u.password_hash.clone(), }, }) })?; let (id, name, hash) = match gate { Gate::NoAdmin => { self.ips.release(ip); return Err(AuthFailure::SetupRequired.into()); } Gate::Locked(left) => { self.ips.release(ip); return Err(throttled(left)); } Gate::Unknown => { if let Err(left) = self.unknown.acquire(&hash_token(&key), now) { self.ips.release(ip); return Err(throttled(left)); } verify_password(None, password); // The typed name stays out of the log: it may be a password // entered in the wrong field. self.log("login", None, Some(ip), false, Some("invalid credentials"))?; return Err(invalid()); } Gate::Known { id, name, hash } => (id, name, hash), }; if !verify_password(Some(&hash), password) { self.log( "login", Some(&name), Some(ip), false, Some("invalid credentials"), )?; return Err(invalid()); } let step = self.store.update(|st| { // The account may have changed while Argon2 ran. let Some(u) = user_mut(st, &id).filter(|u| u.password_hash == hash) else { return Ok(None); }; refund_attempt(u); let epoch = u.auth_epoch; let step = if u.totp_sealed.is_some() { LoginStep::MfaRequired(self.seal_pending(&id, epoch, PENDING_PURPOSE, now)?) } else if u.role == Role::Admin { LoginStep::MfaEnrollRequired(self.seal_pending(&id, epoch, PENDING_PURPOSE, now)?) } else if u.must_change_password { LoginStep::PasswordChangeRequired(self.seal_pending( &id, epoch, PASSWORD_CHANGE_PURPOSE, now, )?) } else { LoginStep::Session(complete_login(st, &id, now)?) }; Ok(Some(step)) })?; let Some(step) = step else { self.log( "login", Some(&name), Some(ip), false, Some("invalid credentials"), )?; return Err(invalid()); }; self.ips.release(ip); let detail = match step { LoginStep::Session(_) => "session", LoginStep::MfaRequired(_) => "mfa required", LoginStep::MfaEnrollRequired(_) => "mfa enrollment required", LoginStep::PasswordChangeRequired(_) => "password change required", }; self.log("login", Some(&name), Some(ip), true, Some(detail))?; Ok(step) } /// Second factor: a TOTP code or a recovery code. Failures count against /// the account, since 6 digits cannot stand unlimited guesses. pub fn confirm_mfa(&self, pending: &str, code: &str, now: u64) -> Result { enum Outcome { Done { step: LoginStep, name: String, method: &'static str, }, Bad(String), } let claims = self.open_pending(pending, PENDING_PURPOSE, now)?; let recovery_hash = hash_recovery_code(code); let outcome = self.store.update(|st| { let u = user_mut(st, &claims.user_id) .filter(|u| u.auth_epoch == claims.epoch) .ok_or_else(invalid)?; let sealed = u.totp_sealed.clone().ok_or_else(invalid)?; check_lock(u, now).map_err(throttled)?; let secret = self.secrets.open_sealed(&sealed)?; let name = u.username.clone(); let method = if let Some(step) = verify_totp(&secret, code, now, u.totp_last_step) { u.totp_last_step = Some(step); "totp" } else if let Some(i) = u.recovery_hashes.iter().position(|h| *h == recovery_hash) { u.recovery_hashes.remove(i); "recovery code" } else { count_failure(u, now); return Ok(Outcome::Bad(name)); }; let step = if u.must_change_password { // Factors passed, so the throttle clears and this pending // token dies, but only the password step opens. u.failed_attempts = 0; u.locked_until = 0; u.auth_epoch = u.auth_epoch.wrapping_add(1); LoginStep::PasswordChangeRequired(self.seal_pending( &claims.user_id, u.auth_epoch, PASSWORD_CHANGE_PURPOSE, now, )?) } else { LoginStep::Session(complete_login(st, &claims.user_id, now)?) }; Ok(Outcome::Done { step, name, method }) })?; match outcome { Outcome::Bad(name) => { self.log("mfa.confirm", Some(&name), None, false, None)?; Err(invalid()) } Outcome::Done { step, name, method } => { self.log("mfa.confirm", Some(&name), None, true, Some(method))?; Ok(step) } } } /// The user a pending token may enroll. Refused once MFA is active, so a /// password alone can never replace an existing second factor. pub fn pending_user(&self, pending: &str, now: u64) -> Result { let claims = self.open_pending(pending, PENDING_PURPOSE, now)?; let allowed = self.store.read(|st| { st.users.iter().any(|u| { u.id == claims.user_id && u.auth_epoch == claims.epoch && u.totp_sealed.is_none() }) })?; if !allowed { return Err(invalid()); } Ok(claims.user_id) } /// Starts (or restarts) enrollment. An active secret stays in force until /// `confirm_enrollment` replaces it. Callers must have checked that the /// actor may do this; a pending token goes through /// `start_enrollment_pending`. pub fn start_enrollment(&self, user_id: &str, _now: u64) -> Result { self.start_enrollment_guarded(user_id, None) } /// Enrollment with only a pending token. `pending_user` alone would leave /// a gap: the token is re-checked inside the update that stores the secret. pub fn start_enrollment_pending(&self, pending: &str, now: u64) -> Result { let claims = self.open_pending(pending, PENDING_PURPOSE, now)?; self.start_enrollment_guarded(&claims.user_id, Some(claims.epoch)) } fn start_enrollment_guarded( &self, user_id: &str, pending_epoch: Option, ) -> Result { let missing = || -> AcauaError { match pending_epoch { Some(_) => invalid(), None => AuthFailure::UserNotFound.into(), } }; let name = self .store .read(|st| { st.users .iter() .find(|u| u.id == user_id) .map(|u| u.username.clone()) })? .ok_or_else(missing)?; let secret = new_totp_secret(); let (uri, qr_png_base64) = totp_uri_and_qr(&secret, &name)?; let manual_key = manual_key(&uri).ok_or_else(|| { AcauaError::InvalidInput("could not encode TOTP enrolment".to_string()) })?; let sealed = self.secrets.seal(&secret)?; self.store.update(|st| { let u = user_mut(st, user_id).ok_or_else(missing)?; check_pending_epoch(u, pending_epoch)?; u.totp_pending_sealed = Some(sealed); Ok(()) })?; self.log("mfa.enroll.start", Some(&name), None, true, None)?; Ok(TotpEnrollment { uri, qr_png_base64, manual_key, }) } /// Activates the started secret and returns the recovery codes, shown only /// here. The accepted step is spent, so finishing a login needs a later /// code. Ends every session of the user. A pending token goes through /// `confirm_enrollment_pending`. pub fn confirm_enrollment(&self, user_id: &str, code: &str, now: u64) -> Result> { self.confirm_enrollment_guarded(user_id, None, code, now) } /// As `start_enrollment_pending`: two racing requests get one activation, /// and the loser cannot replace the factor the winner just set. pub fn confirm_enrollment_pending( &self, pending: &str, code: &str, now: u64, ) -> Result> { let claims = self.open_pending(pending, PENDING_PURPOSE, now)?; self.confirm_enrollment_guarded(&claims.user_id, Some(claims.epoch), code, now) } fn confirm_enrollment_guarded( &self, user_id: &str, pending_epoch: Option, code: &str, now: u64, ) -> Result> { let (texts, hashes) = new_recovery_codes(); let (name, accepted) = self.store.update(|st| { let u = match pending_epoch { Some(_) => user_mut(st, user_id).ok_or_else(invalid)?, None => user_or_missing(st, user_id)?, }; check_pending_epoch(u, pending_epoch)?; let sealed = u .totp_pending_sealed .clone() .ok_or(AuthFailure::EnrollmentNotStarted)?; check_lock(u, now).map_err(throttled)?; let secret = self.secrets.open_sealed(&sealed)?; let name = u.username.clone(); let Some(step) = verify_totp(&secret, code, now, None) else { count_failure(u, now); return Ok((name, false)); }; u.totp_sealed = Some(sealed); u.totp_pending_sealed = None; 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)?; if !accepted { return Err(invalid()); } Ok(texts) } /// Every account, without credentials. Authorization is the caller's. pub fn list_users(&self) -> Result> { self.store.read(|st| { st.users .iter() .map(|u| UserView { id: u.id.clone(), username: u.username.clone(), role: u.role, created_at: u.created_at, mfa_enabled: u.totp_sealed.is_some(), must_change_password: u.must_change_password, }) .collect() }) } /// `actor` names who acted, for the audit log. Authorization is the /// caller's. Returns the new user's id. pub fn create_user( &self, actor: &str, username: &str, password: &str, role: Role, now: u64, ) -> Result { let name = validate_username(username)?; validate_password(password)?; let key = username_key(&name); let taken = |st: &AuthState| st.users.iter().any(|u| username_key(&u.username) == key); if self.store.read(|st| taken(st))? { return Err(AuthFailure::UsernameTaken.into()); } let password_hash = hash_password(password)?; let id = self.store.update(|st| { if taken(st) { return Err(AuthFailure::UsernameTaken.into()); } let id = random_token(ID_BYTES); st.users.push(User { id: id.clone(), username: name.clone(), created_at: now, role, password_hash, ..Default::default() }); Ok(id) })?; self.log("user.create", Some(actor), None, true, Some(&name))?; Ok(id) } /// Any role change ends the user's sessions, so a promoted account has to /// pass through login, and through enrollment if it has no MFA. pub fn set_role(&self, actor: &str, user_id: &str, role: Role, _now: u64) -> Result<()> { let result = self.store.update(|st| { let admins = st.users.iter().filter(|u| u.role == Role::Admin).count(); let u = user_or_missing(st, user_id)?; if u.role == Role::Admin && role != Role::Admin && admins <= 1 { return Err(AuthFailure::LastAdmin.into()); } 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) }); self.log_admin_result("user.role", actor, &result)?; result.map(|_| ()) } pub fn delete_user(&self, actor: &str, user_id: &str, _now: u64) -> Result<()> { let result = self.store.update(|st| { let admins = st.users.iter().filter(|u| u.role == Role::Admin).count(); let u = user_or_missing(st, user_id)?; if u.role == Role::Admin && admins <= 1 { return Err(AuthFailure::LastAdmin.into()); } 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)?; result.map(|_| ()) } /// Audits an administrative outcome; `Ok` holds the target username. fn log_admin_result(&self, action: &str, actor: &str, r: &Result) -> Result<()> { match r { Ok(name) => self.log(action, Some(actor), None, true, Some(name)), Err(AcauaError::Auth(f)) => { self.log(action, Some(actor), None, false, Some(&f.to_string())) } // A store failure is already being returned to the caller. Err(_) => Ok(()), } } /// Requires the current password and throttles like login. Ends the other /// sessions; `keep_session_token` is the caller's own, if any. pub fn change_password( &self, user_id: &str, current: &str, new: &str, keep_session_token: Option<&str>, now: u64, ) -> Result<()> { validate_password(new)?; // Comparing the two inputs reveals nothing about the stored password. if normalize(current) == normalize(new) { return Err(AcauaError::InvalidInput( "new password must differ from the current one".to_string(), )); } 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), current) { self.log("password.change", Some(&name), None, false, None)?; return Err(invalid()); } let new_hash = hash_password(new)?; let changed = 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); u.password_hash = new_hash; 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)?; if !changed { return Err(invalid()); } Ok(()) } /// Spends a `PasswordChangeRequired` ticket: changes the password under /// the rules of `change_password`, then opens the session. pub fn change_required_password( &self, ticket: &str, current: &str, new: &str, now: u64, ) -> Result { let claims = self.open_pending(ticket, PASSWORD_CHANGE_PURPOSE, now)?; let live = self.store.read(|st| { st.users.iter().any(|u| { u.id == claims.user_id && u.auth_epoch == claims.epoch && u.must_change_password }) })?; if !live { return Err(invalid()); } self.change_password(&claims.user_id, current, new, None, now)?; self.store.update(|st| { let u = user_mut(st, &claims.user_id).ok_or_else(invalid)?; if u.must_change_password { return Err(invalid()); } complete_login(st, &claims.user_id, now) }) } /// Refused for administrators. Ends the other sessions. pub fn disable_mfa( &self, actor: &str, user_id: &str, keep_session_token: Option<&str>, _now: u64, ) -> Result<()> { let result = self.store.update(|st| { let u = user_or_missing(st, user_id)?; if u.role == Role::Admin { return Err(AuthFailure::MfaMandatory.into()); } let name = u.username.clone(); u.totp_sealed = None; u.totp_pending_sealed = None; 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)?; result.map(|_| ()) } /// Local recovery for an administrator who lost access: removes MFA and /// sessions, clears the throttle, and returns a temporary password that /// is shown once. The next login must enroll again and change the password /// before any ordinary session. pub fn reset_admin(&self, username: &str, _now: u64) -> Result { let key = username_key(username); let temp = random_token(TEMP_PASSWORD_BYTES); let password_hash = hash_password(&temp)?; let target = self.store.update(|st| { let Some(u) = st .users .iter_mut() .find(|u| u.role == Role::Admin && username_key(&u.username) == key) else { return Ok(None); }; u.password_hash = password_hash; u.must_change_password = true; u.totp_sealed = None; u.totp_pending_sealed = None; u.totp_last_step = None; u.recovery_hashes.clear(); u.failed_attempts = 0; u.locked_until = 0; 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 { self.log("admin.reset", None, None, false, Some("no such admin"))?; return Err(AuthFailure::UserNotFound.into()); }; self.log( "admin.reset", Some(&name), None, true, Some("local command"), )?; Ok(temp) } } #[cfg(test)] #[path = "service_tests.rs"] mod tests;