feat(auth): encrypted secrets, atomic state and audit log

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-04 18:57:45 -03:00
1 parent 0a5fdda0ba
commit ef25bf7eb1
8 files changed
+804 -1

No files matched your search

+261
View File
@@ -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<String>,
}
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,
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", &"<redacted>")
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AuthState {
pub version: u32,
pub users: Vec<User>,
pub sessions: Vec<Session>,
pub tokens: Vec<ApiToken>,
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| 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");
}
}