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, pub ip: Option, pub ok: bool, /// Short non-secret note. pub detail: Option, } #[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> { 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::>(), ["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); } }