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

+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>)"
);
}
}