1use base::telemetry::{
7 ApiErrorPayload, EventPayload, McpConnectionErrorPayload, TelemetryEvent, ToolExecutionPayload,
8};
9
10#[derive(Debug, Clone, Copy)]
11pub struct RedactionPolicy {
12 pub redact_error_messages: bool,
13}
14
15impl RedactionPolicy {
16 pub fn none() -> Self {
17 Self {
18 redact_error_messages: false,
19 }
20 }
21
22 pub fn all() -> Self {
23 Self {
24 redact_error_messages: true,
25 }
26 }
27
28 pub fn scrub_message(&self, message: &str) -> String {
29 match (self.redact_error_messages, message.is_empty()) {
30 (_, true) => String::new(),
31 (true, false) => "[REDACTED]".to_string(),
32 (false, false) => message.to_string(),
33 }
34 }
35}
36
37impl Default for RedactionPolicy {
38 fn default() -> Self {
39 Self::all()
40 }
41}
42
43pub trait Redact {
46 fn redact(self, policy: &RedactionPolicy) -> Self;
47}
48
49impl Redact for ApiErrorPayload {
50 fn redact(mut self, policy: &RedactionPolicy) -> Self {
51 self.error_message = policy.scrub_message(&self.error_message);
52 self
53 }
54}
55
56impl Redact for ToolExecutionPayload {
57 fn redact(mut self, policy: &RedactionPolicy) -> Self {
58 self.error_message = self.error_message.map(|m| policy.scrub_message(&m));
59 self
60 }
61}
62
63impl Redact for McpConnectionErrorPayload {
64 fn redact(mut self, policy: &RedactionPolicy) -> Self {
65 self.error_message = policy.scrub_message(&self.error_message);
66 self
67 }
68}
69
70impl Redact for TelemetryEvent {
71 fn redact(self, policy: &RedactionPolicy) -> Self {
72 let payload = match self.payload {
73 EventPayload::ApiError(p) => EventPayload::ApiError(p.redact(policy)),
74 EventPayload::ToolExecution(p) => EventPayload::ToolExecution(p.redact(policy)),
75 EventPayload::McpConnectionError(p) => {
76 EventPayload::McpConnectionError(p.redact(policy))
77 }
78 other => other,
79 };
80 Self { payload, ..self }
81 }
82}
83
84pub fn sanitize_path(path: &str) -> String {
92 if let Some(rest) = path
94 .strip_prefix("/Users/")
95 .or_else(|| path.strip_prefix("/home/"))
96 {
97 if let Some(pos) = rest.find('/') {
99 return format!("~{}", &rest[pos..]);
100 }
101 return "~".to_string();
103 }
104
105 let bytes = path.as_bytes();
108 if bytes.len() >= 3 && bytes[1] == b':' && (bytes[2] == b'\\' || bytes[2] == b'/') {
109 let prefix = &bytes[0..2]; let rest = &bytes[3..]; if rest.len() >= 6
112 && (rest[0..6].eq_ignore_ascii_case(b"Users\\")
113 || rest[0..6].eq_ignore_ascii_case(b"Users/"))
114 {
115 let after_users = &rest[6..]; if let Some(pos) = after_users.iter().position(|&b| b == b'\\' || b == b'/') {
117 let remaining = std::str::from_utf8(&after_users[pos..]).unwrap_or("");
118 return format!(
119 "{prefix}~{remaining}",
120 prefix = std::str::from_utf8(prefix).unwrap_or("C:")
121 );
122 }
123 return format!("{}~", std::str::from_utf8(prefix).unwrap_or("C:"));
124 }
125 }
126
127 path.to_string()
128}
129
130#[cfg(test)]
131mod tests {
132 use super::*;
133
134 #[test]
135 fn sanitize_users_path() {
136 assert_eq!(
137 sanitize_path("/Users/xbits/project/file.rs"),
138 "~/project/file.rs"
139 );
140 }
141
142 #[test]
143 fn sanitize_home_path() {
144 assert_eq!(
145 sanitize_path("/home/alice/.config/app.toml"),
146 "~/.config/app.toml"
147 );
148 }
149
150 #[test]
151 fn sanitize_nested_users_path() {
152 assert_eq!(
153 sanitize_path("/Users/bob/Documents/work/notes.txt"),
154 "~/Documents/work/notes.txt"
155 );
156 }
157
158 #[test]
159 fn sanitize_windows_path() {
160 let result = sanitize_path("C:\\Users\\bob\\Documents\\notes.txt");
162 assert_eq!(result, "C:~\\Documents\\notes.txt");
163 }
164
165 #[test]
166 fn sanitize_non_home_path_unchanged() {
167 let path = "/opt/app/config.json";
168 assert_eq!(sanitize_path(path), path);
169 }
170
171 #[test]
172 fn sanitize_relative_path_unchanged() {
173 let path = "./src/main.rs";
174 assert_eq!(sanitize_path(path), path);
175 }
176
177 #[test]
178 fn sanitize_empty_string_unchanged() {
179 assert_eq!(sanitize_path(""), "");
180 }
181
182 #[test]
183 fn a_message_is_replaced_whole_or_passed_through() {
184 let message = "mail ops@example.com about /Users/me/x";
185 assert_eq!(RedactionPolicy::all().scrub_message(message), "[REDACTED]");
186 assert_eq!(RedactionPolicy::none().scrub_message(message), message);
187 assert_eq!(RedactionPolicy::all().scrub_message(""), "");
188 }
189
190 #[test]
191 fn api_error_redacts_error_message() {
192 let event = TelemetryEvent::api_error(
193 "sess",
194 1,
195 None,
196 ApiErrorPayload {
197 model: "claude".into(),
198 error_kind: "api".into(),
199 http_status: Some(429),
200 error_message: "You have exceeded your rate limit".into(),
201 latency_ms: 500,
202 },
203 )
204 .redact(&RedactionPolicy::all());
205 let v = serde_json::to_value(event).unwrap();
206 assert_eq!(v["error_message"], "[REDACTED]");
207 assert_eq!(v["error_kind"], "api");
208 assert_eq!(v["http_status"], 429);
209 }
210
211 #[test]
212 fn tool_execution_redacts_error_on_failure() {
213 let event = TelemetryEvent::tool_execution(
214 "sess",
215 3,
216 None,
217 ToolExecutionPayload {
218 tool_name: "Bash".into(),
219 tool_use_id: "tu_01".into(),
220 outcome: base::telemetry::ToolOutcome::Failed,
221 is_error: true,
222 error_message: Some("sensitive stderr output".into()),
223 latency_ms: 200,
224 input_json_size: 10,
225 result_content_size: 500,
226 user_approved: true,
227 },
228 )
229 .redact(&RedactionPolicy::all());
230 let v = serde_json::to_value(event).unwrap();
231 assert_eq!(v["error_message"], "[REDACTED]");
232 assert_eq!(v["tool_name"], "Bash");
233 assert_eq!(v["outcome"], "failed");
234 }
235
236 #[test]
237 fn mcp_connection_error_redacts_error_message() {
238 let event = TelemetryEvent::mcp_connection_error(
239 "sess",
240 1,
241 None,
242 McpConnectionErrorPayload {
243 server_name: "db".into(),
244 error_message: "connection to localhost:5432 refused".into(),
245 },
246 )
247 .redact(&RedactionPolicy::all());
248 let v = serde_json::to_value(event).unwrap();
249 assert_eq!(v["error_message"], "[REDACTED]");
250 }
251}