feat(auth): accounts, first-run setup and MFA login flow

Adds AuthService with single-use setup code, password login, TOTP and
recovery codes, enrollment, account management and local admin reset.
Attempts are reserved before Argon2 so parallel guesses cannot outrun the
per-account delay or the IP limit, and unknown usernames follow the same
schedule as real accounts. Passwords are NFC-normalized; repeated-character
and all-digit passwords are refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-04 19:24:46 -03:00
1 parent deea3e245b
commit 2b71ae41c0
9 files changed
+1998 -10

No files matched your search

+53 -3
View File
@@ -10,6 +10,7 @@ use std::collections::HashSet;
use std::str::FromStr;
use std::sync::OnceLock;
use totp_rs::{Algorithm as TotpAlgorithm, Builder as TotpBuilder, Totp};
use unicode_normalization::UnicodeNormalization;
/// Minimum password length, in characters.
pub const PASSWORD_MIN_CHARS: usize = 12;
@@ -56,9 +57,18 @@ fn is_common(password: &str) -> bool {
!base.is_empty() && base.len() != lower.len() && set.contains(base)
}
/// Rejects short, oversized and common passwords. No composition rules.
/// Error messages never echo the password.
/// NFC form: the same password typed on different keyboards or systems must
/// produce the same bytes. Every password path goes through this.
fn normalize(password: &str) -> String {
password.nfc().collect()
}
/// Rejects short, oversized, common, single-character and all-digit passwords.
/// No composition rules. The checks apply to the NFC form. Error messages
/// never echo the password.
pub fn validate_password(password: &str) -> Result<()> {
let password = normalize(password);
let password = password.as_str();
if password.len() > PASSWORD_MAX_BYTES {
return Err(AcauaError::InvalidInput(format!(
"password must be at most {PASSWORD_MAX_BYTES} bytes"
@@ -74,6 +84,19 @@ pub fn validate_password(password: &str) -> Result<()> {
"password is too common".to_string(),
));
}
let mut chars = password.chars();
if let Some(first) = chars.next() {
if chars.all(|c| c == first) {
return Err(AcauaError::InvalidInput(
"password must not repeat a single character".to_string(),
));
}
}
if password.chars().all(char::is_numeric) {
return Err(AcauaError::InvalidInput(
"password must not be only digits".to_string(),
));
}
Ok(())
}
@@ -91,6 +114,7 @@ fn hash_failure() -> AcauaError {
/// Argon2id (m=19456 KiB, t=2, p=1) hash in PHC string format, random salt.
pub fn hash_password(password: &str) -> Result<String> {
let password = normalize(password);
if password.len() > PASSWORD_MAX_BYTES {
return Err(AcauaError::InvalidInput(format!(
"password must be at most {PASSWORD_MAX_BYTES} bytes"
@@ -114,6 +138,7 @@ fn dummy_hash() -> Option<&'static str> {
/// result is then always `false`. A malformed stored hash also yields `false`.
pub fn verify_password(hash: Option<&str>, candidate: &str) -> bool {
// Oversized input is refused before any Argon2 work.
let candidate = normalize(candidate);
if candidate.len() > PASSWORD_MAX_BYTES {
return false;
}
@@ -141,7 +166,7 @@ pub fn new_totp_secret() -> Vec<u8> {
buf
}
fn build_totp(secret: &[u8], account: &str) -> Result<Totp> {
pub(super) fn build_totp(secret: &[u8], account: &str) -> Result<Totp> {
TotpBuilder::new()
.with_algorithm(TotpAlgorithm::SHA1)
.with_digits(TOTP_DIGITS)
@@ -254,6 +279,31 @@ mod tests {
assert!(!verify_password(None, "correct horse battery staple"));
}
#[test]
fn rejects_repeated_character_and_all_digit_passwords() {
assert!(validate_password("aaaaaaaaaaaaaaaa").is_err(), "repeated");
assert!(validate_password("ãããããããããããããããã").is_err(), "repeated");
// Same repeated character, decomposed: must still be caught after NFC.
assert!(validate_password(&"a\u{0303}".repeat(14)).is_err());
assert!(validate_password("190283746501928").is_err(), "digits");
assert!(validate_password("١٢٣٤٥٦٧٨٩٠١٢٣").is_err(), "other digits");
assert!(validate_password("190283746501928x").is_ok());
assert!(validate_password("abababababababab").is_ok());
}
#[test]
fn password_is_nfc_normalized_everywhere() {
let composed = "maçã açaí pitanga";
let decomposed = "mac\u{0327}a\u{0303} ac\u{0327}ai\u{0301} pitanga";
assert_ne!(composed, decomposed);
let h = hash_password(decomposed).unwrap();
assert!(verify_password(Some(&h), composed));
let h = hash_password(composed).unwrap();
assert!(verify_password(Some(&h), decomposed));
// Length counts the normalized form: 11 composed characters.
assert!(validate_password("e\u{0301}xyzuvwklm1").is_err());
}
fn rfc_secret() -> &'static [u8] {
b"12345678901234567890"
}
+4 -1
View File
@@ -5,11 +5,14 @@
pub mod audit;
pub mod credentials;
pub mod secrets;
pub mod service;
pub mod store;
pub mod throttle;
pub use audit::{AuditEntry, AuditEvent, AuditLog};
pub use secrets::{hash_token, random_token, Secrets};
pub use store::{ApiToken, AuthState, AuthStore, Bootstrap, Session, User};
pub use service::{AuthService, LoginStep, NewSession, PendingMfa, TotpEnrollment};
pub use store::{ApiToken, AuthState, AuthStore, Bootstrap, Role, Session, User};
use crate::error::Result;
use fs2::FileExt;
+790
View File
@@ -0,0 +1,790 @@
//! 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, totp_uri_and_qr,
validate_password, verify_password, verify_totp,
};
use super::store::{AuthState, AuthStore, Bootstrap, Role, 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 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),
}
/// 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>)")
}
}
#[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,
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 {
AuthFailure::Throttled { retry_after_secs }.into()
}
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)
}
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> {
st.users.iter_mut().find(|u| u.id == id)
}
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) {
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> {
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.
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.
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()));
}
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,
});
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<NewSession> {
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<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(),
unknown: UnknownAccounts::default(),
auth_dir,
})
}
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.
pub fn complete_bootstrap(
&self,
code: &str,
username: &str,
password: &str,
now: u64,
) -> Result<PendingMfa> {
let name = validate_username(username)?;
validate_password(password)?;
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))? {
self.log("bootstrap.complete", None, None, false, None)?;
return Err(AuthFailure::BootstrapInvalid.into());
}
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, now)?))
})?;
let Some(pending) = done else {
self.log("bootstrap.complete", None, None, false, None)?;
return Err(AuthFailure::BootstrapInvalid.into());
};
self.log("bootstrap.complete", Some(&name), None, true, None)?;
Ok(pending)
}
fn seal_pending(&self, user_id: &str, epoch: u64, now: u64) -> Result<PendingMfa> {
let exp = now.saturating_add(PENDING_TTL_SECS);
let claims = PendingClaims {
purpose: PENDING_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, 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 != PENDING_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<LoginStep> {
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, now)?)
} else if u.role == Role::Admin {
LoginStep::MfaEnrollRequired(self.seal_pending(&id, epoch, 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",
};
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<NewSession> {
enum Outcome {
Done {
session: NewSession,
name: String,
method: &'static str,
},
Bad(String),
}
let claims = self.open_pending(pending, 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 session = complete_login(st, &claims.user_id, now)?;
Ok(Outcome::Done {
session,
name,
method,
})
})?;
match outcome {
Outcome::Bad(name) => {
self.log("mfa.confirm", Some(&name), None, false, None)?;
Err(invalid())
}
Outcome::Done {
session,
name,
method,
} => {
self.log("mfa.confirm", Some(&name), None, true, Some(method))?;
Ok(session)
}
}
}
/// 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, 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.
pub fn start_enrollment(&self, user_id: &str, _now: u64) -> Result<TotpEnrollment> {
let name = self
.store
.read(|st| {
st.users
.iter()
.find(|u| u.id == user_id)
.map(|u| u.username.clone())
})?
.ok_or(AuthFailure::UserNotFound)?;
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| {
user_or_missing(st, user_id)?.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.
pub fn confirm_enrollment(&self, user_id: &str, code: &str, now: u64) -> Result<Vec<String>> {
let (texts, hashes) = new_recovery_codes();
let (name, accepted) = self.store.update(|st| {
let u = user_or_missing(st, user_id)?;
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);
Ok((name, true))
})?;
self.log("mfa.enroll.confirm", Some(&name), None, accepted, None)?;
if !accepted {
return Err(invalid());
}
Ok(texts)
}
/// `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 {
u.role = role;
u.auth_epoch = u.auth_epoch.wrapping_add(1);
end_sessions(st, user_id, None);
}
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);
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)?;
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.auth_epoch = u.auth_epoch.wrapping_add(1);
end_sessions(st, user_id, keep_session_token);
Ok(true)
})?;
self.log("password.change", Some(&name), None, changed, None)?;
if !changed {
return Err(invalid());
}
Ok(())
}
/// 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);
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.
pub fn reset_admin(&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| u.role == Role::Admin && username_key(&u.username) == key)
else {
return Ok(None);
};
u.password_hash = password_hash;
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);
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;
+795
View File
@@ -0,0 +1,795 @@
use super::*;
use crate::auth::credentials::build_totp;
use crate::error::{AcauaError, AuthFailure};
use tempfile::TempDir;
const T0: u64 = 1_800_000_000;
const PW: &str = "correct horse battery staple";
const PW2: &str = "another long enough passphrase";
const WRONG: &str = "definitely not the passphrase";
fn ip() -> IpAddr {
"192.0.2.1".parse().unwrap()
}
fn svc() -> (TempDir, AuthService) {
let dir = tempfile::tempdir().unwrap();
let s = AuthService::open(dir.path(), None).unwrap();
(dir, s)
}
fn failure<T: std::fmt::Debug>(r: Result<T>) -> AuthFailure {
match r.unwrap_err() {
AcauaError::Auth(f) => f,
other => panic!("expected auth failure, got {other}"),
}
}
fn uid(s: &AuthService, name: &str) -> String {
s.store
.read(|st| {
st.users
.iter()
.find(|u| u.username == name)
.unwrap()
.id
.clone()
})
.unwrap()
}
fn sessions(s: &AuthService, id: &str) -> usize {
s.store
.read(|st| st.sessions.iter().filter(|x| x.user_id == id).count())
.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()
}
/// Enrolls `id`; returns recovery codes.
fn enroll(s: &AuthService, id: &str, now: u64) -> Vec<String> {
s.start_enrollment(id, now).unwrap();
let code = code_at(s, id, now);
s.confirm_enrollment(id, &code, now).unwrap()
}
/// First admin, enrolled. Returns its id.
fn admin(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
}
fn analyst(s: &AuthService, name: &str) -> String {
s.create_user("root", name, PW, Role::Analyst, T0).unwrap()
}
fn session_of(step: LoginStep) -> NewSession {
match step {
LoginStep::Session(x) => x,
other => panic!("expected session, got {other:?}"),
}
}
fn pending_of(step: LoginStep) -> PendingMfa {
match step {
LoginStep::MfaRequired(p) => p,
other => panic!("expected MfaRequired, got {other:?}"),
}
}
#[test]
fn bootstrap_code_single_use_and_expires() {
let (_d, s) = svc();
let code = s.ensure_bootstrap(T0).unwrap().unwrap();
assert_eq!(hash_token(&code).len(), 64);
// 128 bits in URL-safe base64.
assert_eq!(code.len(), 22);
assert_eq!(
failure(s.login("root", PW, ip(), T0)),
AuthFailure::SetupRequired
);
assert_eq!(
failure(s.complete_bootstrap("wrong", "root", PW, T0)),
AuthFailure::BootstrapInvalid
);
assert_eq!(
failure(s.complete_bootstrap(&code, "root", PW, T0 + 3601)),
AuthFailure::BootstrapInvalid
);
// A weak password does not burn the code.
assert!(matches!(
s.complete_bootstrap(&code, "root", "short", T0)
.unwrap_err(),
AcauaError::InvalidInput(_)
));
// Restart renews: the old code dies, the new one works.
let renewed = s.ensure_bootstrap(T0 + 10).unwrap().unwrap();
assert_ne!(renewed, code);
assert_eq!(
failure(s.complete_bootstrap(&code, "root", PW, T0 + 10)),
AuthFailure::BootstrapInvalid
);
s.complete_bootstrap(&renewed, "root", PW, T0 + 3610)
.unwrap();
assert_eq!(
failure(s.complete_bootstrap(&renewed, "other", PW, T0 + 3610)),
AuthFailure::BootstrapInvalid
);
assert_eq!(s.ensure_bootstrap(T0 + 3620).unwrap(), None);
assert!(s.has_admin().unwrap());
}
#[test]
fn bootstrap_code_is_consumed_once_under_concurrency() {
let (_d, s) = svc();
let code = s.ensure_bootstrap(T0).unwrap().unwrap();
let wins = std::thread::scope(|sc| {
let hs: Vec<_> = (0..4)
.map(|i| {
let (s, code) = (&s, &code);
sc.spawn(move || {
s.complete_bootstrap(code, &format!("adm{i}"), PW, T0)
.is_ok()
})
})
.collect();
hs.into_iter()
.map(|h| h.join().unwrap())
.filter(|ok| *ok)
.count()
});
assert_eq!(wins, 1);
assert_eq!(s.store.read(|st| st.users.len()).unwrap(), 1);
}
#[test]
fn admin_cannot_finish_login_without_mfa() {
let (_d, s) = svc();
let code = s.ensure_bootstrap(T0).unwrap().unwrap();
let boot = s.complete_bootstrap(&code, "root", PW, T0).unwrap();
let id = uid(&s, "root");
let LoginStep::MfaEnrollRequired(p) = s.login("root", PW, ip(), T0).unwrap() else {
panic!("admin must enroll");
};
assert_eq!(s.pending_user(&p.token, T0).unwrap(), id);
assert_eq!(s.pending_user(&boot.token, T0).unwrap(), id);
// No code can finish it before enrollment, not even with a started one.
assert_eq!(
failure(s.confirm_mfa(&p.token, "000000", T0)),
AuthFailure::InvalidCredentials
);
let e = s.start_enrollment(&id, T0).unwrap();
assert!(e.uri.starts_with("otpauth://totp/"));
assert!(!e.manual_key.is_empty() && e.uri.contains(&e.manual_key));
assert!(!e.qr_png_base64.is_empty());
let pending_code = code_at(&s, &id, T0);
assert_eq!(
failure(s.confirm_mfa(&p.token, &pending_code, T0)),
AuthFailure::InvalidCredentials
);
assert_eq!(sessions(&s, &id), 0);
let codes = s.confirm_enrollment(&id, &pending_code, T0).unwrap();
assert_eq!(codes.len(), 10);
assert_eq!(sessions(&s, &id), 0, "enrolling is not logging in");
// The enrollment step cannot be replayed; the next one finishes the login.
assert_eq!(
failure(s.confirm_mfa(&p.token, &pending_code, T0)),
AuthFailure::InvalidCredentials
);
let next = code_at(&s, &id, T0 + 60);
let session = s.confirm_mfa(&p.token, &next, T0 + 60).unwrap();
assert_eq!(session.user_id, id);
assert_eq!(sessions(&s, &id), 1);
// Once MFA is active a pending token gives no enrollment access.
assert_eq!(
failure(s.pending_user(&boot.token, T0 + 60)),
AuthFailure::InvalidCredentials
);
}
#[test]
fn analyst_without_mfa_gets_session_with_password() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
let n = session_of(s.login("ana", PW, ip(), T0).unwrap());
assert_eq!(n.user_id, id);
assert_eq!(n.expires_at, T0 + 43_200);
assert_eq!(n.token.len(), 43);
let raw = std::fs::read_to_string(s.auth_dir.join("state.json")).unwrap();
assert!(!raw.contains(&n.token));
assert!(raw.contains(&hash_token(&n.token)));
assert!(!format!("{n:?}").contains(&n.token));
}
#[test]
fn analyst_with_mfa_needs_code() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
enroll(&s, &id, T0);
let raw = std::fs::read_to_string(s.auth_dir.join("state.json")).unwrap();
let seed = s
.secrets
.open_sealed(
&s.store
.read(|st| st.users[1].totp_sealed.clone().unwrap())
.unwrap(),
)
.unwrap();
let b32 = s.start_enrollment(&id, T0).unwrap().manual_key;
assert!(!raw.contains(&b32) && !seed.is_empty());
let p = pending_of(s.login("ana", PW, ip(), T0 + 60).unwrap());
assert_eq!(p.expires_at, T0 + 60 + 300);
assert_eq!(sessions(&s, &id), 0);
assert_eq!(
failure(s.confirm_mfa(&p.token, "000000", T0 + 60)),
AuthFailure::InvalidCredentials
);
assert_eq!(
failure(s.confirm_mfa("garbage", "000000", T0 + 60)),
AuthFailure::InvalidCredentials
);
let good = code_at_active(&s, &id, T0 + 60);
// Expired pending token, even with a valid code for that moment.
let late = code_at_active(&s, &id, T0 + 361);
assert_eq!(
failure(s.confirm_mfa(&p.token, &late, T0 + 361)),
AuthFailure::InvalidCredentials
);
s.confirm_mfa(&p.token, &good, T0 + 60).unwrap();
assert_eq!(sessions(&s, &id), 1);
// Single use, and the same TOTP step cannot serve a second login.
let p2 = pending_of(s.login("ana", PW, ip(), T0 + 60).unwrap());
assert_eq!(
failure(s.confirm_mfa(&p2.token, &good, T0 + 60)),
AuthFailure::InvalidCredentials
);
let next = code_at_active(&s, &id, T0 + 90);
assert_eq!(
failure(s.confirm_mfa(&p.token, &next, T0 + 90)),
AuthFailure::InvalidCredentials,
"used pending token"
);
s.confirm_mfa(&p2.token, &next, T0 + 90).unwrap();
}
fn code_at_active(s: &AuthService, id: &str, unix: u64) -> String {
let sealed = s
.store
.read(|st| {
st.users
.iter()
.find(|u| u.id == id)
.unwrap()
.totp_sealed
.clone()
.unwrap()
})
.unwrap();
let secret = s.secrets.open_sealed(&sealed).unwrap();
build_totp(&secret, "x").unwrap().generate(unix).to_string()
}
#[test]
fn pending_token_is_void_after_password_change() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
enroll(&s, &id, T0);
let p = pending_of(s.login("ana", PW, ip(), T0 + 60).unwrap());
s.change_password(&id, PW, PW2, None, T0 + 60).unwrap();
let code = code_at_active(&s, &id, T0 + 60);
assert_eq!(
failure(s.confirm_mfa(&p.token, &code, T0 + 60)),
AuthFailure::InvalidCredentials
);
}
#[test]
fn promotion_requires_enrollment() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
session_of(s.login("ana", PW, ip(), T0).unwrap());
assert_eq!(sessions(&s, &id), 1);
s.set_role("root", &id, Role::Admin, T0).unwrap();
assert_eq!(sessions(&s, &id), 0);
assert!(matches!(
s.login("ana", PW, ip(), T0).unwrap(),
LoginStep::MfaEnrollRequired(_)
));
assert_eq!(sessions(&s, &id), 0);
}
#[test]
fn cannot_remove_last_admin() {
let (_d, s) = svc();
let root = admin(&s);
assert_eq!(
failure(s.delete_user("root", &root, T0)),
AuthFailure::LastAdmin
);
assert_eq!(
failure(s.set_role("root", &root, Role::Analyst, T0)),
AuthFailure::LastAdmin
);
assert_eq!(
failure(s.disable_mfa("root", &root, None, T0)),
AuthFailure::MfaMandatory
);
// With a second admin the first may go.
s.create_user("root", "second", PW, Role::Admin, T0)
.unwrap();
s.set_role("root", &root, Role::Analyst, T0).unwrap();
s.disable_mfa("root", &root, None, T0).unwrap();
s.delete_user("second", &root, T0).unwrap();
assert_eq!(
failure(s.delete_user("x", "no-such-id", T0)),
AuthFailure::UserNotFound
);
}
#[test]
fn recovery_code_replaces_totp_once() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
let codes = enroll(&s, &id, T0);
let raw = std::fs::read_to_string(s.auth_dir.join("state.json")).unwrap();
assert!(codes.iter().all(|c| !raw.contains(c.as_str())));
let p = pending_of(s.login("ana", PW, ip(), T0).unwrap());
// Canonicalized input is accepted.
s.confirm_mfa(&p.token, &codes[0].replace('-', " ").to_uppercase(), T0)
.unwrap();
let p = pending_of(s.login("ana", PW, ip(), T0).unwrap());
assert_eq!(
failure(s.confirm_mfa(&p.token, &codes[0], T0)),
AuthFailure::InvalidCredentials
);
s.confirm_mfa(&p.token, &codes[1], T0).unwrap();
}
#[test]
fn same_error_for_unknown_user_and_bad_password() {
let (_d, s) = svc();
admin(&s);
analyst(&s, "ana");
let unknown = failure(s.login("ghost", PW, ip(), T0));
let bad = failure(s.login("ana", WRONG, ip(), T0));
assert_eq!(unknown, AuthFailure::InvalidCredentials);
assert_eq!(unknown, bad);
assert_eq!(unknown.to_string(), bad.to_string());
// The throttle must not tell them apart either.
for _ in 0..4 {
let _ = s.login("ghost", PW, "192.0.2.2".parse().unwrap(), T0);
let _ = s.login("ana", WRONG, "192.0.2.2".parse().unwrap(), T0);
}
let unknown = failure(s.login("ghost", PW, "192.0.2.3".parse().unwrap(), T0));
let bad = failure(s.login("ana", WRONG, "192.0.2.3".parse().unwrap(), T0));
assert_eq!(
unknown,
AuthFailure::Throttled {
retry_after_secs: 30
}
);
assert_eq!(unknown, bad);
}
#[test]
fn account_throttle_delay_grows_capped() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
let mut now = T0;
for _ in 0..4 {
assert_eq!(
failure(s.login("ana", WRONG, ip(), now)),
AuthFailure::InvalidCredentials
);
}
assert_eq!(
failure(s.login("ana", WRONG, ip(), now)),
AuthFailure::InvalidCredentials
);
// Locked: even the right password is not evaluated.
assert_eq!(
failure(s.login("ana", PW, ip(), now)),
AuthFailure::Throttled {
retry_after_secs: 30
}
);
now += 31;
assert_eq!(
failure(s.login("ana", WRONG, ip(), now)),
AuthFailure::InvalidCredentials
);
assert_eq!(
failure(s.login("ana", WRONG, ip(), now)),
AuthFailure::Throttled {
retry_after_secs: 60
}
);
// Survives a restart and is capped.
s.store
.update(|st| {
st.users
.iter_mut()
.find(|u| u.id == id)
.unwrap()
.failed_attempts = 50;
Ok(())
})
.unwrap();
let dir = s.auth_dir.parent().unwrap().to_path_buf();
let s2 = AuthService::open(&dir, None).unwrap();
now += 61;
assert_eq!(
failure(s2.login("ana", WRONG, ip(), now)),
AuthFailure::InvalidCredentials
);
assert_eq!(
failure(s2.login("ana", PW, ip(), now)),
AuthFailure::Throttled {
retry_after_secs: 900
}
);
now += 901;
session_of(s2.login("ana", PW, ip(), now).unwrap());
let (f, l) = s2
.store
.read(|st| {
let u = st.users.iter().find(|u| u.id == id).unwrap();
(u.failed_attempts, u.locked_until)
})
.unwrap();
assert_eq!((f, l), (0, 0), "success clears the counter");
}
#[test]
fn bad_codes_count_towards_the_account_throttle() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
enroll(&s, &id, T0);
let p = pending_of(s.login("ana", PW, ip(), T0 + 60).unwrap());
for _ in 0..5 {
assert_eq!(
failure(s.confirm_mfa(&p.token, "000000", T0 + 60)),
AuthFailure::InvalidCredentials
);
}
let good = code_at_active(&s, &id, T0 + 60);
assert_eq!(
failure(s.confirm_mfa(&p.token, &good, T0 + 60)),
AuthFailure::Throttled {
retry_after_secs: 30
}
);
// A correct password alone does not wipe the MFA failures.
let f = |s: &AuthService| {
s.store
.read(|st| {
st.users
.iter()
.find(|u| u.id == id)
.unwrap()
.failed_attempts
})
.unwrap()
};
let p = pending_of(s.login("ana", PW, ip(), T0 + 91).unwrap());
assert_eq!(f(&s), 5);
let good = code_at_active(&s, &id, T0 + 91);
s.confirm_mfa(&p.token, &good, T0 + 91).unwrap();
assert_eq!(f(&s), 0);
}
#[test]
fn concurrent_guesses_cannot_outrun_the_account_throttle() {
let (_d, s) = svc();
admin(&s);
analyst(&s, "ana");
let evaluated = std::thread::scope(|sc| {
let hs: Vec<_> = (0..16u8)
.map(|i| {
let s = &s;
sc.spawn(move || {
let addr = IpAddr::from([192, 0, 2, 100 + i]);
s.login("ana", WRONG, addr, T0)
})
})
.collect();
hs.into_iter()
.map(|h| failure(h.join().unwrap()))
.filter(|f| *f == AuthFailure::InvalidCredentials)
.count()
});
assert_eq!(evaluated, 5);
}
#[test]
fn ip_throttle_blocks_after_20() {
let (_d, s) = svc();
admin(&s);
for _ in 0..19 {
s.ips.acquire(ip(), T0).unwrap();
}
assert_eq!(
failure(s.login("ghost1", WRONG, ip(), T0)),
AuthFailure::InvalidCredentials
);
assert_eq!(
failure(s.login("ghost2", WRONG, ip(), T0)),
AuthFailure::Throttled {
retry_after_secs: 900
}
);
let other: IpAddr = "192.0.2.9".parse().unwrap();
assert_eq!(
failure(s.login("ghost3", WRONG, other, T0)),
AuthFailure::InvalidCredentials
);
assert_eq!(
failure(s.login("ghost4", WRONG, ip(), T0 + 901)),
AuthFailure::InvalidCredentials
);
}
#[test]
fn successful_login_does_not_consume_ip_budget() {
let (_d, s) = svc();
admin(&s);
analyst(&s, "ana");
for _ in 0..19 {
s.ips.acquire(ip(), T0).unwrap();
}
session_of(s.login("ana", PW, ip(), T0).unwrap());
session_of(s.login("ana", PW, ip(), T0).unwrap());
}
#[test]
fn password_or_mfa_change_ends_other_sessions() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "ana");
let keep = session_of(s.login("ana", PW, ip(), T0).unwrap());
session_of(s.login("ana", PW, ip(), T0).unwrap());
assert_eq!(sessions(&s, &id), 2);
assert_eq!(
failure(s.change_password(&id, WRONG, PW2, Some(&keep.token), T0)),
AuthFailure::InvalidCredentials
);
assert_eq!(sessions(&s, &id), 2);
assert!(matches!(
s.change_password(&id, PW, "short", Some(&keep.token), T0)
.unwrap_err(),
AcauaError::InvalidInput(_)
));
s.change_password(&id, PW, PW2, Some(&keep.token), T0)
.unwrap();
let left = s
.store
.read(|st| {
st.sessions
.iter()
.filter(|x| x.user_id == id)
.map(|x| x.id.clone())
.collect::<Vec<_>>()
})
.unwrap();
assert_eq!(left, std::slice::from_ref(&keep.id));
assert_eq!(
failure(s.login("ana", PW, ip(), T0)),
AuthFailure::InvalidCredentials
);
// Enrolling ends every session: its signature has none to keep.
session_of(s.login("ana", PW2, ip(), T0).unwrap());
enroll(&s, &id, T0);
assert_eq!(sessions(&s, &id), 0);
// Disabling MFA keeps only the named session.
let p = pending_of(s.login("ana", PW2, ip(), T0 + 60).unwrap());
let a = s
.confirm_mfa(&p.token, &code_at_active(&s, &id, T0 + 60), T0 + 60)
.unwrap();
let p = pending_of(s.login("ana", PW2, ip(), T0 + 90).unwrap());
s.confirm_mfa(&p.token, &code_at_active(&s, &id, T0 + 90), T0 + 90)
.unwrap();
assert_eq!(sessions(&s, &id), 2);
s.disable_mfa("ana", &id, Some(&a.token), T0 + 90).unwrap();
assert_eq!(sessions(&s, &id), 1);
session_of(s.login("ana", PW2, ip(), T0 + 90).unwrap());
}
#[test]
fn usernames_are_validated_and_unique() {
let (_d, s) = svc();
admin(&s);
for bad in [
"",
"a:b",
"tab\tname",
"nul\0",
"line\nbreak",
" pad",
"pad ",
&"x".repeat(65),
] {
assert!(
matches!(
s.create_user("root", bad, PW, Role::Analyst, T0)
.unwrap_err(),
AcauaError::InvalidInput(_)
),
"{bad:?}"
);
}
let code_user = "joão.silva";
let id = analyst(&s, code_user);
s.start_enrollment(&id, T0).unwrap();
assert_eq!(
failure(s.create_user("root", "JOÃO.SILVA", PW, Role::Analyst, T0)),
AuthFailure::UsernameTaken
);
assert!(matches!(
s.create_user("root", "bob", "short", Role::Analyst, T0)
.unwrap_err(),
AcauaError::InvalidInput(_)
));
}
#[test]
fn login_accepts_any_unicode_form_and_case_of_username() {
let (_d, s) = svc();
admin(&s);
let id = analyst(&s, "joão");
assert_eq!(
session_of(s.login("JOA\u{0303}O", PW, ip(), T0).unwrap()).user_id,
id
);
}
#[test]
fn reset_admin_is_audited_and_forces_enrollment() {
let (_d, s) = svc();
let root = admin(&s);
session_of_any(&s, &root);
let temp = s.reset_admin("root", T0 + 200).unwrap();
assert_eq!(sessions(&s, &root), 0);
assert!(temp.len() >= 24);
assert_eq!(
failure(s.login("root", PW, ip(), T0 + 200)),
AuthFailure::InvalidCredentials
);
assert!(matches!(
s.login("root", &temp, ip(), T0 + 200).unwrap(),
LoginStep::MfaEnrollRequired(_)
));
assert_eq!(
failure(s.reset_admin("ghost", T0)),
AuthFailure::UserNotFound
);
analyst(&s, "ana");
assert_eq!(failure(s.reset_admin("ana", T0)), AuthFailure::UserNotFound);
let log = s.audit_tail(100).unwrap();
assert!(log
.iter()
.any(|e| e.event.action == "admin.reset" && e.event.ok));
let raw = std::fs::read_to_string(s.auth_dir.join("audit.jsonl")).unwrap();
assert!(!raw.contains(&temp));
}
fn session_of_any(s: &AuthService, id: &str) {
let p = pending_of(s.login("root", PW, ip(), T0 + 100).unwrap());
s.confirm_mfa(&p.token, &code_at_active(s, id, T0 + 100), T0 + 100)
.unwrap();
}
#[test]
fn audit_records_operations_without_secrets() {
let (_d, s) = svc();
let code = s.ensure_bootstrap(T0).unwrap().unwrap();
s.complete_bootstrap(&code, "root", PW, T0).unwrap();
let id = uid(&s, "root");
let codes = enroll(&s, &id, T0);
// A password typed into the username field must not reach the log.
let _ = s.login("my-secret-typed-as-name", WRONG, ip(), T0);
let _ = s.login("root", WRONG, ip(), T0);
let p = s.create_user("root", "ana", PW, Role::Analyst, T0).unwrap();
s.set_role("root", &p, Role::Admin, T0).unwrap();
s.set_role("root", &p, Role::Analyst, T0).unwrap();
s.change_password(&p, PW, PW2, None, T0).unwrap();
s.delete_user("root", &p, T0).unwrap();
let actions: Vec<String> = s
.audit_tail(100)
.unwrap()
.into_iter()
.map(|e| e.event.action)
.collect();
for want in [
"bootstrap.complete",
"mfa.enroll.start",
"mfa.enroll.confirm",
"login",
"user.create",
"user.role",
"password.change",
"user.delete",
] {
assert!(
actions.iter().any(|a| a == want),
"missing {want}: {actions:?}"
);
}
let raw = std::fs::read_to_string(s.auth_dir.join("audit.jsonl")).unwrap();
for secret in [
PW,
PW2,
WRONG,
code.as_str(),
codes[0].as_str(),
"my-secret-typed-as-name",
] {
assert!(!raw.contains(secret), "audit leaked {secret}");
}
}
#[test]
fn state_and_debug_hold_no_clear_secrets() {
let (_d, s) = svc();
admin(&s);
let u = s.store.read(|st| st.users[0].clone()).unwrap();
let dbg = format!("{u:?}");
assert!(!dbg.contains(&u.password_hash));
assert!(!dbg.contains(u.totp_sealed.as_deref().unwrap()));
let e = s.start_enrollment(&u.id, T0).unwrap();
let dbg = format!("{e:?}");
assert!(!dbg.contains(&e.manual_key) && !dbg.contains(&e.uri));
let raw = std::fs::read_to_string(s.auth_dir.join("state.json")).unwrap();
assert!(!raw.contains(&e.manual_key));
let p = s.login("root", PW, ip(), T0).unwrap();
let LoginStep::MfaRequired(p) = p else {
panic!()
};
assert!(!format!("{p:?}").contains(&p.token));
}
#[test]
fn open_fails_on_missing_key_without_touching_state() {
let dir = tempfile::tempdir().unwrap();
{
let s = AuthService::open(dir.path(), None).unwrap();
s.ensure_bootstrap(T0).unwrap();
}
let auth = dir.path().join("auth");
std::fs::remove_file(auth.join("secret.key")).unwrap();
let before = std::fs::read(auth.join("state.json")).unwrap();
assert_eq!(
failure(AuthService::open(dir.path(), None).map(|_| ())),
AuthFailure::KeyMissing
);
assert_eq!(std::fs::read(auth.join("state.json")).unwrap(), before);
}
+59 -6
View File
@@ -10,21 +10,73 @@ pub const STATE_VERSION: u32 = 1;
// Later tasks add fields; `#[serde(default)]` keeps older files readable.
// Unknown fields are ignored on read (and so dropped on rewrite).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
Admin,
/// The default is the least-privileged role.
#[default]
Analyst,
}
#[derive(Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct User {
pub id: String,
pub username: String,
pub created_at: String,
/// Unix seconds, like every timestamp here.
pub created_at: u64,
pub role: Role,
/// Argon2id PHC string.
pub password_hash: String,
/// Active TOTP secret, sealed with `Secrets`.
pub totp_sealed: Option<String>,
/// Secret awaiting its first code, sealed. Not usable to log in.
pub totp_pending_sealed: Option<String>,
/// Newest accepted TOTP step; a step is never accepted twice.
pub totp_last_step: Option<u64>,
/// SHA-256 hex of each unused recovery code.
pub recovery_hashes: Vec<String>,
/// Failures since the last completed login; survives restarts.
pub failed_attempts: u32,
/// No attempt is evaluated before this instant.
pub locked_until: u64,
/// Changes when the password changes and at each completed login, which
/// voids the pending MFA tokens issued before it.
pub auth_epoch: u64,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
impl std::fmt::Debug for User {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("User")
.field("id", &self.id)
.field("username", &self.username)
.field("role", &self.role)
.field("mfa", &self.totp_sealed.is_some())
.finish_non_exhaustive()
}
}
#[derive(Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Session {
pub id: String,
pub user_id: String,
pub created_at: String,
pub expires_at: String,
/// SHA-256 hex of the session token; the token itself is never stored.
pub token_hash: String,
pub created_at: u64,
pub last_seen: u64,
pub expires_at: u64,
}
impl std::fmt::Debug for Session {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Session")
.field("id", &self.id)
.field("user_id", &self.user_id)
.field("expires_at", &self.expires_at)
.finish_non_exhaustive()
}
}
#[derive(Clone, Default, Serialize, Deserialize)]
@@ -52,7 +104,8 @@ impl std::fmt::Debug for ApiToken {
#[serde(default)]
pub struct Bootstrap {
pub token_hash: String,
pub created_at: String,
/// Unix seconds.
pub created_at: u64,
}
impl std::fmt::Debug for Bootstrap {
+260
View File
@@ -0,0 +1,260 @@
//! Attempt limits: the per-account delay schedule, the in-memory IP limiter
//! and the in-memory stand-in that makes unknown usernames throttle exactly
//! like real accounts.
use std::collections::{HashMap, VecDeque};
use std::net::{IpAddr, Ipv6Addr};
use std::sync::{Mutex, MutexGuard};
pub const IP_MAX_FAILURES: usize = 20;
pub const IP_WINDOW_SECS: u64 = 900;
pub const ACCOUNT_DELAY_CAP_SECS: u64 = 900;
/// The failure count at which the delay starts.
const ACCOUNT_FREE_FAILURES: u32 = 5;
const ACCOUNT_DELAY_BASE_SECS: u64 = 30;
const IP_TABLE_CAPACITY: usize = 100_000;
const UNKNOWN_TABLE_CAPACITY: usize = 10_000;
/// Delay after `failures` failures: none before the 5th, then 30 s doubling
/// up to 900 s.
pub fn account_delay(failures: u32) -> u64 {
if failures < ACCOUNT_FREE_FAILURES {
return 0;
}
let doublings = failures - ACCOUNT_FREE_FAILURES;
ACCOUNT_DELAY_BASE_SECS
.checked_shl(doublings)
.filter(|d| doublings < 32 && *d < ACCOUNT_DELAY_CAP_SECS)
.unwrap_or(ACCOUNT_DELAY_CAP_SECS)
}
/// Instant until which an account with `failures` failures stays locked.
pub(super) fn lock_until(failures: u32, now: u64) -> u64 {
match account_delay(failures) {
0 => 0,
delay => now.saturating_add(delay),
}
}
fn guard<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
// The tables stay valid whatever a panicking holder did.
m.lock().unwrap_or_else(|e| e.into_inner())
}
/// One holder of an IPv6 /64 can use all of it, so the /64 is what counts; an
/// IPv4-mapped address is the IPv4 address.
fn ip_key(ip: IpAddr) -> IpAddr {
match ip {
IpAddr::V4(_) => ip,
IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
Some(v4) => IpAddr::V4(v4),
None => {
let s = v6.segments();
IpAddr::V6(Ipv6Addr::new(s[0], s[1], s[2], s[3], 0, 0, 0, 0))
}
},
}
}
/// Sliding window of failures per IP. Kept in memory: a restart clears it.
#[derive(Debug)]
pub struct IpLimiter {
capacity: usize,
table: Mutex<HashMap<IpAddr, VecDeque<u64>>>,
}
impl Default for IpLimiter {
fn default() -> Self {
Self::with_capacity(IP_TABLE_CAPACITY)
}
}
impl IpLimiter {
pub fn with_capacity(capacity: usize) -> Self {
Self {
capacity,
table: Mutex::new(HashMap::new()),
}
}
/// Takes a slot before the attempt runs, so parallel requests cannot all
/// pass the check. The slot stands as a failure unless `release`d.
/// `Err` carries the seconds until a slot frees.
pub fn acquire(&self, ip: IpAddr, now: u64) -> Result<(), u64> {
let key = ip_key(ip);
let mut table = guard(&self.table);
if !table.contains_key(&key) && table.len() >= self.capacity {
table.retain(|_, hits| hits.back().is_some_and(|t| t + IP_WINDOW_SECS > now));
if table.len() >= self.capacity {
let stalest = table
.iter()
.min_by_key(|(_, hits)| hits.back().copied().unwrap_or(0))
.map(|(k, _)| *k);
if let Some(k) = stalest {
table.remove(&k);
}
}
}
let hits = table.entry(key).or_default();
while hits.front().is_some_and(|t| t + IP_WINDOW_SECS <= now) {
hits.pop_front();
}
if hits.len() >= IP_MAX_FAILURES {
let oldest = hits.front().copied().unwrap_or(now);
return Err((oldest + IP_WINDOW_SECS).saturating_sub(now));
}
hits.push_back(now);
Ok(())
}
/// Returns the slot of an attempt that was not a failure.
pub fn release(&self, ip: IpAddr) {
let key = ip_key(ip);
let mut table = guard(&self.table);
if let Some(hits) = table.get_mut(&key) {
hits.pop_back();
if hits.is_empty() {
table.remove(&key);
}
}
}
#[cfg(test)]
fn tracked(&self) -> usize {
guard(&self.table).len()
}
}
#[derive(Debug, Clone, Copy)]
struct UnknownEntry {
failures: u32,
locked_until: u64,
last: u64,
}
/// Failure schedule for usernames with no account. Without it, only real
/// accounts would ever answer "throttled", which reveals who exists. Bounded
/// and in memory: an attacker must not be able to grow state on disk.
#[derive(Debug)]
pub struct UnknownAccounts {
capacity: usize,
table: Mutex<HashMap<String, UnknownEntry>>,
}
impl Default for UnknownAccounts {
fn default() -> Self {
Self::with_capacity(UNKNOWN_TABLE_CAPACITY)
}
}
impl UnknownAccounts {
pub fn with_capacity(capacity: usize) -> Self {
Self {
capacity,
table: Mutex::new(HashMap::new()),
}
}
/// Same contract as a real account: `Err` with the remaining delay, or
/// the attempt is counted as a failure.
pub fn acquire(&self, key: &str, now: u64) -> Result<(), u64> {
let mut table = guard(&self.table);
if !table.contains_key(key) && table.len() >= self.capacity {
let stalest = table
.iter()
.min_by_key(|(_, e)| e.last)
.map(|(k, _)| k.clone());
if let Some(k) = stalest {
table.remove(&k);
}
}
let entry = table.entry(key.to_string()).or_insert(UnknownEntry {
failures: 0,
locked_until: 0,
last: now,
});
entry.last = now;
if entry.locked_until > now {
return Err(entry.locked_until - now);
}
entry.failures = entry.failures.saturating_add(1);
entry.locked_until = lock_until(entry.failures, now);
Ok(())
}
#[cfg(test)]
fn tracked(&self) -> usize {
guard(&self.table).len()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn delay_starts_at_fifth_failure_grows_and_caps() {
let seq: Vec<u64> = (0..=12).map(account_delay).collect();
assert_eq!(seq, [0, 0, 0, 0, 0, 30, 60, 120, 240, 480, 900, 900, 900]);
assert_eq!(account_delay(u32::MAX), 900);
}
#[test]
fn ip_window_slides_and_release_returns_the_slot() {
let l = IpLimiter::default();
let ip: IpAddr = "198.51.100.7".parse().unwrap();
for i in 0..20 {
assert!(l.acquire(ip, 1000 + i).is_ok(), "attempt {i}");
}
assert_eq!(l.acquire(ip, 1100), Err(800));
assert!(l.acquire("198.51.100.8".parse().unwrap(), 1100).is_ok());
// The oldest failure (t=1000) leaves the window at t=1900.
assert!(l.acquire(ip, 1899).is_err());
assert!(l.acquire(ip, 1901).is_ok());
l.release(ip);
assert!(l.acquire(ip, 1901).is_ok());
}
#[test]
fn ipv6_is_grouped_by_64_and_mapped_v4_is_v4() {
let l = IpLimiter::default();
for i in 0..20u32 {
let ip: IpAddr = format!("2001:db8:1:2::{:x}", i + 1).parse().unwrap();
assert!(l.acquire(ip, 1000).is_ok());
}
assert!(l
.acquire("2001:db8:1:2:ffff::1".parse().unwrap(), 1000)
.is_err());
assert!(l.acquire("2001:db8:1:3::1".parse().unwrap(), 1000).is_ok());
let l = IpLimiter::default();
for _ in 0..20 {
l.acquire("::ffff:203.0.113.9".parse().unwrap(), 1000)
.unwrap();
}
assert!(l.acquire("203.0.113.9".parse().unwrap(), 1000).is_err());
}
#[test]
fn ip_table_stays_bounded() {
let l = IpLimiter::with_capacity(4);
for i in 0..50u8 {
let _ = l.acquire(IpAddr::from([10, 0, 0, i]), 1000 + u64::from(i));
}
assert!(l.tracked() <= 4);
}
#[test]
fn unknown_accounts_follow_the_account_schedule() {
let u = UnknownAccounts::default();
for _ in 0..4 {
assert!(u.acquire("k", 1000).is_ok());
}
assert!(u.acquire("k", 1000).is_ok(), "fifth attempt is evaluated");
assert_eq!(u.acquire("k", 1000), Err(30));
assert!(u.acquire("k", 1030).is_ok());
assert_eq!(u.acquire("k", 1030), Err(60));
}
#[test]
fn unknown_table_stays_bounded() {
let u = UnknownAccounts::with_capacity(3);
for i in 0..20u64 {
u.acquire(&format!("k{i}"), i).unwrap();
}
assert!(u.tracked() <= 3);
}
}