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//!
18//! # Known limitation: streaming responses
19//!
20//! When the original request had `"stream": true`, the upstream returns a
21//! `text/event-stream` (SSE) body, not a single JSON document. This module
22//! does **not** parse or redact SSE chunks — streaming responses are passed
23//! through byte-for-byte unmodified. [`is_redactable_response`] returns
24//! `false` for such responses so callers can skip this stage entirely. See
25//! "Streaming responses" in `docs/architecture.md` for the current behavior
26//! and the options for closing this gap.
27
28use guardrail_classifiers::PiiRedactor;
29use serde_json::Value;
30
31/// Summary of redactions applied to a response body, for the audit log.
32#[derive(Debug, Clone, Default, serde::Serialize)]
33pub struct ResponseRedactionSummary {
34    /// Total number of redactions applied across all text fields.
35    pub total_redactions: usize,
36    /// Distinct entity types redacted (e.g. `["email", "phone"]`).
37    pub entity_types: Vec<String>,
38}
39
40impl ResponseRedactionSummary {
41    fn is_empty(&self) -> bool {
42        self.total_redactions == 0
43    }
44}
45
46/// Returns `true` if `content_type` and `is_streaming` indicate a response
47/// body that [`redact_response_body`] can process (a single JSON document).
48///
49/// # Examples
50///
51/// ```rust
52/// use guardrail_proxy::response::is_redactable_response;
53///
54/// assert!(is_redactable_response(Some("application/json"), false));
55/// assert!(!is_redactable_response(Some("text/event-stream"), true));
56/// assert!(!is_redactable_response(Some("text/event-stream"), false));
57/// assert!(!is_redactable_response(None, false));
58/// ```
59pub fn is_redactable_response(content_type: Option<&str>, is_streaming: bool) -> bool {
60    if is_streaming {
61        return false;
62    }
63    matches!(content_type, Some(ct) if ct.starts_with("application/json"))
64}
65
66/// Scan a non-streaming JSON response body for PII in assistant-message text
67/// fields and redact it in place.
68///
69/// Returns `None` if the body is not valid JSON, doesn't match a known
70/// response shape, or contains no PII — in all of these cases the caller
71/// should forward the original bytes unchanged.
72///
73/// On success, returns the re-serialized JSON body (as bytes) and a
74/// [`ResponseRedactionSummary`] for the audit log.
75///
76/// # Examples
77///
78/// ```rust
79/// use guardrail_classifiers::PiiRedactor;
80/// use guardrail_proxy::response::redact_response_body;
81///
82/// let redactor = PiiRedactor::default();
83/// let body = br#"{
84///     "id": "chatcmpl-123",
85///     "choices": [{
86///         "index": 0,
87///         "message": {"role": "assistant", "content": "Reach us at help@example.com."},
88///         "finish_reason": "stop"
89///     }]
90/// }"#;
91///
92/// let (new_body, summary) = redact_response_body(body, &redactor).unwrap();
93/// let text = String::from_utf8(new_body).unwrap();
94/// assert!(text.contains("[EMAIL]"));
95/// assert_eq!(summary.total_redactions, 1);
96/// ```
97pub fn redact_response_body(
98    body: &[u8],
99    redactor: &PiiRedactor,
100) -> Option<(Vec<u8>, ResponseRedactionSummary)> {
101    let mut value: Value = serde_json::from_slice(body).ok()?;
102    let mut summary = ResponseRedactionSummary::default();
103    let mut entity_set = std::collections::HashSet::new();
104
105    let mut changed = false;
106
107    // ── OpenAI shape: choices[].message.content ─────────────────────────────
108    if let Some(choices) = value.get_mut("choices").and_then(Value::as_array_mut) {
109        for choice in choices.iter_mut() {
110            if let Some(content) = choice.get_mut("message").and_then(|m| m.get_mut("content")) {
111                if let Some(text) = content.as_str() {
112                    if let Some((sanitized, records)) = redactor.redact_response_text(text) {
113                        for r in &records {
114                            entity_set.insert(format!("{:?}", r.entity_type).to_lowercase());
115                        }
116                        summary.total_redactions += records.len();
117                        *content = Value::String(sanitized);
118                        changed = true;
119                    }
120                }
121            }
122        }
123    }
124
125    // ── Anthropic shape: content[] blocks with type == "text" ───────────────
126    if let Some(blocks) = value.get_mut("content").and_then(Value::as_array_mut) {
127        for block in blocks.iter_mut() {
128            let is_text_block = block.get("type").and_then(Value::as_str) == Some("text");
129            if !is_text_block {
130                continue;
131            }
132            if let Some(text_field) = block.get_mut("text") {
133                if let Some(text) = text_field.as_str() {
134                    if let Some((sanitized, records)) = redactor.redact_response_text(text) {
135                        for r in &records {
136                            entity_set.insert(format!("{:?}", r.entity_type).to_lowercase());
137                        }
138                        summary.total_redactions += records.len();
139                        *text_field = Value::String(sanitized);
140                        changed = true;
141                    }
142                }
143            }
144        }
145    }
146
147    if !changed || summary.is_empty() {
148        return None;
149    }
150
151    summary.entity_types = entity_set.into_iter().collect();
152    summary.entity_types.sort();
153
154    let new_body = serde_json::to_vec(&value).ok()?;
155    Some((new_body, summary))
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161    use serde_json::json;
162
163    #[test]
164    fn test_is_redactable_response() {
165        assert!(is_redactable_response(Some("application/json"), false));
166        assert!(is_redactable_response(
167            Some("application/json; charset=utf-8"),
168            false
169        ));
170        assert!(!is_redactable_response(Some("text/event-stream"), true));
171        assert!(!is_redactable_response(Some("text/event-stream"), false));
172        assert!(!is_redactable_response(Some("application/json"), true));
173        assert!(!is_redactable_response(None, false));
174    }
175
176    #[test]
177    fn test_redact_openai_response_with_pii() {
178        let redactor = PiiRedactor::default();
179        let body = serde_json::to_vec(&json!({
180            "id": "chatcmpl-123",
181            "object": "chat.completion",
182            "choices": [{
183                "index": 0,
184                "message": {
185                    "role": "assistant",
186                    "content": "You can reach our support team at help@example.com or 555-867-5309."
187                },
188                "finish_reason": "stop"
189            }]
190        }))
191        .unwrap();
192
193        let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
194        let value: Value = serde_json::from_slice(&new_body).unwrap();
195
196        let content = value["choices"][0]["message"]["content"].as_str().unwrap();
197        assert!(content.contains("[EMAIL]"), "content: {content}");
198        assert!(content.contains("[PHONE]"), "content: {content}");
199        assert!(!content.contains("help@example.com"));
200
201        assert_eq!(summary.total_redactions, 2);
202        assert!(summary.entity_types.contains(&"email".to_string()));
203        assert!(summary.entity_types.contains(&"phone".to_string()));
204
205        // Other fields must be preserved unchanged.
206        assert_eq!(value["id"], "chatcmpl-123");
207        assert_eq!(value["choices"][0]["finish_reason"], "stop");
208    }
209
210    #[test]
211    fn test_redact_openai_response_multiple_choices() {
212        let redactor = PiiRedactor::default();
213        let body = serde_json::to_vec(&json!({
214            "choices": [
215                {"index": 0, "message": {"role": "assistant", "content": "Email alice@example.com"}},
216                {"index": 1, "message": {"role": "assistant", "content": "No PII in this one."}}
217            ]
218        }))
219        .unwrap();
220
221        let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
222        let value: Value = serde_json::from_slice(&new_body).unwrap();
223
224        assert!(value["choices"][0]["message"]["content"]
225            .as_str()
226            .unwrap()
227            .contains("[EMAIL]"));
228        assert_eq!(
229            value["choices"][1]["message"]["content"],
230            "No PII in this one."
231        );
232        assert_eq!(summary.total_redactions, 1);
233    }
234
235    #[test]
236    fn test_redact_anthropic_response_with_pii() {
237        let redactor = PiiRedactor::default();
238        let body = serde_json::to_vec(&json!({
239            "id": "msg_123",
240            "type": "message",
241            "role": "assistant",
242            "content": [
243                {"type": "text", "text": "Contact us at help@example.com for assistance."}
244            ]
245        }))
246        .unwrap();
247
248        let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
249        let value: Value = serde_json::from_slice(&new_body).unwrap();
250
251        let text = value["content"][0]["text"].as_str().unwrap();
252        assert!(text.contains("[EMAIL]"), "text: {text}");
253        assert_eq!(summary.total_redactions, 1);
254        assert_eq!(summary.entity_types, vec!["email".to_string()]);
255    }
256
257    #[test]
258    fn test_anthropic_non_text_blocks_untouched() {
259        let redactor = PiiRedactor::default();
260        let body = serde_json::to_vec(&json!({
261            "content": [
262                {"type": "tool_use", "id": "toolu_1", "name": "lookup", "input": {"email": "alice@example.com"}},
263                {"type": "text", "text": "Here is the result."}
264            ]
265        }))
266        .unwrap();
267
268        // No PII in the text block, and tool_use blocks are not scanned.
269        assert!(redact_response_body(&body, &redactor).is_none());
270    }
271
272    #[test]
273    fn test_clean_response_returns_none() {
274        let redactor = PiiRedactor::default();
275        let body = serde_json::to_vec(&json!({
276            "id": "chatcmpl-123",
277            "choices": [{
278                "index": 0,
279                "message": {"role": "assistant", "content": "The capital of France is Paris."},
280                "finish_reason": "stop"
281            }]
282        }))
283        .unwrap();
284
285        assert!(redact_response_body(&body, &redactor).is_none());
286    }
287
288    #[test]
289    fn test_invalid_json_returns_none() {
290        let redactor = PiiRedactor::default();
291        assert!(redact_response_body(b"not json", &redactor).is_none());
292    }
293
294    #[test]
295    fn test_empty_choices_returns_none() {
296        let redactor = PiiRedactor::default();
297        let body = serde_json::to_vec(&json!({"choices": []})).unwrap();
298        assert!(redact_response_body(&body, &redactor).is_none());
299    }
300
301    #[test]
302    fn test_response_without_choices_or_content_returns_none() {
303        let redactor = PiiRedactor::default();
304        let body = serde_json::to_vec(&json!({"error": {"message": "not found"}})).unwrap();
305        assert!(redact_response_body(&body, &redactor).is_none());
306    }
307
308    #[test]
309    fn test_preserves_unicode_content() {
310        let redactor = PiiRedactor::default();
311        let body = serde_json::to_vec(&json!({
312            "choices": [{
313                "index": 0,
314                "message": {"role": "assistant", "content": "こんにちは、email: user@example.com です。"}
315            }]
316        }))
317        .unwrap();
318
319        let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
320        let value: Value = serde_json::from_slice(&new_body).unwrap();
321        let content = value["choices"][0]["message"]["content"].as_str().unwrap();
322
323        assert!(content.contains("こんにちは"));
324        assert!(content.contains("[EMAIL]"));
325        assert_eq!(summary.total_redactions, 1);
326    }
327}