use serde_json::{Map, Value}; use thiserror::Error; pub const REDACTED_MARKER: &str = "[REDACTED]"; const TRUNCATED_MARKER: &str = "[TRUNCATED]"; const MIN_EVENT_BYTES: usize = 512; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct RedactionLimits { pub max_string_bytes: usize, pub max_array_items: usize, pub max_object_fields: usize, pub max_depth: usize, pub max_event_bytes: usize, } impl Default for RedactionLimits { fn default() -> Self { Self { max_string_bytes: 1024, max_array_items: 32, max_object_fields: 64, max_depth: 8, max_event_bytes: 16 * 1024, } } } impl RedactionLimits { pub fn validate(self) -> Result<(), RedactionLimitsError> { for (field, value, minimum) in [ ( "max_string_bytes", self.max_string_bytes, TRUNCATED_MARKER.len(), ), ("max_array_items", self.max_array_items, 1), ("max_object_fields", self.max_object_fields, 1), ("max_depth", self.max_depth, 1), ("max_event_bytes", self.max_event_bytes, MIN_EVENT_BYTES), ] { if value < minimum { return Err(RedactionLimitsError::TooSmall { field, minimum }); } } Ok(()) } } #[derive(Debug, Error)] pub enum RedactionLimitsError { #[error("invalid redaction limit {field}: minimum is {minimum}")] TooSmall { field: &'static str, minimum: usize }, } #[derive(Debug, Error)] pub enum SafeJsonError { #[error(transparent)] InvalidLimits(#[from] RedactionLimitsError), #[error(transparent)] Serialization(#[from] serde_json::Error), } pub fn redact_value(value: &Value, limits: RedactionLimits) -> Value { redact_at_depth(value, limits, 0) } pub fn safe_json(value: &Value, limits: RedactionLimits) -> Result { limits.validate()?; let serialized = serde_json::to_string(&redact_value(value, limits))?; if serialized.len() <= limits.max_event_bytes { return Ok(serialized); } Ok(serde_json::to_string(&serde_json::json!({ "truncated": true }))?) } pub(crate) fn truncate_string(value: &str, max_bytes: usize) -> String { if value.len() <= max_bytes { return value.to_owned(); } if max_bytes == 0 { return String::new(); } let marker = if max_bytes >= TRUNCATED_MARKER.len() { TRUNCATED_MARKER } else { "" }; let content_budget = max_bytes.saturating_sub(marker.len()); let mut boundary = content_budget.min(value.len()); while boundary > 0 && !value.is_char_boundary(boundary) { boundary -= 1; } let mut truncated = String::with_capacity(max_bytes); truncated.push_str(&value[..boundary]); if marker.is_empty() { let mut marker_boundary = max_bytes.min(TRUNCATED_MARKER.len()); while marker_boundary > 0 && !TRUNCATED_MARKER.is_char_boundary(marker_boundary) { marker_boundary -= 1; } truncated.clear(); truncated.push_str(&TRUNCATED_MARKER[..marker_boundary]); } else { truncated.push_str(marker); } truncated } fn redact_at_depth(value: &Value, limits: RedactionLimits, depth: usize) -> Value { if depth >= limits.max_depth { return Value::String(TRUNCATED_MARKER.to_owned()); } match value { Value::Null | Value::Bool(_) | Value::Number(_) => value.clone(), Value::String(value) => Value::String(truncate_string(value, limits.max_string_bytes)), Value::Array(values) => redact_array(values, limits, depth), Value::Object(values) => redact_object(values, limits, depth), } } fn redact_array(values: &[Value], limits: RedactionLimits, depth: usize) -> Value { if limits.max_array_items == 0 { return Value::Array(Vec::new()); } let truncated = values.len() > limits.max_array_items; let value_limit = if truncated { limits.max_array_items.saturating_sub(1) } else { limits.max_array_items }; let mut output: Vec<_> = values .iter() .take(value_limit) .map(|value| redact_at_depth(value, limits, depth + 1)) .collect(); if truncated { output.push(Value::String(TRUNCATED_MARKER.to_owned())); } Value::Array(output) } fn redact_object(values: &Map, limits: RedactionLimits, depth: usize) -> Value { if limits.max_object_fields == 0 { return Value::Object(Map::new()); } let truncated = values.len() > limits.max_object_fields; let value_limit = if truncated { limits.max_object_fields.saturating_sub(1) } else { limits.max_object_fields }; let mut output = Map::new(); for (index, (key, value)) in values.iter().take(value_limit).enumerate() { let cleaned = if is_sensitive_key(key) { Value::String(REDACTED_MARKER.to_owned()) } else if is_url_key(key) { value .as_str() .map(sanitize_url) .map(|value| truncate_string(&value, limits.max_string_bytes)) .map(Value::String) .unwrap_or_else(|| redact_at_depth(value, limits, depth + 1)) } else { redact_at_depth(value, limits, depth + 1) }; output.insert( bounded_object_key(key, limits.max_string_bytes, index), cleaned, ); } if truncated { output.insert( "_truncated".to_owned(), Value::String(TRUNCATED_MARKER.to_owned()), ); } Value::Object(output) } fn normalized_key(key: &str) -> String { key.bytes() .filter(|byte| !matches!(byte, b'_' | b'-' | b'.')) .map(|byte| byte.to_ascii_lowercase() as char) .collect() } fn is_sensitive_key(key: &str) -> bool { let key = normalized_key(key); let exact_match = matches!( key.as_str(), "password" | "passwd" | "secret" | "token" | "apikey" | "accesskey" | "secretkey" | "authorization" | "proxyauthorization" | "cookie" | "setcookie" | "query" | "querystring" | "rawquery" | "urlquery" | "payload" | "body" | "requestbody" | "arguments" | "result" | "response" | "context" | "error" | "errormessage" ); let contains_high_risk_name = [ "password", "passwd", "secret", "token", "apikey", "accesskey", "authorization", "cookie", ] .iter() .any(|part| key.contains(part)); exact_match || contains_high_risk_name || key.ends_with("payload") || key.ends_with("body") || key.ends_with("arguments") || key.ends_with("result") || key.ends_with("response") || key.ends_with("query") || key.ends_with("context") || key.starts_with("query") } fn is_url_key(key: &str) -> bool { let key = normalized_key(key); matches!( key.as_str(), "url" | "uri" | "endpoint" | "endpointurl" | "endpointuri" | "requesturl" | "targeturl" ) || key.ends_with("url") || key.ends_with("uri") || key.ends_with("endpoint") } fn sanitize_url(value: &str) -> String { let without_query = value .find(['?', '#']) .map(|index| &value[..index]) .unwrap_or(value); let Some(scheme_end) = without_query.find("://") else { return without_query.to_owned(); }; let authority_start = scheme_end + 3; let authority_end = without_query[authority_start..] .find('/') .map(|index| authority_start + index) .unwrap_or(without_query.len()); let authority = &without_query[authority_start..authority_end]; let Some(userinfo_end) = authority.rfind('@') else { return without_query.to_owned(); }; format!( "{}{}", &without_query[..authority_start], &without_query[authority_start + userinfo_end + 1..] ) } fn bounded_object_key(key: &str, max_bytes: usize, index: usize) -> String { if key.len() <= max_bytes { return key.to_owned(); } truncate_string(&format!("_truncated_key_{index}"), max_bytes) }