guardrail_proxy/
response.rs1use guardrail_classifiers::PiiRedactor;
28use serde_json::Value;
29
30#[derive(Debug, Clone, Default, serde::Serialize)]
32pub struct ResponseRedactionSummary {
33 pub total_redactions: usize,
35 pub entity_types: Vec<String>,
37}
38
39impl ResponseRedactionSummary {
40 fn is_empty(&self) -> bool {
41 self.total_redactions == 0
42 }
43}
44
45pub 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
65pub 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 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 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 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 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}