Skip to main content

guardrail_proxy/
response.rs

1//! Output-side PII redaction for non-streaming chat-completion responses.
2//!
3//! `guardrail-rs` inspects **requests** with the full pipeline
4//! ([`guardrail_core::Pipeline`]). Responses are forwarded back to the client
5//! largely unmodified — except that, when [`PiiRedactor`] is enabled, this
6//! module scans known assistant-message text fields in the JSON response body
7//! and redacts any PII the model echoed back (e.g. from retrieved documents,
8//! tool outputs, or training-data leakage) before the response reaches the
9//! caller.
10//!
11//! # Supported shapes
12//!
13//! | Provider | Field(s) scanned |
14//! |----------|-------------------|
15//! | OpenAI `/v1/chat/completions` | `choices[].message.content` (string) |
16//! | Anthropic `/v1/messages` | `content[]` blocks where `type == "text"`, field `text` |
17//! | OpenAI `/v1/responses` | `output[]` message items, `content[]` parts where `type == "output_text"`, field `text` |
18//!
19//! # Streaming responses
20//!
21//! This module handles complete JSON documents only.
22//! [`is_redactable_response`] returns `false` for `text/event-stream`
23//! bodies; those are redacted incrementally by [`crate::sse`] instead. See
24//! "Streaming responses" in `docs/architecture.md`.
25
26use guardrail_classifiers::PiiRedactor;
27use serde_json::Value;
28
29/// Summary of redactions applied to a response body, for the audit log.
30#[derive(Debug, Clone, Default, serde::Serialize)]
31pub struct ResponseRedactionSummary {
32    /// Total number of redactions applied across all text fields.
33    pub total_redactions: usize,
34    /// Distinct entity types redacted (e.g. `["email", "phone"]`).
35    pub entity_types: Vec<String>,
36}
37
38impl ResponseRedactionSummary {
39    fn is_empty(&self) -> bool {
40        self.total_redactions == 0
41    }
42}
43
44/// Returns `true` if `content_type` and `is_streaming` indicate a response
45/// body that [`redact_response_body`] can process (a single JSON document).
46///
47/// # Examples
48///
49/// ```rust
50/// use guardrail_proxy::response::is_redactable_response;
51///
52/// assert!(is_redactable_response(Some("application/json"), false));
53/// assert!(!is_redactable_response(Some("text/event-stream"), true));
54/// assert!(!is_redactable_response(Some("text/event-stream"), false));
55/// assert!(!is_redactable_response(None, false));
56/// ```
57pub fn is_redactable_response(content_type: Option<&str>, is_streaming: bool) -> bool {
58    if is_streaming {
59        return false;
60    }
61    matches!(content_type, Some(ct) if ct.starts_with("application/json"))
62}
63
64/// Scan a non-streaming JSON response body for PII in assistant-message text
65/// fields and redact it in place.
66///
67/// Returns `None` if the body is not valid JSON, doesn't match a known
68/// response shape, or contains no PII — in all of these cases the caller
69/// should forward the original bytes unchanged.
70///
71/// On success, returns the re-serialized JSON body (as bytes) and a
72/// [`ResponseRedactionSummary`] for the audit log.
73///
74/// # Examples
75///
76/// ```rust
77/// use guardrail_classifiers::PiiRedactor;
78/// use guardrail_proxy::response::redact_response_body;
79///
80/// let redactor = PiiRedactor::default();
81/// let body = br#"{
82///     "id": "chatcmpl-123",
83///     "choices": [{
84///         "index": 0,
85///         "message": {"role": "assistant", "content": "Reach us at help@example.com."},
86///         "finish_reason": "stop"
87///     }]
88/// }"#;
89///
90/// let (new_body, summary) = redact_response_body(body, &redactor).unwrap();
91/// let text = String::from_utf8(new_body).unwrap();
92/// assert!(text.contains("[EMAIL]"));
93/// assert_eq!(summary.total_redactions, 1);
94/// ```
95pub fn redact_response_body(
96    body: &[u8],
97    redactor: &PiiRedactor,
98) -> Option<(Vec<u8>, ResponseRedactionSummary)> {
99    try_redact_response_body(body, redactor).ok().flatten()
100}
101
102/// Like [`redact_response_body`], but tells a body that isn't JSON apart
103/// from one that needed no changes.
104///
105/// Returns `Ok(None)` if the body is JSON but contains no PII in a known
106/// text field, and `Ok(Some(..))` with the redacted body otherwise.
107///
108/// # Errors
109///
110/// Returns the parse error if `body` is not valid JSON. The proxy uses this
111/// to count responses it could not inspect.
112///
113/// # Examples
114///
115/// ```rust
116/// use guardrail_classifiers::PiiRedactor;
117/// use guardrail_proxy::response::try_redact_response_body;
118///
119/// let redactor = PiiRedactor::default();
120/// assert!(try_redact_response_body(b"\x1f\x8b not json", &redactor).is_err());
121/// assert!(try_redact_response_body(br#"{"choices":[]}"#, &redactor).unwrap().is_none());
122/// ```
123pub fn try_redact_response_body(
124    body: &[u8],
125    redactor: &PiiRedactor,
126) -> Result<Option<(Vec<u8>, ResponseRedactionSummary)>, serde_json::Error> {
127    let mut value: Value = serde_json::from_slice(body)?;
128    let mut summary = ResponseRedactionSummary::default();
129    let mut entity_set = std::collections::HashSet::new();
130
131    let mut changed = false;
132
133    // ── OpenAI shape: choices[].message.content ─────────────────────────────
134    if let Some(choices) = value.get_mut("choices").and_then(Value::as_array_mut) {
135        for choice in choices.iter_mut() {
136            if let Some(content) = choice.get_mut("message").and_then(|m| m.get_mut("content")) {
137                if let Some(text) = content.as_str() {
138                    if let Some((sanitized, records)) = redactor.redact_response_text(text) {
139                        for r in &records {
140                            entity_set.insert(format!("{:?}", r.entity_type).to_lowercase());
141                        }
142                        summary.total_redactions += records.len();
143                        *content = Value::String(sanitized);
144                        changed = true;
145                    }
146                }
147            }
148        }
149    }
150
151    // ── Anthropic shape: content[] blocks with type == "text" ───────────────
152    if let Some(blocks) = value.get_mut("content").and_then(Value::as_array_mut) {
153        for block in blocks.iter_mut() {
154            let is_text_block = block.get("type").and_then(Value::as_str) == Some("text");
155            if !is_text_block {
156                continue;
157            }
158            if let Some(text_field) = block.get_mut("text") {
159                if let Some(text) = text_field.as_str() {
160                    if let Some((sanitized, records)) = redactor.redact_response_text(text) {
161                        for r in &records {
162                            entity_set.insert(format!("{:?}", r.entity_type).to_lowercase());
163                        }
164                        summary.total_redactions += records.len();
165                        *text_field = Value::String(sanitized);
166                        changed = true;
167                    }
168                }
169            }
170        }
171    }
172
173    // ── OpenAI Responses shape: output[].content[] output_text parts ───────
174    if let Some(items) = value.get_mut("output").and_then(Value::as_array_mut) {
175        let parts = items
176            .iter_mut()
177            .filter(|item| item.get("type").and_then(Value::as_str) == Some("message"))
178            .filter_map(|item| item.get_mut("content").and_then(Value::as_array_mut))
179            .flatten()
180            .filter(|part| part.get("type").and_then(Value::as_str) == Some("output_text"));
181        for part in parts {
182            if let Some(text_field) = part.get_mut("text") {
183                if let Some(text) = text_field.as_str() {
184                    if let Some((sanitized, records)) = redactor.redact_response_text(text) {
185                        for r in &records {
186                            entity_set.insert(format!("{:?}", r.entity_type).to_lowercase());
187                        }
188                        summary.total_redactions += records.len();
189                        *text_field = Value::String(sanitized);
190                        changed = true;
191                    }
192                }
193            }
194        }
195    }
196
197    if !changed || summary.is_empty() {
198        return Ok(None);
199    }
200
201    summary.entity_types = entity_set.into_iter().collect();
202    summary.entity_types.sort();
203
204    let new_body = serde_json::to_vec(&value)?;
205    Ok(Some((new_body, summary)))
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211    use serde_json::json;
212
213    #[test]
214    fn test_is_redactable_response() {
215        assert!(is_redactable_response(Some("application/json"), false));
216        assert!(is_redactable_response(
217            Some("application/json; charset=utf-8"),
218            false
219        ));
220        assert!(!is_redactable_response(Some("text/event-stream"), true));
221        assert!(!is_redactable_response(Some("text/event-stream"), false));
222        assert!(!is_redactable_response(Some("application/json"), true));
223        assert!(!is_redactable_response(None, false));
224    }
225
226    #[test]
227    fn test_redact_openai_response_with_pii() {
228        let redactor = PiiRedactor::default();
229        let body = serde_json::to_vec(&json!({
230            "id": "chatcmpl-123",
231            "object": "chat.completion",
232            "choices": [{
233                "index": 0,
234                "message": {
235                    "role": "assistant",
236                    "content": "You can reach our support team at help@example.com or 555-867-5309."
237                },
238                "finish_reason": "stop"
239            }]
240        }))
241        .unwrap();
242
243        let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
244        let value: Value = serde_json::from_slice(&new_body).unwrap();
245
246        let content = value["choices"][0]["message"]["content"].as_str().unwrap();
247        assert!(content.contains("[EMAIL]"), "content: {content}");
248        assert!(content.contains("[PHONE]"), "content: {content}");
249        assert!(!content.contains("help@example.com"));
250
251        assert_eq!(summary.total_redactions, 2);
252        assert!(summary.entity_types.contains(&"email".to_string()));
253        assert!(summary.entity_types.contains(&"phone".to_string()));
254
255        // Other fields must be preserved unchanged.
256        assert_eq!(value["id"], "chatcmpl-123");
257        assert_eq!(value["choices"][0]["finish_reason"], "stop");
258    }
259
260    #[test]
261    fn test_redact_openai_response_multiple_choices() {
262        let redactor = PiiRedactor::default();
263        let body = serde_json::to_vec(&json!({
264            "choices": [
265                {"index": 0, "message": {"role": "assistant", "content": "Email alice@example.com"}},
266                {"index": 1, "message": {"role": "assistant", "content": "No PII in this one."}}
267            ]
268        }))
269        .unwrap();
270
271        let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
272        let value: Value = serde_json::from_slice(&new_body).unwrap();
273
274        assert!(value["choices"][0]["message"]["content"]
275            .as_str()
276            .unwrap()
277            .contains("[EMAIL]"));
278        assert_eq!(
279            value["choices"][1]["message"]["content"],
280            "No PII in this one."
281        );
282        assert_eq!(summary.total_redactions, 1);
283    }
284
285    #[test]
286    fn test_redact_anthropic_response_with_pii() {
287        let redactor = PiiRedactor::default();
288        let body = serde_json::to_vec(&json!({
289            "id": "msg_123",
290            "type": "message",
291            "role": "assistant",
292            "content": [
293                {"type": "text", "text": "Contact us at help@example.com for assistance."}
294            ]
295        }))
296        .unwrap();
297
298        let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
299        let value: Value = serde_json::from_slice(&new_body).unwrap();
300
301        let text = value["content"][0]["text"].as_str().unwrap();
302        assert!(text.contains("[EMAIL]"), "text: {text}");
303        assert_eq!(summary.total_redactions, 1);
304        assert_eq!(summary.entity_types, vec!["email".to_string()]);
305    }
306
307    #[test]
308    fn test_anthropic_non_text_blocks_untouched() {
309        let redactor = PiiRedactor::default();
310        let body = serde_json::to_vec(&json!({
311            "content": [
312                {"type": "tool_use", "id": "toolu_1", "name": "lookup", "input": {"email": "alice@example.com"}},
313                {"type": "text", "text": "Here is the result."}
314            ]
315        }))
316        .unwrap();
317
318        // No PII in the text block, and tool_use blocks are not scanned.
319        assert!(redact_response_body(&body, &redactor).is_none());
320    }
321
322    #[test]
323    fn test_redact_responses_api_output() {
324        let redactor = PiiRedactor::default();
325        let body = serde_json::to_vec(&json!({
326            "id": "resp_1",
327            "object": "response",
328            "output": [
329                {"type": "reasoning", "id": "rs_1", "summary": []},
330                {"type": "message", "role": "assistant", "content": [
331                    {"type": "output_text", "text": "Write to help@example.com", "annotations": []}
332                ]}
333            ]
334        }))
335        .unwrap();
336
337        let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
338        let value: Value = serde_json::from_slice(&new_body).unwrap();
339        assert_eq!(value["output"][1]["content"][0]["text"], "Write to [EMAIL]");
340        assert_eq!(value["output"][0]["type"], "reasoning");
341        assert_eq!(summary.total_redactions, 1);
342    }
343
344    #[test]
345    fn test_clean_response_returns_none() {
346        let redactor = PiiRedactor::default();
347        let body = serde_json::to_vec(&json!({
348            "id": "chatcmpl-123",
349            "choices": [{
350                "index": 0,
351                "message": {"role": "assistant", "content": "The capital of France is Paris."},
352                "finish_reason": "stop"
353            }]
354        }))
355        .unwrap();
356
357        assert!(redact_response_body(&body, &redactor).is_none());
358    }
359
360    #[test]
361    fn test_invalid_json_returns_none() {
362        let redactor = PiiRedactor::default();
363        assert!(redact_response_body(b"not json", &redactor).is_none());
364    }
365
366    #[test]
367    fn test_empty_choices_returns_none() {
368        let redactor = PiiRedactor::default();
369        let body = serde_json::to_vec(&json!({"choices": []})).unwrap();
370        assert!(redact_response_body(&body, &redactor).is_none());
371    }
372
373    #[test]
374    fn test_response_without_choices_or_content_returns_none() {
375        let redactor = PiiRedactor::default();
376        let body = serde_json::to_vec(&json!({"error": {"message": "not found"}})).unwrap();
377        assert!(redact_response_body(&body, &redactor).is_none());
378    }
379
380    #[test]
381    fn test_preserves_unicode_content() {
382        let redactor = PiiRedactor::default();
383        let body = serde_json::to_vec(&json!({
384            "choices": [{
385                "index": 0,
386                "message": {"role": "assistant", "content": "こんにちは、email: user@example.com です。"}
387            }]
388        }))
389        .unwrap();
390
391        let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
392        let value: Value = serde_json::from_slice(&new_body).unwrap();
393        let content = value["choices"][0]["message"]["content"].as_str().unwrap();
394
395        assert!(content.contains("こんにちは"));
396        assert!(content.contains("[EMAIL]"));
397        assert_eq!(summary.total_redactions, 1);
398    }
399}