macro_rules! static_regex {
($pattern:expr_2021) => {{
static RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
RE.get_or_init(|| {
regex::Regex::new($pattern).expect(concat!("BUG: invalid static regex: ", $pattern))
})
}};
}
pub(crate) fn redaction_enabled_for_active_role() -> bool {
let role = crate::core::roles::active_role();
if role.role.name == "admin" {
role.io.redact_outputs
} else {
true
}
}
pub(crate) fn redact_text_if_enabled(input: &str) -> String {
if !redaction_enabled_for_active_role() {
return input.to_string();
}
let (out, hits) = redact_counting(input, config_exclude_patterns().as_slice());
crate::core::security_events::note(
crate::core::security_events::SecurityKind::SecretRedacted,
hits,
);
out
}
fn looks_like_number(v: &str) -> bool {
if v.is_empty() {
return false;
}
let s = v.trim_start_matches(['+', '-']);
if s.is_empty() {
return false;
}
s.parse::<f64>().is_ok()
&& s.chars()
.all(|c| c.is_ascii_digit() || c == '.' || c == 'e' || c == 'E' || c == '+' || c == '-')
}
fn looks_like_uuid(value: &str) -> bool {
let value = value
.trim()
.trim_matches(|c| c == '"' || c == '\'' || c == '`' || c == '{' || c == '}');
let groups: Vec<&str> = value.split('-').collect();
groups.len() == 5
&& [8, 4, 4, 4, 12].iter().zip(&groups).all(|(len, group)| {
group.len() == *len && group.chars().all(|ch| ch.is_ascii_hexdigit())
})
}
fn is_env_reference(v: &str) -> bool {
if v.starts_with("os.environ/")
|| v.starts_with("os.getenv(")
|| v.starts_with("process.env.")
|| v.starts_with("System.getenv(")
|| v.starts_with("ENV[")
|| v.starts_with("env(")
{
return true;
}
if (v.starts_with("${") && v.ends_with('}'))
|| (v.starts_with('$')
&& v[1..]
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_'))
|| (v.starts_with('%') && v.ends_with('%') && v.len() > 2)
{
return true;
}
if let Some(prefix) = v.split('.').next() {
let pl = prefix.to_ascii_lowercase();
if matches!(
pl.as_str(),
"env" | "inputenv" | "serverenv" | "secrets" | "vars" | "environ"
) && v.contains('.')
{
return true;
}
}
false
}
fn is_identifier_reference(value: &str) -> bool {
let v = value.trim();
if v.is_empty() || v.starts_with('"') || v.starts_with('\'') || v.starts_with('`') {
return false;
}
if is_env_reference(v) {
return true;
}
if v.contains(|c: char| c.is_ascii_digit()) {
return false;
}
v.split('.').all(|segment| {
let mut chars = segment.chars();
matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$')
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
})
}
fn is_placeholder_value(value: &str) -> bool {
let v = value
.trim()
.trim_matches(|c| c == '"' || c == '\'' || c == '`')
.to_ascii_lowercase();
if v.starts_with('<') && v.ends_with('>') {
return true;
}
if !v.is_empty() && v.chars().all(|c| c == '*') {
return true;
}
const MARKERS: &[&str] = &[
"change_me",
"change-me",
"changeme",
"example",
"placeholder",
"your_",
"your-",
"xxx",
"dummy",
"sample",
"todo",
"fixme",
"replace_me",
"replace-me",
"redacted",
"...",
"…",
];
MARKERS.iter().any(|m| v.contains(m))
}
fn is_non_secret_literal(value: &str) -> bool {
let v = value
.trim()
.trim_matches(|c| c == '"' || c == '\'' || c == '`');
if looks_like_number(v) {
return true;
}
if v.contains(['<', '>', '|', '(', ')', '[', ']', '{', '}']) {
return true;
}
matches!(
v.to_ascii_lowercase().as_str(),
"" | "undefined"
| "null"
| "none"
| "nil"
| "true"
| "false"
| "string"
| "number"
| "boolean"
| "bigint"
| "symbol"
| "object"
| "any"
| "unknown"
| "never"
| "void"
| "nan"
| "date"
) || is_primitive_type_name(v)
}
fn is_primitive_type_name(value: &str) -> bool {
matches!(
value,
"bool"
| "char"
| "str"
| "usize"
| "isize"
| "u8"
| "u16"
| "u32"
| "u64"
| "u128"
| "i8"
| "i16"
| "i32"
| "i64"
| "i128"
| "f32"
| "f64"
| "int"
| "int8"
| "int16"
| "int32"
| "int64"
| "uint"
| "uint8"
| "uint16"
| "uint32"
| "uint64"
| "uintptr"
| "float"
| "float32"
| "float64"
| "double"
| "long"
| "short"
| "byte"
| "rune"
| "error"
| "Self"
)
}
struct Rule {
label: &'static str,
re: &'static regex::Regex,
guard_value: bool,
}
fn normalize_for_secret_matching(input: &str) -> (String, Vec<usize>) {
let mut normalized = String::with_capacity(input.len());
let mut original_boundaries = vec![0usize];
for (start, ch) in input.char_indices() {
let end = start + ch.len_utf8();
let Some(folded) = fold_secret_match_char(ch) else {
if let Some(boundary) = original_boundaries.last_mut() {
*boundary = end;
}
continue;
};
let folded_len = folded.len_utf8();
normalized.push(folded);
for byte in 1..=folded_len {
original_boundaries.push(if byte == folded_len { end } else { start });
}
}
(normalized, original_boundaries)
}
fn fold_secret_match_char(ch: char) -> Option<char> {
if matches!(
ch,
'\u{200b}' | '\u{200c}' | '\u{200d}' | '\u{2060}' | '\u{feff}'
) {
return None;
}
Some(match ch {
'\u{3000}' => ' ',
'\u{ff01}'..='\u{ff5e}' => char::from_u32(ch as u32 - 0xfee0).unwrap_or(ch),
_ => ch,
})
}
pub(crate) fn normalize_secret_text(input: &str) -> String {
input.chars().filter_map(fold_secret_match_char).collect()
}
pub(crate) fn bearer_value_is_credential(value: &str) -> bool {
let classes = [
value.bytes().any(|b| b.is_ascii_uppercase()),
value.bytes().any(|b| b.is_ascii_lowercase()),
value.bytes().any(|b| b.is_ascii_digit()),
];
value.len() >= 16
&& classes.iter().filter(|present| **present).count() >= 2
&& !is_placeholder_value(value)
}
pub(crate) fn is_benign_secret_value(value: &str) -> bool {
is_comparison_operator_residue(value)
|| is_non_secret_literal(value)
|| is_identifier_reference(value)
|| is_placeholder_value(value)
|| looks_like_uuid(value)
}
pub(crate) fn is_benign_quoted_value(value: &str) -> bool {
is_comparison_operator_residue(value)
|| is_non_secret_literal(value)
|| is_placeholder_value(value)
|| looks_like_uuid(value)
|| (!value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()))
}
fn is_comparison_operator_residue(value: &str) -> bool {
let v = value.trim();
matches!(v, "=" | "==" | "!=" | "<=" | ">=" | "===" | "!==")
}
fn redaction_rules() -> Vec<Rule> {
vec![
Rule {
label: "Bearer token",
re: static_regex!(r"(?i)(bearer[ \t]+)([a-zA-Z0-9_\-\.]{8,})"),
guard_value: false,
},
Rule {
label: "Authorization header",
re: static_regex!(
r"(?i)(authorization:[ \t]*(?:basic|bearer|token)[ \t]+)([A-Za-z0-9._~+/=-]+)"
),
guard_value: false,
},
Rule {
label: "AWS key",
re: static_regex!(r"(?:AKIA|ASIA)[0-9A-Z]{16}"),
guard_value: false,
},
Rule {
label: "Private key block",
re: static_regex!(
r"(?s)-----BEGIN\s+(?:RSA\s+|EC\s+|DSA\s+|OPENSSH\s+)?PRIVATE\s+KEY-----(?:.+?-----END\s+(?:RSA\s+|EC\s+|DSA\s+|OPENSSH\s+)?PRIVATE\s+KEY-----|(?-s:[^\n]*)(?:\r?\n[A-Za-z-]+:(?-s:[^\n]*))*(?:\r?\n[A-Za-z0-9+/=]+[ \t]*(?m:$))*)"
),
guard_value: false,
},
Rule {
label: "GitHub token",
re: static_regex!(r"(gh[pousr]_)[a-zA-Z0-9_]{20,}"),
guard_value: false,
},
Rule {
label: "GitHub fine-grained token",
re: static_regex!(r"(github_pat_)[A-Za-z0-9_]{20,}"),
guard_value: false,
},
Rule {
label: "GitLab token",
re: static_regex!(r"(glpat-)[A-Za-z0-9_\-]{20,}"),
guard_value: false,
},
Rule {
label: "Anthropic API key",
re: crate::core::secret_detection::anthropic_key_re(),
guard_value: false,
},
Rule {
label: "OpenAI API key",
re: crate::core::secret_detection::openai_key_re(),
guard_value: false,
},
Rule {
label: "JWT",
re: static_regex!(
r"eyJ[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}(?:\.[A-Za-z0-9_\-]{8,})?"
),
guard_value: false,
},
Rule {
label: "Slack token",
re: static_regex!(r"(xox[bpas]-)[0-9a-zA-Z\-]{10,}"),
guard_value: false,
},
Rule {
label: "Stripe key",
re: static_regex!(r"([sr]k_live_)[0-9a-zA-Z]{10,}"),
guard_value: false,
},
Rule {
label: "npm token",
re: static_regex!(r"(npm_)[A-Za-z0-9]{10,}"),
guard_value: false,
},
Rule {
label: "API key param",
re: static_regex!(
r#"(?im)((?:^|[^a-z0-9])(?:aws[_-]?secret[_-]?access[_-]?key|secret[_-]?access[_-]?key|api[_-]?key|apikey|access[_-]?key|secret[_-]?key|access[_-]?token|client[_-]?secret|token|password|passwd|pwd|secret)(?:\\?["'])?[ \t]*[=:][ \t]*(?:\\?["'])?)([^\s\r\n,;&"']+)"#
),
guard_value: true,
},
Rule {
label: "URL-encoded secret",
re: static_regex!(
r"(?im)((?:^|[^a-z0-9])(?:aws[_-]?secret[_-]?access[_-]?key|secret[_-]?access[_-]?key|api[_-]?key|apikey|access[_-]?key|secret[_-]?key|access[_-]?token|client[_-]?secret|token|password|passwd|pwd|secret)[ \t]*[=:][ \t]*)(?:((?:%[0-9a-f]{2}|[A-Za-z0-9_\-]){20,}))"
),
guard_value: true,
},
Rule {
label: "Generic long secret",
re: static_regex!(
r#"(?im)((?:^|[^a-z0-9])(?:key|token|secret|password|credential|auth)(?:\\?["'])?[ \t]*[=:][ \t]*(?:\\?["'])?)([a-zA-Z0-9+/=\-_]{32,})"#
),
guard_value: true,
},
]
}
pub(crate) fn redact_text(input: &str) -> String {
redact_text_with_excludes(input, &[])
}
pub(crate) fn redact_text_with_excludes(input: &str, excludes: &[regex::Regex]) -> String {
redact_counting(input, excludes).0
}
pub(crate) fn redact_text_with_excludes_for_detection(
input: &str,
excludes: &[regex::Regex],
) -> String {
redact_counting_with_labels(input, excludes, true).0
}
fn redact_counting(input: &str, excludes: &[regex::Regex]) -> (String, usize) {
redact_counting_with_labels(input, excludes, false)
}
fn redact_counting_with_labels(
input: &str,
excludes: &[regex::Regex],
detector_labels: bool,
) -> (String, usize) {
let (normalized, boundaries) = normalize_for_secret_matching(input);
let mut replacements = Vec::new();
let database_re = static_regex!(
r"(?i)((?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis)://)([^:/@?#\s]+):([^@/?#\s]+)@([^/?#\s]+)"
);
for caps in database_re.captures_iter(&normalized) {
let Some(whole) = caps.get(0) else {
continue;
};
let start = boundaries[whole.start()];
let end = boundaries[whole.end()];
let original = input.get(start..end).unwrap_or(whole.as_str());
if excluded(excludes, whole.as_str()) || excluded(excludes, original) {
continue;
}
if caps
.get(3)
.is_some_and(|password| is_placeholder_value(password.as_str()))
{
continue;
}
let scheme = caps
.get(1)
.map_or("", |m| original_span(input, &boundaries, m));
let host = caps
.get(4)
.map_or("", |m| original_span(input, &boundaries, m));
let label = if detector_labels {
"db_url"
} else {
"Database credentials"
};
replacements.push((start, end, format!("{scheme}[REDACTED:{label}]@{host}")));
}
for rule in redaction_rules() {
for caps in rule.re.captures_iter(&normalized) {
let Some(whole) = caps.get(0) else {
continue;
};
let start = boundaries[whole.start()];
let end = boundaries[whole.end()];
let original = input.get(start..end).unwrap_or(whole.as_str());
if excluded(excludes, whole.as_str()) || excluded(excludes, original) {
continue;
}
if rule.guard_value
&& let Some(value) = caps.get(2)
&& if is_quoted_at(&normalized, value.start()) {
is_benign_quoted_value(value.as_str())
} else {
is_benign_secret_value(value.as_str())
}
{
continue;
}
if rule.label == "Bearer token"
&& caps
.get(2)
.is_some_and(|value| !bearer_value_is_credential(value.as_str()))
{
continue;
}
let overlapping: Vec<usize> = replacements
.iter()
.enumerate()
.filter(|(_, (other_start, other_end, _))| start < *other_end && *other_start < end)
.map(|(i, _)| i)
.collect();
if overlapping.iter().any(|&i| {
let (other_start, other_end, _) = &replacements[i];
*other_start <= start && end <= *other_end
}) {
continue;
}
let start = overlapping
.iter()
.map(|&i| replacements[i].0)
.fold(start, usize::min);
let end = overlapping
.iter()
.map(|&i| replacements[i].1)
.fold(end, usize::max);
for &i in overlapping.iter().rev() {
replacements.remove(i);
}
let label = if detector_labels {
detector_redaction_label(rule.label, caps.get(2).map(|value| value.as_str()))
} else {
rule.label
};
let replacement = caps.get(1).map_or_else(
|| format!("[REDACTED:{label}]"),
|prefix| {
let original_prefix = original_span(input, &boundaries, prefix);
format!("{original_prefix}[REDACTED:{label}]")
},
);
replacements.push((start, end, replacement));
}
}
replacements.sort_by_key(|(start, _, _)| *start);
let hits = replacements.len();
let mut out = input.to_string();
for (start, end, replacement) in replacements.into_iter().rev() {
out.replace_range(start..end, &replacement);
}
(out, hits)
}
fn original_span<'a>(input: &'a str, boundaries: &[usize], matched: regex::Match<'_>) -> &'a str {
let start = boundaries.get(matched.start()).copied().unwrap_or_default();
let end = boundaries.get(matched.end()).copied().unwrap_or(start);
input.get(start..end).unwrap_or("")
}
fn detector_redaction_label(label: &str, value: Option<&str>) -> &'static str {
match label {
"Bearer token" | "Authorization header" => "authorization_header",
"URL-encoded secret" => "url_encoded_secret",
"AWS key" => "aws_key",
"Private key block" => "private_key",
"GitHub token" => "github_token",
"GitHub fine-grained token" => "github_fine_grained",
"GitLab token" => "gitlab_pat",
"Anthropic API key" => "anthropic_key",
"OpenAI API key" => "openai_key",
"JWT" => "jwt",
"Slack token" => "slack_token",
"Stripe key" => "stripe_key",
"npm token" => "npm_token",
"Generic long secret" if value.is_some_and(|v| v.len() >= 40) => "high_entropy_secret",
"API key param" | "Generic long secret" => "generic_api_key",
_ => "secret",
}
}
fn is_quoted_at(text: &str, pos: usize) -> bool {
pos > 0 && matches!(text.as_bytes()[pos - 1], b'"' | b'\'')
}
fn excluded(excludes: &[regex::Regex], value: &str) -> bool {
excludes.iter().any(|pattern| pattern.is_match(value))
}
pub(crate) fn config_exclude_patterns() -> std::sync::Arc<Vec<regex::Regex>> {
type Cache = Option<(
std::sync::Arc<crate::core::config::Config>,
std::sync::Arc<Vec<regex::Regex>>,
)>;
static CACHE: std::sync::Mutex<Cache> = std::sync::Mutex::new(None);
let cfg = crate::core::config::Config::load_arc();
if let Ok(guard) = CACHE.lock()
&& let Some((cached_cfg, patterns)) = &*guard
&& std::sync::Arc::ptr_eq(cached_cfg, &cfg)
{
return std::sync::Arc::clone(patterns);
}
let compiled = std::sync::Arc::new(
cfg.secret_detection
.exclude_patterns
.iter()
.filter_map(|p| regex::Regex::new(p).ok())
.collect::<Vec<_>>(),
);
if let Ok(mut guard) = CACHE.lock() {
*guard = Some((cfg, std::sync::Arc::clone(&compiled)));
}
compiled
}
#[must_use]
pub(crate) fn redact_with_patterns(
input: &str,
patterns: &[(String, regex::Regex)],
) -> (String, usize) {
let mut out = input.to_string();
let mut hits = 0usize;
for (label, re) in patterns {
let mut local = 0usize;
out = re
.replace_all(&out, |_caps: ®ex::Captures| {
local += 1;
format!("[REDACTED:{label}]")
})
.to_string();
hits += local;
}
(out, hits)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn standalone_provider_keys_are_fully_masked_in_nested_values() {
let suffix = "aB3_".repeat(9);
for prefix in ["sk-proj-", "sk-svcacct-", "sk-ant-"] {
let secret = format!("{prefix}{suffix}");
let raw = serde_json::json!({"nested":[secret.clone()]}).to_string();
let safe = redact_text(&raw);
assert!(!safe.contains(&suffix), "must mask the entire token");
assert!(!safe.contains(prefix), "must not retain the secret prefix");
assert!(safe.contains("REDACTED"));
assert!(!crate::core::secret_detection::detect_secrets(&secret).is_empty());
}
assert_eq!(
redact_text("sk-proj-your_key_here"),
"sk-proj-your_key_here"
);
}
#[test]
fn config_exclude_patterns_reuses_compiled_regexes_when_config_unchanged() {
let _lock = crate::core::data_dir::test_env_lock();
let first = config_exclude_patterns();
let second = config_exclude_patterns();
assert!(
std::sync::Arc::ptr_eq(&first, &second),
"unchanged config must reuse the cached compiled patterns, not recompile"
);
}
#[test]
fn redacts_bearer_token() {
let s = "Authorization: Bearer abcdefghijklmnopqrstuvwxyz012345";
let out = redact_text(s);
assert!(out.contains("[REDACTED"));
assert!(!out.contains("abcdefghijklmnopqrstuvwxyz"));
}
#[test]
fn redacts_private_key_block() {
let s = "-----BEGIN PRIVATE KEY-----\nabc\n-----END PRIVATE KEY-----";
let out = redact_text(s);
assert!(out.contains("[REDACTED"));
assert!(!out.contains("\nabc\n"));
}
#[test]
fn redacts_a_truncated_private_key_but_not_the_code_around_it() {
let s = concat!(
"config:\n-----BEGIN RSA PRIVATE",
" KEY-----\nProc-Type: 4,ENCRYPTED\nMIIEpAIBAAKCAQEA\nqx7Wmore"
);
let out = redact_text(s);
assert!(out.starts_with("config:\n"), "{out}");
assert!(out.contains("[REDACTED"), "{out}");
for leaked in ["RSA PRIVATE", "Proc-Type", "MIIEpAIBAAKCAQEA", "qx7Wmore"] {
assert!(!out.contains(leaked), "{leaked} leaked: {out}");
}
let source = concat!(
"const HEADER: &str = \"-----BEGIN PRIVATE",
" KEY-----\";\nfn parse(pem: &str) -> bool {\n pem.starts_with(HEADER)\n}\n"
);
let out = redact_text(source);
assert!(out.contains("fn parse(pem: &str) -> bool {"), "{out}");
assert!(out.contains("pem.starts_with(HEADER)"), "{out}");
}
#[test]
fn redacts_api_key_param_value() {
let out = redact_text("password=hunter2-super-secret-value");
assert!(
out.contains("password=[REDACTED:API key param]"),
"got: {out}"
);
assert!(!out.contains("hunter2"));
}
#[test]
fn keeps_non_secret_literals() {
for s in [
"password: undefined",
"secret: string",
"token: null",
"apiKey: boolean",
"password = false",
"secret: any",
"let pwd: number = 1",
] {
assert_eq!(redact_text(s), s, "must not redact non-secret literal: {s}");
}
}
#[test]
fn keeps_type_annotations() {
for s in [
"password: Promise<string>",
"apiKey: Record<string, unknown>",
"token: string[]",
"secret: () => void",
"password: string | undefined",
"credential: { value: string }",
] {
assert_eq!(redact_text(s), s, "must not redact type annotation: {s}");
}
}
#[test]
fn keeps_primitive_type_declarations() {
for s in [
"const ESTIMATED_CHARS_PER_TOKEN: u64 = 4;",
"const MAX_TOKEN: usize = 4;",
" max_token: u32,",
"var Token int64",
"secret: bool = false",
"fn token(&self) -> Self",
"private long token;",
] {
assert_eq!(redact_text(s), s, "must not redact a type declaration: {s}");
}
let out = redact_text("password: usize4Hunter2");
assert!(
out.contains("[REDACTED"),
"a real value stays masked: {out}"
);
}
#[test]
fn fully_redacts_aws_key() {
let aws_key = concat!("AK", "IAIOSFODNN7EXAMPLE");
let out = redact_text(aws_key);
assert!(!out.contains(aws_key), "AWS key leaked: {out}");
assert!(out.contains("[REDACTED:AWS key]"));
}
#[test]
fn fully_redacts_generic_long_secret() {
let secret = "A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6"; let out = redact_text(&format!("credential={secret}"));
assert!(!out.contains(secret), "long secret leaked: {out}");
assert!(
out.contains("credential=[REDACTED:Generic long secret]"),
"got: {out}"
);
}
#[test]
fn redacts_github_token_keeping_prefix() {
let github_token = concat!("gh", "p_", "abcdefghijklmnopqrstuvwxyz0123");
let out = redact_text(github_token);
assert!(
out.starts_with(concat!("gh", "p_", "[REDACTED:GitHub token]")),
"got: {out}"
);
assert!(!out.contains("abcdefghijklmnopqrstuvwxyz"));
}
#[test]
fn keeps_prose_identifier_after_keyword() {
let s = "the CSRF token: SvelteKit's native origin-check on form actions";
assert_eq!(redact_text(s), s, "prose must survive verbatim");
}
#[test]
fn keeps_identifier_and_property_references() {
for s in [
"superuserPassword: inputEnv.POCKETBASE_SUPERUSER_PASSWORD",
"export const getStripeSecretKey = serverEnv.getStripeSecretKey;",
"const apiKey = config.stripeApiKey",
] {
assert_eq!(redact_text(s), s, "identifier reference redacted: {s}");
}
}
#[test]
fn keeps_long_schema_identifier() {
let s = "endpoint_key: confirmRequiredEndpointKeySchema,";
assert_eq!(redact_text(s), s, "schema identifier must not be redacted");
}
#[test]
fn keeps_placeholder_values() {
for s in [
concat!("GITHUB_FEEDBACK_TOKEN=gh", "p_change_me"),
"API_KEY=your_key_here",
"password=<insert-password>",
"SECRET_KEY=xxxxxxxx",
] {
assert_eq!(redact_text(s), s, "placeholder redacted: {s}");
}
}
#[test]
fn a_valueless_key_does_not_reach_into_the_next_line() {
for s in [
"+token:\n+ accesstoken: acc",
"token:\n refreshtoken: ref",
"password =\n- old_value",
"Authorization: Bearer\nnext_line_word",
"credential:\n ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef012345",
] {
assert_eq!(redact_text(s), s, "crossed a line break: {s:?}");
}
let out = redact_text("token:\n password: hunter2-real-value");
assert!(!out.contains("hunter2"), "leaked: {out}");
assert!(
out.starts_with("token:\n password: [REDACTED"),
"got: {out}"
);
}
#[test]
fn keeps_asterisk_masks() {
for s in [
"password: *****",
"password: ***",
r#"expected := []string{"password: *****", "title: My Home"}"#,
"token=*",
] {
assert_eq!(redact_text(s), s, "mask redacted: {s}");
}
assert!(redact_text("password: ab*cd1234").contains("[REDACTED"));
}
#[test]
fn key_value_redaction_never_crosses_a_line_break() {
let samples = [
concat!("token:", "\n", "refreshtoken: harmless"),
concat!("Authorization: Bearer", "\n", "next_line_word"),
concat!(
"credential:",
"\n ",
"ABCDEFGHIJKLMNOP",
"QRSTUVWXYZabcdef",
"012345"
),
];
for s in samples {
assert_eq!(redact_text(s), s, "redaction crossed a line: {s:?}");
}
let same_line_secret = ["token: ", "abc123", "def456", "ghi789"].concat();
let out = redact_text(&same_line_secret);
assert!(
out.contains("[REDACTED:API key param]"),
"same-line secrets must remain redacted: {out}"
);
}
#[test]
fn asterisk_masks_survive_redaction() {
for s in [
"password: *****",
"password: ***",
r#"expected := []string{"password: *****", "title: My Home"}"#,
"token=*",
] {
assert_eq!(redact_text(s), s, "mask changed: {s}");
}
}
#[test]
fn still_redacts_real_secret_values() {
let out = redact_text("GITHUB_TOKEN=ghpA1b2c3d4e5f6g7h8");
assert!(!out.contains("ghpA1b2c3d4e5f6g7h8"), "leaked: {out}");
let out = redact_text("MY_SECRET=abc123def456ghi789");
assert!(!out.contains("abc123def456ghi789"), "leaked: {out}");
let quoted = "key: 'abcdefghijklmnopqrstuvwxyzabcdef'";
let out = redact_text(quoted);
assert!(
!out.contains("abcdefghijklmnopqrstuvwxyzabcdef"),
"leaked: {out}"
);
}
#[test]
fn exclude_patterns_skip_matching_redactions() {
let excludes = vec![regex::Regex::new(r"LCTX_TEST_\w+").unwrap()];
let input = "token=LCTX_TEST_a1b2c3d4e5";
assert_eq!(
redact_text_with_excludes(input, &excludes),
input,
"excluded match must stay verbatim"
);
assert!(redact_text(input).contains("[REDACTED"));
}
#[test]
fn identifier_and_placeholder_heuristics() {
assert!(is_identifier_reference("serverEnv.getStripeSecretKey"));
assert!(is_identifier_reference("confirmRequiredEndpointKeySchema"));
assert!(is_identifier_reference("$scope._private"));
assert!(!is_identifier_reference("abc123"), "digits → secret-shaped");
assert!(!is_identifier_reference("\"quoted\""), "literal value");
assert!(!is_identifier_reference("a-b"), "dash is not identifier");
assert!(is_placeholder_value(concat!("gh", "p_change_me")));
assert!(is_placeholder_value("<token>"));
assert!(is_placeholder_value("your_api_key_123"));
assert!(!is_placeholder_value("A1b2C3d4E5f6G7h8"));
}
#[test]
fn policy_patterns_redact_with_label_and_count() {
let patterns = vec![(
"employee_id".to_string(),
regex::Regex::new(r"EMP-\d{4}").unwrap(),
)];
let (out, hits) = redact_with_patterns("user EMP-1234 and EMP-5678", &patterns);
assert_eq!(hits, 2);
assert!(!out.contains("EMP-1234"));
assert!(out.contains("[REDACTED:employee_id]"));
}
#[test]
fn policy_patterns_noop_when_no_match() {
let patterns = vec![("iban".to_string(), regex::Regex::new(r"CH\d{2}").unwrap())];
let (out, hits) = redact_with_patterns("nothing sensitive here", &patterns);
assert_eq!(hits, 0);
assert_eq!(out, "nothing sensitive here");
}
#[test]
fn keeps_numeric_values_827() {
for (input, desc) in [
("input_cost_per_token: 1.4e-06", "scientific notation"),
("output_cost_per_token: 4.4e-06", "scientific notation"),
(
"cache_read_input_token_cost: 1.9e-07",
"scientific notation",
),
("token: 600", "plain integer"),
("secret: 0.5", "decimal float"),
("api_key: 42", "small integer"),
("password: 3.14", "pi float"),
] {
assert_eq!(
redact_text(input),
input,
"must not redact numeric value ({desc}): {input}"
);
}
}
#[test]
fn keeps_env_references_827() {
for (input, desc) in [
(
"api_key: os.environ/MY_SERVICE_API_KEY",
"Python os.environ/",
),
("secret: os.getenv(MY_KEY)", "Python os.getenv()"),
("token: process.env.API_TOKEN", "Node process.env"),
(
"password: inputEnv.POCKETBASE_SUPERUSER_PASSWORD",
"inputEnv dot ref",
),
("api_key: ${MY_API_KEY}", "shell interpolation ${}"),
("secret: $MY_SECRET", "shell $VAR"),
("token: %API_TOKEN%", "Windows %VAR%"),
("api_key: ENV[API_KEY]", "Ruby ENV[]"),
("secret: env(SECRET_KEY)", "Laravel env()"),
("password: System.getenv(DB_PASS)", "Java System.getenv"),
] {
assert_eq!(
redact_text(input),
input,
"must not redact env ref ({desc}): {input}"
);
}
}
#[test]
fn still_redacts_real_secrets_827() {
for input in [
"api_key: sk-1234567890abcdef1234567890abcdef",
"password: hunter2-super-secret-value",
"token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.payload.signature",
] {
let out = redact_text(input);
assert!(
out.contains("[REDACTED"),
"must redact real secret: {input} -> {out}"
);
}
}
#[test]
fn keeps_comparison_operators_in_source() {
for s in [
r#"if token == "" {"#,
r#"if token, err = checkPulsares(); token == "" || err != nil {"#,
r#"if password != "" {"#,
r"assert secret == expected_value",
] {
assert_eq!(redact_text(s), s, "comparison operator corrupted: {s}");
}
}
}