santh-error 0.2.0

Actionable error primitives - stable error codes, fix hints, and built-in secret redaction
Documentation
use regex::Regex;
use std::sync::LazyLock;

// Every `source` below is a hardcoded literal validated by the redaction
// tests (each pattern is exercised by `tests/adversarial.rs`), so a compile
// failure here can only mean a literal in *this file* was edited to be
// invalid - a build-time programming error. We deliberately fail loud rather
// than skip the pattern: silently dropping a rule would let the matching
// secret class leak, which is strictly worse than a panic for a redaction
// primitive. `clippy::panic` is allowed for exactly this fail-loud-on-static-
// misconfiguration case.
#[allow(clippy::panic)]
fn compile(tag: &'static str, source: &'static str) -> Regex {
    Regex::new(source).unwrap_or_else(|e| {
        panic!(
            "santh-error::redact: secret pattern `{tag}` failed to compile: {e}. \
             Fix: correct the regex source in `redact.rs` for `{tag}`."
        )
    })
}

static SECRET_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
    vec![
        compile("aws_access_key", r"AKIA[0-9A-Z]{16}"),
        compile("github_pat_classic", r"gh[pousr]_[A-Za-z0-9_]{36,}"),
        compile("github_pat_fine", r"github_pat_[A-Za-z0-9_]{22,}"),
        compile(
            "jwt",
            r"eyJ[A-Za-z0-9_-]*\.eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*",
        ),
        compile("bearer", r"Bearer\s+[A-Za-z0-9_-]+"),
        compile("password_kv", r"(?i)password\s*[=:]\s*\S+"),
        compile("passwd_kv", r"(?i)passwd\s*[=:]\s*\S+"),
        compile("api_key_kv", r"(?i)api[_-]?key\s*[=:]\s*\S+"),
        compile("token_kv", r"(?i)token\s*[=:]\s*\S+"),
        compile("secret_kv", r"(?i)secret\s*[=:]\s*\S+"),
        compile("openai_api_key", r"sk-[a-zA-Z0-9]{20,}"),
        compile(
            "pem_private_key",
            r"-----BEGIN (RSA |DSA |EC |OPENSSH )?PRIVATE KEY-----[\s\S]*?-----END (RSA |DSA |EC |OPENSSH )?PRIVATE KEY-----",
        ),
    ]
});

/// URL userinfo carrying credentials: `scheme://user:pass@host`. Rewritten to
/// `scheme://***@host`, preserving the scheme and host (not secret) while
/// stripping the embedded credentials. Kept separate from [`SECRET_PATTERNS`]
/// because it rewrites only the userinfo span instead of replacing the whole
/// match with `[REDACTED]`.
static URL_USERINFO: LazyLock<Regex> =
    LazyLock::new(|| compile("url_userinfo", r"://[^/@\s]*:[^/@\s]*@"));

/// Strip known-sensitive patterns from the input string.
///
/// Replaces known secret patterns (API keys, tokens, JWTs, `password=` pairs,
/// PEM private keys) with `[REDACTED]`, and masks credentials embedded in URL
/// userinfo (`scheme://user:pass@host` becomes `scheme://***@host`). This is a
/// safe-default measure to ensure secrets do not leak into logs, error
/// messages, or temp files. The operation is idempotent.
///
/// # Examples
///
/// ```
/// use santh_error::redact_secrets;
///
/// let raw = "password=hunter2";
/// let safe = redact_secrets(raw);
/// assert!(!safe.contains("hunter2"));
/// assert!(safe.contains("[REDACTED]"));
///
/// // URL credentials are masked while the scheme and host survive.
/// let url = redact_secrets("https://admin:s3cret@example.com/path");
/// assert!(!url.contains("s3cret"));
/// assert!(url.contains("https://***@example.com/path"));
/// ```
pub fn redact_secrets(input: &str) -> String {
    let mut output = input.to_string();
    for pattern in SECRET_PATTERNS.iter() {
        output = pattern.replace_all(&output, "[REDACTED]").into_owned();
    }
    // Mask credentials embedded in URL userinfo, preserving scheme and host.
    output = URL_USERINFO.replace_all(&output, "://***@").into_owned();
    output
}