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