warder 0.1.0

A policy gate for MCP tool calls - blocks destructive AI agent actions before they run
Documentation
//! Audit records and the bounded local buffer.
//!
//! Two rules drive this module, both taken from defects found in the v1 schema:
//!
//! 1. **No raw payloads by default.** Tool-call arguments are exactly where customer PII,
//!    credentials, SQL and free-text prompts live. Storing them unbounded turns the
//!    governance product into the largest sensitive-data honeypot in the customer's
//!    estate. We store a canonical hash plus argument *key* names and value *shapes*.
//!    Full capture is per-tenant opt-in with configured retention and per-tenant DEK
//!    encryption, handled in the control plane — never here.
//!
//! 2. **Timers are split and integral.** `latency_ms NUMERIC(6,2)` in the v1 schema
//!    errors at 9,999.99ms, so a ten-second Salesforce call would fail the audit insert
//!    rather than clamp — silently losing the record for a call that succeeded. Integer
//!    microseconds in a u64 cannot overflow in any realistic lifetime, and three separate
//!    timers are the only way to substantiate a latency SLO.

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>,
    /// SHA-256 over the canonical argument JSON. Lets you prove two calls were identical
    /// without ever storing what they contained.
    pub arguments_sha256: String,
    /// Key names only. Never values.
    pub argument_keys: Vec<String>,
    pub timers: Timers,
    /// Set only when the tenant has opted in to full payload capture.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub raw_arguments: Option<serde_json::Value>,
}

impl AuditRecord {
    // Nine parameters, all distinct and named at the single call site. Bundling them
    // into a builder would add indirection without removing any decision.
    #[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
            },
        }
    }
}

/// Deterministic serialisation with object keys sorted, so the hash of semantically
/// identical arguments is stable regardless of map ordering.
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(),
    }
}

/// Bounded ring buffer. When it fills, the oldest records are dropped and the drop is
/// counted — an audit product must be able to say how many records it lost, and must
/// never let audit backpressure block or crash a developer's tool call.
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);
    }

    /// Take everything currently buffered for batched shipment to ClickHouse.
    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() {
        // The v1 schema's NUMERIC(6,2) raises `numeric field overflow` above 9999.99ms.
        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"));
    }
}