1pub fn redact_secrets(input: &str) -> std::borrow::Cow<'_, str> {
18 use regex_lite::Regex;
20 use std::borrow::Cow;
21 use std::sync::OnceLock;
22
23 static REDACT_PATTERNS: OnceLock<Vec<(Regex, &'static str)>> = OnceLock::new();
24 let patterns = REDACT_PATTERNS.get_or_init(|| {
25 vec![
26 (Regex::new(r"\bsk-[a-zA-Z0-9]{20,}\b").unwrap(), "openai_key"),
28 (Regex::new(r"\bsk-ant-[a-zA-Z0-9-]{20,}\b").unwrap(), "anthropic_key"),
29 (Regex::new(r"\bAKIA[0-9A-Z]{16}\b").unwrap(), "aws_access_key"),
31 (Regex::new(r"\baws_secret_access_key\s*[:=]\s*[A-Za-z0-9/+=]{40}\b").unwrap(), "aws_secret_key"),
32 (Regex::new(r"\bghp_[A-Za-z0-9]{36}\b").unwrap(), "github_pat"),
34 (Regex::new(r"\bghs_[A-Za-z0-9]{36}\b").unwrap(), "github_app_token"),
35 (Regex::new(r"\bAIza[0-9A-Za-z_-]{35}\b").unwrap(), "gcp_api_key"),
37 (Regex::new(r"\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b").unwrap(), "jwt"),
39 (Regex::new(r"-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY-----").unwrap(), "pem_private_key"),
41 (Regex::new(r"\bhooks\.slack\.com/services/T[A-Z0-9]+/B[A-Z0-9]+/[A-Za-z0-9]+\b").unwrap(), "slack_webhook"),
43 (Regex::new(r"(?i)\b(api_key|api_secret|secret_key|access_token|password|token)\s*[:=]\s*[A-Za-z0-9_\-./+=]{20,}\b").unwrap(), "env_assignment"),
45 ]
46 });
47
48 let mut out: Cow<'_, str> = Cow::Borrowed(input);
49 for (rx, label) in patterns {
50 if rx.is_match(&out) {
51 let replacement = format!("[REDACTED:{label}]");
52 out = Cow::Owned(rx.replace_all(&out, replacement.as_str()).into_owned());
53 }
54 }
55 out
56}
57
58pub fn redact_home_path(input: &str) -> std::borrow::Cow<'_, str> {
65 use regex_lite::Regex;
66 use std::borrow::Cow;
67 use std::sync::OnceLock;
68
69 static RE_UNIX: OnceLock<Regex> = OnceLock::new();
70 static RE_MAC: OnceLock<Regex> = OnceLock::new();
71 static RE_WIN: OnceLock<Regex> = OnceLock::new();
72
73 let unix = RE_UNIX.get_or_init(|| Regex::new(r"/home/[^/\s]+/").unwrap());
74 let mac = RE_MAC.get_or_init(|| Regex::new(r"/Users/[^/\s]+/").unwrap());
75 let win = RE_WIN.get_or_init(|| Regex::new(r"(?i)[A-Z]:\\Users\\[^\\\s]+\\").unwrap());
76
77 let mut out: Cow<'_, str> = Cow::Borrowed(input);
78 for rx in [unix, mac] {
79 if rx.is_match(&out) {
80 out = Cow::Owned(rx.replace_all(&out, "~/").into_owned());
81 }
82 }
83 if win.is_match(&out) {
84 out = Cow::Owned(win.replace_all(&out, "~\\").into_owned());
85 }
86 out
87}
88
89pub fn redact_value(value: &mut serde_json::Value) {
96 match value {
97 serde_json::Value::String(s) => {
98 let stage1 = redact_secrets(s);
99 let stage2 = redact_home_path(&stage1);
100 if stage2 != *s {
102 *s = stage2.into_owned();
103 }
104 }
105 serde_json::Value::Array(items) => {
106 for item in items {
107 redact_value(item);
108 }
109 }
110 serde_json::Value::Object(map) => {
111 for v in map.values_mut() {
112 redact_value(v);
113 }
114 }
115 serde_json::Value::Bool(_) | serde_json::Value::Number(_) | serde_json::Value::Null => {}
116 }
117}