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)(?:pass(?:word|wd|code)|passphrase)\s*[=:]\s*{KV_VALUE}")),
44        compile("api_key_kv", &format!(r"(?i)(?:api|secret|access|private|master|signing|encryption|auth|session)[_-]?key\s*[=:]\s*{KV_VALUE}")),
45        compile("token_kv", &format!(r"(?i)(?:[a-z0-9_-]+[_-])?token\s*[=:]\s*{KV_VALUE}")),
46        compile("secret_kv", &format!(r"(?i)(?:[a-z0-9_-]+[_-])?secret(?:[_-][a-z0-9_-]+)?\s*[=:]\s*{KV_VALUE}")),
47        compile("slack_token", r"xox[baprs]-[a-zA-Z0-9_-]{10,}"),
48        compile("gcp_api_key", r"AIzaSy[A-Za-z0-9_-]{33}"),
49        compile("stripe_api_key", r"(?:sk|rk)_(?:live|test)_[0-9a-zA-Z]{24,}"),
50        // Body allows '-' and '_' so project keys (sk-proj-...) and other
51        // hyphen/underscore-bearing key shapes are redacted, not just classic
52        // sk- keys whose body is pure alphanumeric.
53        compile("openai_api_key", r"sk-[a-zA-Z0-9_-]{20,}"),
54        compile(
55            "pem_private_key",
56            r"-----BEGIN (RSA |DSA |EC |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (RSA |DSA |EC |OPENSSH )?PRIVATE KEY-----",
57        ),
58    ]
59});
60
61/// URL userinfo carrying credentials: `scheme://user:pass@host`. Rewritten to
62/// `scheme://***@host`, preserving the scheme and host (not secret) while
63/// stripping the embedded credentials. Kept separate from [`SECRET_PATTERNS`]
64/// because it rewrites only the userinfo span instead of replacing the whole
65/// match with `[REDACTED]`.
66static URL_USERINFO: LazyLock<Regex> =
67    LazyLock::new(|| compile("url_userinfo", r"://[^/@\s]*:[^/@\s]*@"));
68
69/// Strip known-sensitive patterns from the input string.
70///
71/// Replaces known secret patterns (API keys, tokens, JWTs, `password=` pairs,
72/// PEM private keys) with `[REDACTED]`, and masks credentials embedded in URL
73/// userinfo (`scheme://user:pass@host` becomes `scheme://***@host`). This is a
74/// safe-default measure to ensure secrets do not leak into logs, error
75/// messages, or temp files. The operation is idempotent.
76///
77/// # Examples
78///
79/// ```
80/// use santh_error::redact_secrets;
81///
82/// let raw = "password=hunter2";
83/// let safe = redact_secrets(raw);
84/// assert!(!safe.contains("hunter2"));
85/// assert!(safe.contains("[REDACTED]"));
86///
87/// // URL credentials are masked while the scheme and host survive.
88/// let url = redact_secrets("https://admin:s3cret@example.com/path");
89/// assert!(!url.contains("s3cret"));
90/// assert!(url.contains("https://***@example.com/path"));
91/// ```
92pub fn redact_secrets(input: &str) -> String {
93    let mut output = input.to_string();
94    for pattern in SECRET_PATTERNS.iter() {
95        // `replace_all` returns `Cow::Borrowed` when the pattern does not match,
96        // so only take (and keep) a new allocation when a redaction actually
97        // happened. On the common no-secret path this avoids one String clone
98        // per pattern (12+ per call), and this runs on every error/log line.
99        if let Cow::Owned(replaced) = pattern.replace_all(&output, "[REDACTED]") {
100            output = replaced;
101        }
102    }
103    // Mask credentials embedded in URL userinfo, preserving scheme and host.
104    if let Cow::Owned(replaced) = URL_USERINFO.replace_all(&output, "://***@") {
105        output = replaced;
106    }
107    output
108}