guardrail_proxy/
response.rs1use guardrail_classifiers::PiiRedactor;
26use serde_json::Value;
27
28#[derive(Debug, Clone, Default, serde::Serialize)]
30pub struct ResponseRedactionSummary {
31 pub total_redactions: usize,
33 pub entity_types: Vec<String>,
35}
36
37impl ResponseRedactionSummary {
38 fn is_empty(&self) -> bool {
39 self.total_redactions == 0
40 }
41}
42
43pub 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
63pub fn redact_response_body(
95 body: &[u8],
96 redactor: &PiiRedactor,
97) -> Option<(Vec<u8>, ResponseRedactionSummary)> {
98 let mut value: Value = serde_json::from_slice(body).ok()?;
99 let mut summary = ResponseRedactionSummary::default();
100 let mut entity_set = std::collections::HashSet::new();
101
102 let mut changed = false;
103
104 if let Some(choices) = value.get_mut("choices").and_then(Value::as_array_mut) {
106 for choice in choices.iter_mut() {
107 if let Some(content) = choice.get_mut("message").and_then(|m| m.get_mut("content")) {
108 if let Some(text) = content.as_str() {
109 if let Some((sanitized, records)) = redactor.redact_response_text(text) {
110 for r in &records {
111 entity_set.insert(format!("{:?}", r.entity_type).to_lowercase());
112 }
113 summary.total_redactions += records.len();
114 *content = Value::String(sanitized);
115 changed = true;
116 }
117 }
118 }
119 }
120 }
121
122 if let Some(blocks) = value.get_mut("content").and_then(Value::as_array_mut) {
124 for block in blocks.iter_mut() {
125 let is_text_block = block.get("type").and_then(Value::as_str) == Some("text");
126 if !is_text_block {
127 continue;
128 }
129 if let Some(text_field) = block.get_mut("text") {
130 if let Some(text) = text_field.as_str() {
131 if let Some((sanitized, records)) = redactor.redact_response_text(text) {
132 for r in &records {
133 entity_set.insert(format!("{:?}", r.entity_type).to_lowercase());
134 }
135 summary.total_redactions += records.len();
136 *text_field = Value::String(sanitized);
137 changed = true;
138 }
139 }
140 }
141 }
142 }
143
144 if !changed || summary.is_empty() {
145 return None;
146 }
147
148 summary.entity_types = entity_set.into_iter().collect();
149 summary.entity_types.sort();
150
151 let new_body = serde_json::to_vec(&value).ok()?;
152 Some((new_body, summary))
153}
154
155#[cfg(test)]
156mod tests {
157 use super::*;
158 use serde_json::json;
159
160 #[test]
161 fn test_is_redactable_response() {
162 assert!(is_redactable_response(Some("application/json"), false));
163 assert!(is_redactable_response(
164 Some("application/json; charset=utf-8"),
165 false
166 ));
167 assert!(!is_redactable_response(Some("text/event-stream"), true));
168 assert!(!is_redactable_response(Some("text/event-stream"), false));
169 assert!(!is_redactable_response(Some("application/json"), true));
170 assert!(!is_redactable_response(None, false));
171 }
172
173 #[test]
174 fn test_redact_openai_response_with_pii() {
175 let redactor = PiiRedactor::default();
176 let body = serde_json::to_vec(&json!({
177 "id": "chatcmpl-123",
178 "object": "chat.completion",
179 "choices": [{
180 "index": 0,
181 "message": {
182 "role": "assistant",
183 "content": "You can reach our support team at help@example.com or 555-867-5309."
184 },
185 "finish_reason": "stop"
186 }]
187 }))
188 .unwrap();
189
190 let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
191 let value: Value = serde_json::from_slice(&new_body).unwrap();
192
193 let content = value["choices"][0]["message"]["content"].as_str().unwrap();
194 assert!(content.contains("[EMAIL]"), "content: {content}");
195 assert!(content.contains("[PHONE]"), "content: {content}");
196 assert!(!content.contains("help@example.com"));
197
198 assert_eq!(summary.total_redactions, 2);
199 assert!(summary.entity_types.contains(&"email".to_string()));
200 assert!(summary.entity_types.contains(&"phone".to_string()));
201
202 assert_eq!(value["id"], "chatcmpl-123");
204 assert_eq!(value["choices"][0]["finish_reason"], "stop");
205 }
206
207 #[test]
208 fn test_redact_openai_response_multiple_choices() {
209 let redactor = PiiRedactor::default();
210 let body = serde_json::to_vec(&json!({
211 "choices": [
212 {"index": 0, "message": {"role": "assistant", "content": "Email alice@example.com"}},
213 {"index": 1, "message": {"role": "assistant", "content": "No PII in this one."}}
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 assert!(value["choices"][0]["message"]["content"]
222 .as_str()
223 .unwrap()
224 .contains("[EMAIL]"));
225 assert_eq!(
226 value["choices"][1]["message"]["content"],
227 "No PII in this one."
228 );
229 assert_eq!(summary.total_redactions, 1);
230 }
231
232 #[test]
233 fn test_redact_anthropic_response_with_pii() {
234 let redactor = PiiRedactor::default();
235 let body = serde_json::to_vec(&json!({
236 "id": "msg_123",
237 "type": "message",
238 "role": "assistant",
239 "content": [
240 {"type": "text", "text": "Contact us at help@example.com for assistance."}
241 ]
242 }))
243 .unwrap();
244
245 let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
246 let value: Value = serde_json::from_slice(&new_body).unwrap();
247
248 let text = value["content"][0]["text"].as_str().unwrap();
249 assert!(text.contains("[EMAIL]"), "text: {text}");
250 assert_eq!(summary.total_redactions, 1);
251 assert_eq!(summary.entity_types, vec!["email".to_string()]);
252 }
253
254 #[test]
255 fn test_anthropic_non_text_blocks_untouched() {
256 let redactor = PiiRedactor::default();
257 let body = serde_json::to_vec(&json!({
258 "content": [
259 {"type": "tool_use", "id": "toolu_1", "name": "lookup", "input": {"email": "alice@example.com"}},
260 {"type": "text", "text": "Here is the result."}
261 ]
262 }))
263 .unwrap();
264
265 assert!(redact_response_body(&body, &redactor).is_none());
267 }
268
269 #[test]
270 fn test_clean_response_returns_none() {
271 let redactor = PiiRedactor::default();
272 let body = serde_json::to_vec(&json!({
273 "id": "chatcmpl-123",
274 "choices": [{
275 "index": 0,
276 "message": {"role": "assistant", "content": "The capital of France is Paris."},
277 "finish_reason": "stop"
278 }]
279 }))
280 .unwrap();
281
282 assert!(redact_response_body(&body, &redactor).is_none());
283 }
284
285 #[test]
286 fn test_invalid_json_returns_none() {
287 let redactor = PiiRedactor::default();
288 assert!(redact_response_body(b"not json", &redactor).is_none());
289 }
290
291 #[test]
292 fn test_empty_choices_returns_none() {
293 let redactor = PiiRedactor::default();
294 let body = serde_json::to_vec(&json!({"choices": []})).unwrap();
295 assert!(redact_response_body(&body, &redactor).is_none());
296 }
297
298 #[test]
299 fn test_response_without_choices_or_content_returns_none() {
300 let redactor = PiiRedactor::default();
301 let body = serde_json::to_vec(&json!({"error": {"message": "not found"}})).unwrap();
302 assert!(redact_response_body(&body, &redactor).is_none());
303 }
304
305 #[test]
306 fn test_preserves_unicode_content() {
307 let redactor = PiiRedactor::default();
308 let body = serde_json::to_vec(&json!({
309 "choices": [{
310 "index": 0,
311 "message": {"role": "assistant", "content": "こんにちは、email: user@example.com です。"}
312 }]
313 }))
314 .unwrap();
315
316 let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
317 let value: Value = serde_json::from_slice(&new_body).unwrap();
318 let content = value["choices"][0]["message"]["content"].as_str().unwrap();
319
320 assert!(content.contains("こんにちは"));
321 assert!(content.contains("[EMAIL]"));
322 assert_eq!(summary.total_redactions, 1);
323 }
324}