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