use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::VecDeque;
use crate::policy::{Decision, Effect};
use crate::preflight::PreflightReport;
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
pub struct Timers {
pub proxy_overhead_us: u64,
pub policy_eval_us: u64,
pub upstream_us: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditRecord {
pub audit_id: String,
pub agent_id: String,
pub server: String,
pub tool: String,
pub effect: Effect,
pub matched_policies: Vec<String>,
pub reason: String,
pub operation_class: String,
pub signals: Vec<String>,
pub arguments_sha256: String,
pub argument_keys: Vec<String>,
pub timers: Timers,
#[serde(skip_serializing_if = "Option::is_none")]
pub raw_arguments: Option<serde_json::Value>,
}
impl AuditRecord {
#[allow(clippy::too_many_arguments)]
pub fn new(
agent_id: &str,
server: &str,
tool: &str,
arguments: &serde_json::Value,
argument_keys: Vec<String>,
report: &PreflightReport,
decision: &Decision,
timers: Timers,
capture_raw: bool,
) -> Self {
let canonical = canonical_json(arguments);
let mut h = Sha256::new();
h.update(canonical.as_bytes());
AuditRecord {
audit_id: uuid::Uuid::new_v4().to_string(),
agent_id: agent_id.into(),
server: server.into(),
tool: tool.into(),
effect: decision.effect,
matched_policies: decision.matched_policies.clone(),
reason: decision.reason.clone(),
operation_class: format!("{:?}", report.class).to_lowercase(),
signals: report.signals.clone(),
arguments_sha256: format!("{:x}", h.finalize()),
argument_keys,
timers,
raw_arguments: if capture_raw {
Some(arguments.clone())
} else {
None
},
}
}
}
fn canonical_json(v: &serde_json::Value) -> String {
use serde_json::Value;
match v {
Value::Object(m) => {
let mut keys: Vec<&String> = m.keys().collect();
keys.sort();
let inner: Vec<String> = keys
.iter()
.map(|k| {
format!(
"{}:{}",
serde_json::to_string(k).unwrap_or_default(),
canonical_json(&m[*k])
)
})
.collect();
format!("{{{}}}", inner.join(","))
}
Value::Array(a) => {
let inner: Vec<String> = a.iter().map(canonical_json).collect();
format!("[{}]", inner.join(","))
}
other => other.to_string(),
}
}
pub struct AuditSink {
buf: VecDeque<AuditRecord>,
capacity: usize,
dropped: u64,
}
impl AuditSink {
pub fn new(capacity: usize) -> Self {
AuditSink {
buf: VecDeque::with_capacity(capacity),
capacity: capacity.max(1),
dropped: 0,
}
}
pub fn push(&mut self, r: AuditRecord) {
if self.buf.len() == self.capacity {
self.buf.pop_front();
self.dropped += 1;
}
self.buf.push_back(r);
}
pub fn drain(&mut self) -> Vec<AuditRecord> {
self.buf.drain(..).collect()
}
pub fn dropped(&self) -> u64 {
self.dropped
}
pub fn len(&self) -> usize {
self.buf.len()
}
pub fn is_empty(&self) -> bool {
self.buf.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::policy::Decision;
use crate::preflight::classify_sql;
use serde_json::json;
fn rec(sql: &str) -> AuditRecord {
let args = json!({ "sql": sql });
let report = classify_sql(sql);
let d = Decision {
effect: Effect::Allow,
matched_policies: vec![],
reason: "t".into(),
};
AuditRecord::new(
"a",
"pg",
"run",
&args,
vec!["sql".into()],
&report,
&d,
Timers::default(),
false,
)
}
#[test]
fn raw_arguments_are_absent_unless_opted_in() {
let r = rec("SELECT 1");
assert!(r.raw_arguments.is_none());
let s = serde_json::to_string(&r).unwrap();
assert!(
!s.contains("raw_arguments"),
"opt-out must not emit the field at all"
);
assert!(
!s.contains("SELECT 1"),
"the statement must not leak into the record"
);
}
#[test]
fn opt_in_captures_raw() {
let args = json!({"sql": "SELECT 1"});
let report = classify_sql("SELECT 1");
let d = Decision {
effect: Effect::Allow,
matched_policies: vec![],
reason: "t".into(),
};
let r = AuditRecord::new(
"a",
"pg",
"run",
&args,
vec![],
&report,
&d,
Timers::default(),
true,
);
assert!(r.raw_arguments.is_some());
}
#[test]
fn hash_is_stable_across_key_order() {
let a = json!({"b": 2, "a": 1});
let b = json!({"a": 1, "b": 2});
assert_eq!(canonical_json(&a), canonical_json(&b));
}
#[test]
fn different_arguments_hash_differently() {
assert_ne!(
rec("SELECT 1").arguments_sha256,
rec("SELECT 2").arguments_sha256
);
}
#[test]
fn ring_buffer_drops_oldest_and_counts_it() {
let mut s = AuditSink::new(2);
s.push(rec("SELECT 1"));
s.push(rec("SELECT 2"));
s.push(rec("SELECT 3"));
assert_eq!(s.len(), 2);
assert_eq!(s.dropped(), 1);
let out = s.drain();
assert_eq!(out.len(), 2);
assert!(s.is_empty());
}
#[test]
fn timers_do_not_overflow_at_ten_seconds() {
let t = Timers {
proxy_overhead_us: 800,
policy_eval_us: 120,
upstream_us: 10_000_000,
};
let json = serde_json::to_string(&t).unwrap();
assert!(json.contains("10000000"));
}
}