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

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

387 lines
13 KiB
Rust

use super::{set_mode, DirLock, STATE_FILE};
use crate::error::{AcauaError, AuthFailure, Result};
use serde::{Deserialize, Serialize};
use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
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, 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,
/// 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>,
/// MFA and session-password failures since the last completed login; one
/// is forgotten per 900 s. Wrong login passwords are not counted here: see
/// `throttle::LoginThrottle`.
pub failed_attempts: u32,
/// Start of the current decay period of `failed_attempts`.
pub failed_at: u64,
/// No MFA code or session password 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,
/// Set by `reset_account`: no ordinary session until the password changes.
pub must_change_password: bool,
/// Addresses of recent completed logins, for `throttle`'s budget exception.
/// Hashes only: never a raw address.
pub known_addresses: Vec<KnownAddress>,
/// Login failures from unknown addresses, as last written. The daemon's
/// memory leads this by at most a minute.
pub budget_failures: u32,
/// Start of the current decay period of `budget_failures`.
pub budget_at: u64,
/// When `login.budget_exhausted` was last audited for this account.
pub budget_audited_at: u64,
/// Moved by `reset_account`, which may run in another process: the daemon
/// drops what it holds in memory for this account when this changes.
pub budget_generation: u64,
}
/// A hashed address prefix and when a login from it last completed.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct KnownAddress {
pub hash: String,
pub last_seen: u64,
}
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,
/// 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,
/// Unix seconds of the last `reauthenticate` of this session; 0 if never.
pub last_reauth: 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()
}
}
/// How much an API token may do. `Read` < `Admin`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Scope {
#[default]
Read,
Admin,
}
#[derive(Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct ApiToken {
pub id: String,
pub user_id: String,
pub name: String,
/// SHA-256 hex of the token; the token itself is never stored.
pub token_hash: String,
pub scope: Scope,
/// Unix seconds.
pub created_at: u64,
/// Unix seconds; every token expires.
pub expires_at: u64,
}
impl std::fmt::Debug for ApiToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ApiToken")
.field("id", &self.id)
.field("name", &self.name)
.field("token_hash", &"<redacted>")
.finish_non_exhaustive()
}
}
#[derive(Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Bootstrap {
pub token_hash: String,
/// Unix seconds.
pub created_at: u64,
}
impl std::fmt::Debug for Bootstrap {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Bootstrap")
.field("token_hash", &"<redacted>")
.finish_non_exhaustive()
}
}
/// `version` is required: `{}` or an unrelated JSON object must not load as an
/// empty state that the next update would overwrite.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthState {
pub version: u32,
#[serde(default)]
pub users: Vec<User>,
#[serde(default)]
pub sessions: Vec<Session>,
#[serde(default)]
pub tokens: Vec<ApiToken>,
#[serde(default)]
pub bootstrap: Option<Bootstrap>,
}
impl Default for AuthState {
fn default() -> Self {
Self {
version: STATE_VERSION,
users: Vec::new(),
sessions: Vec::new(),
tokens: Vec::new(),
bootstrap: None,
}
}
}
/// File-backed state. Every operation takes the directory lock and rereads
/// `state.json`, so several processes or instances stay coherent.
#[derive(Debug, Clone)]
pub struct AuthStore {
dir: PathBuf,
}
impl AuthStore {
/// Opens (creating the directory if needed) and validates existing state.
/// Corrupted state is an error and is never overwritten.
pub fn open(dir: &Path) -> Result<AuthStore> {
let store = AuthStore {
dir: dir.to_path_buf(),
};
store.read(|_| ())?;
Ok(store)
}
pub fn read<T>(&self, f: impl FnOnce(&AuthState) -> T) -> Result<T> {
let _lock = DirLock::acquire(&self.dir, false)?;
let state = self.load()?;
Ok(f(&state))
}
/// Runs `f` on a copy under an exclusive lock; the copy is persisted
/// atomically only if `f` returns `Ok`.
pub fn update<T>(&self, f: impl FnOnce(&mut AuthState) -> Result<T>) -> Result<T> {
let _lock = DirLock::acquire(&self.dir, true)?;
let mut state = self.load()?;
let out = f(&mut state)?;
state.version = STATE_VERSION;
self.persist(&state)?;
Ok(out)
}
fn load(&self) -> Result<AuthState> {
let raw = match fs::read(self.dir.join(STATE_FILE)) {
Ok(raw) => raw,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(AuthState::default()),
Err(e) => return Err(e.into()),
};
let state: AuthState = serde_json::from_slice(&raw).map_err(|e| {
// Serde's message can quote the file, which holds hashes and
// sealed secrets: the position is enough to find the damage.
AcauaError::Auth(AuthFailure::StateCorrupt(format!(
"invalid JSON at line {}, column {}",
e.line(),
e.column()
)))
})?;
if state.version == 0 || state.version > STATE_VERSION {
return Err(AuthFailure::StateVersionUnsupported(state.version).into());
}
Ok(state)
}
fn persist(&self, state: &AuthState) -> Result<()> {
let tmp = self.dir.join(format!("{STATE_FILE}.tmp"));
let data = serde_json::to_vec_pretty(state)?;
let mut opts = OpenOptions::new();
opts.write(true).create(true).truncate(true);
set_mode(&mut opts, 0o600);
let mut file = opts.open(&tmp)?;
let written = file.write_all(&data).and_then(|_| file.sync_all());
drop(file);
if let Err(e) = written.and_then(|_| fs::rename(&tmp, self.dir.join(STATE_FILE))) {
let _ = fs::remove_file(&tmp);
return Err(e.into());
}
// Persist the rename itself.
if let Ok(d) = File::open(&self.dir) {
let _ = d.sync_all();
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::unix::fs::PermissionsExt;
fn user(name: &str) -> User {
User {
id: name.into(),
username: name.into(),
..Default::default()
}
}
#[test]
fn state_file_is_0600_and_atomic() {
let dir = tempfile::tempdir().unwrap();
let store = AuthStore::open(dir.path()).unwrap();
store
.update(|s| {
s.users.push(user("ana"));
Ok(())
})
.unwrap();
let mode = fs::metadata(dir.path().join(STATE_FILE))
.unwrap()
.permissions()
.mode();
assert_eq!(mode & 0o777, 0o600);
assert!(!dir.path().join("state.json.tmp").exists());
assert_eq!(store.read(|s| s.users.len()).unwrap(), 1);
}
#[test]
fn corrupted_state_fails_closed() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(STATE_FILE);
fs::write(&path, "{not json").unwrap();
let err = AuthStore::open(dir.path()).unwrap_err();
assert!(matches!(
err,
AcauaError::Auth(AuthFailure::StateCorrupt(_))
));
let store = AuthStore {
dir: dir.path().to_path_buf(),
};
assert!(store.update(|_| Ok(())).is_err());
assert_eq!(fs::read_to_string(&path).unwrap(), "{not json");
}
#[test]
fn state_without_version_fails_closed() {
for body in ["{}", r#"{"foo":1}"#, r#"{"users":[]}"#, "[]", "null"] {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(STATE_FILE);
fs::write(&path, body).unwrap();
assert!(matches!(
AuthStore::open(dir.path()).unwrap_err(),
AcauaError::Auth(AuthFailure::StateCorrupt(_))
));
let store = AuthStore {
dir: dir.path().to_path_buf(),
};
assert!(store.update(|_| Ok(())).is_err());
assert_eq!(fs::read_to_string(&path).unwrap(), body);
}
}
#[test]
fn future_version_rejected() {
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join(STATE_FILE), r#"{"version":99}"#).unwrap();
assert!(matches!(
AuthStore::open(dir.path()).unwrap_err(),
AcauaError::Auth(AuthFailure::StateVersionUnsupported(99))
));
}
#[test]
fn update_failure_keeps_state() {
let dir = tempfile::tempdir().unwrap();
let store = AuthStore::open(dir.path()).unwrap();
store
.update(|s| {
s.users.push(user("ana"));
Ok(())
})
.unwrap();
let before = fs::read(dir.path().join(STATE_FILE)).unwrap();
let r: Result<()> = store.update(|s| {
s.users.push(user("bob"));
Err(AcauaError::InvalidInput("nope".into()))
});
assert!(r.is_err());
assert_eq!(fs::read(dir.path().join(STATE_FILE)).unwrap(), before);
assert_eq!(store.read(|s| s.users.len()).unwrap(), 1);
}
#[test]
fn external_change_is_seen() {
let dir = tempfile::tempdir().unwrap();
let a = AuthStore::open(dir.path()).unwrap();
let b = AuthStore::open(dir.path()).unwrap();
a.update(|s| {
s.users.push(user("ana"));
Ok(())
})
.unwrap();
assert_eq!(b.read(|s| s.users[0].username.clone()).unwrap(), "ana");
}
#[test]
fn older_files_with_missing_fields_load() {
let dir = tempfile::tempdir().unwrap();
fs::write(
dir.path().join(STATE_FILE),
r#"{"version":1,"users":[{"id":"u1"}]}"#,
)
.unwrap();
let store = AuthStore::open(dir.path()).unwrap();
assert_eq!(store.read(|s| s.users[0].id.clone()).unwrap(), "u1");
}
}