From ef25bf7eb176fb950d9b39fd3c9b143647b3803d Mon Sep 17 00:00:00 2001 From: Lucas Rayan Date: Wed, 4 Nov 2026 18:57:45 -0300 Subject: [PATCH] feat(auth): encrypted secrets, atomic state and audit log Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 124 ++++++++++++ crates/acaua-core/Cargo.toml | 3 + crates/acaua-core/src/auth/audit.rs | 123 ++++++++++++ crates/acaua-core/src/auth/mod.rs | 63 +++++++ crates/acaua-core/src/auth/secrets.rs | 207 ++++++++++++++++++++ crates/acaua-core/src/auth/store.rs | 261 ++++++++++++++++++++++++++ crates/acaua-core/src/error.rs | 21 +++ crates/acaua-core/src/lib.rs | 3 +- 8 files changed, 804 insertions(+), 1 deletion(-) create mode 100644 crates/acaua-core/src/auth/audit.rs create mode 100644 crates/acaua-core/src/auth/mod.rs create mode 100644 crates/acaua-core/src/auth/secrets.rs create mode 100644 crates/acaua-core/src/auth/store.rs diff --git a/Cargo.lock b/Cargo.lock index 31add81..5428cd0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -23,8 +23,11 @@ dependencies = [ name = "acaua-core" version = "0.2.0" dependencies = [ + "aes-gcm", + "base64 0.22.1", "chrono", "duckdb", + "fs2", "serde", "serde_json", "sha2 0.10.9", @@ -39,6 +42,41 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common 0.1.7", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + [[package]] name = "ahash" version = "0.8.12" @@ -456,6 +494,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout", +] + [[package]] name = "clap" version = "4.6.7" @@ -624,6 +672,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", + "rand_core", "typenum", ] @@ -636,6 +685,15 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + [[package]] name = "deranged" version = "0.5.9" @@ -756,6 +814,16 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" +dependencies = [ + "libc", + "winapi", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -832,6 +900,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + [[package]] name = "half" version = "2.7.1" @@ -996,6 +1074,15 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + [[package]] name = "is_terminal_polyfill" version = "1.70.2" @@ -1263,6 +1350,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + [[package]] name = "parking_lot" version = "0.12.5" @@ -1304,6 +1397,18 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + [[package]] name = "powerfmt" version = "0.2.1" @@ -1340,6 +1445,15 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -1990,6 +2104,16 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common 0.1.7", + "subtle", +] + [[package]] name = "untrusted" version = "0.9.0" diff --git a/crates/acaua-core/Cargo.toml b/crates/acaua-core/Cargo.toml index 0c39b1e..ef72436 100644 --- a/crates/acaua-core/Cargo.toml +++ b/crates/acaua-core/Cargo.toml @@ -19,6 +19,9 @@ chrono = { version = "0.4", default-features = false, features = ["std"] } # never enable `bundled`, `parquet`, `json` or `extensions-full`, which compile # DuckDB from source. Parquet, JSON and ICU are already inside libduckdb.so. duckdb = "~1.10506.1" +aes-gcm = "0.10" +base64 = "0.22" +fs2 = "0.4" [dev-dependencies] tempfile = "3" diff --git a/crates/acaua-core/src/auth/audit.rs b/crates/acaua-core/src/auth/audit.rs new file mode 100644 index 0000000..260648a --- /dev/null +++ b/crates/acaua-core/src/auth/audit.rs @@ -0,0 +1,123 @@ +use super::{set_mode, DirLock, AUDIT_FILE}; +use crate::error::{AcauaError, AuthFailure, Result}; +use serde::{Deserialize, Serialize}; +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use time::format_description::well_known::Rfc3339; +use time::OffsetDateTime; + +/// What happened. Deliberately has no field for passwords, tokens, codes or +/// keys: callers can only describe the event, never attach a secret. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct AuditEvent { + /// Machine-readable action, e.g. `login`, `token.create`. + pub action: String, + pub actor: Option, + pub ip: Option, + pub ok: bool, + /// Short non-secret note. + pub detail: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct AuditEntry { + pub ts: String, + #[serde(flatten)] + pub event: AuditEvent, +} + +#[derive(Debug, Clone)] +pub struct AuditLog { + dir: PathBuf, +} + +impl AuditLog { + pub fn open(dir: &Path) -> AuditLog { + AuditLog { + dir: dir.to_path_buf(), + } + } + + pub fn record(&self, event: AuditEvent) -> Result<()> { + let _lock = DirLock::acquire(&self.dir, true)?; + let ts = OffsetDateTime::now_utc() + .format(&Rfc3339) + .map_err(|e| AcauaError::InvalidInput(e.to_string()))?; + let mut line = serde_json::to_vec(&AuditEntry { ts, event })?; + line.push(b'\n'); + let mut opts = OpenOptions::new(); + opts.append(true).create(true); + set_mode(&mut opts, 0o600); + let mut file = opts.open(self.dir.join(AUDIT_FILE))?; + file.write_all(&line)?; + file.sync_all()?; + Ok(()) + } + + /// Last `limit` entries, oldest first. + pub fn tail(&self, limit: usize) -> Result> { + let _lock = DirLock::acquire(&self.dir, false)?; + let raw = match fs::read_to_string(self.dir.join(AUDIT_FILE)) { + Ok(raw) => raw, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(e) => return Err(e.into()), + }; + let lines: Vec<&str> = raw.lines().filter(|l| !l.trim().is_empty()).collect(); + let start = lines.len().saturating_sub(limit); + lines[start..] + .iter() + .map(|l| { + serde_json::from_str(l) + .map_err(|e| AcauaError::Auth(AuthFailure::AuditCorrupt(e.to_string()))) + }) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::os::unix::fs::PermissionsExt; + + #[test] + fn audit_appends_and_never_serializes_secret() { + let dir = tempfile::tempdir().unwrap(); + let log = AuditLog::open(dir.path()); + assert!(log.tail(5).unwrap().is_empty()); + for i in 0..3 { + log.record(AuditEvent { + action: format!("a{i}"), + actor: Some("ana".into()), + ok: i % 2 == 0, + ..Default::default() + }) + .unwrap(); + } + let all = log.tail(10).unwrap(); + assert_eq!( + all.iter() + .map(|e| e.event.action.as_str()) + .collect::>(), + ["a0", "a1", "a2"] + ); + let last = log.tail(2).unwrap(); + assert_eq!(last[0].event.action, "a1"); + assert!(!all[0].ts.is_empty()); + + let raw = fs::read_to_string(dir.path().join(AUDIT_FILE)).unwrap(); + assert_eq!(raw.lines().count(), 3); + for key in ["password", "secret", "token", "code", "key"] { + assert!( + !raw.contains(&format!("\"{key}\"")), + "unexpected field {key}" + ); + } + let mode = fs::metadata(dir.path().join(AUDIT_FILE)) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o777, 0o600); + } +} diff --git a/crates/acaua-core/src/auth/mod.rs b/crates/acaua-core/src/auth/mod.rs new file mode 100644 index 0000000..045f187 --- /dev/null +++ b/crates/acaua-core/src/auth/mod.rs @@ -0,0 +1,63 @@ +//! Authentication foundation: encrypted secrets, atomic state, audit log. +//! +//! Layout: `/auth/{state.json,secret.key,audit.jsonl,.lock}`. + +pub mod audit; +pub mod secrets; +pub mod store; + +pub use audit::{AuditEntry, AuditEvent, AuditLog}; +pub use secrets::{hash_token, random_token, Secrets}; +pub use store::{ApiToken, AuthState, AuthStore, Bootstrap, Session, User}; + +use crate::error::Result; +use fs2::FileExt; +use std::fs::{self, File, OpenOptions}; +use std::path::Path; + +pub(crate) const STATE_FILE: &str = "state.json"; +pub(crate) const KEY_FILE: &str = "secret.key"; +pub(crate) const AUDIT_FILE: &str = "audit.jsonl"; +pub(crate) const LOCK_FILE: &str = ".lock"; + +/// Advisory inter-process lock on `/.lock`, released on drop. +pub(crate) struct DirLock { + _file: File, +} + +impl DirLock { + pub(crate) fn acquire(dir: &Path, exclusive: bool) -> Result { + ensure_dir(dir)?; + let mut opts = OpenOptions::new(); + opts.read(true).write(true).create(true).truncate(false); + set_mode(&mut opts, 0o600); + let file = opts.open(dir.join(LOCK_FILE))?; + if exclusive { + FileExt::lock_exclusive(&file)?; + } else { + FileExt::lock_shared(&file)?; + } + Ok(Self { _file: file }) + } +} + +pub(crate) fn ensure_dir(dir: &Path) -> Result<()> { + if !dir.is_dir() { + fs::create_dir_all(dir)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(dir, fs::Permissions::from_mode(0o700))?; + } + } + Ok(()) +} + +#[cfg(unix)] +pub(crate) fn set_mode(opts: &mut OpenOptions, mode: u32) { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(mode); +} + +#[cfg(not(unix))] +pub(crate) fn set_mode(_opts: &mut OpenOptions, _mode: u32) {} diff --git a/crates/acaua-core/src/auth/secrets.rs b/crates/acaua-core/src/auth/secrets.rs new file mode 100644 index 0000000..ad5cb56 --- /dev/null +++ b/crates/acaua-core/src/auth/secrets.rs @@ -0,0 +1,207 @@ +use super::{ensure_dir, set_mode, KEY_FILE, STATE_FILE}; +use crate::error::{AcauaError, AuthFailure, Result}; +use aes_gcm::aead::{rand_core::RngCore, Aead, AeadCore, KeyInit, OsRng}; +use aes_gcm::{Aes256Gcm, Key, Nonce}; +use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; +use base64::Engine; +use sha2::{Digest, Sha256}; +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::path::Path; + +const KEY_LEN: usize = 32; +const NONCE_LEN: usize = 12; + +/// AES-256-GCM sealing of small secrets (TOTP seeds and similar). +pub struct Secrets { + cipher: Aes256Gcm, +} + +impl std::fmt::Debug for Secrets { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Secrets()") + } +} + +impl Secrets { + /// Loads the key from `key_file` (e.g. a Docker secret) or from + /// `/secret.key`. A new key is generated only when no auth state + /// exists yet; a missing key next to existing state is an error. + pub fn open(auth_dir: &Path, key_file: Option<&Path>) -> Result { + if let Some(path) = key_file { + let raw = fs::read(path).map_err(|e| { + if e.kind() == std::io::ErrorKind::NotFound { + AcauaError::Auth(AuthFailure::KeyMissing) + } else { + AcauaError::Io(e) + } + })?; + return Self::from_bytes(&raw); + } + let path = auth_dir.join(KEY_FILE); + match fs::read(&path) { + Ok(raw) => Self::from_bytes(&raw), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + if auth_dir.join(STATE_FILE).exists() { + return Err(AuthFailure::KeyMissing.into()); + } + ensure_dir(auth_dir)?; + let mut key = [0u8; KEY_LEN]; + OsRng.fill_bytes(&mut key); + let mut opts = OpenOptions::new(); + opts.write(true).create_new(true); + set_mode(&mut opts, 0o600); + let mut file = opts.open(&path)?; + file.write_all(STANDARD.encode(key).as_bytes())?; + file.sync_all()?; + Self::from_bytes(&key) + } + Err(e) => Err(e.into()), + } + } + + /// Accepts the key as raw 32 bytes or as base64 text (whitespace trimmed). + fn from_bytes(raw: &[u8]) -> Result { + let key: Vec = if raw.len() == KEY_LEN { + raw.to_vec() + } else { + let text = std::str::from_utf8(raw) + .map_err(|_| AuthFailure::KeyInvalid("not raw 32 bytes nor base64 text"))?; + STANDARD + .decode(text.trim()) + .map_err(|_| AuthFailure::KeyInvalid("not raw 32 bytes nor base64 text"))? + }; + if key.len() != KEY_LEN { + return Err(AuthFailure::KeyInvalid("must be 32 bytes").into()); + } + Ok(Secrets { + cipher: Aes256Gcm::new(Key::::from_slice(&key)), + }) + } + + /// Returns base64(nonce || ciphertext+tag) with a fresh random nonce. + pub fn seal(&self, plain: &[u8]) -> Result { + let nonce = Aes256Gcm::generate_nonce(&mut OsRng); + let ct = self + .cipher + .encrypt(&nonce, plain) + .map_err(|_| AuthFailure::SealInvalid)?; + let mut out = nonce.to_vec(); + out.extend_from_slice(&ct); + Ok(STANDARD.encode(out)) + } + + pub fn open_sealed(&self, sealed: &str) -> Result> { + let raw = STANDARD + .decode(sealed.trim()) + .map_err(|_| AuthFailure::SealInvalid)?; + if raw.len() < NONCE_LEN + 16 { + return Err(AuthFailure::SealInvalid.into()); + } + let (nonce, ct) = raw.split_at(NONCE_LEN); + self.cipher + .decrypt(Nonce::from_slice(nonce), ct) + .map_err(|_| AuthFailure::SealInvalid.into()) + } +} + +/// URL-safe base64 (no padding) of `bytes` random bytes from the OS CSPRNG. +/// An OS RNG failure is unrecoverable and aborts, as in `OsRng::fill_bytes`. +pub fn random_token(bytes: usize) -> String { + let mut buf = vec![0u8; bytes]; + OsRng.fill_bytes(&mut buf); + URL_SAFE_NO_PAD.encode(buf) +} + +/// Hex SHA-256 of a token; only this digest is ever stored. +pub fn hash_token(token: &str) -> String { + Sha256::digest(token.as_bytes()) + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::os::unix::fs::PermissionsExt; + + #[test] + fn seal_roundtrip_and_tamper_rejected() { + let dir = tempfile::tempdir().unwrap(); + let s = Secrets::open(dir.path(), None).unwrap(); + let sealed = s.seal(b"totp-seed").unwrap(); + assert_ne!(sealed, s.seal(b"totp-seed").unwrap(), "nonce must vary"); + assert_eq!(s.open_sealed(&sealed).unwrap(), b"totp-seed"); + + let mut raw = STANDARD.decode(&sealed).unwrap(); + let last = raw.len() - 1; + raw[last] ^= 1; + assert!(s.open_sealed(&STANDARD.encode(raw)).is_err()); + assert!(s.open_sealed("not base64!").is_err()); + assert!(s.open_sealed("").is_err()); + let other = Secrets::open(tempfile::tempdir().unwrap().path(), None).unwrap(); + assert!(other.open_sealed(&sealed).is_err()); + } + + #[test] + fn key_file_created_0600_and_missing_key_with_state_fails() { + let dir = tempfile::tempdir().unwrap(); + let a = Secrets::open(dir.path(), None).unwrap(); + let mode = fs::metadata(dir.path().join(KEY_FILE)) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o777, 0o600); + // Reopen yields the same key. + let sealed = a.seal(b"x").unwrap(); + assert_eq!( + Secrets::open(dir.path(), None) + .unwrap() + .open_sealed(&sealed) + .unwrap(), + b"x" + ); + + let dir2 = tempfile::tempdir().unwrap(); + fs::write(dir2.path().join(STATE_FILE), "{}").unwrap(); + let err = Secrets::open(dir2.path(), None).unwrap_err(); + assert!(matches!(err, AcauaError::Auth(AuthFailure::KeyMissing))); + assert!( + !dir2.path().join(KEY_FILE).exists(), + "must not recreate the key" + ); + } + + #[test] + fn external_key_file_is_used_and_validated() { + let dir = tempfile::tempdir().unwrap(); + let kf = dir.path().join("docker-secret"); + fs::write(&kf, format!("{}\n", STANDARD.encode([7u8; 32]))).unwrap(); + let s = Secrets::open(dir.path(), Some(&kf)).unwrap(); + assert_eq!(s.open_sealed(&s.seal(b"a").unwrap()).unwrap(), b"a"); + assert!(!dir.path().join(KEY_FILE).exists()); + + fs::write(&kf, "short").unwrap(); + assert!(Secrets::open(dir.path(), Some(&kf)).is_err()); + let missing = dir.path().join("nope"); + assert!(Secrets::open(dir.path(), Some(&missing)).is_err()); + } + + #[test] + fn tokens_are_random_and_hash_is_stable() { + assert_ne!(random_token(32), random_token(32)); + assert_eq!(random_token(32).len(), 43); + assert_eq!( + hash_token("abc"), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + assert_eq!( + format!( + "{:?}", + Secrets::open(tempfile::tempdir().unwrap().path(), None).unwrap() + ), + "Secrets()" + ); + } +} diff --git a/crates/acaua-core/src/auth/store.rs b/crates/acaua-core/src/auth/store.rs new file mode 100644 index 0000000..1de71b6 --- /dev/null +++ b/crates/acaua-core/src/auth/store.rs @@ -0,0 +1,261 @@ +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, Default, Serialize, Deserialize)] +#[serde(default)] +pub struct User { + pub id: String, + pub username: String, + pub created_at: String, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(default)] +pub struct Session { + pub id: String, + pub user_id: String, + pub created_at: String, + pub expires_at: String, +} + +#[derive(Clone, Default, Serialize, Deserialize)] +#[serde(default)] +pub struct ApiToken { + pub id: String, + pub name: String, + /// SHA-256 hex of the token; the token itself is never stored. + pub token_hash: String, + pub created_at: String, + pub expires_at: Option, +} + +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", &"") + .finish_non_exhaustive() + } +} + +#[derive(Clone, Default, Serialize, Deserialize)] +#[serde(default)] +pub struct Bootstrap { + pub token_hash: String, + pub created_at: String, +} + +impl std::fmt::Debug for Bootstrap { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Bootstrap") + .field("token_hash", &"") + .finish_non_exhaustive() + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(default)] +pub struct AuthState { + pub version: u32, + pub users: Vec, + pub sessions: Vec, + pub tokens: Vec, + pub bootstrap: Option, +} + +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 { + let store = AuthStore { + dir: dir.to_path_buf(), + }; + store.read(|_| ())?; + Ok(store) + } + + pub fn read(&self, f: impl FnOnce(&AuthState) -> T) -> Result { + 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(&self, f: impl FnOnce(&mut AuthState) -> Result) -> Result { + 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 { + 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| AcauaError::Auth(AuthFailure::StateCorrupt(e.to_string())))?; + 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 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"); + } +} diff --git a/crates/acaua-core/src/error.rs b/crates/acaua-core/src/error.rs index 57e68fa..2217c00 100644 --- a/crates/acaua-core/src/error.rs +++ b/crates/acaua-core/src/error.rs @@ -19,6 +19,27 @@ pub enum AcauaError { #[error("database error: {0}")] Database(#[from] duckdb::Error), + + #[error("authentication error: {0}")] + Auth(#[from] AuthFailure), +} + +/// Every refusal the authentication layer can raise. Variants never carry +/// secret material, only a description of what went wrong. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum AuthFailure { + #[error("secret key is missing while auth state already exists")] + KeyMissing, + #[error("secret key is invalid: {0}")] + KeyInvalid(&'static str), + #[error("sealed value is malformed or failed authentication")] + SealInvalid, + #[error("auth state is corrupted: {0}")] + StateCorrupt(String), + #[error("auth state version {0} is not supported")] + StateVersionUnsupported(u32), + #[error("audit log is corrupted: {0}")] + AuditCorrupt(String), } pub type Result = std::result::Result; diff --git a/crates/acaua-core/src/lib.rs b/crates/acaua-core/src/lib.rs index 080bb76..bca09ec 100644 --- a/crates/acaua-core/src/lib.rs +++ b/crates/acaua-core/src/lib.rs @@ -1,3 +1,4 @@ +pub mod auth; pub mod dns_store; pub mod doctor; pub mod error; @@ -11,4 +12,4 @@ pub mod storage; pub mod update; pub mod zeek; -pub use error::{AcauaError, Result}; +pub use error::{AcauaError, AuthFailure, Result};