use std::collections::BTreeMap;
use serde::Serialize;
use crate::audit::{AuditAction, AuditOutcome, AuditRecord, record_hash};
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct LineError {
pub line: usize,
pub message: String,
}
pub fn parse_json_lines(text: &str) -> (Vec<AuditRecord>, Vec<LineError>) {
let mut records = Vec::new();
let mut errors = Vec::new();
for (index, line) in text.lines().enumerate() {
if line.trim().is_empty() {
continue;
}
match serde_json::from_str::<AuditRecord>(line) {
Ok(record) => records.push(record),
Err(error) => errors.push(LineError {
line: index + 1,
message: error.to_string(),
}),
}
}
(records, errors)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct Period {
pub from_ms: u64,
pub to_ms: u64,
pub from: String,
pub to: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum BreakKind {
Unchained,
Broken,
Tampered,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct ChainBreak {
pub index: usize,
pub kind: BreakKind,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct ChainStatus {
pub ok: bool,
pub head: Option<String>,
pub breaks: Vec<ChainBreak>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Anchors {
pub head: Option<String>,
pub start: Option<String>,
}
impl Anchors {
pub fn head(mut self, head: impl Into<String>) -> Self {
self.head = Some(head.into());
self
}
pub fn start(mut self, start: impl Into<String>) -> Self {
self.start = Some(start.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct AnchorCheck {
pub kind: &'static str,
pub expected: String,
pub found: Option<String>,
pub ok: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct TimestampCheck {
pub label: String,
pub ok: bool,
pub gen_time: Option<i64>,
pub time: Option<String>,
pub policy: Option<String>,
pub serial: Option<String>,
pub error: Option<String>,
}
impl TimestampCheck {
pub fn verified(label: impl Into<String>, gen_time: i64, policy: String, serial: String) -> Self {
Self {
label: label.into(),
ok: true,
gen_time: Some(gen_time),
time: Some(format_unix_seconds(gen_time)),
policy: Some(policy),
serial: Some(serial),
error: None,
}
}
pub fn failed(label: impl Into<String>, error: impl Into<String>) -> Self {
Self {
label: label.into(),
ok: false,
gen_time: None,
time: None,
policy: None,
serial: None,
error: Some(error.into()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct ConformanceReport {
pub records: usize,
pub unreadable_lines: Vec<LineError>,
pub period: Option<Period>,
pub by_action: BTreeMap<String, BTreeMap<String, u64>>,
pub changes_by_actor: BTreeMap<String, u64>,
pub refusals_by_invariant: BTreeMap<String, u64>,
pub refusals_without_invariant: u64,
pub chain: ChainStatus,
pub anchors: Vec<AnchorCheck>,
pub timestamps: Vec<TimestampCheck>,
}
fn name_of<T: Serialize>(value: &T) -> String {
serde_json::to_value(value)
.ok()
.and_then(|v| v.as_str().map(str::to_owned))
.unwrap_or_default()
}
fn is_change(action: AuditAction) -> bool {
matches!(
action,
AuditAction::GrantAdd
| AuditAction::GrantRemove
| AuditAction::TupleAdd
| AuditAction::TupleRemove
| AuditAction::RoleAssign
| AuditAction::RoleRevoke
)
}
fn invariant_of(violation: &str) -> &str {
if let Some(rest) = violation.strip_prefix('[')
&& let Some((name, _)) = rest.split_once(']')
{
return name;
}
violation.split_once(": ").map_or(violation, |(name, _)| name)
}
impl ConformanceReport {
pub fn build(records: &[AuditRecord], anchors: &Anchors) -> Self {
let mut by_action: BTreeMap<String, BTreeMap<String, u64>> = BTreeMap::new();
let mut changes_by_actor: BTreeMap<String, u64> = BTreeMap::new();
let mut refusals_by_invariant: BTreeMap<String, u64> = BTreeMap::new();
let mut refusals_without_invariant = 0;
let mut breaks = Vec::new();
let mut previous: Option<&str> = None;
for (index, record) in records.iter().enumerate() {
*by_action
.entry(name_of(&record.action))
.or_default()
.entry(name_of(&record.outcome))
.or_default() += 1;
if is_change(record.action) && record.outcome == AuditOutcome::Applied {
*changes_by_actor.entry(record.actor.clone()).or_default() += 1;
}
if record.outcome == AuditOutcome::Rejected {
if record.violations.is_empty() {
refusals_without_invariant += 1;
}
for violation in &record.violations {
*refusals_by_invariant
.entry(invariant_of(violation).to_owned())
.or_default() += 1;
}
}
match record.hash.as_deref() {
None => breaks.push(ChainBreak {
index,
kind: BreakKind::Unchained,
}),
Some(hash) => {
if index > 0 && record.prev_hash.as_deref() != previous {
breaks.push(ChainBreak {
index,
kind: BreakKind::Broken,
});
}
if record_hash(record).ok().as_deref() != Some(hash) {
breaks.push(ChainBreak {
index,
kind: BreakKind::Tampered,
});
}
}
}
previous = record.hash.as_deref();
}
let head = records.last().and_then(|r| r.hash.clone());
let mut checks = Vec::new();
if let Some(expected) = &anchors.head {
checks.push(AnchorCheck {
kind: "head",
expected: expected.clone(),
found: head.clone(),
ok: head.as_deref() == Some(expected.as_str()),
});
}
if let Some(expected) = &anchors.start {
let found = records.first().and_then(|r| r.prev_hash.clone());
checks.push(AnchorCheck {
kind: "start",
expected: expected.clone(),
ok: found.as_deref() == Some(expected.as_str()),
found,
});
}
let period = records
.iter()
.map(|r| r.at)
.min()
.zip(records.iter().map(|r| r.at).max())
.map(|(from, to)| Period {
from_ms: from,
to_ms: to,
from: format_unix_millis(from),
to: format_unix_millis(to),
});
Self {
records: records.len(),
unreadable_lines: Vec::new(),
period,
by_action,
changes_by_actor,
refusals_by_invariant,
refusals_without_invariant,
chain: ChainStatus {
ok: breaks.is_empty() && !records.is_empty(),
head,
breaks,
},
anchors: checks,
timestamps: Vec::new(),
}
}
pub fn from_json_lines(text: &str, anchors: &Anchors) -> Self {
let (records, errors) = parse_json_lines(text);
let mut report = Self::build(&records, anchors);
report.unreadable_lines = errors;
report
}
pub fn with_timestamps(mut self, timestamps: Vec<TimestampCheck>) -> Self {
self.timestamps = timestamps;
self
}
pub fn is_conforming(&self) -> bool {
self.unreadable_lines.is_empty()
&& self.chain.ok
&& self.anchors.iter().all(|a| a.ok)
&& self.timestamps.iter().all(|t| t.ok)
}
}
fn civil_from_days(days: i64) -> (i64, i64, i64) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let year = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
(if month <= 2 { year + 1 } else { year }, month, day)
}
pub fn format_unix_seconds(seconds: i64) -> String {
let (year, month, day) = civil_from_days(seconds.div_euclid(86_400));
let rest = seconds.rem_euclid(86_400);
format!(
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
rest / 3600,
rest % 3600 / 60,
rest % 60
)
}
pub fn format_unix_millis(millis: u64) -> String {
let seconds = (millis / 1000) as i64;
let base = format_unix_seconds(seconds);
format!("{}.{:03}Z", &base[..base.len() - 1], millis % 1000)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn time_formatting() {
assert_eq!(format_unix_seconds(0), "1970-01-01T00:00:00Z");
assert_eq!(format_unix_seconds(1_795_868_280), "2026-11-28T12:18:00Z");
assert_eq!(format_unix_millis(1_700_000_000_123), "2023-11-14T22:13:20.123Z");
}
#[test]
fn invariant_names() {
assert_eq!(invariant_of("no_self_management"), "no_self_management");
assert_eq!(invariant_of("no_self_management: you cannot"), "no_self_management");
assert_eq!(invariant_of("[no_self_management] you cannot"), "no_self_management");
}
#[test]
fn an_empty_trail_is_not_conforming() {
let report = ConformanceReport::build(&[], &Anchors::default());
assert_eq!(report.records, 0);
assert!(report.period.is_none());
assert!(!report.is_conforming());
}
}