fix(auth): require state version, atomic key creation, torn audit lines

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-04 19:01:11 -03:00
1 parent ef25bf7eb1
commit c757db209d
3 files changed
+139 -20

No files matched your search

+60 -12
View File
@@ -1,4 +1,4 @@
use super::{ensure_dir, set_mode, KEY_FILE, STATE_FILE};
use super::{set_mode, DirLock, 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};
@@ -45,21 +45,46 @@ impl Secrets {
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)
Self::create_key(auth_dir, &path)
}
Err(e) => Err(e.into()),
}
}
/// First-run key creation, serialized by the dir lock. The key appears
/// atomically (temp file, fsync, hard link that never overwrites).
fn create_key(auth_dir: &Path, path: &Path) -> Result<Secrets> {
let _lock = DirLock::acquire(auth_dir, true)?;
// Recheck under the lock: another process may have won the race.
match fs::read(path) {
Ok(raw) => return Self::from_bytes(&raw),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
if auth_dir.join(STATE_FILE).exists() {
return Err(AuthFailure::KeyMissing.into());
}
let mut key = [0u8; KEY_LEN];
OsRng.fill_bytes(&mut key);
let tmp = auth_dir.join(format!("{KEY_FILE}.tmp"));
let _ = fs::remove_file(&tmp);
let mut opts = OpenOptions::new();
opts.write(true).create_new(true);
set_mode(&mut opts, 0o600);
let mut file = opts.open(&tmp)?;
let written = file
.write_all(STANDARD.encode(key).as_bytes())
.and_then(|_| file.sync_all());
drop(file);
let linked = written.and_then(|_| fs::hard_link(&tmp, path));
let _ = fs::remove_file(&tmp);
linked?;
if let Ok(d) = fs::File::open(auth_dir) {
let _ = d.sync_all();
}
Self::from_bytes(&key)
}
/// 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 {
@@ -164,7 +189,7 @@ mod tests {
);
let dir2 = tempfile::tempdir().unwrap();
fs::write(dir2.path().join(STATE_FILE), "{}").unwrap();
fs::write(dir2.path().join(STATE_FILE), r#"{"version":1}"#).unwrap();
let err = Secrets::open(dir2.path(), None).unwrap_err();
assert!(matches!(err, AcauaError::Auth(AuthFailure::KeyMissing)));
assert!(
@@ -173,6 +198,29 @@ mod tests {
);
}
#[test]
fn concurrent_first_open_agrees_on_one_key() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("auth");
let sealed: Vec<(String, Secrets)> = std::thread::scope(|sc| {
let hs: Vec<_> = (0..8)
.map(|_| {
sc.spawn(|| {
let s = Secrets::open(&path, None).unwrap();
(s.seal(b"v").unwrap(), s)
})
})
.collect();
hs.into_iter().map(|h| h.join().unwrap()).collect()
});
let reopened = Secrets::open(&path, None).unwrap();
for (sl, s) in &sealed {
assert_eq!(reopened.open_sealed(sl).unwrap(), b"v");
assert_eq!(s.open_sealed(sl).unwrap(), b"v");
}
assert!(!path.join("secret.key.tmp").exists());
}
#[test]
fn external_key_file_is_used_and_validated() {
let dir = tempfile::tempdir().unwrap();