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