use base::telemetry::{
ApiErrorPayload, EventPayload, McpConnectionErrorPayload, TelemetryEvent, ToolExecutionPayload,
};
#[derive(Debug, Clone, Copy)]
pub struct RedactionPolicy {
pub redact_error_messages: bool,
}
impl RedactionPolicy {
pub fn none() -> Self {
Self {
redact_error_messages: false,
}
}
pub fn all() -> Self {
Self {
redact_error_messages: true,
}
}
pub fn scrub_message(&self, message: &str) -> String {
match (self.redact_error_messages, message.is_empty()) {
(_, true) => String::new(),
(true, false) => "[REDACTED]".to_string(),
(false, false) => message.to_string(),
}
}
}
impl Default for RedactionPolicy {
fn default() -> Self {
Self::all()
}
}
pub trait Redact {
fn redact(self, policy: &RedactionPolicy) -> Self;
}
impl Redact for ApiErrorPayload {
fn redact(mut self, policy: &RedactionPolicy) -> Self {
self.error_message = policy.scrub_message(&self.error_message);
self
}
}
impl Redact for ToolExecutionPayload {
fn redact(mut self, policy: &RedactionPolicy) -> Self {
self.error_message = self.error_message.map(|m| policy.scrub_message(&m));
self
}
}
impl Redact for McpConnectionErrorPayload {
fn redact(mut self, policy: &RedactionPolicy) -> Self {
self.error_message = policy.scrub_message(&self.error_message);
self
}
}
impl Redact for TelemetryEvent {
fn redact(self, policy: &RedactionPolicy) -> Self {
let payload = match self.payload {
EventPayload::ApiError(p) => EventPayload::ApiError(p.redact(policy)),
EventPayload::ToolExecution(p) => EventPayload::ToolExecution(p.redact(policy)),
EventPayload::McpConnectionError(p) => {
EventPayload::McpConnectionError(p.redact(policy))
}
other => other,
};
Self { payload, ..self }
}
}
pub fn sanitize_path(path: &str) -> String {
if let Some(rest) = path
.strip_prefix("/Users/")
.or_else(|| path.strip_prefix("/home/"))
{
if let Some(pos) = rest.find('/') {
return format!("~{}", &rest[pos..]);
}
return "~".to_string();
}
let bytes = path.as_bytes();
if bytes.len() >= 3 && bytes[1] == b':' && (bytes[2] == b'\\' || bytes[2] == b'/') {
let prefix = &bytes[0..2]; let rest = &bytes[3..]; if rest.len() >= 6
&& (rest[0..6].eq_ignore_ascii_case(b"Users\\")
|| rest[0..6].eq_ignore_ascii_case(b"Users/"))
{
let after_users = &rest[6..]; if let Some(pos) = after_users.iter().position(|&b| b == b'\\' || b == b'/') {
let remaining = std::str::from_utf8(&after_users[pos..]).unwrap_or("");
return format!(
"{prefix}~{remaining}",
prefix = std::str::from_utf8(prefix).unwrap_or("C:")
);
}
return format!("{}~", std::str::from_utf8(prefix).unwrap_or("C:"));
}
}
path.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sanitize_users_path() {
assert_eq!(
sanitize_path("/Users/xbits/project/file.rs"),
"~/project/file.rs"
);
}
#[test]
fn sanitize_home_path() {
assert_eq!(
sanitize_path("/home/alice/.config/app.toml"),
"~/.config/app.toml"
);
}
#[test]
fn sanitize_nested_users_path() {
assert_eq!(
sanitize_path("/Users/bob/Documents/work/notes.txt"),
"~/Documents/work/notes.txt"
);
}
#[test]
fn sanitize_windows_path() {
let result = sanitize_path("C:\\Users\\bob\\Documents\\notes.txt");
assert_eq!(result, "C:~\\Documents\\notes.txt");
}
#[test]
fn sanitize_non_home_path_unchanged() {
let path = "/opt/app/config.json";
assert_eq!(sanitize_path(path), path);
}
#[test]
fn sanitize_relative_path_unchanged() {
let path = "./src/main.rs";
assert_eq!(sanitize_path(path), path);
}
#[test]
fn sanitize_empty_string_unchanged() {
assert_eq!(sanitize_path(""), "");
}
#[test]
fn a_message_is_replaced_whole_or_passed_through() {
let message = "mail ops@example.com about /Users/me/x";
assert_eq!(RedactionPolicy::all().scrub_message(message), "[REDACTED]");
assert_eq!(RedactionPolicy::none().scrub_message(message), message);
assert_eq!(RedactionPolicy::all().scrub_message(""), "");
}
#[test]
fn api_error_redacts_error_message() {
let event = TelemetryEvent::api_error(
"sess",
1,
None,
ApiErrorPayload {
model: "claude".into(),
error_kind: "api".into(),
http_status: Some(429),
error_message: "You have exceeded your rate limit".into(),
latency_ms: 500,
},
)
.redact(&RedactionPolicy::all());
let v = serde_json::to_value(event).unwrap();
assert_eq!(v["error_message"], "[REDACTED]");
assert_eq!(v["error_kind"], "api");
assert_eq!(v["http_status"], 429);
}
#[test]
fn tool_execution_redacts_error_on_failure() {
let event = TelemetryEvent::tool_execution(
"sess",
3,
None,
ToolExecutionPayload {
tool_name: "Bash".into(),
tool_use_id: "tu_01".into(),
outcome: base::telemetry::ToolOutcome::Failed,
is_error: true,
error_message: Some("sensitive stderr output".into()),
latency_ms: 200,
input_json_size: 10,
result_content_size: 500,
user_approved: true,
},
)
.redact(&RedactionPolicy::all());
let v = serde_json::to_value(event).unwrap();
assert_eq!(v["error_message"], "[REDACTED]");
assert_eq!(v["tool_name"], "Bash");
assert_eq!(v["outcome"], "failed");
}
#[test]
fn mcp_connection_error_redacts_error_message() {
let event = TelemetryEvent::mcp_connection_error(
"sess",
1,
None,
McpConnectionErrorPayload {
server_name: "db".into(),
error_message: "connection to localhost:5432 refused".into(),
},
)
.redact(&RedactionPolicy::all());
let v = serde_json::to_value(event).unwrap();
assert_eq!(v["error_message"], "[REDACTED]");
}
}