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

+3
View File
@@ -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"
+123
View File
@@ -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<String>,
pub ip: Option<String>,
pub ok: bool,
/// Short non-secret note.
pub detail: Option<String>,
}
#[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<Vec<AuditEntry>> {
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::<Vec<_>>(),
["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);
}
}
+63
View File
@@ -0,0 +1,63 @@
//! Authentication foundation: encrypted secrets, atomic state, audit log.
//!
//! Layout: `<data_dir>/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 `<dir>/.lock`, released on drop.
pub(crate) struct DirLock {
_file: File,
}
impl DirLock {
pub(crate) fn acquire(dir: &Path, exclusive: bool) -> Result<Self> {
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) {}
+207
View File
@@ -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(<redacted>)")
}
}
impl Secrets {
/// Loads the key from `key_file` (e.g. a Docker secret) or from
/// `<auth_dir>/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<Secrets> {
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<Secrets> {
let key: Vec<u8> = 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::<Aes256Gcm>::from_slice(&key)),
})
}
/// Returns base64(nonce || ciphertext+tag) with a fresh random nonce.
pub fn seal(&self, plain: &[u8]) -> Result<String> {
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<Vec<u8>> {
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(<redacted>)"
);
}
}
+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");
}
}
+21
View File
@@ -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<T> = std::result::Result<T, AcauaError>;
+2 -1
View File
@@ -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};