use guardrail_classifiers::PiiRedactor;
use serde_json::Value;
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct ResponseRedactionSummary {
pub total_redactions: usize,
pub entity_types: Vec<String>,
}
impl ResponseRedactionSummary {
fn is_empty(&self) -> bool {
self.total_redactions == 0
}
}
pub fn is_redactable_response(content_type: Option<&str>, is_streaming: bool) -> bool {
if is_streaming {
return false;
}
matches!(content_type, Some(ct) if ct.starts_with("application/json"))
}
pub fn redact_response_body(
body: &[u8],
redactor: &PiiRedactor,
) -> Option<(Vec<u8>, ResponseRedactionSummary)> {
try_redact_response_body(body, redactor).ok().flatten()
}
pub fn try_redact_response_body(
body: &[u8],
redactor: &PiiRedactor,
) -> Result<Option<(Vec<u8>, ResponseRedactionSummary)>, serde_json::Error> {
let mut value: Value = serde_json::from_slice(body)?;
let mut summary = ResponseRedactionSummary::default();
let mut entity_set = std::collections::HashSet::new();
let mut changed = false;
if let Some(choices) = value.get_mut("choices").and_then(Value::as_array_mut) {
for choice in choices.iter_mut() {
if let Some(content) = choice.get_mut("message").and_then(|m| m.get_mut("content")) {
if let Some(text) = content.as_str() {
if let Some((sanitized, records)) = redactor.redact_response_text(text) {
for r in &records {
entity_set.insert(format!("{:?}", r.entity_type).to_lowercase());
}
summary.total_redactions += records.len();
*content = Value::String(sanitized);
changed = true;
}
}
}
}
}
if let Some(blocks) = value.get_mut("content").and_then(Value::as_array_mut) {
for block in blocks.iter_mut() {
let is_text_block = block.get("type").and_then(Value::as_str) == Some("text");
if !is_text_block {
continue;
}
if let Some(text_field) = block.get_mut("text") {
if let Some(text) = text_field.as_str() {
if let Some((sanitized, records)) = redactor.redact_response_text(text) {
for r in &records {
entity_set.insert(format!("{:?}", r.entity_type).to_lowercase());
}
summary.total_redactions += records.len();
*text_field = Value::String(sanitized);
changed = true;
}
}
}
}
}
if let Some(items) = value.get_mut("output").and_then(Value::as_array_mut) {
let parts = items
.iter_mut()
.filter(|item| item.get("type").and_then(Value::as_str) == Some("message"))
.filter_map(|item| item.get_mut("content").and_then(Value::as_array_mut))
.flatten()
.filter(|part| part.get("type").and_then(Value::as_str) == Some("output_text"));
for part in parts {
if let Some(text_field) = part.get_mut("text") {
if let Some(text) = text_field.as_str() {
if let Some((sanitized, records)) = redactor.redact_response_text(text) {
for r in &records {
entity_set.insert(format!("{:?}", r.entity_type).to_lowercase());
}
summary.total_redactions += records.len();
*text_field = Value::String(sanitized);
changed = true;
}
}
}
}
}
if !changed || summary.is_empty() {
return Ok(None);
}
summary.entity_types = entity_set.into_iter().collect();
summary.entity_types.sort();
let new_body = serde_json::to_vec(&value)?;
Ok(Some((new_body, summary)))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_is_redactable_response() {
assert!(is_redactable_response(Some("application/json"), false));
assert!(is_redactable_response(
Some("application/json; charset=utf-8"),
false
));
assert!(!is_redactable_response(Some("text/event-stream"), true));
assert!(!is_redactable_response(Some("text/event-stream"), false));
assert!(!is_redactable_response(Some("application/json"), true));
assert!(!is_redactable_response(None, false));
}
#[test]
fn test_redact_openai_response_with_pii() {
let redactor = PiiRedactor::default();
let body = serde_json::to_vec(&json!({
"id": "chatcmpl-123",
"object": "chat.completion",
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": "You can reach our support team at help@example.com or 555-867-5309."
},
"finish_reason": "stop"
}]
}))
.unwrap();
let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
let value: Value = serde_json::from_slice(&new_body).unwrap();
let content = value["choices"][0]["message"]["content"].as_str().unwrap();
assert!(content.contains("[EMAIL]"), "content: {content}");
assert!(content.contains("[PHONE]"), "content: {content}");
assert!(!content.contains("help@example.com"));
assert_eq!(summary.total_redactions, 2);
assert!(summary.entity_types.contains(&"email".to_string()));
assert!(summary.entity_types.contains(&"phone".to_string()));
assert_eq!(value["id"], "chatcmpl-123");
assert_eq!(value["choices"][0]["finish_reason"], "stop");
}
#[test]
fn test_redact_openai_response_multiple_choices() {
let redactor = PiiRedactor::default();
let body = serde_json::to_vec(&json!({
"choices": [
{"index": 0, "message": {"role": "assistant", "content": "Email alice@example.com"}},
{"index": 1, "message": {"role": "assistant", "content": "No PII in this one."}}
]
}))
.unwrap();
let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
let value: Value = serde_json::from_slice(&new_body).unwrap();
assert!(value["choices"][0]["message"]["content"]
.as_str()
.unwrap()
.contains("[EMAIL]"));
assert_eq!(
value["choices"][1]["message"]["content"],
"No PII in this one."
);
assert_eq!(summary.total_redactions, 1);
}
#[test]
fn test_redact_anthropic_response_with_pii() {
let redactor = PiiRedactor::default();
let body = serde_json::to_vec(&json!({
"id": "msg_123",
"type": "message",
"role": "assistant",
"content": [
{"type": "text", "text": "Contact us at help@example.com for assistance."}
]
}))
.unwrap();
let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
let value: Value = serde_json::from_slice(&new_body).unwrap();
let text = value["content"][0]["text"].as_str().unwrap();
assert!(text.contains("[EMAIL]"), "text: {text}");
assert_eq!(summary.total_redactions, 1);
assert_eq!(summary.entity_types, vec!["email".to_string()]);
}
#[test]
fn test_anthropic_non_text_blocks_untouched() {
let redactor = PiiRedactor::default();
let body = serde_json::to_vec(&json!({
"content": [
{"type": "tool_use", "id": "toolu_1", "name": "lookup", "input": {"email": "alice@example.com"}},
{"type": "text", "text": "Here is the result."}
]
}))
.unwrap();
assert!(redact_response_body(&body, &redactor).is_none());
}
#[test]
fn test_redact_responses_api_output() {
let redactor = PiiRedactor::default();
let body = serde_json::to_vec(&json!({
"id": "resp_1",
"object": "response",
"output": [
{"type": "reasoning", "id": "rs_1", "summary": []},
{"type": "message", "role": "assistant", "content": [
{"type": "output_text", "text": "Write to help@example.com", "annotations": []}
]}
]
}))
.unwrap();
let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
let value: Value = serde_json::from_slice(&new_body).unwrap();
assert_eq!(value["output"][1]["content"][0]["text"], "Write to [EMAIL]");
assert_eq!(value["output"][0]["type"], "reasoning");
assert_eq!(summary.total_redactions, 1);
}
#[test]
fn test_clean_response_returns_none() {
let redactor = PiiRedactor::default();
let body = serde_json::to_vec(&json!({
"id": "chatcmpl-123",
"choices": [{
"index": 0,
"message": {"role": "assistant", "content": "The capital of France is Paris."},
"finish_reason": "stop"
}]
}))
.unwrap();
assert!(redact_response_body(&body, &redactor).is_none());
}
#[test]
fn test_invalid_json_returns_none() {
let redactor = PiiRedactor::default();
assert!(redact_response_body(b"not json", &redactor).is_none());
}
#[test]
fn test_empty_choices_returns_none() {
let redactor = PiiRedactor::default();
let body = serde_json::to_vec(&json!({"choices": []})).unwrap();
assert!(redact_response_body(&body, &redactor).is_none());
}
#[test]
fn test_response_without_choices_or_content_returns_none() {
let redactor = PiiRedactor::default();
let body = serde_json::to_vec(&json!({"error": {"message": "not found"}})).unwrap();
assert!(redact_response_body(&body, &redactor).is_none());
}
#[test]
fn test_preserves_unicode_content() {
let redactor = PiiRedactor::default();
let body = serde_json::to_vec(&json!({
"choices": [{
"index": 0,
"message": {"role": "assistant", "content": "こんにちは、email: user@example.com です。"}
}]
}))
.unwrap();
let (new_body, summary) = redact_response_body(&body, &redactor).unwrap();
let value: Value = serde_json::from_slice(&new_body).unwrap();
let content = value["choices"][0]["message"]["content"].as_str().unwrap();
assert!(content.contains("こんにちは"));
assert!(content.contains("[EMAIL]"));
assert_eq!(summary.total_redactions, 1);
}
}