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