use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use crate::util;
pub struct AuditLog {
path: PathBuf,
file: Mutex<Option<std::fs::File>>,
}
impl AuditLog {
#[must_use]
pub fn new(dir: &Path) -> Self {
let (y, m, d) = util::today_utc();
let path = dir.join(format!("audit-{y:04}{m:02}{d:02}.log"));
let file = if fs::create_dir_all(dir).is_ok() {
OpenOptions::new()
.create(true)
.append(true)
.open(&path)
.ok()
} else {
None
};
Self {
path,
file: Mutex::new(file),
}
}
#[must_use]
pub fn path(&self) -> &Path {
&self.path
}
pub fn log(&self, user: &str, method: &str, target: &str, ok: bool, detail: &str) {
let line = serde_json::json!({
"at": crate::server::now_ms(),
"user": user,
"method": method,
"target": target,
"ok": ok,
"detail": detail,
})
.to_string();
eprintln!("[audit] {line}");
if let Ok(mut g) = self.file.lock()
&& let Some(f) = g.as_mut()
{
let _ = writeln!(f, "{line}");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn writes_json_line() {
let dir = std::env::temp_dir().join(format!("ek-api-audit-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let a = AuditLog::new(&dir);
a.log("alice", "cfg.save", "dm", true, "saved=true");
let text = std::fs::read_to_string(a.path()).unwrap();
let v: serde_json::Value = serde_json::from_str(text.trim()).unwrap();
assert_eq!(v["user"], "alice");
assert_eq!(v["method"], "cfg.save");
assert_eq!(v["ok"], true);
assert!(!text.contains("secret-value"));
std::fs::remove_dir_all(&dir).ok();
}
}