fix(auth): close unauthenticated lockout and tighten the daemon's edges

Key login failures by username and client address with decay, plus a loose
per-username limit that delays every address by a bounded time. Refused
attempts write nothing. Unknown usernames share the code path. MFA and session
password checks keep a persistent user-bound count that needs a password or a
session to reach.

Also: local mode refuses a non-loopback bind outside a container; security
headers on every response; the Argon2 permit lives as long as the blocking
task; a required password change rechecks role, MFA and epoch; auth reset
works for any user; mfa_enabled in /api/auth/state; disabling MFA that is off
is refused with no side effects; StateCorrupt keeps only line and column.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-04 21:03:27 -03:00
1 parent 3e4c4201e5
commit 348e61ca95
10 files changed
+725 -199

No files matched your search

+89 -77
View File
@@ -11,7 +11,7 @@ use super::credentials::{
totp_uri_and_qr, validate_password, verify_password, verify_totp,
};
use super::store::{AuthState, AuthStore, Bootstrap, Role, Scope, Session, User};
use super::throttle::{lock_until, IpLimiter, UnknownAccounts};
use super::throttle::{decayed, lock_until, IpLimiter, LoginThrottle};
use super::{hash_token, random_token, AuditEntry, AuditEvent, AuditLog, Secrets};
use crate::error::{AcauaError, AuthFailure, Result};
use serde::{Deserialize, Serialize};
@@ -111,7 +111,7 @@ pub struct AuthService {
pub(super) secrets: Secrets,
pub(super) audit: AuditLog,
pub(super) ips: IpLimiter,
unknown: UnknownAccounts,
logins: LoginThrottle,
#[cfg_attr(not(test), allow(dead_code))]
pub(super) auth_dir: PathBuf,
}
@@ -173,8 +173,13 @@ pub(super) fn user_or_missing<'a>(st: &'a mut AuthState, id: &str) -> Result<&'a
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) {
u.failed_attempts = u.failed_attempts.saturating_add(1);
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);
}
@@ -246,6 +251,25 @@ fn complete_login(st: &mut AuthState, user_id: &str, now: u64) -> Result<NewSess
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,
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, now)
}
fn bootstrap_valid(st: &AuthState, code_hash: &str, now: u64) -> bool {
!has_admin(st)
&& st.bootstrap.as_ref().is_some_and(|b| {
@@ -273,7 +297,7 @@ impl AuthService {
secrets,
audit: AuditLog::open(&auth_dir),
ips: IpLimiter::default(),
unknown: UnknownAccounts::default(),
logins: LoginThrottle::default(),
auth_dir,
})
}
@@ -414,61 +438,44 @@ impl AuthService {
}
/// First factor. Unknown user and wrong password are indistinguishable:
/// same error, same Argon2 cost, same store write, same throttle schedule.
/// same error, same Argon2 cost, same throttle schedule, and no store write
/// for either. A refused attempt writes nothing at all.
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,
},
struct 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 found = self.store.read(|st| {
has_admin(st).then(|| {
st.users
.iter()
.find(|u| username_key(&u.username) == key)
.map(|u| 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),
let Some(found) = found else {
self.ips.release(ip);
return Err(AuthFailure::SetupRequired.into());
};
// The hash keeps a password typed into the wrong field out of memory.
let throttle_key = hash_token(&key);
if let Err(left) = self.logins.acquire(&throttle_key, ip, now) {
self.ips.release(ip);
return Err(throttled(left));
}
let Some(Known { id, name, hash }) = found else {
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());
};
if !verify_password(Some(&hash), password) {
self.log(
@@ -485,7 +492,6 @@ impl AuthService {
let Some(u) = user_mut(st, &id).filter(|u| u.password_hash == hash) else {
return Ok(None);
};
refund_attempt(u);
let epoch = u.auth_epoch;
let step = if u.totp_sealed.is_some() {
LoginStep::MfaRequired(self.seal_pending(&id, epoch, PENDING_PURPOSE, now)?)
@@ -514,6 +520,7 @@ impl AuthService {
return Err(invalid());
};
self.ips.release(ip);
self.logins.right_password(&throttle_key, ip);
let detail = match step {
LoginStep::Session(_) => "session",
LoginStep::MfaRequired(_) => "mfa required",
@@ -714,6 +721,15 @@ impl AuthService {
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| {
@@ -891,16 +907,12 @@ impl AuthService {
return Err(invalid());
}
self.change_password(&claims.user_id, current, new, None, now)?;
self.store.update(|st| {
let u = user_mut(st, &claims.user_id).ok_or_else(invalid)?;
if u.must_change_password {
return Err(invalid());
}
complete_login(st, &claims.user_id, now)
})
self.store
.update(|st| finish_required_change(st, &claims.user_id, claims.epoch, now))
}
/// Refused for administrators. Ends the other sessions.
/// 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,
@@ -913,6 +925,9 @@ impl AuthService {
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;
@@ -922,15 +937,18 @@ impl AuthService {
drop_admin_tokens(st, user_id);
Ok(name)
});
self.log_admin_result("mfa.disable", actor, &result)?;
if !matches!(result, Err(AcauaError::Auth(AuthFailure::MfaNotEnabled))) {
self.log_admin_result("mfa.disable", actor, &result)?;
}
result.map(|_| ())
}
/// Local recovery for an administrator who lost access: removes MFA and
/// sessions, clears the throttle, and returns a temporary password that
/// is shown once. The next login must enroll again and change the password
/// before any ordinary session.
pub fn reset_admin(&self, username: &str, _now: u64) -> Result<String> {
/// 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. Login
/// counts live in the daemon's memory and are not touched from here.
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)?;
@@ -938,7 +956,7 @@ impl AuthService {
let Some(u) = st
.users
.iter_mut()
.find(|u| u.role == Role::Admin && username_key(&u.username) == key)
.find(|u| username_key(&u.username) == key)
else {
return Ok(None);
};
@@ -957,16 +975,10 @@ impl AuthService {
Ok(Some(name))
})?;
let Some(name) = target else {
self.log("admin.reset", None, None, false, Some("no such admin"))?;
self.log("auth.reset", None, None, false, Some("no such user"))?;
return Err(AuthFailure::UserNotFound.into());
};
self.log(
"admin.reset",
Some(&name),
None,
true,
Some("local command"),
)?;
self.log("auth.reset", Some(&name), None, true, Some("local command"))?;
Ok(temp)
}
}