Files
acaua/crates/acaua-core/src/auth/service.rs
T
Lucas RayanandClaude Opus 5.5 b9137e0948 feat(auth): cap login guessing with a per-account budget
Failures from unknown addresses are capped at 100 per rolling 24 hours per
username, refused before Argon2 and before the hashing queue. Addresses with
a completed login in the last 30 days skip the budget, stored hashed on the
user. IPv6 counts per /48 for the pair throttle and the budget. Unknown names
take the same path, with their budget in the stand-in table. Crossing the cap
audits login.budget_exhausted once per account per 24 hours. Eviction drops
faded entries, then the least counted, not the oldest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 06:27:38 -03:00

1192 lines
42 KiB
Rust

//! 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, KnownAddress, Role, Scope, Session, User};
use super::throttle::{
address_key, decayed, lock_until, BudgetState, IpLimiter, LoginThrottle, BUDGET_MAX_FAILURES,
};
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 completed login makes its address known for this long.
const KNOWN_ADDRESS_SECS: u64 = 30 * 86_400;
const KNOWN_ADDRESS_MAX: usize = 10;
/// 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(<redacted>)")
}
}
/// 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,
}
struct Known {
id: String,
name: String,
hash: String,
}
/// A login that passed every check that needs no Argon2. Holds reservations:
/// see `AuthService::login_begin`.
pub struct LoginAttempt {
throttle_key: String,
/// `None` for a username with no account.
account: Option<Known>,
ip: IpAddr,
/// Hash that makes `ip` known to this account once the login completes.
address: String,
/// The reservation was charged to the budget.
budgeted: bool,
}
impl std::fmt::Debug for LoginAttempt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("LoginAttempt(<redacted>)")
}
}
#[derive(Serialize, Deserialize)]
struct PendingClaims {
purpose: String,
user_id: String,
epoch: u64,
exp: u64,
/// Address hash of the password step, known once the login completes.
#[serde(default)]
address: Option<String>,
}
pub struct AuthService {
pub(super) store: AuthStore,
pub(super) secrets: Secrets,
pub(super) audit: AuditLog,
pub(super) ips: IpLimiter,
logins: LoginThrottle,
#[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::<String>().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<String> {
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<u64>) -> 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())
}
/// Counts against the user-bound throttle: MFA codes and the password checks
/// of a live session. Only someone past the password or inside a session can
/// reach it, so a stranger cannot use it against the owner.
pub(super) fn count_failure(u: &mut User, now: u64) {
let (failures, last) = decayed(u.failed_attempts, u.failed_at, now);
u.failed_attempts = failures.saturating_add(1);
u.failed_at = if failures == 0 { now } else { last };
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,
}
}
/// Only ever a hash, salted per account so lists cannot be compared. The IPv4
/// space is small enough to enumerate for someone who can read `state.json`, who
/// has far better things to take from it.
fn address_hash(user_id: &str, ip: IpAddr) -> String {
hash_token(&format!("known-address\0{user_id}\0{}", address_key(ip)))
}
fn is_known(u: &User, hash: &str, now: u64) -> bool {
u.known_addresses
.iter()
.any(|k| k.hash == hash && now.saturating_sub(k.last_seen) < KNOWN_ADDRESS_SECS)
}
fn remember_address(u: &mut User, hash: &str, now: u64) {
let list = &mut u.known_addresses;
list.retain(|k| k.hash != hash && now.saturating_sub(k.last_seen) < KNOWN_ADDRESS_SECS);
list.push(KnownAddress {
hash: hash.to_string(),
last_seen: now,
});
while list.len() > KNOWN_ADDRESS_MAX {
let oldest = list
.iter()
.enumerate()
.min_by_key(|(_, k)| k.last_seen)
.map(|(i, _)| i);
match oldest {
Some(i) => list.remove(i),
None => break,
};
}
}
fn stored_budget(u: &User) -> BudgetState {
BudgetState {
failures: u.budget_failures,
last: u.budget_at,
audited_at: u.budget_audited_at,
generation: u.budget_generation,
}
}
/// Clears the throttle, voids outstanding pending tokens and opens a session.
/// `address` is where the login came from, the only thing that makes one known.
fn complete_login(
st: &mut AuthState,
user_id: &str,
address: Option<&str>,
now: u64,
) -> Result<NewSession> {
let u = user_or_missing(st, user_id)?;
if let Some(hash) = address {
remember_address(u, hash, now);
}
u.failed_attempts = 0;
u.locked_until = 0;
u.auth_epoch = u.auth_epoch.wrapping_add(1);
Ok(issue_session(st, user_id, now))
}
/// Last step of a required password change. `change_password` moved the epoch
/// by exactly one; anything else means the account changed in between. An
/// administrator never gets a session without MFA, even if promoted meanwhile.
fn finish_required_change(
st: &mut AuthState,
user_id: &str,
ticket_epoch: u64,
address: Option<&str>,
now: u64,
) -> Result<NewSession> {
let u = user_mut(st, user_id).ok_or_else(invalid)?;
if u.must_change_password
|| u.auth_epoch != ticket_epoch.wrapping_add(1)
|| (u.role == Role::Admin && u.totp_sealed.is_none())
{
return Err(invalid());
}
complete_login(st, user_id, address, 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<String> {
let query = uri.split_once('?')?.1;
query
.split('&')
.find_map(|kv| kv.strip_prefix("secret="))
.map(str::to_string)
}
impl AuthService {
/// Opens `<data_dir>/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<AuthService> {
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(),
logins: LoginThrottle::default(),
auth_dir,
})
}
pub(super) fn log(
&self,
action: &str,
actor: Option<&str>,
ip: Option<IpAddr>,
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<bool> {
self.store.read(has_admin)
}
pub fn audit_tail(&self, limit: usize) -> Result<Vec<AuditEntry>> {
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<Option<String>> {
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<PendingMfa> {
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,
None,
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<PendingMfa> {
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,
address: Option<&str>,
now: u64,
) -> Result<PendingMfa> {
let exp = now.saturating_add(PENDING_TTL_SECS);
let claims = PendingClaims {
purpose: purpose.to_string(),
user_id: user_id.to_string(),
epoch,
exp,
address: address.map(str::to_string),
};
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<PendingClaims> {
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 throttle schedule.
pub fn login(&self, username: &str, password: &str, ip: IpAddr, now: u64) -> Result<LoginStep> {
let attempt = self.login_begin(username, ip, now)?;
self.login_finish(attempt, password, now)
}
/// Everything that can refuse a login without Argon2. On `Ok` the attempt
/// already counts as a failure: pass it to `login_finish`, or to
/// `login_abandon` if it will never be evaluated. A refusal writes nothing.
pub fn login_begin(&self, username: &str, ip: IpAddr, now: u64) -> Result<LoginAttempt> {
self.ips.acquire(ip, now).map_err(throttled)?;
let key = username_key(username);
let found = self.store.read(|st| {
has_admin(st).then(|| {
st.users
.iter()
.find(|u| username_key(&u.username) == key)
.map(|u| {
let address = address_hash(&u.id, ip);
(
Known {
id: u.id.clone(),
name: u.username.clone(),
hash: u.password_hash.clone(),
},
is_known(u, &address, now),
address,
stored_budget(u),
)
})
})
})?;
let Some(found) = found else {
self.ips.release(ip);
return Err(AuthFailure::SetupRequired.into());
};
// A name with no account is never known; its budget lives only in the
// throttle's table.
let (account, known, address, stored) = match found {
Some((account, known, address, stored)) => (Some(account), known, address, stored),
None => (None, false, String::new(), BudgetState::default()),
};
// The hash keeps a password typed into the wrong field out of memory.
let throttle_key = hash_token(&key);
let budgeted = match self.logins.acquire(&throttle_key, ip, known, stored, now) {
Ok(budgeted) => budgeted,
Err(left) => {
self.ips.release(ip);
return Err(throttled(left));
}
};
Ok(LoginAttempt {
throttle_key,
account,
ip,
address,
budgeted,
})
}
/// Returns the reservations of an attempt that was never evaluated.
pub fn login_abandon(&self, attempt: LoginAttempt) {
self.ips.release(attempt.ip);
self.logins
.abandon(&attempt.throttle_key, attempt.ip, attempt.budgeted);
}
/// Records an evaluated failure and returns its refusal.
pub fn login_failed(&self, attempt: LoginAttempt, now: u64) -> Result<LoginStep> {
let note = if attempt.budgeted {
self.logins.failed(&attempt.throttle_key, now)
} else {
Default::default()
};
let id = attempt.account.as_ref().map(|k| k.id.as_str());
if let Some(state) = note.write {
// A name with no account writes too, with nothing to store: a real
// name must not answer slower once a minute.
self.store.update(|st| {
if let Some(u) = id
.and_then(|id| user_mut(st, id))
.filter(|u| u.budget_generation == state.generation)
{
u.budget_failures = state.failures;
u.budget_at = state.last;
u.budget_audited_at = state.audited_at;
}
Ok(())
})?;
}
let name = attempt.account.map(|k| k.name);
// An unknown name stays out of the log: it may be a password entered
// in the wrong field.
self.log(
"login",
name.as_deref(),
Some(attempt.ip),
false,
Some("invalid credentials"),
)?;
if note.audit {
self.log(
"login.budget_exhausted",
name.as_deref(),
None,
false,
Some(&format!(
"{BUDGET_MAX_FAILURES}+ failures from unknown addresses in 24 h"
)),
)?;
}
Err(invalid())
}
/// Runs Argon2 for an attempt `login_begin` let through.
pub fn login_finish(
&self,
attempt: LoginAttempt,
password: &str,
now: u64,
) -> Result<LoginStep> {
let Some(known) = &attempt.account else {
verify_password(None, password);
return self.login_failed(attempt, now);
};
if !verify_password(Some(&known.hash), password) {
return self.login_failed(attempt, now);
}
let (id, name, hash) = (known.id.clone(), known.name.clone(), known.hash.clone());
let address = attempt.address.as_str();
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);
};
let epoch = u.auth_epoch;
let step = if u.totp_sealed.is_some() {
LoginStep::MfaRequired(self.seal_pending(
&id,
epoch,
PENDING_PURPOSE,
Some(address),
now,
)?)
} else if u.role == Role::Admin {
LoginStep::MfaEnrollRequired(self.seal_pending(
&id,
epoch,
PENDING_PURPOSE,
Some(address),
now,
)?)
} else if u.must_change_password {
LoginStep::PasswordChangeRequired(self.seal_pending(
&id,
epoch,
PASSWORD_CHANGE_PURPOSE,
Some(address),
now,
)?)
} else {
LoginStep::Session(complete_login(st, &id, Some(address), now)?)
};
Ok(Some(step))
})?;
let Some(step) = step else {
return self.login_failed(attempt, now);
};
self.ips.release(attempt.ip);
self.logins
.right_password(&attempt.throttle_key, attempt.ip, attempt.budgeted);
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(attempt.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<LoginStep> {
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,
claims.address.as_deref(),
now,
)?)
} else {
LoginStep::Session(complete_login(
st,
&claims.user_id,
claims.address.as_deref(),
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<String> {
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<TotpEnrollment> {
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<TotpEnrollment> {
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<u64>,
) -> Result<TotpEnrollment> {
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<Vec<String>> {
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<Vec<String>> {
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<u64>,
code: &str,
now: u64,
) -> Result<Vec<String>> {
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;
u.known_addresses.clear();
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)
}
/// Whether the account has an active second factor.
pub fn mfa_enabled(&self, user_id: &str) -> Result<bool> {
self.store.read(|st| {
st.users
.iter()
.any(|u| u.id == user_id && u.totp_sealed.is_some())
})
}
/// Every account, without credentials. Authorization is the caller's.
pub fn list_users(&self) -> Result<Vec<UserView>> {
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<String> {
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<String>) -> 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.known_addresses.clear();
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<NewSession> {
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| {
finish_required_change(
st,
&claims.user_id,
claims.epoch,
claims.address.as_deref(),
now,
)
})
}
/// Refused for administrators, and when MFA is already off, which changes
/// nothing and writes no audit line. 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());
}
if u.totp_sealed.is_none() {
return Err(AuthFailure::MfaNotEnabled.into());
}
let name = u.username.clone();
u.totp_sealed = None;
u.totp_pending_sealed = None;
u.totp_last_step = None;
u.recovery_hashes.clear();
u.known_addresses.clear();
end_sessions(st, user_id, keep_session_token);
drop_admin_tokens(st, user_id);
Ok(name)
});
if !matches!(result, Err(AcauaError::Auth(AuthFailure::MfaNotEnabled))) {
self.log_admin_result("mfa.disable", actor, &result)?;
}
result.map(|_| ())
}
/// Local recovery for anyone who lost access: removes MFA, sessions and
/// tokens, clears the user-bound throttle, and returns a temporary password
/// that is shown once. The next login must change the password before any
/// ordinary session; an administrator must enroll MFA again first. Clears the
/// known addresses and the login budget; a running daemon notices through
/// `budget_generation`.
pub fn reset_account(&self, username: &str, _now: u64) -> Result<String> {
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| 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.known_addresses.clear();
u.budget_failures = 0;
u.budget_at = 0;
u.budget_audited_at = 0;
u.budget_generation = u.budget_generation.wrapping_add(1);
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("auth.reset", None, None, false, Some("no such user"))?;
return Err(AuthFailure::UserNotFound.into());
};
self.log("auth.reset", Some(&name), None, true, Some("local command"))?;
Ok(temp)
}
}
#[cfg(test)]
#[path = "service_tests.rs"]
mod tests;