use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use sha2::{Digest, Sha256};
pub const AUDIT_SCHEMA: u32 = 1;
pub const GENESIS: &str = "0000000000000000000000000000000000000000000000000000000000000000";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AuditRecord {
pub schema: u32,
pub eventid: String,
pub ts: String,
pub event: String,
pub actor: String,
pub target: String,
pub result: String,
pub code: String,
pub source: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub extra: Option<Map<String, Value>>,
pub prev: String,
pub hash: String,
}
impl AuditRecord {
pub fn seal(&mut self) {
let prev = self.prev.clone();
let body = serde_json::to_value(&*self).unwrap_or(Value::Null);
self.hash = chain_hash(&prev, &body);
}
pub fn links_from(&self, prev_hash: &str) -> bool {
if self.prev != prev_hash {
return false;
}
let body = serde_json::to_value(self).unwrap_or(Value::Null);
chain_hash(&self.prev, &body) == self.hash
}
}
pub fn chain_hash(prev: &str, body: &Value) -> String {
let mut stripped = body.clone();
if let Some(object) = stripped.as_object_mut() {
object.remove("hash");
}
let canonical = serde_json::to_string(&stripped).unwrap_or_default();
let mut hasher = Sha256::new();
hasher.update(prev.as_bytes());
hasher.update(b"\n");
hasher.update(canonical.as_bytes());
hasher
.finalize()
.iter()
.map(|byte| format!("{byte:02x}"))
.collect()
}
pub fn walk_chain(records: &[AuditRecord]) -> Result<String, usize> {
let mut prev = GENESIS.to_owned();
for (index, record) in records.iter().enumerate() {
if !record.links_from(&prev) {
return Err(index);
}
prev = record.hash.clone();
}
Ok(prev)
}
pub fn parse_line(line: &str) -> Option<AuditRecord> {
let trimmed = line.trim();
if !trimmed.starts_with('{') {
return None;
}
serde_json::from_str(trimmed).ok()
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used)]
use super::*;
use serde_json::json;
fn sample(prev: &str) -> AuditRecord {
AuditRecord {
schema: AUDIT_SCHEMA,
eventid: "log-0123456789abcdef".to_owned(),
ts: "2026-11-30T20:00:00.000Z".to_owned(),
event: "audit.login".to_owned(),
actor: "local".to_owned(),
target: String::new(),
result: "ok".to_owned(),
code: String::new(),
source: "pipe".to_owned(),
extra: None,
prev: prev.to_owned(),
hash: String::new(),
}
}
#[test]
fn a_sealed_record_links_and_a_tampered_one_does_not() {
let mut first = sample(GENESIS);
first.seal();
assert_eq!(first.hash.len(), 64, "hex digest");
assert!(first.links_from(GENESIS));
let mut second = sample(&first.hash);
second.seal();
assert!(second.links_from(&first.hash), "the chain advances");
let mut tampered = second.clone();
tampered.result = "denied".to_owned();
assert!(
!tampered.links_from(&first.hash),
"a changed record must not link"
);
assert!(!second.links_from(GENESIS));
}
#[test]
fn walk_accepts_a_chain_and_rejects_a_removed_link() {
let mut first = sample(GENESIS);
first.seal();
let mut second = sample(&first.hash);
second.seal();
let mut third = sample(&second.hash);
third.seal();
let tail = walk_chain(&[first.clone(), second.clone(), third.clone()]).unwrap();
assert_eq!(tail, third.hash);
let broken = walk_chain(&[first, third]).expect_err("a gap breaks the chain");
assert_eq!(broken, 1, "the record that does not link");
}
#[test]
fn a_line_round_trips_and_the_body_is_canonical() {
let mut record = sample(GENESIS);
record.extra = Some(Map::from_iter([("note".to_owned(), json!("backup"))]));
record.seal();
let line = serde_json::to_string(&record).unwrap();
let back = parse_line(&line).expect("parses");
assert_eq!(back, record);
let mut copy = back;
copy.hash.clear();
copy.seal();
assert_eq!(copy.hash, record.hash);
}
#[test]
fn the_audit_event_name_shape_holds() {
for name in ["audit.login", "audit.backup_taken", "audit.pruned"] {
assert!(
crate::eventlog::is_valid_event_name(name),
"{name} must be category.action"
);
}
assert!(!crate::eventlog::is_valid_event_name("audit"));
}
}