Skip to main content

santh_error/
redact.rs

1use regex::Regex;
2use std::borrow::Cow;
3use std::sync::LazyLock;
4
5// Every `source` below is a hardcoded literal validated by the redaction
6// tests (each pattern is exercised by `tests/adversarial.rs`), so a compile
7// failure here can only mean a literal in *this file* was edited to be
8// invalid - a build-time programming error. We deliberately fail loud rather
9// than skip the pattern: silently dropping a rule would let the matching
10// secret class leak, which is strictly worse than a panic for a redaction
11// primitive. `clippy::panic` is allowed for exactly this fail-loud-on-static-
12// misconfiguration case.
13/// Value fragment for `key = value` secret patterns: a double-quoted string, a
14/// single-quoted string, or an unquoted whitespace-delimited token. Defined
15/// once so every KV rule redacts quoted/spaced secrets identically (a bare
16/// `\S+` stops at the first space and leaks the rest of a quoted secret).
17const KV_VALUE: &str = r#"("[^"]*"|'[^']*'|\S+)"#;
18
19#[allow(clippy::panic)]
20fn compile(tag: &'static str, source: &str) -> Regex {
21    Regex::new(source).unwrap_or_else(|e| {
22        panic!(
23            "santh-error::redact: secret pattern `{tag}` failed to compile: {e}. \
24             Fix: correct the regex source in `redact.rs` for `{tag}`."
25        )
26    })
27}
28
29static SECRET_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
30    vec![
31        // Covers both long-term (AKIA) and temporary/STS session (ASIA) access keys.
32        compile("aws_access_key", r"A[KS]IA[0-9A-Z]{16}"),
33        compile("github_pat_classic", r"gh[pousr]_[A-Za-z0-9_]{36,}"),
34        compile("github_pat_fine", r"github_pat_[A-Za-z0-9_]{22,}"),
35        compile(
36            "jwt",
37            r"eyJ[A-Za-z0-9_-]*\.eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*",
38        ),
39        // The token body may also carry dots (OAuth access tokens are not
40        // always JWTs, and compact serialization separates segments with
41        // `.`), so the charset includes `.` alongside URL-safe base64.
42        compile("bearer", r"(?i)Bearer\s+[A-Za-z0-9_.-]+"),
43        compile("password_kv", &format!(r"(?i)password\s*[=:]\s*{KV_VALUE}")),
44        compile("passwd_kv", &format!(r"(?i)passwd\s*[=:]\s*{KV_VALUE}")),
45        compile("api_key_kv", &format!(r"(?i)api[_-]?key\s*[=:]\s*{KV_VALUE}")),
46        compile("token_kv", &format!(r"(?i)token\s*[=:]\s*{KV_VALUE}")),
47        compile("secret_kv", &format!(r"(?i)secret\s*[=:]\s*{KV_VALUE}")),
48        // Body allows '-' and '_' so project keys (sk-proj-...) and other
49        // hyphen/underscore-bearing key shapes are redacted, not just classic
50        // sk- keys whose body is pure alphanumeric.
51        compile("openai_api_key", r"sk-[a-zA-Z0-9_-]{20,}"),
52        compile(
53            "pem_private_key",
54            r"-----BEGIN (RSA |DSA |EC |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (RSA |DSA |EC |OPENSSH )?PRIVATE KEY-----",
55        ),
56    ]
57});
58
59/// URL userinfo carrying credentials: `scheme://user:pass@host`. Rewritten to
60/// `scheme://***@host`, preserving the scheme and host (not secret) while
61/// stripping the embedded credentials. Kept separate from [`SECRET_PATTERNS`]
62/// because it rewrites only the userinfo span instead of replacing the whole
63/// match with `[REDACTED]`.
64static URL_USERINFO: LazyLock<Regex> =
65    LazyLock::new(|| compile("url_userinfo", r"://[^/@\s]*:[^/@\s]*@"));
66
67/// Strip known-sensitive patterns from the input string.
68///
69/// Replaces known secret patterns (API keys, tokens, JWTs, `password=` pairs,
70/// PEM private keys) with `[REDACTED]`, and masks credentials embedded in URL
71/// userinfo (`scheme://user:pass@host` becomes `scheme://***@host`). This is a
72/// safe-default measure to ensure secrets do not leak into logs, error
73/// messages, or temp files. The operation is idempotent.
74///
75/// # Examples
76///
77/// ```
78/// use santh_error::redact_secrets;
79///
80/// let raw = "password=hunter2";
81/// let safe = redact_secrets(raw);
82/// assert!(!safe.contains("hunter2"));
83/// assert!(safe.contains("[REDACTED]"));
84///
85/// // URL credentials are masked while the scheme and host survive.
86/// let url = redact_secrets("https://admin:s3cret@example.com/path");
87/// assert!(!url.contains("s3cret"));
88/// assert!(url.contains("https://***@example.com/path"));
89/// ```
90pub fn redact_secrets(input: &str) -> String {
91    let mut output = input.to_string();
92    for pattern in SECRET_PATTERNS.iter() {
93        // `replace_all` returns `Cow::Borrowed` when the pattern does not match,
94        // so only take (and keep) a new allocation when a redaction actually
95        // happened. On the common no-secret path this avoids one String clone
96        // per pattern (12+ per call), and this runs on every error/log line.
97        if let Cow::Owned(replaced) = pattern.replace_all(&output, "[REDACTED]") {
98            output = replaced;
99        }
100    }
101    // Mask credentials embedded in URL userinfo, preserving scheme and host.
102    if let Cow::Owned(replaced) = URL_USERINFO.replace_all(&output, "://***@") {
103        output = replaced;
104    }
105    output
106}