Skip to main content

guardrail_proxy/
audit.rs

1//! Structured audit logging for blocked and redacted requests.
2//!
3//! Audit records are emitted as structured `tracing` events at the `info`
4//! level under the `guardrail::audit` target, so they can be filtered,
5//! shipped to a SIEM, or written to a dedicated audit log file independently
6//! of general application logs.
7//!
8//! ## Audit record shape (§10 of the spec)
9//!
10//! ```json
11//! {
12//!   "timestamp": "2026-06-11T10:00:00.000Z",
13//!   "request_id": "01J9XK...",
14//!   "decision": "block",
15//!   "stage": "onnx_injection",
16//!   "reason": "prompt_injection",
17//!   "score": 0.97,
18//!   "model": "gpt-4o",
19//!   "role_scanned": "user",
20//!   "pii_entities_found": [],
21//!   "latency_pipeline_ms": 0.8,
22//!   "latency_total_ms": 312.4
23//! }
24//! ```
25//!
26//! **Privacy invariants (never violated):**
27//! - Audit records never contain message content or API keys.
28//! - Only metadata needed for security analysis is logged.
29
30use chrono::{Datelike, Timelike};
31use guardrail_core::{
32    decision::{BlockCode, Decision},
33    request::GuardrailRequest,
34};
35use serde::Serialize;
36
37/// A structured audit record for a single pipeline decision.
38///
39/// This type is serializable to JSON for log shipping. The shape matches
40/// §10 of the spec exactly, including optional fields that are only present
41/// when relevant (e.g. `score` only for ONNX decisions, `pii_entities_found`
42/// only for redaction decisions).
43#[derive(Debug, Clone, Serialize)]
44pub struct AuditRecord {
45    /// ISO 8601 timestamp with millisecond precision and `Z` suffix.
46    pub timestamp: String,
47    /// The unique request ID (UUID v4).
48    pub request_id: String,
49    /// Final pipeline decision: `"allow"`, `"redact"`, or `"block"`.
50    pub decision: &'static str,
51    /// The name of the stage that produced this decision. `None` for
52    /// `"allow"` decisions where all stages passed.
53    #[serde(skip_serializing_if = "Option::is_none")]
54    pub stage: Option<String>,
55    /// Human-readable reason string. `None` for `"allow"` decisions.
56    #[serde(skip_serializing_if = "Option::is_none")]
57    pub reason: Option<String>,
58    /// Machine-readable block code (`"prompt_injection"`, `"toxicity"`,
59    /// `"policy_violation"`, …). Present only on `"block"` decisions.
60    #[serde(skip_serializing_if = "Option::is_none")]
61    pub code: Option<String>,
62    /// Classifier confidence score in `[0, 1]`. Present only when an ONNX
63    /// classifier made the decision.
64    #[serde(skip_serializing_if = "Option::is_none")]
65    pub score: Option<f32>,
66    /// The model the request was destined for.
67    pub model: String,
68    /// The provider (lowercase).
69    pub provider: String,
70    /// Number of messages in the request.
71    pub message_count: usize,
72    /// PII entity types found, e.g. `["email", "phone"]`. Empty for non-redact decisions.
73    pub pii_entities_found: Vec<String>,
74    /// Pipeline-only evaluation latency in milliseconds.
75    pub latency_pipeline_ms: f64,
76    /// End-to-end request latency including upstream, in milliseconds.
77    pub latency_total_ms: f64,
78    /// Stages that errored on this request and failed open (`on_error =
79    /// "allow"`): the request went on without their check. Empty when every
80    /// stage ran normally. Omitted from JSON when empty.
81    #[serde(skip_serializing_if = "Vec::is_empty")]
82    pub failed_open_stages: Vec<String>,
83}
84
85impl AuditRecord {
86    /// Build an audit record from a request and its final decision.
87    ///
88    /// # Examples
89    ///
90    /// ```rust
91    /// use guardrail_proxy::audit::AuditRecord;
92    /// use guardrail_core::{decision::{Decision, BlockCode}, test_helpers::clean_request};
93    ///
94    /// let req = clean_request();
95    /// let record = AuditRecord::from_decision(&req, &Decision::Allow, 0.05, 120.0);
96    /// assert_eq!(record.decision, "allow");
97    /// assert!(record.code.is_none());
98    /// ```
99    ///
100    /// PII entity types are read directly from `Decision::Redact`'s own
101    /// `entities` field — there is no separate parameter to thread through
102    /// (and therefore no way to pass a list that doesn't match the actual
103    /// decision, which was a real bug in an earlier version of this API).
104    ///
105    /// ```rust
106    /// use guardrail_proxy::audit::AuditRecord;
107    /// use guardrail_core::{decision::Decision, test_helpers::clean_request};
108    ///
109    /// let req = clean_request();
110    /// let decision = Decision::Redact {
111    ///     reason: "PII redacted: Email".into(),
112    ///     mutated: req.clone(),
113    ///     entities: vec!["email".to_string()],
114    /// };
115    /// let record = AuditRecord::from_decision(&req, &decision, 0.02, 250.0);
116    /// assert_eq!(record.pii_entities_found, vec!["email"]);
117    /// ```
118    pub fn from_decision(
119        req: &GuardrailRequest,
120        decision: &Decision,
121        latency_pipeline_ms: f64,
122        latency_total_ms: f64,
123    ) -> Self {
124        let now = chrono_timestamp();
125
126        let (decision_name, stage, reason, code, pii_entities) = match decision {
127            Decision::Allow => ("allow", None, None, None, Vec::new()),
128            Decision::Redact {
129                reason, entities, ..
130            } => ("redact", None, Some(reason.clone()), None, entities.clone()),
131            Decision::Block { reason, code } => (
132                "block",
133                None, // stage name is best-effort from caller context
134                Some(reason.clone()),
135                Some(block_code_str(code)),
136                Vec::new(),
137            ),
138        };
139
140        Self {
141            timestamp: now,
142            request_id: req.id.to_string(),
143            decision: decision_name,
144            stage,
145            reason,
146            code,
147            score: None, // populated by `with_score`
148            model: req.model.clone(),
149            provider: format!("{:?}", req.provider).to_lowercase(),
150            message_count: req.messages.len(),
151            pii_entities_found: pii_entities,
152            latency_pipeline_ms,
153            latency_total_ms,
154            failed_open_stages: Vec::new(),
155        }
156    }
157
158    /// Record the stages that errored and failed open on this request.
159    /// Returns `self` for chaining.
160    ///
161    /// # Examples
162    ///
163    /// ```rust
164    /// use guardrail_proxy::audit::AuditRecord;
165    /// use guardrail_core::{decision::Decision, test_helpers::clean_request};
166    ///
167    /// let record = AuditRecord::from_decision(&clean_request(), &Decision::Allow, 0.1, 50.0)
168    ///     .with_failed_open_stages(vec!["toxicity".to_string()]);
169    /// assert_eq!(record.failed_open_stages, vec!["toxicity"]);
170    /// ```
171    #[must_use]
172    pub fn with_failed_open_stages(mut self, stages: Vec<String>) -> Self {
173        self.failed_open_stages = stages;
174        self
175    }
176
177    /// Set the ONNX classifier score on a record already constructed with
178    /// `from_decision`. Returns `self` for chaining.
179    ///
180    /// # Examples
181    ///
182    /// ```rust
183    /// use guardrail_proxy::audit::AuditRecord;
184    /// use guardrail_core::{decision::{Decision, BlockCode}, test_helpers::clean_request};
185    ///
186    /// let req = clean_request();
187    /// let record = AuditRecord::from_decision(
188    ///     &req,
189    ///     &Decision::Block { reason: "test".into(), code: BlockCode::PromptInjection },
190    ///     0.8,
191    ///     312.0,
192    /// )
193    /// .with_score(0.97)
194    /// .with_stage("onnx_injection");
195    ///
196    /// assert_eq!(record.score, Some(0.97));
197    /// assert_eq!(record.stage.as_deref(), Some("onnx_injection"));
198    /// ```
199    #[must_use]
200    pub fn with_score(mut self, score: f32) -> Self {
201        self.score = Some(score);
202        self
203    }
204
205    /// Set the pipeline stage that produced the decision. Returns `self` for
206    /// chaining.
207    #[must_use]
208    pub fn with_stage(mut self, stage: impl Into<String>) -> Self {
209        self.stage = Some(stage.into());
210        self
211    }
212
213    /// Emit this record as a structured `tracing` event at `info` level
214    /// under the `guardrail::audit` target.
215    ///
216    /// The `tracing` event fields are designed to be captured by the NDJSON
217    /// audit-log writer in [`crate::audit_log`] and also appear in the
218    /// structured JSON application log when `log_format = "json"`.
219    pub fn emit(&self) {
220        tracing::info!(
221            target: "guardrail::audit",
222            timestamp         = %self.timestamp,
223            request_id        = %self.request_id,
224            decision          = %self.decision,
225            stage             = ?self.stage,
226            reason            = ?self.reason,
227            code              = ?self.code,
228            score             = ?self.score,
229            model             = %self.model,
230            provider          = %self.provider,
231            message_count     = self.message_count,
232            pii_entities_found = ?self.pii_entities_found,
233            latency_pipeline_ms = self.latency_pipeline_ms,
234            latency_total_ms  = self.latency_total_ms,
235            failed_open_stages = ?self.failed_open_stages,
236            "pipeline decision"
237        );
238    }
239}
240
241fn block_code_str(code: &BlockCode) -> String {
242    code.as_str().to_string()
243}
244
245/// Return the current UTC time formatted as an ISO 8601 string with
246/// millisecond precision and a `Z` suffix, without pulling in the `chrono`
247/// crate (which would add a heavy dependency for a non-critical path).
248///
249/// Format: `"2026-06-11T10:00:00.123Z"`
250fn chrono_timestamp() -> String {
251    use std::time::{SystemTime, UNIX_EPOCH};
252
253    let now = SystemTime::now()
254        .duration_since(UNIX_EPOCH)
255        .unwrap_or_default();
256
257    let total_secs = now.as_secs();
258    let millis = now.subsec_millis();
259
260    // Convert UNIX epoch seconds to (year, month, day, hour, min, sec)
261    // using a minimal algorithm to avoid pulling in `chrono`.
262    let (year, month, day, hour, min, sec) = unix_secs_to_datetime(total_secs);
263
264    format!("{year:04}-{month:02}-{day:02}T{hour:02}:{min:02}:{sec:02}.{millis:03}Z")
265}
266
267/// Minimal, allocation-free conversion of UNIX seconds to calendar fields
268/// (Gregorian calendar, UTC). Handles dates from 1970 to ~2200 correctly.
269fn unix_secs_to_datetime(secs: u64) -> (u64, u64, u64, u64, u64, u64) {
270    let dt = chrono::DateTime::from_timestamp(secs as i64, 0)
271        .unwrap_or_else(|| chrono::DateTime::from_timestamp(0, 0).unwrap());
272    let dt = dt.naive_utc();
273    (
274        dt.year() as u64,
275        dt.month() as u64,
276        dt.day() as u64,
277        dt.hour() as u64,
278        dt.minute() as u64,
279        dt.second() as u64,
280    )
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286    use guardrail_core::{
287        decision::BlockCode,
288        test_helpers::{clean_request, injection_request},
289    };
290
291    #[test]
292    fn test_audit_record_allow() {
293        let req = clean_request();
294        let record = AuditRecord::from_decision(&req, &Decision::Allow, 0.05, 120.0);
295        assert_eq!(record.decision, "allow");
296        assert!(record.code.is_none());
297        assert!(record.reason.is_none());
298        assert!(record.score.is_none());
299        assert!(record.pii_entities_found.is_empty());
300    }
301
302    #[test]
303    fn test_audit_record_block() {
304        let req = injection_request();
305        let decision = Decision::Block {
306            reason: "Prompt injection detected.".into(),
307            code: BlockCode::PromptInjection,
308        };
309        let record = AuditRecord::from_decision(&req, &decision, 0.8, 0.9)
310            .with_score(0.97)
311            .with_stage("onnx_injection");
312
313        assert_eq!(record.decision, "block");
314        assert_eq!(record.code, Some("prompt_injection".to_string()));
315        assert_eq!(record.score, Some(0.97));
316        assert_eq!(record.stage.as_deref(), Some("onnx_injection"));
317        assert_eq!(record.latency_pipeline_ms, 0.8);
318    }
319
320    #[test]
321    fn test_audit_record_redact_with_pii() {
322        // Entities now come directly from Decision::Redact's own field —
323        // no separate parameter to keep in sync, closing the gap where a
324        // caller could previously pass an entity list that didn't match
325        // the decision it was supposedly describing.
326        let req = clean_request();
327        let decision = Decision::Redact {
328            reason: "PII redacted: Email".into(),
329            mutated: req.clone(),
330            entities: vec!["email".to_string(), "phone".to_string()],
331        };
332        let record = AuditRecord::from_decision(&req, &decision, 0.02, 250.0);
333
334        assert_eq!(record.decision, "redact");
335        assert_eq!(record.pii_entities_found, vec!["email", "phone"]);
336        assert_eq!(record.latency_total_ms, 250.0);
337    }
338
339    #[test]
340    fn test_audit_record_redact_entities_empty_when_stage_provides_none() {
341        // A custom stage that redacts without populating `entities` (e.g.
342        // a free-form policy match) must still produce a valid record with
343        // an empty entity list, not panic or default to something wrong.
344        let req = clean_request();
345        let decision = Decision::Redact {
346            reason: "custom redaction".into(),
347            mutated: req.clone(),
348            entities: Vec::new(),
349        };
350        let record = AuditRecord::from_decision(&req, &decision, 0.01, 10.0);
351
352        assert_eq!(record.decision, "redact");
353        assert!(record.pii_entities_found.is_empty());
354    }
355
356    #[test]
357    fn test_audit_record_serializes_to_correct_json_shape() {
358        let req = clean_request();
359        let record = AuditRecord::from_decision(&req, &Decision::Allow, 0.05, 120.0);
360        let json: serde_json::Value = serde_json::to_value(&record).unwrap();
361
362        // Required fields per spec §10
363        assert!(json.get("timestamp").is_some());
364        assert!(json.get("request_id").is_some());
365        assert_eq!(json["decision"], "allow");
366        assert_eq!(json["model"], "gpt-4o");
367        assert!(json.get("latency_pipeline_ms").is_some());
368        assert!(json.get("latency_total_ms").is_some());
369        assert!(json.get("pii_entities_found").is_some());
370
371        // Optional fields must be absent for an allow decision
372        assert!(json.get("code").is_none());
373        assert!(json.get("score").is_none());
374        assert!(json.get("stage").is_none());
375    }
376
377    #[test]
378    fn test_timestamp_format() {
379        let ts = chrono_timestamp();
380        // Must match "YYYY-MM-DDTHH:MM:SS.mmmZ"
381        assert_eq!(ts.len(), 24, "unexpected length: {ts}");
382        assert_eq!(&ts[10..11], "T");
383        assert_eq!(&ts[23..24], "Z");
384        assert_eq!(&ts[19..20], ".");
385    }
386
387    #[test]
388    fn test_emit_does_not_panic() {
389        let req = clean_request();
390        let record = AuditRecord::from_decision(&req, &Decision::Allow, 0.0, 0.0);
391        record.emit(); // must not panic even without a subscriber
392    }
393
394    #[test]
395    fn test_unix_secs_epoch() {
396        let (y, mo, d, h, mi, s) = unix_secs_to_datetime(0);
397        assert_eq!((y, mo, d, h, mi, s), (1970, 1, 1, 0, 0, 0));
398    }
399
400    #[test]
401    fn test_unix_secs_known_date() {
402        // 2026-06-11T00:00:00Z = 1_781_136_000
403        let (y, mo, d, h, mi, s) = unix_secs_to_datetime(1_781_136_000);
404        assert_eq!(y, 2026);
405        assert_eq!(mo, 6);
406        assert_eq!(d, 11);
407        assert_eq!((h, mi, s), (0, 0, 0));
408    }
409}