1use guardrail_classifiers::PiiRedactor;
27use serde_json::Value;
28
29#[derive(Debug, Clone, Default, serde::Serialize)]
31pub struct ResponseRedactionSummary {
32 pub total_redactions: usize,
34 pub entity_types: Vec<String>,
36}
37
38impl ResponseRedactionSummary {
39 fn is_empty(&self) -> bool {
40 self.total_redactions == 0
41 }
42}
43
44pub fn is_redactable_response(content_type: Option<&str>, is_streaming: bool) -> bool {
58 if is_streaming {
59 return false;
60 }
61 matches!(content_type, Some(ct) if ct.starts_with("application/json"))
62}
63
64pub fn redact_response_body(
96 body: &[u8],
97 redactor: &PiiRedactor,
98) -> Option<(Vec<u8>, ResponseRedactionSummary)> {
99 try_redact_response_body(body, redactor).ok().flatten()
100}
101
102pub fn try_redact_response_body(
124 body: &[u8],
125 redactor: &PiiRedactor,
126) -> Result<Option<(Vec<u8>, ResponseRedactionSummary)>, serde_json::Error> {
127 let mut value: Value = serde_json::from_slice(body)?;
128 let mut summary = ResponseRedactionSummary::default();
129 let mut entity_set = std::collections::HashSet::new();
130
131 let mut changed = false;
132
133 if let Some(choices) = value.get_mut("choices").and_then(Value::as_array_mut) {
135 for choice in choices.iter_mut() {
136 if let Some(content) = choice.get_mut("message").and_then(|m| m.get_mut("content")) {
137 if let Some(text) = content.as_str() {
138 if let Some((sanitized, records)) = redactor.redact_response_text(text) {
139 for r in &records {
140 entity_set.insert(format!("{:?}", r.entity_type).to_lowercase());
141 }
142 summary.total_redactions += records.len();
143 *content = Value::String(sanitized);
144 changed = true;
145 }
146 }
147 }
148 }
149 }
150
151 if let Some(blocks) = value.get_mut("content").and_then(Value::as_array_mut) {
153 for block in blocks.iter_mut() {
154 let is_text_block = block.get("type").and_then(Value::as_str) == Some("text");
155 if !is_text_block {
156 continue;
157 }
158 if let Some(text_field) = block.get_mut("text") {
159 if let Some(text) = text_field.as_str() {
160 if let Some((sanitized, records)) = redactor.redact_response_text(text) {
161 for r in &records {
162 entity_set.insert(format!("{:?}", r.entity_type).to_lowercase());
163 }
164 summary.total_redactions += records.len();
165 *text_field = Value::String(sanitized);
166 changed = true;
167 }
168 }
169 }
170 }
171 }
172
173 if let Some(items) = value.get_mut("output").and_then(Value::as_array_mut) {
175 let parts = items
176 .iter_mut()
177 .filter(|item| item.get("type").and_then(Value::as_str) == Some("message"))
178 .filter_map(|item| item.get_mut("content").and_then(Value::as_array_mut))
179 .flatten()
180 .filter(|part| part.get("type").and_then(Value::as_str) == Some("output_text"));
181 for part in parts {
182 if let Some(text_field) = part.get_mut("text") {
183 if let Some(text) = text_field.as_str() {
184 if let Some((sanitized, records)) = redactor.redact_response_text(text) {
185 for r in &records {
186 entity_set.insert(format!("{:?}", r.entity_type).to_lowercase());
187 }
188 summary.total_redactions += records.len();
189 *text_field = Value::String(sanitized);
190 changed = true;
191 }
192 }
193 }
194 }
195 }
196
197 if !changed || summary.is_empty() {
198 return Ok(None);
199 }
200
201 summary.entity_types = entity_set.into_iter().collect();
202 summary.entity_types.sort();
203
204 let new_body = serde_json::to_vec(&value)?;
205 Ok(Some((new_body, summary)))
206}
207
208#[cfg(test)]
209mod tests {
210 use super::*;
211 use serde_json::json;
212
213 #[test]
214 fn test_is_redactable_response() {
215 assert!(is_redactable_response(Some("application/json"), false));
216 assert!(is_redactable_response(
217 Some("application/json; charset=utf-8"),
218 false
219 ));
220 assert!(!is_redactable_response(Some("text/event-stream"), true));
221 assert!(!is_redactable_response(Some("text/event-stream"), false));
222 assert!(!is_redactable_response(Some("application/json"), true));
223 assert!(!is_redactable_response(None, false));
224 }
225
226 #[test]
227 fn test_redact_openai_response_with_pii() {
228 let redactor = PiiRedactor::default();
229 let body = serde_json::to_vec(&json!({
230 "id": "chatcmpl-123",
231 "object": "chat.completion",
232 "choices": [{
233 "index": 0,
234 "message": {
235 "role": "assistant",
236 "content": "You can reach our support team at help@example.com or 555-867-5309."
237 },
238 "finish_reason": "stop"
239 }]
240 }))
241 .unwrap();
242
243 let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
244 let value: Value = serde_json::from_slice(&new_body).unwrap();
245
246 let content = value["choices"][0]["message"]["content"].as_str().unwrap();
247 assert!(content.contains("[EMAIL]"), "content: {content}");
248 assert!(content.contains("[PHONE]"), "content: {content}");
249 assert!(!content.contains("help@example.com"));
250
251 assert_eq!(summary.total_redactions, 2);
252 assert!(summary.entity_types.contains(&"email".to_string()));
253 assert!(summary.entity_types.contains(&"phone".to_string()));
254
255 assert_eq!(value["id"], "chatcmpl-123");
257 assert_eq!(value["choices"][0]["finish_reason"], "stop");
258 }
259
260 #[test]
261 fn test_redact_openai_response_multiple_choices() {
262 let redactor = PiiRedactor::default();
263 let body = serde_json::to_vec(&json!({
264 "choices": [
265 {"index": 0, "message": {"role": "assistant", "content": "Email alice@example.com"}},
266 {"index": 1, "message": {"role": "assistant", "content": "No PII in this one."}}
267 ]
268 }))
269 .unwrap();
270
271 let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
272 let value: Value = serde_json::from_slice(&new_body).unwrap();
273
274 assert!(value["choices"][0]["message"]["content"]
275 .as_str()
276 .unwrap()
277 .contains("[EMAIL]"));
278 assert_eq!(
279 value["choices"][1]["message"]["content"],
280 "No PII in this one."
281 );
282 assert_eq!(summary.total_redactions, 1);
283 }
284
285 #[test]
286 fn test_redact_anthropic_response_with_pii() {
287 let redactor = PiiRedactor::default();
288 let body = serde_json::to_vec(&json!({
289 "id": "msg_123",
290 "type": "message",
291 "role": "assistant",
292 "content": [
293 {"type": "text", "text": "Contact us at help@example.com for assistance."}
294 ]
295 }))
296 .unwrap();
297
298 let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
299 let value: Value = serde_json::from_slice(&new_body).unwrap();
300
301 let text = value["content"][0]["text"].as_str().unwrap();
302 assert!(text.contains("[EMAIL]"), "text: {text}");
303 assert_eq!(summary.total_redactions, 1);
304 assert_eq!(summary.entity_types, vec!["email".to_string()]);
305 }
306
307 #[test]
308 fn test_anthropic_non_text_blocks_untouched() {
309 let redactor = PiiRedactor::default();
310 let body = serde_json::to_vec(&json!({
311 "content": [
312 {"type": "tool_use", "id": "toolu_1", "name": "lookup", "input": {"email": "alice@example.com"}},
313 {"type": "text", "text": "Here is the result."}
314 ]
315 }))
316 .unwrap();
317
318 assert!(redact_response_body(&body, &redactor).is_none());
320 }
321
322 #[test]
323 fn test_redact_responses_api_output() {
324 let redactor = PiiRedactor::default();
325 let body = serde_json::to_vec(&json!({
326 "id": "resp_1",
327 "object": "response",
328 "output": [
329 {"type": "reasoning", "id": "rs_1", "summary": []},
330 {"type": "message", "role": "assistant", "content": [
331 {"type": "output_text", "text": "Write to help@example.com", "annotations": []}
332 ]}
333 ]
334 }))
335 .unwrap();
336
337 let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
338 let value: Value = serde_json::from_slice(&new_body).unwrap();
339 assert_eq!(value["output"][1]["content"][0]["text"], "Write to [EMAIL]");
340 assert_eq!(value["output"][0]["type"], "reasoning");
341 assert_eq!(summary.total_redactions, 1);
342 }
343
344 #[test]
345 fn test_clean_response_returns_none() {
346 let redactor = PiiRedactor::default();
347 let body = serde_json::to_vec(&json!({
348 "id": "chatcmpl-123",
349 "choices": [{
350 "index": 0,
351 "message": {"role": "assistant", "content": "The capital of France is Paris."},
352 "finish_reason": "stop"
353 }]
354 }))
355 .unwrap();
356
357 assert!(redact_response_body(&body, &redactor).is_none());
358 }
359
360 #[test]
361 fn test_invalid_json_returns_none() {
362 let redactor = PiiRedactor::default();
363 assert!(redact_response_body(b"not json", &redactor).is_none());
364 }
365
366 #[test]
367 fn test_empty_choices_returns_none() {
368 let redactor = PiiRedactor::default();
369 let body = serde_json::to_vec(&json!({"choices": []})).unwrap();
370 assert!(redact_response_body(&body, &redactor).is_none());
371 }
372
373 #[test]
374 fn test_response_without_choices_or_content_returns_none() {
375 let redactor = PiiRedactor::default();
376 let body = serde_json::to_vec(&json!({"error": {"message": "not found"}})).unwrap();
377 assert!(redact_response_body(&body, &redactor).is_none());
378 }
379
380 #[test]
381 fn test_preserves_unicode_content() {
382 let redactor = PiiRedactor::default();
383 let body = serde_json::to_vec(&json!({
384 "choices": [{
385 "index": 0,
386 "message": {"role": "assistant", "content": "こんにちは、email: user@example.com です。"}
387 }]
388 }))
389 .unwrap();
390
391 let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
392 let value: Value = serde_json::from_slice(&new_body).unwrap();
393 let content = value["choices"][0]["message"]["content"].as_str().unwrap();
394
395 assert!(content.contains("こんにちは"));
396 assert!(content.contains("[EMAIL]"));
397 assert_eq!(summary.total_redactions, 1);
398 }
399}