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:
1 parent
deea3e245b
commit
2b71ae41c0
9 files changed
+1998
-10
No files matched your search
@@ -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;
|
||||
Reference in new issue
Block a user