1use super::AuditEvent;
21use serde_json::Value;
22
23pub const REDACTED: &str = "[REDACTED]";
25
26pub trait Redactor: Send + Sync {
28 fn redacts(&self, key: &str, path: &str) -> bool;
33
34 fn redact_event(&self, event: &mut AuditEvent) {
40 for (key, value) in &mut event.metadata {
41 if self.redacts(key, key) {
42 *value = Value::String(REDACTED.to_string());
43 } else {
44 redact_within(self, value, key);
45 }
46 }
47 if let Some(params) = &mut event.params {
48 redact_within(self, params, "params");
49 }
50 }
51}
52
53fn redact_within<R: Redactor + ?Sized>(redactor: &R, value: &mut Value, path: &str) {
55 match value {
56 Value::Object(map) => {
57 for (key, child) in map.iter_mut() {
58 let child_path = format!("{path}.{key}");
59 if redactor.redacts(key, &child_path) {
60 *child = Value::String(REDACTED.to_string());
61 } else {
62 redact_within(redactor, child, &child_path);
63 }
64 }
65 }
66 Value::Array(items) => {
67 for (index, item) in items.iter_mut().enumerate() {
68 redact_within(redactor, item, &format!("{path}[{index}]"));
69 }
70 }
71 _ => {}
72 }
73}
74
75#[derive(Debug, Clone, Copy, Default)]
77pub struct NoRedaction;
78
79impl Redactor for NoRedaction {
80 fn redacts(&self, _key: &str, _path: &str) -> bool {
81 false
82 }
83
84 fn redact_event(&self, _event: &mut AuditEvent) {}
85}
86
87#[derive(Debug, Clone)]
104pub struct KeyRedactor {
105 keys: Vec<String>,
106 substring_match: bool,
107}
108
109impl KeyRedactor {
110 pub const DEFAULT_KEYS: &'static [&'static str] = &[
115 "password",
116 "passwd",
117 "secret",
118 "token",
119 "authorization",
120 "auth",
121 "credential",
122 "api_key",
123 "apikey",
124 "private_key",
125 "session",
126 "cookie",
127 "ssn",
128 "credit_card",
129 "card_number",
130 "cvv",
131 "pin",
132 ];
133
134 #[must_use]
136 pub fn new<I, S>(keys: I) -> Self
137 where
138 I: IntoIterator<Item = S>,
139 S: Into<String>,
140 {
141 Self {
142 keys: keys.into_iter().map(|k| normalize(&k.into())).collect(),
143 substring_match: true,
144 }
145 }
146
147 #[must_use]
149 pub fn and<S: Into<String>>(mut self, key: S) -> Self {
150 self.keys.push(normalize(&key.into()));
151 self
152 }
153
154 #[must_use]
160 pub const fn exact(mut self) -> Self {
161 self.substring_match = false;
162 self
163 }
164
165 #[must_use]
170 pub fn keys(&self) -> &[String] {
171 &self.keys
172 }
173}
174
175impl Default for KeyRedactor {
176 fn default() -> Self {
178 Self::new(Self::DEFAULT_KEYS.iter().copied())
179 }
180}
181
182fn normalize(key: &str) -> String {
191 key.chars()
192 .filter(|c| c.is_alphanumeric())
193 .flat_map(char::to_lowercase)
194 .collect()
195}
196
197impl Redactor for KeyRedactor {
198 fn redacts(&self, key: &str, _path: &str) -> bool {
199 let key = normalize(key);
204 if self.substring_match {
205 self.keys.iter().any(|listed| key.contains(listed.as_str()))
206 } else {
207 self.keys.contains(&key)
208 }
209 }
210}
211
212pub struct FnRedactor<F: Fn(&str, &str) -> bool + Send + Sync>(F);
214
215impl<F: Fn(&str, &str) -> bool + Send + Sync> FnRedactor<F> {
216 pub const fn new(f: F) -> Self {
218 Self(f)
219 }
220}
221
222impl<F: Fn(&str, &str) -> bool + Send + Sync> Redactor for FnRedactor<F> {
223 fn redacts(&self, key: &str, path: &str) -> bool {
224 (self.0)(key, path)
225 }
226}
227
228impl<T: Redactor + ?Sized> Redactor for std::sync::Arc<T> {
229 fn redacts(&self, key: &str, path: &str) -> bool {
230 (**self).redacts(key, path)
231 }
232
233 fn redact_event(&self, event: &mut AuditEvent) {
234 (**self).redact_event(event);
235 }
236}
237
238#[cfg(test)]
239mod tests {
240 use super::*;
241 use crate::{AuditEventType, AuditResult};
242 use serde_json::json;
243
244 fn event_with(metadata: Vec<(&str, Value)>, params: Option<Value>) -> AuditEvent {
245 let mut builder = AuditEvent::builder()
246 .event_type(AuditEventType::AuthenticationAttempt)
247 .result(AuditResult::Success);
248 for (key, value) in metadata {
249 builder = builder.metadata(key, value);
250 }
251 if let Some(params) = params {
252 builder = builder.params(params);
253 }
254 builder.build()
255 }
256
257 #[test]
258 fn test_default_keys_are_redacted_in_metadata() {
259 let mut event = event_with(
260 vec![
261 ("password", json!("hunter2")),
262 ("user", json!("alice")),
263 ("api_key", json!("sk-live-123")),
264 ],
265 None,
266 );
267
268 KeyRedactor::default().redact_event(&mut event);
269
270 assert_eq!(event.metadata["password"], json!(REDACTED));
271 assert_eq!(event.metadata["api_key"], json!(REDACTED));
272 assert_eq!(
273 event.metadata["user"],
274 json!("alice"),
275 "non-secrets survive"
276 );
277 }
278
279 #[test]
280 fn test_matching_is_case_insensitive_and_substring() {
281 let redactor = KeyRedactor::default();
282 assert!(redactor.redacts("Authorization", "Authorization"));
283 assert!(
284 redactor.redacts("X-API-Key", "X-API-Key"),
285 "separators must not defeat the match: a hyphenated header is the \
286 shape most secrets arrive in"
287 );
288 assert!(
289 redactor.redacts("apiKey", "apiKey"),
290 "camelCase matches too"
291 );
292 assert!(redactor.redacts("user_password", "user_password"));
293 assert!(!redactor.redacts("username", "username"));
294 }
295
296 #[test]
297 fn test_exact_matching_avoids_false_positives() {
298 let loose = KeyRedactor::default();
301 assert!(loose.redacts("password_last_changed_at", ""));
302
303 let strict = KeyRedactor::default().exact();
304 assert!(!strict.redacts("password_last_changed_at", ""));
305 assert!(strict.redacts("password", ""));
306 }
307
308 #[test]
309 fn test_nested_params_are_walked() {
310 let mut event = event_with(
311 vec![],
312 Some(json!({
313 "user": {
314 "name": "alice",
315 "password": "hunter2",
316 },
317 "items": [
318 { "token": "abc" },
319 { "label": "safe" },
320 ],
321 })),
322 );
323
324 KeyRedactor::default().redact_event(&mut event);
325
326 let params = event.params.expect("params present");
327 assert_eq!(params["user"]["password"], json!(REDACTED));
328 assert_eq!(params["user"]["name"], json!("alice"));
329 assert_eq!(
330 params["items"][0]["token"],
331 json!(REDACTED),
332 "objects inside arrays are walked"
333 );
334 assert_eq!(params["items"][1]["label"], json!("safe"));
335 }
336
337 #[test]
338 fn test_a_secret_named_container_is_replaced_whole() {
339 let mut event = event_with(vec![], Some(json!({ "tokens": [{ "label": "safe" }] })));
343
344 KeyRedactor::default().redact_event(&mut event);
345 assert_eq!(event.params.expect("params")["tokens"], json!(REDACTED));
346 }
347
348 #[test]
349 fn test_a_redacted_object_is_replaced_wholesale() {
350 let mut event = event_with(
353 vec![],
354 Some(json!({ "credential": { "user": "alice", "pass": "x" } })),
355 );
356
357 KeyRedactor::default().redact_event(&mut event);
358
359 assert_eq!(
360 event.params.expect("params")["credential"],
361 json!(REDACTED),
362 "the whole subtree is replaced, not just its secret leaves"
363 );
364 }
365
366 #[test]
367 fn test_no_redaction_leaves_events_untouched() {
368 let mut event = event_with(vec![("password", json!("hunter2"))], None);
369 NoRedaction.redact_event(&mut event);
370 assert_eq!(event.metadata["password"], json!("hunter2"));
371 }
372
373 #[test]
374 fn test_fn_redactor_receives_the_path() {
375 let mut event = event_with(vec![], Some(json!({ "outer": { "value": 1 }, "value": 2 })));
376
377 FnRedactor::new(|_key, path| path == "params.outer.value").redact_event(&mut event);
379
380 let params = event.params.expect("params");
381 assert_eq!(params["outer"]["value"], json!(REDACTED));
382 assert_eq!(params["value"], json!(2), "the top-level value survives");
383 }
384
385 #[test]
386 fn test_typed_fields_are_not_redacted() {
387 let mut event = AuditEvent::builder()
390 .event_type(AuditEventType::AuthenticationAttempt)
391 .principal("alice@example.com")
392 .result(AuditResult::Success)
393 .metadata("token", json!("secret"))
394 .build();
395
396 KeyRedactor::default().redact_event(&mut event);
397
398 assert_eq!(event.principal.as_deref(), Some("alice@example.com"));
399 assert_eq!(event.metadata["token"], json!(REDACTED));
400 }
401}