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:
1 parent
ef25bf7eb1
commit
c757db209d
3 files changed
+139
-20
No files matched your search
@@ -1,5 +1,8 @@
|
||||
use super::{set_mode, DirLock, AUDIT_FILE};
|
||||
use crate::error::{AcauaError, AuthFailure, Result};
|
||||
use crate::error::{AcauaError, Result};
|
||||
|
||||
/// Action of the synthetic entry `tail` emits for an unparseable line.
|
||||
pub const CORRUPT_ACTION: &str = "audit.corrupt_line";
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs::{self, OpenOptions};
|
||||
use std::io::Write;
|
||||
@@ -50,7 +53,15 @@ impl AuditLog {
|
||||
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))?;
|
||||
let path = self.dir.join(AUDIT_FILE);
|
||||
// A crash can leave an unterminated fragment; close it so the new
|
||||
// entry starts on its own line. `tail` reports the fragment.
|
||||
if let Ok(existing) = fs::read(&path) {
|
||||
if existing.last().is_some_and(|b| *b != b'\n') {
|
||||
line.insert(0, b'\n');
|
||||
}
|
||||
}
|
||||
let mut file = opts.open(&path)?;
|
||||
file.write_all(&line)?;
|
||||
file.sync_all()?;
|
||||
Ok(())
|
||||
@@ -66,13 +77,23 @@ impl AuditLog {
|
||||
};
|
||||
let lines: Vec<&str> = raw.lines().filter(|l| !l.trim().is_empty()).collect();
|
||||
let start = lines.len().saturating_sub(limit);
|
||||
lines[start..]
|
||||
// A torn line does not fail the read: it is surfaced as a visible
|
||||
// `audit.corrupt_line` entry (ok = false) at its position.
|
||||
Ok(lines[start..]
|
||||
.iter()
|
||||
.map(|l| {
|
||||
serde_json::from_str(l)
|
||||
.map_err(|e| AcauaError::Auth(AuthFailure::AuditCorrupt(e.to_string())))
|
||||
.enumerate()
|
||||
.map(|(i, l)| {
|
||||
serde_json::from_str(l).unwrap_or_else(|_| AuditEntry {
|
||||
ts: String::new(),
|
||||
event: AuditEvent {
|
||||
action: CORRUPT_ACTION.into(),
|
||||
ok: false,
|
||||
detail: Some(format!("unparseable audit line #{}", start + i + 1)),
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,4 +141,31 @@ mod tests {
|
||||
.mode();
|
||||
assert_eq!(mode & 0o777, 0o600);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn torn_line_is_reported_and_next_record_is_separate() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let log = AuditLog::open(dir.path());
|
||||
let ev = |a: &str| AuditEvent {
|
||||
action: a.into(),
|
||||
ok: true,
|
||||
..Default::default()
|
||||
};
|
||||
log.record(ev("a0")).unwrap();
|
||||
let path = dir.path().join(AUDIT_FILE);
|
||||
let mut f = OpenOptions::new().append(true).open(&path).unwrap();
|
||||
f.write_all(br#"{"ts":"2026-01-01T00:0"#).unwrap();
|
||||
drop(f);
|
||||
// Reading over the fragment works and flags it.
|
||||
let t = log.tail(10).unwrap();
|
||||
assert_eq!(t.len(), 2);
|
||||
assert_eq!(t[1].event.action, CORRUPT_ACTION);
|
||||
assert!(!t[1].event.ok);
|
||||
// The next record must not join the fragment.
|
||||
log.record(ev("a1")).unwrap();
|
||||
let t = log.tail(10).unwrap();
|
||||
let actions: Vec<_> = t.iter().map(|e| e.event.action.as_str()).collect();
|
||||
assert_eq!(actions, ["a0", CORRUPT_ACTION, "a1"]);
|
||||
assert!(t[2].event.ok);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -63,13 +63,18 @@ impl std::fmt::Debug for Bootstrap {
|
||||
}
|
||||
}
|
||||
|
||||
/// `version` is required: `{}` or an unrelated JSON object must not load as an
|
||||
/// empty state that the next update would overwrite.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct AuthState {
|
||||
pub version: u32,
|
||||
#[serde(default)]
|
||||
pub users: Vec<User>,
|
||||
#[serde(default)]
|
||||
pub sessions: Vec<Session>,
|
||||
#[serde(default)]
|
||||
pub tokens: Vec<ApiToken>,
|
||||
#[serde(default)]
|
||||
pub bootstrap: Option<Bootstrap>,
|
||||
}
|
||||
|
||||
@@ -204,6 +209,24 @@ mod tests {
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "{not json");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_without_version_fails_closed() {
|
||||
for body in ["{}", r#"{"foo":1}"#, r#"{"users":[]}"#, "[]", "null"] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(STATE_FILE);
|
||||
fs::write(&path, body).unwrap();
|
||||
assert!(matches!(
|
||||
AuthStore::open(dir.path()).unwrap_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(), body);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn future_version_rejected() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
Reference in new issue
Block a user