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 try_redact_response_body(body, redactor).ok().flatten()
99}
100
101pub 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 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 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 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 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}