use super::pattern::{self, PrefixShape};
use super::scoped_context;
use super::text::{
OPENCODE_REFERENCE_OPENERS, ascii_run_len, char_at, contains_ci, ends_with_ci, find_ci,
is_command_substitution_reference, is_env_var_identifier, is_fully_delimited,
is_glued_instructional_placeholder, is_glued_my_placeholder, is_horizontal_js_whitespace,
is_instructional_token_placeholder, is_js_whitespace, is_lead_word_phrase_placeholder,
is_line_start, is_opencode_reference, is_repeated_character_filler,
is_ruby_interpolation_reference, is_template_reference, is_windows_env_reference,
matches_placeholder_vocabulary, prev_char, rskip_while_chars, skip_while_chars,
starts_with_bare_dollar_reference, starts_with_ci, starts_with_digest_label,
};
use crate::error::DetectorFailure;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};
const HIGH_SIGNAL_NAMES: &[&str] = &[
"api_key",
"apikey",
"secret",
"secret_key",
"access_token",
"refresh_token",
"session_token",
"aws_secret_access_key",
"secret_access_key",
"aws_session_token",
"password",
"passwd",
"private_key",
"client_secret",
"webhook_secret",
"auth_token",
"code_verifier",
];
const EXACT_HIGH_SIGNAL_NAMES: &[&str] = &[
"hapikey",
"x_jfrog_art_api",
"mac_secret_base64",
"personal_access_key",
"hubspot_personal_access_key",
"db_pass",
"fal_key",
"convex_deploy_key",
"convex_self_hosted_admin_key",
];
const PREFIXED_EXACT_HIGH_SIGNAL_NAMES: &[&str] = &["personal_access_key", "hapikey"];
const AMBIGUOUS_NAMES: &[&str] = &["auth", "credential", "credentials", "signing_key"];
const QUERY_ONLY_AMBIGUOUS_NAMES: &[&str] = &["code"];
const NON_CREDENTIAL_TOKEN_NAMES: &[&str] = &[
"csrf_token",
"xsrf_token",
"page_token",
"next_page_token",
"prev_page_token",
"pagination_token",
"continuation_token",
"cancel_token",
"cancellation_token",
"sync_token",
"resume_token",
"device_token",
"push_token",
];
const OBJECT_REFERENCE_SECRET_NAMES: &[&str] = &["existing_secret", "existing_secret_name"];
pub(super) const DEDICATED_PROVIDER_SEGMENTS: &[&str] = &[
"anthropic",
"atlassian",
"jira",
"confluence",
"cloudflare",
"cf",
"confluent",
"databricks",
"datadog",
"dd",
"digitalocean",
"discord",
"docker",
"dockerhub",
"fireworks",
"github",
"gh",
"gitlab",
"grafana",
"groq",
"heroku",
"huggingface",
"hf",
"langfuse",
"langsmith",
"langchain",
"linear",
"mailchimp",
"mailgun",
"neon",
"netlify",
"newrelic",
"notion",
"npm",
"okta",
"openai",
"openrouter",
"perplexity",
"pplx",
"pinecone",
"postman",
"pulumi",
"pypi",
"replicate",
"sendgrid",
"sentry",
"shopify",
"slack",
"stripe",
"supabase",
"telegram",
"terraform",
"travis",
"travisci",
"twilio",
"vault",
"vercel",
"xai",
];
const DEDICATED_PROVIDER_PHRASES: &[&str] = &["new_relic", "digital_ocean", "hugging_face"];
const NON_SECRET_NAME_LEADS: &[&str] = &[
"redacted",
"masked",
"hashed",
"hash",
"obfuscated",
"truncated",
"sanitized",
"publishable",
];
fn prefix_says_not_secret(normalized: &str) -> bool {
normalized
.split('_')
.next()
.is_some_and(|lead| NON_SECRET_NAME_LEADS.contains(&lead))
}
const VALUE_CHECKED_NAME_LEADS: &[&str] = &[
"redacted",
"masked",
"hashed",
"hash",
"obfuscated",
"truncated",
"sanitized",
];
const HASH_NAME_LEADS: &[&str] = &["hashed", "hash"];
const HEX_DIGEST_LENGTHS: &[usize] = &[32, 40, 56, 64, 96, 128];
const MIN_X_MASK_RUN: usize = 4;
fn value_shows_masking_or_hashing(lead: &str, value: &str) -> bool {
let bytes = value.as_bytes();
let x_run = bytes
.chunk_by(|left, right| left == right)
.any(|run| matches!(run[0], b'x' | b'X') && run.len() >= MIN_X_MASK_RUN);
let shows_mask = value.contains(['*', '\u{2022}', '\u{2026}'])
|| value.contains("...")
|| x_run
|| contains_ci(value, "redacted")
|| contains_ci(value, "masked")
|| starts_with_digest_label(value);
if shows_mask {
return true;
}
HASH_NAME_LEADS.contains(&lead)
&& ((HEX_DIGEST_LENGTHS.contains(&value.len()) && bytes.iter().all(u8::is_ascii_hexdigit))
|| (value.starts_with('$') && value[1..].contains('$')))
}
fn value_checked_lead_rest(normalized: &str) -> Option<(&str, &str)> {
let (lead, rest) = normalized.split_once('_')?;
(VALUE_CHECKED_NAME_LEADS.contains(&lead) && !rest.is_empty()).then_some((lead, rest))
}
pub(super) fn is_unmasked_under_masking_lead(normalized: &str, value: &str) -> bool {
value_checked_lead_rest(normalized)
.is_some_and(|(lead, _)| !value_shows_masking_or_hashing(lead, value))
}
pub(super) fn masking_lead_hides_value(normalized: &str, value: &str) -> bool {
normalized.split('_').next() == Some("publishable")
|| value_checked_lead_rest(normalized)
.is_some_and(|(lead, _)| value_shows_masking_or_hashing(lead, value))
}
fn names_dedicated_provider(normalized: &str) -> bool {
normalized
.split('_')
.any(|segment| DEDICATED_PROVIDER_SEGMENTS.contains(&segment))
|| DEDICATED_PROVIDER_PHRASES
.iter()
.any(|phrase| normalized.contains(phrase))
}
fn ends_with_prefixed_name(normalized: &str, names: &[&str]) -> bool {
names.iter().any(|name| {
normalized.len() > name.len() + 1
&& normalized.ends_with(name)
&& normalized.as_bytes()[normalized.len() - name.len() - 1] == b'_'
})
}
fn has_prefixed_name(normalized: &str, names: &[&str]) -> bool {
ends_with_prefixed_name(normalized, names)
&& !prefix_says_not_secret(normalized)
&& !names_dedicated_provider(normalized)
}
fn has_prefixed_credential_name(normalized: &str, names: &[&str]) -> bool {
ends_with_prefixed_name(normalized, names) && !prefix_says_not_secret(normalized)
}
pub(crate) fn is_high_signal_name(normalized: &str) -> bool {
if is_object_reference_secret_name(normalized) {
return false;
}
HIGH_SIGNAL_NAMES.contains(&normalized)
|| EXACT_HIGH_SIGNAL_NAMES.contains(&normalized)
|| has_prefixed_credential_name(normalized, HIGH_SIGNAL_NAMES)
|| has_prefixed_credential_name(normalized, PREFIXED_EXACT_HIGH_SIGNAL_NAMES)
|| (!AMBIGUOUS_NAMES.contains(&normalized)
&& has_prefixed_credential_name(normalized, &["token"])
&& !NON_CREDENTIAL_TOKEN_NAMES.contains(&normalized)
&& !ends_with_prefixed_name(normalized, NON_CREDENTIAL_TOKEN_NAMES))
}
fn is_object_reference_secret_name(normalized: &str) -> bool {
OBJECT_REFERENCE_SECRET_NAMES.iter().any(|name| {
normalized == *name
|| normalized
.strip_suffix(name)
.is_some_and(|prefix| prefix.ends_with('_'))
})
}
fn is_ambiguous_name(normalized: &str) -> bool {
!is_high_signal_name(normalized) && is_ambiguous_vocabulary_name(normalized)
}
fn is_ambiguous_vocabulary_name(normalized: &str) -> bool {
AMBIGUOUS_NAMES.contains(&normalized) || has_prefixed_name(normalized, AMBIGUOUS_NAMES)
}
const MIN_CONTEXT_VALUE_LENGTH: usize = 8;
const MIN_HIGH_ENTROPY_LENGTH: usize = 16;
const HIGH_ENTROPY_THRESHOLD: f64 = 3.0;
const AMBIGUOUS_ENTROPY_THRESHOLD: f64 = 3.5;
const MAX_CONTEXT_VALUE_LENGTH: usize = 4_096;
const MIN_AUTHORIZATION_VALUE_LENGTH: usize = 12;
pub(crate) fn normalize_name(name: &str) -> String {
let mut out = String::with_capacity(name.len() + 4);
normalize_name_into(name, &mut out);
out
}
fn normalize_name_into(name: &str, out: &mut String) {
out.clear();
let bytes = name.as_bytes();
for (index, &byte) in bytes.iter().enumerate() {
if index > 0 {
let previous = bytes[index - 1];
let previous_is_lower_or_digit =
previous.is_ascii_lowercase() || previous.is_ascii_digit();
if previous_is_lower_or_digit && byte.is_ascii_uppercase() {
out.push('_');
}
}
out.push(match byte {
b'.' | b'-' => '_',
other => other.to_ascii_lowercase() as char,
});
}
}
fn is_open_assignment_boundary_char(ch: char) -> bool {
is_js_whitespace(ch) || matches!(ch, '{' | '(' | ',' | ';' | '?' | '&' | '#')
}
#[must_use]
pub(crate) fn is_reserved_name(normalized: &str) -> bool {
is_high_signal_name(normalized) || is_ambiguous_name(normalized)
}
pub(crate) const RULESET_NAMES_DETECTOR_ID: &str = "generic-token-ruleset-names";
pub(crate) fn has_open_contextual_assignment(input: &str) -> bool {
let mut end = rskip_while_chars(input, input.len(), is_js_whitespace);
if let Some(ch) = prev_char(input, end)
&& (ch == '=' || ch == ':')
{
end -= ch.len_utf8();
if ch == '=' && prev_char(input, end) == Some(':') {
end -= 1;
}
end = rskip_while_chars(input, end, is_js_whitespace);
}
if let Some(ch @ ('"' | '\'')) = prev_char(input, end) {
end -= ch.len_utf8();
if prev_char(input, end) == Some('\\') {
end -= 1;
}
}
let name_end = end;
let mut name_start = end;
while let Some(ch) = prev_char(input, name_start) {
if ch.is_ascii_alphanumeric() || matches!(ch, '_' | '.' | '-') {
name_start -= ch.len_utf8();
} else {
break;
}
}
if name_start == name_end {
return false;
}
let Some(first) = char_at(input, name_start) else {
return false;
};
if !first.is_ascii_alphabetic() {
return false;
}
let boundary_ok = prev_char(input, name_start)
.is_none_or(|ch| is_open_assignment_boundary_char(ch) || matches!(ch, '"' | '\'' | '`'));
if !boundary_ok {
return false;
}
let name = &input[name_start..name_end];
let normalized = normalize_name(name);
is_high_signal_name(&normalized)
|| is_ambiguous_name(&normalized)
|| is_open_jwk_secret_member(input, name_start, name_end)
|| value_checked_lead_rest(&normalized)
.is_some_and(|(_, rest)| is_high_signal_name(rest) || is_ambiguous_name(rest))
}
fn is_open_jwk_secret_member(input: &str, name_start: usize, name_end: usize) -> bool {
if !(JWK_SECRET_MEMBERS.contains(&&input[name_start..name_end])
&& input[..name_start].ends_with('"')
&& input[name_end..].starts_with('"'))
{
return false;
}
let (line_start, line_end) = super::text::line_around(input, name_start, name_end);
input[line_start..line_end].contains("\"kty\"")
}
const PLACEHOLDER_WORDS: &[&str] = &[
"example",
"sample",
"placeholder",
"redacted",
"changeme",
"password",
"secret",
"replaceme",
];
const DIGIT_SUFFIX_PLACEHOLDER_WORDS: &[&str] = &[
"example",
"sample",
"placeholder",
"redacted",
"changeme",
"replaceme",
];
pub(super) fn is_generic_placeholder_word(value: &str) -> bool {
matches_placeholder_vocabulary(value, PLACEHOLDER_WORDS, DIGIT_SUFFIX_PLACEHOLDER_WORDS)
|| is_placeholder_led_phrase(value)
}
const PLACEHOLDER_PHRASE_WORDS: &[&str] = &["not", "a", "an", "real", "value", "only"];
fn is_placeholder_led_phrase(value: &str) -> bool {
let is_listed =
|word: &str, words: &[&str]| words.iter().any(|listed| word.eq_ignore_ascii_case(listed));
let mut words = value.split(['-', '_', '.']);
let Some(lead) = words.next() else {
return false;
};
if !is_listed(lead, DIGIT_SUFFIX_PLACEHOLDER_WORDS) {
return false;
}
let mut count = 0usize;
for word in words {
if word.is_empty()
|| !word.bytes().all(|byte| byte.is_ascii_alphabetic())
|| !(is_listed(word, PLACEHOLDER_PHRASE_WORDS)
|| super::text::is_placeholder_credential_word(word))
{
return false;
}
count += 1;
}
count > 0
}
fn is_boolean_null_or_digits(value: &str) -> bool {
["true", "false", "null", "undefined"]
.iter()
.any(|word| value.eq_ignore_ascii_case(word))
|| (!value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()))
}
fn starts_with_env_reference(value: &str) -> bool {
if value.starts_with("${") {
return true;
}
if starts_with_bare_dollar_reference(value) {
return true;
}
starts_with_ci(value, 0, "process.env.") || starts_with_ci(value, 0, "import.meta.env.")
}
fn starts_with_angle_bracket_reference(value: &str) -> bool {
let bytes = value.as_bytes();
if bytes.first() != Some(&b'<') {
return false;
}
matches!(bytes[1..].iter().position(|&byte| byte == b'>'), Some(index) if index > 0)
}
fn starts_with_path_like(value: &str) -> bool {
starts_with_angle_bracket_reference(value)
|| value.starts_with('/')
|| value.starts_with("./")
|| value.starts_with("../")
}
fn ends_with_key_or_pem(value: &str) -> bool {
ends_with_ci(value, ".key") || ends_with_ci(value, ".pem")
}
fn is_runtime_expression_reference(value: &str) -> bool {
is_fully_delimited(value, "$[", "]")
}
pub(super) fn is_backtick_reference(value: &str) -> bool {
is_fully_delimited(value, "`", "`")
}
fn is_interpolation_reference(value: &str) -> bool {
is_command_substitution_reference(value)
|| is_runtime_expression_reference(value)
|| is_ruby_interpolation_reference(value)
|| is_opencode_reference(value)
|| is_backtick_reference(value)
}
fn is_segment_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')
}
fn is_segment(value: &str) -> bool {
!value.is_empty() && value.bytes().all(is_segment_byte)
}
fn is_path_byte(byte: u8) -> bool {
is_segment_byte(byte) || byte == b'/'
}
fn is_path(value: &str) -> bool {
!value.is_empty() && value.bytes().all(is_path_byte)
}
fn is_sql_bind_parameter(value: &str) -> bool {
value.strip_prefix(':').is_some_and(is_env_var_identifier)
}
fn is_onepassword_reference(value: &str) -> bool {
let Some(rest) = value.strip_prefix("op://") else {
return false;
};
let mut segments = rest.split('/');
let (Some(vault), Some(item), Some(field), None) = (
segments.next(),
segments.next(),
segments.next(),
segments.next(),
) else {
return false;
};
is_segment(vault) && is_segment(item) && is_segment(field)
}
fn is_litellm_env_reference(value: &str) -> bool {
value
.strip_prefix("os.environ/")
.is_some_and(is_env_var_identifier)
}
fn is_gcp_project_id(value: &str) -> bool {
if !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) {
return true;
}
matches!(value.as_bytes().first(), Some(first) if first.is_ascii_lowercase())
&& value
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
}
fn is_gcp_secret_version(value: &str) -> bool {
value == "latest" || (!value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()))
}
fn is_gcp_secret_manager_reference(value: &str) -> bool {
if !value.starts_with("projects/") {
return false;
}
let mut segments = value.split('/');
let (Some("projects"), Some(project), Some("secrets"), Some(name)) = (
segments.next(),
segments.next(),
segments.next(),
segments.next(),
) else {
return false;
};
match (segments.next(), segments.next(), segments.next()) {
(None, _, _) => {}
(Some("versions"), Some(version), None) if is_gcp_secret_version(version) => {}
_ => return false,
}
is_gcp_project_id(project) && is_segment(name)
}
fn is_vals_reference(value: &str) -> bool {
let Some(rest) = value.strip_prefix("ref+") else {
return false;
};
let Some((scheme, after_scheme)) = rest.split_once("://") else {
return false;
};
if scheme.is_empty()
|| !scheme
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
{
return false;
}
let Some((path, key)) = after_scheme.split_once('#') else {
return false;
};
is_path(path) && is_path(key)
}
fn is_bank_vaults_reference(value: &str) -> bool {
let Some(rest) = value.strip_prefix("vault:") else {
return false;
};
let mut parts = rest.split('#');
let (Some(path), Some(key)) = (parts.next(), parts.next()) else {
return false;
};
let version = parts.next();
if parts.next().is_some() {
return false;
}
is_path(path) && is_segment(key) && version.is_none_or(is_segment)
}
fn is_aws_secretsmanager_partition(value: &str) -> bool {
matches!(value, "aws" | "aws-cn" | "aws-us-gov")
}
fn is_aws_region(value: &str) -> bool {
!value.is_empty()
&& value
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
}
fn is_aws_account_id(value: &str) -> bool {
value.len() == 12 && value.bytes().all(|byte| byte.is_ascii_digit())
}
fn is_secretsmanager_secret_name(value: &str) -> bool {
!value.is_empty()
&& value
.bytes()
.all(|byte| is_segment_byte(byte) || matches!(byte, b'/' | b'+' | b'=' | b'@'))
}
fn is_aws_secretsmanager_arn(value: &str) -> bool {
let mut segments = value.splitn(7, ':');
let (
Some("arn"),
Some(partition),
Some("secretsmanager"),
Some(region),
Some(account),
Some("secret"),
Some(name),
) = (
segments.next(),
segments.next(),
segments.next(),
segments.next(),
segments.next(),
segments.next(),
segments.next(),
)
else {
return false;
};
is_aws_secretsmanager_partition(partition)
&& is_aws_region(region)
&& is_aws_account_id(account)
&& is_secretsmanager_secret_name(name)
}
fn is_dns_label(label: &str) -> bool {
let bytes = label.as_bytes();
!bytes.is_empty()
&& bytes.len() <= 63
&& bytes[0] != b'-'
&& bytes[bytes.len() - 1] != b'-'
&& bytes
.iter()
.all(|byte| byte.is_ascii_alphanumeric() || *byte == b'-')
}
fn is_https_hostname(host: &str) -> bool {
if host.is_empty() || host.len() > 255 {
return false;
}
let mut count = 0usize;
let all_labels = host.split('.').all(|label| {
count += 1;
is_dns_label(label)
});
all_labels && count >= 2
}
fn is_azure_keyvault_secret_uri(value: &str) -> bool {
let Some(rest) = value.strip_prefix("https://") else {
return false;
};
let Some(slash) = rest.find('/') else {
return false;
};
let (host, path) = rest.split_at(slash);
is_https_hostname(host) && path.strip_prefix("/secrets/").is_some_and(is_path)
}
fn is_azure_keyvault_reference(value: &str) -> bool {
let Some(inner) = value
.strip_prefix("@Microsoft.KeyVault(")
.and_then(|rest| rest.strip_suffix(')'))
else {
return false;
};
if let Some(uri) = inner.strip_prefix("SecretUri=") {
return is_azure_keyvault_secret_uri(uri);
}
let mut has_vault_name = false;
let mut has_secret_name = false;
for field in inner.split(';') {
let Some((key, value)) = field.split_once('=') else {
return false;
};
if !is_segment(value) {
return false;
}
match key {
"VaultName" => has_vault_name = true,
"SecretName" => has_secret_name = true,
"SecretVersion" => {}
_ => return false,
}
}
has_vault_name && has_secret_name
}
fn is_keychain_reference(value: &str) -> bool {
value
.strip_prefix("{keychain:")
.and_then(|rest| rest.strip_suffix('}'))
.is_some_and(is_segment)
}
fn is_secret_manager_reference(value: &str) -> bool {
is_onepassword_reference(value)
|| is_litellm_env_reference(value)
|| is_gcp_secret_manager_reference(value)
|| is_vals_reference(value)
|| is_bank_vaults_reference(value)
|| is_aws_secretsmanager_arn(value)
|| is_azure_keyvault_reference(value)
|| is_keychain_reference(value)
}
fn is_mask_char(ch: char) -> bool {
matches!(ch, '*' | '\u{2022}')
}
const MIN_MASK_RUN: usize = 4;
const MAX_MASK_VISIBLE_SIDE: usize = 12;
fn is_mask_visible_char(ch: char) -> bool {
ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '-')
}
fn is_partially_masked_display(value: &str) -> bool {
let Some(mask_start) = value.find(is_mask_char) else {
return false;
};
let Some(mask) = value[mask_start..].chars().next() else {
return false;
};
let mask_end = value[mask_start..]
.find(|ch: char| ch != mask)
.map_or(value.len(), |offset| mask_start + offset);
let (head, tail) = (&value[..mask_start], &value[mask_end..]);
let run = value[mask_start..mask_end].chars().count();
let visible_side = |side: &str| {
(1..=MAX_MASK_VISIBLE_SIDE).contains(&side.len()) && side.chars().all(is_mask_visible_char)
};
run >= MIN_MASK_RUN
&& visible_side(head)
&& visible_side(tail)
&& run >= head.len() + tail.len()
}
const MIN_MASKED_KEY_RUN: usize = 16;
const MAX_MASKED_KEY_TAIL: usize = 4;
fn is_mask_separator(ch: char) -> bool {
matches!(ch, '-' | '_' | '.' | ':' | '=')
}
fn is_masked_key_display(value: &str) -> bool {
let Some(first_mask) = value.find(is_mask_char) else {
return false;
};
let Some(mask) = value[first_mask..].chars().next() else {
return false;
};
let allowed = |ch: char| ch == mask || ch.is_ascii_alphanumeric() || is_mask_separator(ch);
if !value.chars().all(allowed) {
return false;
}
let head = &value[..first_mask];
let head_visible = head.chars().filter(char::is_ascii_alphanumeric).count();
if head_visible > MAX_MASK_VISIBLE_SIDE {
return false;
}
let rest = &value[first_mask..];
let body = match rest.rfind(is_mask_separator) {
Some(index)
if (1..=MAX_MASKED_KEY_TAIL).contains(&(rest.len() - index - 1))
&& rest[index + 1..]
.chars()
.all(|ch| ch.is_ascii_alphanumeric()) =>
{
&rest[..index]
}
_ => rest,
};
body.chars().all(|ch| ch == mask || is_mask_separator(ch))
&& body.chars().filter(|&ch| ch == mask).count() >= MIN_MASKED_KEY_RUN
}
fn is_ellipsis_truncated_display(value: &str) -> bool {
let head = value.trim_end_matches(['.', '\u{2026}']);
let ellipsis = &value[head.len()..];
let elided = ellipsis.contains('\u{2026}') || ellipsis.len() >= 3;
elided
&& ((1..=MAX_MASK_VISIBLE_SIDE).contains(&head.len()) || is_elided_vendor_prefix(head))
&& head
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
}
const MAX_ELIDED_PREFIX_LEN: usize = 24;
const MAX_ELIDED_PREFIX_SEGMENT_LEN: usize = 8;
fn is_elided_vendor_prefix(head: &str) -> bool {
head.len() <= MAX_ELIDED_PREFIX_LEN
&& head.ends_with(['_', '-'])
&& head.bytes().all(|byte| {
byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'_' | b'-')
})
&& head[..head.len() - 1]
.split(['_', '-'])
.all(|segment| (1..=MAX_ELIDED_PREFIX_SEGMENT_LEN).contains(&segment.len()))
}
fn starts_with_command_substitution(value: &str) -> bool {
value.starts_with("$$(")
|| value.starts_with("$${")
|| (value.starts_with("$$")
&& value
.as_bytes()
.get(2)
.is_some_and(|byte| byte.is_ascii_alphabetic() || *byte == b'_'))
}
const PUBLIC_KEY_PREFIXES: &[&str] = &[
"pk_live_",
"pk_test_",
"sb_publishable_",
"pk-lf-",
"phc_",
"pk_dev_",
"pk_stg_",
"pk_prod_",
"pk_preview_",
];
fn is_public_key_value(value: &str) -> bool {
PUBLIC_KEY_PREFIXES.iter().any(|prefix| {
value.len() > prefix.len()
&& value.starts_with(prefix)
&& value[prefix.len()..]
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
})
}
fn is_confluent_key_id_assignment(name: &str, value: &str) -> bool {
name.split('_').any(|segment| segment == "confluent")
&& value.len() == 16
&& value
.bytes()
.all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit())
}
fn is_atlas_public_api_key_assignment(name: &str, value: &str) -> bool {
matches!(name, "public_api_key" | "mongodb_atlas_public_api_key") && value.len() == 8
}
fn is_scope_segment(segment: &str) -> bool {
if segment == "*" {
return true;
}
let mut chars = segment.chars();
matches!(chars.next(), Some(first) if first.is_ascii_lowercase())
&& chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || matches!(ch, '_' | '-'))
}
fn is_colon_scope_identifier(separator: &str, value: &str) -> bool {
separator == ":" && value.contains(':') && value.split(':').all(is_scope_segment)
}
fn is_parameter_expansion_message(
input: &str,
name_start: usize,
name_end: usize,
value_start: usize,
) -> bool {
&input[name_end..value_start] == ":"
&& input.as_bytes().get(value_start) == Some(&b'?')
&& input[..name_start].ends_with("${")
}
const CODE_REFERENCE_ROOTS: &[&str] = &[
"settings", "config", "cfg", "options", "self", "this", "var", "local", "data",
"env",
];
fn starts_with_code_reference_root(value: &str) -> bool {
CODE_REFERENCE_ROOTS.iter().any(|root| {
value
.strip_prefix(root)
.is_some_and(|rest| rest.starts_with('.'))
})
}
fn is_lower_snake_case_segment(segment: &str) -> bool {
let mut chars = segment.chars();
matches!(chars.next(), Some(first) if first.is_ascii_lowercase())
&& chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_')
}
fn is_snake_case_attribute_chain(value: &str) -> bool {
if !value.contains('_') || !value.contains('.') {
return false;
}
value
.split('.')
.all(|segment| !segment.is_empty() && is_lower_snake_case_segment(segment))
}
fn contains_generic_or_subscript_syntax(value: &str) -> bool {
let bytes = value.as_bytes();
let type_expression_bytes_only = bytes.iter().all(|&byte| {
byte.is_ascii_alphanumeric()
|| matches!(
byte,
b'_' | b'.'
| b':'
| b'<'
| b'>'
| b'['
| b']'
| b','
| b'&'
| b'\''
| b'*'
| b'?'
| b' '
)
});
type_expression_bytes_only
&& bytes.iter().enumerate().any(|(index, &byte)| {
matches!(byte, b'<' | b'[')
&& index > 0
&& matches!(bytes[index - 1], b'0'..=b'9' | b'a'..=b'z' | b'A'..=b'Z' | b'_')
})
}
fn ends_with_open_call_or_subscript(value: &str) -> bool {
matches!(value.as_bytes().last(), Some(b'(' | b'['))
}
fn is_identifier_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'_'
}
fn closing_bracket_for(open: u8) -> u8 {
match open {
b'(' => b')',
b'[' => b']',
_ => b'}',
}
}
fn balanced_group_end(bytes: &[u8], open: usize) -> Option<usize> {
let mut stack: Vec<u8> = Vec::new();
for (index, &byte) in bytes.iter().enumerate().skip(open) {
match byte {
b'(' | b'[' | b'{' => stack.push(byte),
b')' | b']' | b'}' => {
let opener = stack.pop()?;
if byte != closing_bracket_for(opener) {
return None;
}
if stack.is_empty() {
return Some(index + 1);
}
}
_ => {}
}
}
None
}
enum ChainScan {
Complete { saw_call: bool },
Truncated,
Other,
}
fn scan_identifier_chain(value: &str) -> ChainScan {
let bytes = value.as_bytes();
let mut index = 0usize;
let mut saw_call = false;
loop {
let segment_start = index;
while index < bytes.len() && is_identifier_byte(bytes[index]) {
index += 1;
}
if index == segment_start {
return ChainScan::Other;
}
while let Some(&open @ (b'(' | b'[')) = bytes.get(index) {
match balanced_group_end(bytes, index) {
Some(after) => {
index = after;
saw_call |= open == b'(';
}
None => return ChainScan::Truncated,
}
}
match bytes.get(index) {
None => return ChainScan::Complete { saw_call },
Some(b'.') => index += 1,
Some(b':') => {
index += if bytes.get(index + 1) == Some(&b':') {
2
} else {
1
}
}
Some(_) => return ChainScan::Other,
}
}
}
fn is_call_expression(value: &str) -> bool {
matches!(
scan_identifier_chain(value),
ChainScan::Complete { saw_call: true }
)
}
fn is_truncated_call_expression(value: &str) -> bool {
matches!(scan_identifier_chain(value), ChainScan::Truncated)
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum ValueForm {
Quoted,
Unquoted,
}
fn is_source_code_expression(value: &str, form: ValueForm) -> bool {
starts_with_code_reference_root(value)
|| is_snake_case_attribute_chain(value)
|| contains_generic_or_subscript_syntax(value)
|| ends_with_open_call_or_subscript(value)
|| is_call_expression(value)
|| (form == ValueForm::Unquoted && is_truncated_call_expression(value))
}
fn is_non_secret_reference(value: &str, form: ValueForm) -> bool {
is_boolean_null_or_digits(value) || is_non_secret_reference_beyond_digits(value, form)
}
const MIN_NUMERIC_SECRET_DIGITS: usize = 16;
fn is_all_digits(value: &str) -> bool {
!value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit())
}
fn is_non_secret_assignment_reference(value: &str, form: ValueForm) -> bool {
let is_literal_word = ["true", "false", "null", "undefined"]
.iter()
.any(|word| value.eq_ignore_ascii_case(word));
let is_small_number = is_all_digits(value)
&& (value.len() < MIN_NUMERIC_SECRET_DIGITS || is_ascending_digit_run(value));
is_literal_word || is_small_number || is_non_secret_reference_beyond_digits(value, form)
}
fn is_non_secret_reference_beyond_digits(value: &str, form: ValueForm) -> bool {
is_generic_placeholder_word(value)
|| is_instructional_token_placeholder(value)
|| is_glued_my_placeholder(value)
|| starts_with_env_reference(value)
|| starts_with_path_like(value)
|| ends_with_key_or_pem(value)
|| is_template_reference(value)
|| is_interpolation_reference(value)
|| is_secret_manager_reference(value)
|| is_repeated_character_filler(value)
|| is_partially_masked_display(value)
|| is_masked_key_display(value)
|| is_ellipsis_truncated_display(value)
|| starts_with_command_substitution(value)
|| is_public_key_value(value)
|| is_source_code_expression(value, form)
|| is_windows_env_reference(value)
|| is_sql_bind_parameter(value)
|| is_twilio_public_sid(value)
|| is_vendor_prefixed_placeholder(value)
|| is_prefixed_filler(value)
|| starts_with_digest_label(value)
|| is_html_escaped_angle_reference(value)
|| is_aws_arn(value)
|| (form == ValueForm::Quoted && is_string_concatenation_seam(value))
|| is_quoted_reference(value, form)
|| (form == ValueForm::Unquoted && is_credential_variable_name_value(value))
|| is_reverse_dns_identifier(value)
|| is_composite_with_placeholder_secret_part(value)
|| is_terraform_sensitive_marker(value)
|| is_pem_framed_placeholder(value)
|| is_brace_placeholder_reference(value)
|| is_elided_middle_display(value)
|| is_email_token_credential_with_placeholder(value)
}
const MAX_BRACE_PLACEHOLDER_WORD_LEN: usize = 24;
const MAX_BRACE_PLACEHOLDER_NAME_LEN: usize = 48;
fn brace_group_len(bytes: &[u8]) -> Option<usize> {
let close = match bytes.first() {
Some(b'{') => b'}',
Some(b'[') => b']',
_ => return None,
};
let mut word = 0usize;
let mut index = 1usize;
while let Some(&byte) = bytes.get(index) {
match byte {
byte if byte == close && word > 0 => return Some(index + 1),
b'_' | b'-' | b'.' | b' ' if word > 0 => word = 0,
letter if letter.is_ascii_alphabetic() => {
word += 1;
if word > MAX_BRACE_PLACEHOLDER_WORD_LEN {
return None;
}
}
_ => return None,
}
index += 1;
if index > MAX_BRACE_PLACEHOLDER_NAME_LEN + 1 {
return None;
}
}
None
}
fn placeholder_half_len(bytes: &[u8]) -> Option<usize> {
if let Some(len) = brace_group_len(bytes) {
return Some(len);
}
let boundary = |at: usize| bytes.get(at).is_none_or(|b| !b.is_ascii_alphanumeric());
match bytes.first() {
None => Some(0),
Some(b'<') => {
let limit = bytes.len().min(MAX_BRACE_PLACEHOLDER_NAME_LEN + 2);
let close = bytes[1..limit]
.iter()
.position(|&b| matches!(b, b'>' | b'<'))?;
(bytes[1 + close] == b'>' && close > 0).then_some(close + 2)
}
Some(b'*') => {
let run = bytes.iter().take_while(|&&b| b == b'*').count();
(run >= 3 && boundary(run)).then_some(run)
}
Some(0xE2) => {
let bullet = "\u{2022}".as_bytes();
let mut run = 0usize;
while bytes.get(run * 3..run * 3 + 3) == Some(bullet) {
run += 1;
}
(run >= 3 && boundary(run * 3)).then_some(run * 3)
}
Some(b'$') => {
let (start, close) = if bytes.get(1) == Some(&b'{') {
(2, true)
} else {
(1, false)
};
let name = bytes[start..]
.iter()
.take_while(|b| b.is_ascii_alphanumeric() || **b == b'_')
.count();
let end = start + name;
if name == 0 || (close && bytes.get(end) != Some(&b'}')) {
return None;
}
Some(end + usize::from(close))
}
Some(&byte) if is_query_value_stop(byte) => Some(0),
Some(_) => None,
}
}
fn brace_placeholder_len(bytes: &[u8]) -> Option<usize> {
let first = brace_group_len(bytes)?;
if matches!(bytes.get(first), Some(b'|' | b':'))
&& let Some(second) = placeholder_half_len(&bytes[first + 1..])
{
return Some(first + 1 + second);
}
Some(first)
}
pub(super) fn is_brace_placeholder_reference(value: &str) -> bool {
brace_placeholder_len(value.as_bytes()) == Some(value.len())
}
fn query_brace_placeholder(input: &str, start: usize) -> Option<(usize, usize)> {
let bytes = input.as_bytes();
let len = brace_placeholder_len(bytes.get(start..)?)?;
let end = start + len;
bytes
.get(end)
.is_none_or(|&byte| is_query_value_stop(byte))
.then_some((start, end))
}
fn is_elided_middle_display(value: &str) -> bool {
let visible = |side: &str| {
(1..=MAX_MASK_VISIBLE_SIDE).contains(&side.len())
&& side
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
};
if let Some((head, tail)) = value.split_once('\u{2026}') {
return visible(head) && visible(tail);
}
value
.split_once("...")
.is_some_and(|(head, tail)| visible(head) && visible(tail))
}
const TERRAFORM_SENSITIVE_MARKER: &str = "(sensitive value)";
fn is_terraform_sensitive_marker(value: &str) -> bool {
value == TERRAFORM_SENSITIVE_MARKER
}
fn is_pem_framed_placeholder(value: &str) -> bool {
let Some(rest) = value.strip_prefix("-----BEGIN ") else {
return false;
};
let Some(header_end) = rest.find("-----") else {
return false;
};
let after_header = &rest[header_end + 5..];
let Some(footer_start) = after_header.rfind("-----END ") else {
return false;
};
let footer = &after_header[footer_start + 9..];
let Some(footer_end) = footer.find("-----") else {
return false;
};
let separators_only = |text: &str| {
text.replace("\\r", "")
.replace("\\n", "")
.chars()
.all(char::is_whitespace)
};
if !separators_only(&footer[footer_end + 5..]) {
return false;
}
let body = after_header[..footer_start]
.replace("\\r", "")
.replace("\\n", "");
let body = body.trim();
!body.is_empty()
&& !body.contains(char::is_whitespace)
&& (is_credential_variable_name_value(body) || is_instructional_token_placeholder(body))
}
const CREDENTIAL_NAME_TAIL_WORDS: &[&str] = &[
"TOKEN",
"SECRET",
"PASSWORD",
"PASSWD",
"PASSPHRASE",
"KEY",
"CREDENTIAL",
"CREDENTIALS",
];
fn is_credential_variable_name_value(value: &str) -> bool {
let identifier = value.trim_end_matches(')');
let mut segments = identifier.split('_');
let segment_count = identifier.split('_').count();
segment_count >= 2
&& segments.all(|segment| {
segment
.bytes()
.next()
.is_some_and(|first| first.is_ascii_uppercase())
&& segment
.bytes()
.all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit())
&& !matches!(segment, "YOUR" | "INSERT" | "ENTER" | "PASTE" | "REPLACE")
})
&& identifier
.rsplit('_')
.next()
.is_some_and(|tail| CREDENTIAL_NAME_TAIL_WORDS.contains(&tail))
}
fn is_quoted_variable_name_for_slot(name: &str, value: &str) -> bool {
fn family(word: &str) -> &str {
match word {
"passwd" | "passphrase" => "password",
other => other,
}
}
let Some(value_tail) = value.rsplit('_').next() else {
return false;
};
let value_tail = value_tail.to_ascii_lowercase();
let slot_tail = name.rsplit('_').next().unwrap_or(name);
!value.ends_with(')')
&& is_credential_variable_name_value(value)
&& family(&value_tail) == family(slot_tail)
}
const CREDENTIAL_PHRASE_TAIL_WORDS: &[&str] = &[
"key",
"secret",
"token",
"password",
"passwd",
"passphrase",
"credential",
"credentials",
];
fn is_credential_noun_phrase(value: &str) -> bool {
let mut count = 0usize;
let mut tail = "";
let all_words = value.split(['-', '_']).all(|word| {
count += 1;
tail = word;
!word.is_empty() && word.bytes().all(|byte| byte.is_ascii_lowercase())
});
all_words && count >= 2 && CREDENTIAL_PHRASE_TAIL_WORDS.contains(&tail)
}
const OWN_NAME_PLACEHOLDER_LEADS: &[&str] = &["your", "insert", "enter", "paste", "replace"];
fn is_own_name_placeholder(raw_name: &str, value: &str) -> bool {
let Some(lead) = OWN_NAME_PLACEHOLDER_LEADS
.iter()
.find(|lead| starts_with_ci(value, 0, lead))
else {
return false;
};
let rest = &value[lead.len()..];
if rest.is_empty()
|| !rest
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.' | b' '))
{
return false;
}
let glued: String = rest
.bytes()
.filter(u8::is_ascii_alphanumeric)
.map(|b| char::from(b.to_ascii_lowercase()))
.collect();
let mut glued = glued.as_str();
while let Some(next) = OWN_NAME_PLACEHOLDER_LEADS
.iter()
.find_map(|lead| glued.strip_prefix(lead).filter(|rest| !rest.is_empty()))
{
glued = next;
}
if glued.is_empty() {
return false;
}
let name = normalize_name(raw_name);
let words: Vec<&str> = name.split('_').collect();
(0..words.len()).any(|from| words[from..].concat() == glued)
}
fn is_credential_name_phrase(value: &str) -> bool {
if is_credential_noun_phrase(value) {
return true;
}
let bytes = value.as_bytes();
let Some(last_capital) = bytes.iter().rposition(u8::is_ascii_uppercase) else {
return false;
};
bytes.first().is_some_and(u8::is_ascii_lowercase)
&& bytes.iter().all(u8::is_ascii_alphabetic)
&& last_capital > 0
&& matches!(
&value[last_capital..],
"Key"
| "Secret"
| "Token"
| "Password"
| "Passwd"
| "Passphrase"
| "Credential"
| "Credentials"
)
}
fn is_composite_with_placeholder_secret_part(value: &str) -> bool {
let plain = |part: &str| {
!part
.bytes()
.any(|byte| byte.is_ascii_whitespace() || matches!(byte, b'/' | b'@'))
};
let Some(last) = value.rsplit(['|', ':']).next() else {
return false;
};
if last.len() == value.len() {
return false;
}
let head = &value[..value.len() - last.len() - 1];
if head.is_empty()
|| last.is_empty()
|| !plain(head)
|| !(plain(last) || is_template_reference(last))
{
return false;
}
starts_with_env_reference(last)
|| is_template_reference(last)
|| is_interpolation_reference(last)
|| starts_with_angle_bracket_reference(last)
|| is_generic_placeholder_word(last)
|| is_instructional_token_placeholder(last)
|| is_repeated_character_filler(last)
|| is_credential_noun_phrase(last)
|| (last.ends_with('}') && head.contains("${"))
}
const REVERSE_DNS_ROOTS: &[&str] = &[
"com", "org", "net", "io", "dev", "app", "co", "me", "ai", "edu", "gov", "de", "uk", "fr",
"jp", "kr", "us",
];
fn is_reverse_dns_identifier(value: &str) -> bool {
let mut labels = value.split('.');
labels
.next()
.is_some_and(|root| REVERSE_DNS_ROOTS.contains(&root))
&& value.split('.').count() >= 3
&& labels.all(|label| {
(1..=63).contains(&label.len())
&& label.as_bytes()[0].is_ascii_alphabetic()
&& label
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
})
}
fn is_html_escaped_angle_reference(value: &str) -> bool {
value
.strip_prefix("<")
.and_then(|rest| rest.strip_suffix(">"))
.is_some_and(|inner| !inner.is_empty() && !inner.contains(['<', '>', '&']))
}
fn is_aws_arn(value: &str) -> bool {
let mut segments = value.splitn(6, ':');
let (Some("arn"), Some(partition), Some(service), Some(region), Some(account), Some(resource)) = (
segments.next(),
segments.next(),
segments.next(),
segments.next(),
segments.next(),
segments.next(),
) else {
return false;
};
is_aws_secretsmanager_partition(partition)
&& !service.is_empty()
&& service
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
&& (region.is_empty() || is_aws_region(region))
&& (account.is_empty() || account == "aws" || is_aws_account_id(account))
&& !resource.is_empty()
&& !resource.bytes().any(|byte| byte.is_ascii_whitespace())
}
fn is_string_concatenation_seam(value: &str) -> bool {
let trimmed = value.trim_matches(|ch: char| ch == ' ' || ch == '\t');
trimmed.len() + 2 <= value.len()
&& value.starts_with([' ', '\t'])
&& value.ends_with([' ', '\t'])
&& trimmed.len() >= 2
&& trimmed.starts_with(['+', '.'])
&& trimmed.ends_with(['+', '.'])
}
fn is_quoted_reference(value: &str, form: ValueForm) -> bool {
let bytes = value.as_bytes();
bytes.len() >= 3
&& matches!(bytes[0], b'\'' | b'"')
&& bytes[bytes.len() - 1] == bytes[0]
&& is_non_secret_reference(&value[1..value.len() - 1], form)
}
const MAX_FILLER_PREFIX_LEN: usize = 8;
const MIN_FILLER_LEN: usize = 8;
fn is_prefixed_filler(value: &str) -> bool {
let without_label = value
.rsplit_once('-')
.filter(|(head, label)| {
!head.is_empty()
&& (1..=MAX_MASKED_KEY_TAIL).contains(&label.len())
&& label.bytes().all(|byte| byte.is_ascii_alphanumeric())
})
.map(|(head, _)| head);
is_prefixed_filler_body(value) || without_label.is_some_and(is_prefixed_filler_body)
}
fn is_prefixed_filler_body(value: &str) -> bool {
let mut len = 0usize;
let mut run = 0usize;
let mut last = 0u8;
for byte in value
.trim_end_matches('=')
.bytes()
.filter(|byte| !matches!(byte, b'-' | b'_' | b'.' | b':'))
{
if !byte.is_ascii_alphanumeric() {
return false;
}
run = if len > 0 && byte == last { run + 1 } else { 1 };
last = byte;
len += 1;
}
run >= MIN_FILLER_LEN && len - run <= MAX_FILLER_PREFIX_LEN
}
const MAX_VENDOR_PLACEHOLDER_PREFIX_LEN: usize = 12;
const LONG_VENDOR_PLACEHOLDER_PREFIXES: &[&str] = &["sk-ant-admin01", "sandbox-sq0csb"];
const MAX_LONG_VENDOR_PLACEHOLDER_PREFIX_LEN: usize = 14;
const UPPERCASE_PLACEHOLDER_PREFIXES: &[&str] = &["EAAA", "CFPAT"];
fn is_uppercase_prefixed_placeholder(value: &str) -> bool {
UPPERCASE_PLACEHOLDER_PREFIXES.iter().any(|prefix| {
let Some(rest) = value.strip_prefix(prefix) else {
return false;
};
if let Some(body) = rest.strip_prefix(['-', '_']) {
return !body.is_empty()
&& (is_instructional_token_placeholder(body)
|| is_lead_word_phrase_placeholder(body)
|| is_repeated_character_filler(body)
|| is_whole_angle_reference(body));
}
is_whole_angle_reference(rest)
})
}
fn is_whole_angle_reference(value: &str) -> bool {
value
.strip_prefix('<')
.and_then(|rest| rest.strip_suffix('>'))
.is_some_and(|inner| !inner.is_empty() && !inner.contains(['<', '>']))
}
pub(super) fn is_vendor_prefixed_placeholder(value: &str) -> bool {
is_uppercase_prefixed_placeholder(value)
|| value
.char_indices()
.take_while(|&(index, _)| index <= MAX_LONG_VENDOR_PLACEHOLDER_PREFIX_LEN)
.filter(|&(index, ch)| {
index > 0
&& matches!(ch, '_' | '-')
&& (index <= MAX_VENDOR_PLACEHOLDER_PREFIX_LEN
|| LONG_VENDOR_PLACEHOLDER_PREFIXES.contains(&&value[..index]))
})
.any(|(index, _)| {
let rest = &value[index + 1..];
let prefix = &value[..index];
let upper_prefix_ok = prefix
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
&& rest.len() > 2
&& rest.starts_with('<')
&& rest.ends_with('>')
&& !rest[1..rest.len() - 1].contains(['<', '>']);
!rest.is_empty()
&& (upper_prefix_ok
|| prefix.bytes().all(|byte| {
byte.is_ascii_lowercase()
|| byte.is_ascii_digit()
|| matches!(byte, b'_' | b'-')
}))
&& (is_instructional_token_placeholder(rest)
|| is_glued_instructional_placeholder(rest)
|| is_lead_word_phrase_placeholder(rest)
|| is_ascending_digit_run(rest)
|| is_counting_run_body(rest)
|| starts_with_angle_bracket_reference(rest)
|| is_repeated_character_filler(rest)
|| is_generic_placeholder_word(rest))
})
}
const MIN_ASCENDING_DIGITS: usize = 4;
fn is_ascending_digit_run(value: &str) -> bool {
let bytes = value.as_bytes();
bytes.len() >= MIN_ASCENDING_DIGITS
&& bytes.iter().all(u8::is_ascii_digit)
&& bytes
.windows(2)
.all(|pair| pair[1] == if pair[0] == b'9' { b'0' } else { pair[0] + 1 })
}
const MIN_COUNTING_SEGMENT: usize = 3;
fn is_counting_segment(segment: &str) -> bool {
let bytes = segment.as_bytes();
let digits_from = bytes
.iter()
.position(u8::is_ascii_digit)
.unwrap_or(bytes.len());
let (letters, digits) = bytes.split_at(digits_from);
let counts =
|run: &[u8], next: fn(u8) -> u8| run.windows(2).all(|pair| pair[1] == next(pair[0]));
bytes.len() >= MIN_COUNTING_SEGMENT
&& letters.iter().all(u8::is_ascii_lowercase)
&& digits.iter().all(u8::is_ascii_digit)
&& counts(letters, |byte| byte + 1)
&& counts(digits, |byte| if byte == b'9' { b'0' } else { byte + 1 })
}
const COUNTING_BODY_LEN: std::ops::RangeInclusive<usize> = 6..=12;
fn is_counting_run_body(value: &str) -> bool {
let body_len = value
.bytes()
.filter(|byte| !matches!(byte, b'-' | b'_'))
.count();
COUNTING_BODY_LEN.contains(&body_len) && value.split(['-', '_']).all(is_counting_segment)
}
fn is_twilio_public_sid(value: &str) -> bool {
let bytes = value.as_bytes();
bytes.len() == 34
&& (bytes.starts_with(b"AC") || bytes.starts_with(b"SK"))
&& bytes[2..]
.iter()
.all(|&byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum NameSource {
BuiltIn,
Ruleset(Vec<String>),
}
fn is_self_reference(name: &str, value: &str) -> bool {
value.len() <= name.len()
&& name.len() <= value.len() * 2
&& value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))
&& normalize_name(value) == name
}
fn assignment_confidence(
name: &str,
value: &str,
form: ValueForm,
names: &NameSource,
query: bool,
) -> Option<Confidence> {
let (high_signal, ambiguous) = match names {
NameSource::BuiltIn => {
let high_signal = is_high_signal_name(name);
let ambiguous = (!high_signal && is_ambiguous_vocabulary_name(name))
|| (query && QUERY_ONLY_AMBIGUOUS_NAMES.contains(&name));
(high_signal, ambiguous)
}
NameSource::Ruleset(extra_ambiguous_names) => (
false,
extra_ambiguous_names.iter().any(|extra| extra == name),
),
};
if !high_signal && !ambiguous {
return None;
}
if value.len() < MIN_CONTEXT_VALUE_LENGTH
|| value.len() > MAX_CONTEXT_VALUE_LENGTH
|| is_non_secret_assignment_reference(value, form)
|| is_confluent_key_id_assignment(name, value)
|| is_atlas_public_api_key_assignment(name, value)
|| is_self_reference(name, value)
|| (form == ValueForm::Quoted && is_quoted_variable_name_for_slot(name, value))
{
return None;
}
let entropy = crate::shannon_entropy(value);
if high_signal {
return Some(
if value.len() >= MIN_HIGH_ENTROPY_LENGTH
&& entropy >= HIGH_ENTROPY_THRESHOLD
&& !is_all_digits(value)
{
Confidence::High
} else {
Confidence::Medium
},
);
}
(value.len() >= MIN_HIGH_ENTROPY_LENGTH && entropy >= AMBIGUOUS_ENTROPY_THRESHOLD)
.then_some(Confidence::Medium)
}
fn is_quoted_value_boundary(ch: Option<char>) -> bool {
match ch {
None => true,
Some(c) => matches!(
c,
' ' | '\t'
| '\u{0B}'
| '\u{0C}'
| '\r'
| '\n'
| ','
| ';'
| '}'
| ']'
| ')'
| '"'
| '\''
| '`'
),
}
}
fn is_unquoted_value_boundary(ch: Option<char>) -> bool {
match ch {
None => true,
Some(c) => matches!(
c,
' ' | '\t'
| '\u{0B}'
| '\u{0C}'
| '\r'
| '\n'
| ','
| ';'
| '}'
| ']'
| '"'
| '\''
| '`'
),
}
}
fn quoted_assignment_value(input: &str, opening_quote: usize) -> Option<(usize, usize)> {
let quote = char_at(input, opening_quote)?;
if quote != '"' && quote != '\'' {
return None;
}
let start = opening_quote + quote.len_utf8();
let mut cursor = start;
let mut backslash_run: u32 = 0;
while let Some(ch) = char_at(input, cursor) {
if ch == '\r' || ch == '\n' {
return None;
}
if cursor - start > MAX_CONTEXT_VALUE_LENGTH {
return None;
}
if ch == '\\' {
backslash_run += 1;
cursor += ch.len_utf8();
continue;
}
if ch == quote && backslash_run.is_multiple_of(2) {
let after = char_at(input, cursor + ch.len_utf8());
return is_quoted_value_boundary(after).then_some((start, cursor));
}
backslash_run = 0;
cursor += ch.len_utf8();
}
None
}
struct DelimitedOpener {
open: &'static str,
nest_open: char,
close: char,
}
const DELIMITED_REFERENCE_OPENERS: &[DelimitedOpener] = &[
DelimitedOpener {
open: "$(",
nest_open: '(',
close: ')',
},
DelimitedOpener {
open: "$[",
nest_open: '[',
close: ']',
},
DelimitedOpener {
open: "#{",
nest_open: '{',
close: '}',
},
DelimitedOpener {
open: "{env:",
nest_open: '{',
close: '}',
},
DelimitedOpener {
open: "{file:",
nest_open: '{',
close: '}',
},
DelimitedOpener {
open: "<",
nest_open: '<',
close: '>',
},
];
fn scan_nested_delimiter(
input: &str,
start: usize,
open_len: usize,
nest_open: char,
close: char,
) -> Option<usize> {
let mut cursor = start + open_len;
let mut depth: u32 = 1;
while let Some(ch) = char_at(input, cursor) {
if matches!(ch, '\r' | '\n') || cursor - start > MAX_CONTEXT_VALUE_LENGTH {
return None;
}
if ch == nest_open {
depth += 1;
} else if ch == close {
depth -= 1;
if depth == 0 {
return Some(cursor + ch.len_utf8());
}
}
cursor += ch.len_utf8();
}
None
}
fn scan_backtick_delimiter(input: &str, start: usize) -> Option<usize> {
let mut cursor = start + 1;
let mut backslash_run: u32 = 0;
while let Some(ch) = char_at(input, cursor) {
if matches!(ch, '\r' | '\n') || cursor - start > MAX_CONTEXT_VALUE_LENGTH {
return None;
}
if ch == '\\' {
backslash_run += 1;
cursor += ch.len_utf8();
continue;
}
if ch == '`' && backslash_run.is_multiple_of(2) {
return Some(cursor + ch.len_utf8());
}
backslash_run = 0;
cursor += ch.len_utf8();
}
None
}
fn delimited_reference_value(input: &str, start: usize) -> Option<(usize, usize)> {
if input[start..].starts_with(TERRAFORM_SENSITIVE_MARKER) {
let end = start + TERRAFORM_SENSITIVE_MARKER.len();
if is_unquoted_value_boundary(char_at(input, end)) {
return Some((start, end));
}
}
for opener in DELIMITED_REFERENCE_OPENERS {
if input[start..].starts_with(opener.open) {
let end = scan_nested_delimiter(
input,
start,
opener.open.len(),
opener.nest_open,
opener.close,
)?;
return is_unquoted_value_boundary(char_at(input, end)).then_some((start, end));
}
}
if char_at(input, start) == Some('`') {
let end = scan_backtick_delimiter(input, start)?;
return is_unquoted_value_boundary(char_at(input, end)).then_some((start, end));
}
None
}
fn starts_with_opencode_prefix(input: &str, start: usize) -> bool {
OPENCODE_REFERENCE_OPENERS
.iter()
.any(|open| input[start..].starts_with(open))
}
fn unquoted_assignment_value(
input: &str,
start: usize,
reach: &mut ValueReach,
) -> Option<(usize, usize)> {
unquoted_assignment_value_with(input, start, Some(reach))
}
fn unquoted_assignment_value_with(
input: &str,
start: usize,
reach: Option<&mut ValueReach>,
) -> Option<(usize, usize)> {
if starts_query_parameter(input, start) {
return None;
}
if let Some(span) = delimited_reference_value(input, start) {
return Some(span);
}
if matches!(char_at(input, start), Some('{' | '['))
&& !starts_with_opencode_prefix(input, start)
{
return None;
}
if let Some(reach) = reach {
let stop = reach.first_stop(input, start, is_unquoted_walk_stop)?;
let ends_here = match input.as_bytes().get(stop) {
Some(b'}' | b']') => false,
Some(b'&') => stop > start && starts_query_parameter(input, stop),
Some(b'`') => stop > start,
None | Some(_) => true,
};
if ends_here {
return (stop > start).then_some((start, stop));
}
}
let mut cursor = start;
let mut open_brackets: u32 = 0;
while let Some(ch) = char_at(input, cursor) {
match ch {
'{' | '[' => open_brackets += 1,
'}' | ']' if open_brackets > 0 => {
open_brackets -= 1;
cursor += 1;
continue;
}
_ => {}
}
if is_unquoted_value_boundary(Some(ch)) && !(ch == '`' && cursor == start) {
break;
}
if cursor > start && starts_query_parameter(input, cursor) {
break;
}
cursor += ch.len_utf8();
#[cfg(test)]
VALUE_WALK_BYTES.with(|bytes| bytes.set(bytes.get() + ch.len_utf8()));
if cursor - start > MAX_CONTEXT_VALUE_LENGTH {
return None;
}
}
(cursor > start).then_some((start, cursor))
}
fn is_unquoted_walk_stop(byte: u8) -> bool {
matches!(
byte,
b' ' | b'\t'
| 0x0B
| 0x0C
| b'\r'
| b'\n'
| b','
| b';'
| b'}'
| b']'
| b'"'
| b'\''
| b'`'
| b'&'
)
}
#[derive(Default)]
struct ValueReach {
from: usize,
to: usize,
hit: bool,
}
impl ValueReach {
fn first_stop(&mut self, input: &str, start: usize, stops: fn(u8) -> bool) -> Option<usize> {
let bytes = input.as_bytes();
if start < self.from || start > self.to {
*self = Self {
from: start,
to: start,
hit: false,
};
}
let limit = start.saturating_add(MAX_CONTEXT_VALUE_LENGTH);
while !self.hit && self.to <= limit {
#[cfg(test)]
VALUE_REACH_BYTES.with(|bytes| bytes.set(bytes.get() + 1));
match bytes.get(self.to) {
None => self.hit = true,
Some(&byte) if stops(byte) => self.hit = true,
Some(_) => self.to += 1,
}
}
(self.hit && self.to <= limit).then_some(self.to)
}
}
#[cfg(test)]
thread_local! {
static VALUE_WALK_BYTES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
static VALUE_REACH_BYTES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
fn escaped_quoted_assignment_value(input: &str, backslash: usize) -> Option<(usize, usize)> {
let quote = char_at(input, backslash + 1)?;
if quote != '"' && quote != '\'' {
return None;
}
let start = backslash + 1 + quote.len_utf8();
let mut cursor = start;
let mut backslash_run: u32 = 0;
while let Some(ch) = char_at(input, cursor) {
if ch == '\r' || ch == '\n' || cursor - start > MAX_CONTEXT_VALUE_LENGTH {
return None;
}
if ch == '\\' {
backslash_run += 1;
cursor += 1;
continue;
}
if ch == quote && backslash_run == 1 {
let after = char_at(input, cursor + ch.len_utf8());
return is_quoted_value_boundary(after).then_some((start, cursor - 1));
}
backslash_run = 0;
cursor += ch.len_utf8();
}
None
}
fn assignment_value(
input: &str,
start: usize,
reach: &mut ValueReach,
) -> Option<(usize, usize, ValueForm)> {
match char_at(input, start) {
Some('"' | '\'') => quoted_assignment_value(input, start)
.map(|(value_start, value_end)| (value_start, value_end, ValueForm::Quoted)),
Some('@') if char_at(input, start + 1) == Some('"') => {
quoted_assignment_value(input, start + 1)
.map(|(value_start, value_end)| (value_start, value_end, ValueForm::Quoted))
}
Some('\\') if matches!(char_at(input, start + 1), Some('"' | '\'')) => {
escaped_quoted_assignment_value(input, start)
.map(|(value_start, value_end)| (value_start, value_end, ValueForm::Quoted))
}
_ => unquoted_assignment_value(input, start, reach)
.map(|(value_start, value_end)| (value_start, value_end, ValueForm::Unquoted)),
}
}
fn is_prefix_boundary_char(ch: char) -> bool {
is_js_whitespace(ch) || matches!(ch, '{' | ',' | ';' | '"' | '\'' | '`')
}
fn parse_name_and_operator(input: &str, start: usize) -> Option<(usize, usize, usize)> {
let mut cursor = start;
if let Some(ch @ ('"' | '\'')) = char_at(input, cursor) {
cursor += ch.len_utf8();
}
let name_start = cursor;
let first = char_at(input, cursor)?;
if !first.is_ascii_alphabetic() {
return None;
}
cursor += 1;
while let Some(ch) = char_at(input, cursor) {
if ch.is_ascii_alphanumeric() || matches!(ch, '_' | '.' | '-') {
cursor += 1;
} else {
break;
}
}
let name_end = cursor;
if let Some(ch @ ('"' | '\'')) = char_at(input, cursor) {
cursor += ch.len_utf8();
} else if char_at(input, cursor) == Some('\\')
&& let Some(ch @ ('"' | '\'')) = char_at(input, cursor + 1)
{
cursor += 1 + ch.len_utf8();
}
cursor = skip_while_chars(input, cursor, is_js_whitespace);
match char_at(input, cursor) {
Some('=') => cursor += 1,
Some(':') => {
cursor += 1;
if char_at(input, cursor) == Some('=') {
cursor += 1;
}
}
_ => return None,
}
cursor = skip_while_chars(input, cursor, is_horizontal_js_whitespace);
Some((name_start, name_end, cursor))
}
fn starts_query_parameter(input: &str, pos: usize) -> bool {
char_at(input, pos) == Some('&') && parse_query_parameter(input, pos + 1).is_some()
}
fn parse_query_parameter(input: &str, start: usize) -> Option<(usize, usize, usize)> {
let bytes = input.as_bytes();
if !bytes.get(start)?.is_ascii_alphabetic() {
return None;
}
let mut cursor = start + 1;
while bytes
.get(cursor)
.is_some_and(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-'))
{
cursor += 1;
}
(bytes.get(cursor) == Some(&b'=')).then_some((start, cursor, cursor + 1))
}
fn query_parameter_value(
input: &str,
start: usize,
reach: &mut ValueReach,
) -> Option<(usize, usize)> {
if let Some(span) = query_brace_placeholder(input, start) {
return Some(span);
}
let stop = reach.first_stop(input, start, is_query_value_stop)?;
(stop > start).then_some((start, stop))
}
fn is_query_value_stop(byte: u8) -> bool {
is_unquoted_walk_stop(byte) || matches!(byte, b'#' | b')' | b'<' | b'>')
}
#[cfg(test)]
fn query_parameter_value_walk(input: &str, start: usize) -> Option<(usize, usize)> {
if let Some(span) = query_brace_placeholder(input, start) {
return Some(span);
}
let mut cursor = start;
while let Some(ch) = char_at(input, cursor) {
if is_unquoted_value_boundary(Some(ch)) || matches!(ch, '&' | '#' | ')' | '<' | '>') {
break;
}
cursor += ch.len_utf8();
if cursor - start > MAX_CONTEXT_VALUE_LENGTH {
return None;
}
}
(cursor > start).then_some((start, cursor))
}
fn otpauth_uri_spans(input: &str) -> Vec<(usize, usize)> {
const SCHEME: &[u8] = b"otpauth://";
let bytes = input.as_bytes();
let mut spans = Vec::new();
let mut index = 0usize;
while index + SCHEME.len() <= bytes.len() {
if matches!(bytes[index], b'o' | b'O')
&& bytes[index..index + SCHEME.len()].eq_ignore_ascii_case(SCHEME)
{
let mut end = index + SCHEME.len();
while end < bytes.len() && !matches!(bytes[end], b'\r' | b'\n' | b'"' | b'\'' | b'`') {
end += 1;
}
spans.push((index, end));
index = end;
} else {
index += 1;
}
}
spans
}
const JWK_SECRET_MEMBERS: &[&str] = &["k", "d", "p", "q", "dp", "dq", "qi"];
fn jwk_line_spans(input: &str) -> Vec<(usize, usize)> {
super::text::lines(input)
.filter(|&(start, end)| input[start..end].contains("\"kty\""))
.collect()
}
fn is_jwk_secret_member(
input: &str,
name_start: usize,
name_end: usize,
jwk_lines: &[(usize, usize)],
) -> bool {
JWK_SECRET_MEMBERS.contains(&&input[name_start..name_end])
&& input[..name_start].ends_with('"')
&& input[name_end..].starts_with('"')
&& jwk_lines
.partition_point(|&(start, _)| start <= name_start)
.checked_sub(1)
.is_some_and(|index| name_start < jwk_lines[index].1)
}
struct AssignmentPrefix {
name_start: usize,
name_end: usize,
prefix_end: usize,
query: bool,
call_open: bool,
}
fn try_match_assignment_prefix(input: &str, pos: usize) -> Option<AssignmentPrefix> {
let plain = |(name_start, name_end, prefix_end)| AssignmentPrefix {
name_start,
name_end,
prefix_end,
query: false,
call_open: false,
};
if is_line_start(input, pos)
&& let Some(m) = parse_name_and_operator(input, pos)
{
return Some(plain(m));
}
let ch = char_at(input, pos)?;
if is_prefix_boundary_char(ch) {
return parse_name_and_operator(input, pos + ch.len_utf8()).map(plain);
}
if matches!(ch, '[' | '(')
&& let Some(store) = super::text::keyed_store_prefix(input, pos)
{
return Some(AssignmentPrefix {
name_start: store.name_start,
name_end: store.name_end,
prefix_end: store.value_start,
query: false,
call_open: store.call,
});
}
if ch == '(' {
return parse_name_and_operator(input, pos + 1).map(
|(name_start, name_end, prefix_end)| AssignmentPrefix {
name_start,
name_end,
prefix_end,
query: false,
call_open: true,
},
);
}
if matches!(ch, '?' | '&' | '#') {
return parse_query_parameter(input, pos + 1).map(|(name_start, name_end, prefix_end)| {
AssignmentPrefix {
name_start,
name_end,
prefix_end,
query: true,
call_open: false,
}
});
}
None
}
fn next_assignment_position(input: &str, from: usize) -> usize {
const fn table() -> [bool; 256] {
let mut stops = [false; 256];
let mut byte = 0u8;
loop {
stops[byte as usize] = matches!(
byte,
b'\t'
| b'\n'
| 0x0B
| 0x0C
| b'\r'
| b' '
| b'{'
| b','
| b';'
| b'"'
| b'\''
| b'`'
| b'['
| b'('
| b'?'
| b'&'
| b'#'
) || byte >= 0xC0;
if byte == u8::MAX {
break;
}
byte += 1;
}
stops
}
static STOPS: [bool; 256] = table();
let bytes = input.as_bytes();
let mut index = from;
while index < bytes.len() {
let byte = bytes[index];
if byte & 0xC0 != 0x80 {
if STOPS[usize::from(byte)] {
return index;
}
if index == 0 || matches!(bytes[index - 1], b'\n' | b'\r' | 0xA8 | 0xA9) {
return index;
}
}
index += 1;
}
bytes.len()
}
fn assignment_candidates(input: &str, names: &NameSource) -> Vec<Candidate> {
let mut candidates = Vec::new();
let mut cursor = 0usize;
let otpauth_spans = otpauth_uri_spans(input);
let jwk_lines = jwk_line_spans(input);
let mut templates = OpenTemplateTracker::default();
let mut value_lines = ValueLinePairing::default();
let mut query_reach = ValueReach::default();
let mut unquoted_reach = ValueReach::default();
let mut normalized = String::new();
while cursor < input.len() {
let Some(AssignmentPrefix {
name_start,
name_end,
prefix_end,
query,
call_open,
}) = try_match_assignment_prefix(input, cursor).filter(|prefix| {
!prefix.query
|| otpauth_spans
.partition_point(|&(start, _)| start < cursor)
.checked_sub(1)
.is_none_or(|index| otpauth_spans[index].1 <= cursor)
})
else {
cursor = next_assignment_position(
input,
cursor + char_at(input, cursor).map_or(1, char::len_utf8),
);
continue;
};
let value_span = if query {
query_parameter_value(input, prefix_end, &mut query_reach)
.map(|(value_start, value_end)| (value_start, value_end, ValueForm::Unquoted))
} else {
assignment_value(input, prefix_end, &mut unquoted_reach)
};
if let Some((value_start, value_end, form)) = value_span
&& (!call_open || form == ValueForm::Quoted)
{
let value = &input[value_start..value_end];
normalize_name_into(&input[name_start..name_end], &mut normalized);
let mut name_phrase_is_reference = false;
if matches!(names, NameSource::BuiltIn)
&& is_jwk_secret_member(input, name_start, name_end, &jwk_lines)
{
normalized.clear();
normalized.push_str("private_key");
} else if matches!(names, NameSource::BuiltIn)
&& let Some(scoped) =
scoped_context::scoped_alias(input, name_start, name_end, &normalized)
{
normalized.clear();
normalized.push_str(scoped.alias);
name_phrase_is_reference = scoped.name_phrase_is_reference;
} else if matches!(names, NameSource::BuiltIn)
&& is_unmasked_under_masking_lead(&normalized, value)
&& let Some((_, rest)) = value_checked_lead_rest(&normalized)
{
let rest = rest.to_owned();
normalized.clear();
normalized.push_str(&rest);
} else if matches!(names, NameSource::BuiltIn)
&& &input[name_start..name_end] == "value"
&& let Some(paired) = value_lines.paired_name(input, name_start, name_end)
{
normalize_name_into(paired, &mut normalized);
}
if !is_colon_scope_identifier(&input[name_end..value_start], value)
&& !is_parameter_expansion_message(input, name_start, name_end, value_start)
&& (!name_phrase_is_reference || !is_credential_name_phrase(value))
&& !is_own_name_placeholder(&input[name_start..name_end], value)
&& let Some(confidence) =
assignment_confidence(&normalized, value, form, names, query)
&& !is_templated_lookup_path(&mut templates, input, name_start, value)
&& let Some(range) = ByteRange::new(value_start, value_end)
{
let name_signal =
if matches!(names, NameSource::BuiltIn) && is_high_signal_name(&normalized) {
"high-signal-name"
} else {
"ambiguous-name"
};
let entropy_signal = if confidence == Confidence::High {
"bounded-entropy"
} else {
"context-only"
};
candidates.push(
Candidate::built_in("contextual_secret", confidence, range)
.with_specificity(Specificity::Contextual)
.with_signals([name_signal, entropy_signal]),
);
}
}
cursor = prev_char(input, prefix_end)
.filter(|&ch| is_horizontal_js_whitespace(ch))
.map_or(prefix_end, |ch| prefix_end - ch.len_utf8());
}
candidates
}
const EMAIL_TOKEN_ANCHOR: &str = "/token:";
fn email_address_start(prefix: &str) -> Option<usize> {
let bytes = prefix.as_bytes();
let mut domain_start = bytes.len();
while domain_start > 0
&& (bytes[domain_start - 1].is_ascii_alphanumeric()
|| matches!(bytes[domain_start - 1], b'.' | b'-'))
{
domain_start -= 1;
}
if domain_start == 0 || bytes[domain_start - 1] != b'@' {
return None;
}
let domain = &prefix[domain_start..];
let last_label = domain.rsplit('.').next()?;
let labels_ok = domain.split('.').count() >= 2
&& domain.split('.').all(|label| {
!label.is_empty()
&& !label.starts_with('-')
&& !label.ends_with('-')
&& label
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
});
if !labels_ok || last_label.len() < 2 || !last_label.bytes().all(|b| b.is_ascii_alphabetic()) {
return None;
}
let at = domain_start - 1;
let mut local_start = at;
while local_start > 0
&& (bytes[local_start - 1].is_ascii_alphanumeric()
|| matches!(bytes[local_start - 1], b'.' | b'_' | b'%' | b'+' | b'-'))
{
local_start -= 1;
}
(local_start < at).then_some(local_start)
}
fn is_email_token_credential_with_placeholder(value: &str) -> bool {
if let Some(email) = value.strip_suffix("/token") {
return email_address_start(email) == Some(0);
}
let Some(at) = value.find(EMAIL_TOKEN_ANCHOR) else {
return false;
};
let token = &value[at + EMAIL_TOKEN_ANCHOR.len()..];
let token = token.find('\\').map_or(token, |end| &token[..end]);
email_address_start(&value[..at]) == Some(0)
&& (token.is_empty()
|| starts_with_reference_opener(token)
|| is_non_secret_reference_beyond_digits(token, ValueForm::Unquoted))
}
fn starts_with_reference_opener(token: &str) -> bool {
token.starts_with(['{', '[', '<', '$', '`'])
}
fn email_token_candidates(input: &str) -> Vec<Candidate> {
let mut candidates = Vec::new();
let mut from = 0usize;
while let Some(found) = input[from..].find(EMAIL_TOKEN_ANCHOR) {
let anchor = from + found;
from = anchor + 1;
if email_address_start(&input[..anchor]).is_none() {
continue;
}
let value_start = anchor + EMAIL_TOKEN_ANCHOR.len();
let Some((start, end)) = unquoted_assignment_value_with(input, value_start, None) else {
continue;
};
let end = input[start..end].find('\\').map_or(end, |at| start + at);
let value = &input[start..end];
if value.len() < MIN_CONTEXT_VALUE_LENGTH
|| value.len() > MAX_CONTEXT_VALUE_LENGTH
|| starts_with_reference_opener(value)
|| is_non_secret_assignment_reference(value, ValueForm::Unquoted)
{
continue;
}
let Some(range) = ByteRange::new(start, end) else {
continue;
};
let confidence = if value.len() >= MIN_HIGH_ENTROPY_LENGTH
&& crate::shannon_entropy(value) >= HIGH_ENTROPY_THRESHOLD
&& !is_all_digits(value)
{
Confidence::High
} else {
Confidence::Medium
};
let entropy_signal = if confidence == Confidence::High {
"bounded-entropy"
} else {
"context-only"
};
candidates.push(
Candidate::built_in("contextual_secret", confidence, range)
.with_specificity(Specificity::Contextual)
.with_signals(["high-signal-name", entropy_signal]),
);
}
candidates
}
fn is_templated_lookup_path(
templates: &mut OpenTemplateTracker,
input: &str,
name_start: usize,
value: &str,
) -> bool {
is_secret_manager_path(value) && templates.is_open_at(input, name_start)
}
fn is_secret_manager_path(value: &str) -> bool {
let path = value.split_once(':').map_or(value, |(path, _)| path);
let field_ok = value.split_once(':').is_none_or(|(_, field)| {
!field.is_empty()
&& field
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-'))
});
field_ok
&& path.split('/').count() >= 2
&& path.split('/').all(|segment| {
!segment.is_empty()
&& segment
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-'))
})
}
#[derive(Default)]
struct OpenTemplateTracker {
position: usize,
previous: u8,
opened: bool,
closed: bool,
}
impl OpenTemplateTracker {
fn is_open_at(&mut self, input: &str, position: usize) -> bool {
let end = position.min(input.len());
if end < self.position {
*self = Self::default();
}
let bytes = input.as_bytes();
for &byte in &bytes[self.position..end] {
match byte {
b'\n' | b'\r' => {
self.opened = false;
self.closed = false;
}
b'{' if self.previous == b'{' => {
self.opened = true;
self.closed = false;
}
b'}' if self.previous == b'}' && self.opened => self.closed = true,
_ => {}
}
self.previous = byte;
}
self.position = end;
self.opened && !self.closed
}
}
#[derive(Default)]
struct ValueLinePairing<'a> {
last: Option<((usize, usize), Option<&'a str>)>,
}
impl<'a> ValueLinePairing<'a> {
fn paired_name(
&mut self,
input: &'a str,
name_start: usize,
name_end: usize,
) -> Option<&'a str> {
if let Some(((line_start, line_end), paired)) = self.last
&& line_start <= name_start
&& name_end <= line_end
{
return paired;
}
#[cfg(test)]
VALUE_LINE_READS.with(|reads| reads.set(reads.get() + 1));
let line = super::text::line_around(input, name_start, name_end);
let paired = super::text::list_item_paired_name(input, line);
self.last = Some((line, paired));
paired
}
}
#[cfg(test)]
thread_local! {
static VALUE_LINE_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
fn call_argument_candidates(input: &str) -> Vec<Candidate> {
let bytes = input.as_bytes();
let mut candidates = Vec::new();
for (open, _) in input.match_indices('(') {
let mut callee_start = open;
while callee_start > 0 && is_identifier_byte(bytes[callee_start - 1]) {
callee_start -= 1;
}
if callee_start == open || !bytes[callee_start].is_ascii_alphabetic() {
continue;
}
let normalized = normalize_name(&input[callee_start..open]);
if !is_high_signal_name(&normalized) {
continue;
}
let quote_pos = skip_while_chars(input, open + 1, is_horizontal_js_whitespace);
let Some((value_start, value_end)) = quoted_assignment_value(input, quote_pos) else {
continue;
};
let after_quote = skip_while_chars(input, value_end + 1, is_horizontal_js_whitespace);
if char_at(input, after_quote) != Some(')') {
continue;
}
let value = &input[value_start..value_end];
let separated = value.bytes().any(|byte| matches!(byte, b'-' | b'_' | b'.'));
if !value.bytes().all(|byte| byte.is_ascii_graphic())
|| !value.bytes().any(|byte| byte.is_ascii_alphabetic())
|| !value.bytes().any(|byte| byte.is_ascii_digit())
|| (separated
&& !(value.bytes().any(|byte| byte.is_ascii_uppercase())
&& value.bytes().any(|byte| byte.is_ascii_lowercase())))
{
continue;
}
if assignment_confidence(
&normalized,
value,
ValueForm::Quoted,
&NameSource::BuiltIn,
false,
) != Some(Confidence::High)
{
continue;
}
if let Some(range) = ByteRange::new(value_start, value_end) {
candidates.push(
Candidate::built_in("contextual_secret", Confidence::High, range)
.with_specificity(Specificity::Contextual)
.with_signal_pack(crate::types::signal_pack!(
"high-signal-name",
"bounded-entropy",
"sdk-call-argument"
)),
);
}
}
candidates
}
fn is_space_or_tab_byte(byte: u8) -> bool {
byte == b' ' || byte == b'\t'
}
fn is_authorization_value_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/' | b'=' | b'_' | b'-')
}
fn is_key_scheme_value_byte(byte: u8) -> bool {
is_authorization_value_byte(byte) || byte == b':'
}
struct AuthorizationMatch {
scheme: &'static str,
value_start: usize,
value_end: usize,
}
fn parse_authorization_from(input: &str, start: usize) -> Option<AuthorizationMatch> {
let bytes = input.as_bytes();
let mut cursor = start + ascii_run_len(bytes, start, is_space_or_tab_byte);
if starts_with_ci(input, cursor, "proxy-authorization") {
cursor += "proxy-".len();
}
if !starts_with_ci(input, cursor, "authorization") {
return None;
}
cursor += "authorization".len();
if matches!(bytes.get(cursor), Some(b'"' | b'\'')) {
cursor += 1;
}
cursor += ascii_run_len(bytes, cursor, is_space_or_tab_byte);
if bytes.get(cursor) != Some(&b':') {
return None;
}
cursor += 1;
cursor += ascii_run_len(bytes, cursor, is_space_or_tab_byte);
if matches!(bytes.get(cursor), Some(b'"' | b'\'')) {
cursor += 1;
}
let scheme = if starts_with_ci(input, cursor, "basic") {
cursor += "basic".len();
"basic"
} else if starts_with_ci(input, cursor, "token") {
cursor += "token".len();
"token"
} else if starts_with_ci(input, cursor, "key") {
cursor += "key".len();
"key"
} else if starts_with_ci(input, cursor, "apikey") {
cursor += "apikey".len();
"apikey"
} else {
return None;
};
let ws_len = ascii_run_len(bytes, cursor, is_space_or_tab_byte);
if ws_len == 0 {
return None;
}
let value_start = cursor + ws_len;
let mut value_len = if scheme == "key" {
ascii_run_len(bytes, value_start, is_key_scheme_value_byte)
} else {
ascii_run_len(bytes, value_start, is_authorization_value_byte)
};
while value_len > 0 && bytes[value_start + value_len - 1] == b':' {
value_len -= 1;
}
if value_len < MIN_AUTHORIZATION_VALUE_LENGTH {
return None;
}
Some(AuthorizationMatch {
scheme,
value_start,
value_end: value_start + value_len,
})
}
fn try_match_authorization_at(input: &str, pos: usize) -> Option<AuthorizationMatch> {
if is_line_start(input, pos)
&& let Some(m) = parse_authorization_from(input, pos)
{
return Some(m);
}
match char_at(input, pos) {
Some(ch @ ('\r' | '\n')) => parse_authorization_from(input, pos + ch.len_utf8()),
Some(ch)
if matches!(ch, 'a' | 'A' | 'p' | 'P')
&& prev_char(input, pos).is_some_and(|previous| {
!previous.is_ascii_alphanumeric()
&& !matches!(previous, '_' | '-' | '\r' | '\n')
}) =>
{
parse_authorization_from(input, pos)
.filter(|m| matches!(m.scheme, "basic" | "key" | "apikey"))
}
_ => None,
}
}
fn is_authorization_lead_byte(byte: u8) -> bool {
matches!(
byte,
b' ' | b'\t'
| b'\r'
| b'\n'
| b'-'
| b'p'
| b'P'
| b'r'
| b'R'
| b'o'
| b'O'
| b'x'
| b'X'
| b'y'
| b'Y'
)
}
fn next_authorization_match(input: &str, mut cursor: usize) -> Option<(usize, AuthorizationMatch)> {
let bytes = input.as_bytes();
while cursor < bytes.len() {
let keyword = find_ci(bytes, cursor, b"authorization")?;
let mut start = keyword;
while start > cursor && is_authorization_lead_byte(bytes[start - 1]) {
start -= 1;
}
for pos in start..=keyword {
if let Some(m) = try_match_authorization_at(input, pos) {
return Some((pos, m));
}
}
cursor = keyword + 1;
}
None
}
fn authorization_candidate(m: &AuthorizationMatch, input: &str) -> Option<Candidate> {
let value = &input[m.value_start..m.value_end];
if is_non_secret_reference(value, ValueForm::Unquoted) {
return None;
}
let range = ByteRange::new(m.value_start, m.value_end)?;
let confidence = if value.len() >= MIN_HIGH_ENTROPY_LENGTH
&& crate::shannon_entropy(value) >= HIGH_ENTROPY_THRESHOLD
{
Confidence::High
} else {
Confidence::Medium
};
Some(
Candidate::built_in("authorization_credential", confidence, range)
.with_specificity(Specificity::Structural)
.with_signals([format!("authorization-{}-scheme", m.scheme)]),
)
}
fn authorization_candidates(input: &str) -> Vec<Candidate> {
let mut candidates = Vec::new();
let mut cursor = 0usize;
while let Some((pos, m)) = next_authorization_match(input, cursor) {
candidates.extend(authorization_candidate(&m, input));
cursor = m.value_end.max(pos + 1);
}
candidates
}
const VENDOR_PREFIXED_POLICY_PREFIXES: [&str; 4] = ["sk-proj-", "sk-svcacct-", "sk-admin-", "sk-"];
const VENDOR_PREFIXED_POLICY_BODY_LEN: usize = 48;
fn bare_vendor_prefix_candidates(input: &str) -> Vec<Candidate> {
let shapes: Vec<PrefixShape<'_>> = VENDOR_PREFIXED_POLICY_PREFIXES
.iter()
.map(|prefix| {
PrefixShape::exact(
prefix,
VENDOR_PREFIXED_POLICY_BODY_LEN,
pattern::is_alnum,
&[],
)
.with_post_check(vendor_prefixed_policy_body_is_high_entropy)
})
.collect();
pattern::scan_prefixed_shapes(input, &shapes, pattern::is_alnum_dash)
.into_iter()
.filter_map(|(start, end, _signals)| {
let range = ByteRange::new(start, end)?;
Some(
Candidate::built_in("vendor_prefixed_credential", Confidence::Medium, range)
.with_specificity(Specificity::Entropy)
.with_signal_pack(crate::types::signal_pack!("vendor-prefix-policy")),
)
})
.collect()
}
fn vendor_prefixed_policy_body_is_high_entropy(bytes: &[u8], _start: usize, end: usize) -> bool {
let body_start = end - VENDOR_PREFIXED_POLICY_BODY_LEN;
let body = std::str::from_utf8(&bytes[body_start..end]).unwrap_or_default();
crate::shannon_entropy(body) >= HIGH_ENTROPY_THRESHOLD
}
const NPMRC_CREDENTIAL_KEYS: [&str; 3] = ["_authToken", "_auth", "_password"];
fn npmrc_credential_candidates(input: &str) -> Vec<Candidate> {
let mut candidates = Vec::new();
let mut auth = input
.match_indices("_auth")
.map(|(start, _)| start)
.peekable();
let mut password = input
.match_indices("_password")
.map(|(start, _)| start)
.peekable();
let key_starts = std::iter::from_fn(|| match (auth.peek(), password.peek()) {
(Some(&a), Some(&p)) if p < a => password.next(),
(Some(_), _) => auth.next(),
(None, _) => password.next(),
});
let mut run_end = 0usize;
for key_start in key_starts {
let Some(key) = NPMRC_CREDENTIAL_KEYS
.iter()
.filter(|key| input[key_start..].starts_with(**key))
.max_by_key(|key| key.len())
else {
continue;
};
let bytes = input.as_bytes();
let scoped = key_start >= 2 && bytes[key_start - 1] == b':' && bytes[key_start - 2] == b'/';
let indented_line_start = {
let lead = rskip_while_chars(input, key_start, is_horizontal_js_whitespace);
is_line_start(input, lead)
};
if !scoped && !indented_line_start {
continue;
}
let mut cursor =
skip_while_chars(input, key_start + key.len(), is_horizontal_js_whitespace);
if char_at(input, cursor) != Some('=') {
continue;
}
cursor = skip_while_chars(input, cursor + 1, is_horizontal_js_whitespace);
let (value_start, value_end, form) = match char_at(input, cursor) {
Some('"' | '\'') => {
let Some((start, end)) = quoted_assignment_value(input, cursor) else {
continue;
};
(start, end, ValueForm::Quoted)
}
Some(_) => {
let end = if cursor < run_end {
run_end
} else {
skip_while_chars(input, cursor, |ch| {
!is_js_whitespace(ch) && !matches!(ch, '"' | '\'' | '`')
})
};
run_end = end;
(cursor, end, ValueForm::Unquoted)
}
None => continue,
};
let value = &input[value_start..value_end];
if value.len() < MIN_CONTEXT_VALUE_LENGTH
|| value.len() > MAX_CONTEXT_VALUE_LENGTH
|| is_non_secret_reference(value, form)
{
continue;
}
if let Some(range) = ByteRange::new(value_start, value_end) {
candidates.push(
Candidate::built_in("contextual_secret", Confidence::High, range)
.with_specificity(Specificity::Contextual)
.with_signal_pack(crate::types::signal_pack!(
"npmrc-credential-key",
"credential-by-construction"
)),
);
}
}
candidates
}
pub(super) struct GenericTokenDetector {
names: NameSource,
}
pub(super) static GENERIC_TOKEN: GenericTokenDetector = GenericTokenDetector {
names: NameSource::BuiltIn,
};
impl Detector for GenericTokenDetector {
fn id(&self) -> &'static str {
match &self.names {
NameSource::BuiltIn => "generic-token",
NameSource::Ruleset(_) => RULESET_NAMES_DETECTOR_ID,
}
}
fn detect(
&self,
input: &str,
_context: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
let mut candidates = assignment_candidates(input, &self.names);
if matches!(self.names, NameSource::BuiltIn) {
candidates.extend(authorization_candidates(input));
candidates.extend(bare_vendor_prefix_candidates(input));
candidates.extend(call_argument_candidates(input));
candidates.extend(npmrc_credential_candidates(input));
candidates.extend(email_token_candidates(input));
candidates.extend(super::curl_user::candidates(input));
}
Ok(candidates)
}
}
#[must_use]
pub(crate) fn generic_token_ruleset_names_detector(names: Vec<String>) -> Box<dyn Detector> {
Box::new(GenericTokenDetector {
names: NameSource::Ruleset(names),
})
}
#[cfg(test)]
mod tests {
use super::*;
fn authorization_candidates_oracle(input: &str) -> Vec<Candidate> {
let mut candidates = Vec::new();
let mut cursor = 0usize;
while cursor < input.len() {
let Some(m) = try_match_authorization_at(input, cursor) else {
cursor += char_at(input, cursor).map_or(1, char::len_utf8);
continue;
};
candidates.extend(authorization_candidate(&m, input));
cursor = m.value_end.max(cursor + 1);
}
candidates
}
#[test]
fn the_keyword_jump_equals_the_per_character_authorization_pass() {
let pieces = [
"Authorization",
"authorization",
"AUTHORIZATION",
"Proxy-Authorization",
"proxy-",
"Basic",
"basic",
"Token",
"Key",
"ApiKey",
" ",
" ",
"\t",
":",
"\"",
"'",
"\r",
"\n",
"\r\n",
"\u{2028}",
"\u{e9}",
"-",
"_",
"a",
"p",
"curl -H '",
"U1lOVEhFVElDX1JFVk9LRUQ=",
"SYNTHETICREVOKED0123",
"x",
"Authorization: Basic U1lOVEhFVElDX1JFVk9LRUQ=",
"Proxy-Authorization: Key SYNTHETICREVOKED0123",
"Proxy-Authorization: ApiKey U1lOVEhFVElDUkVWT0tFRDowMTIz",
"authorization : token U1lOVEhFVElDX1JFVk9LRUQ=",
];
let mut state: u64 = 0x1234_5678_9ABC_DEF1;
let mut next = move || {
state = state
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(state >> 33) as usize
};
assert!(authorization_candidates("").is_empty());
let mut matched = 0usize;
for _ in 0..6000 {
let mut input = String::new();
for _ in 0..next() % 24 {
input.push_str(pieces[next() % pieces.len()]);
}
let fast = authorization_candidates(&input);
matched += fast.len();
assert_eq!(fast, authorization_candidates_oracle(&input), "{input:?}");
}
assert!(
matched > 100,
"the generator must exercise real matches: {matched}"
);
}
fn detect(input: &str) -> Vec<Candidate> {
GenericTokenDetector {
names: NameSource::BuiltIn,
}
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
fn detect_with_ruleset_names(input: &str, names: &[&str]) -> Vec<Candidate> {
GenericTokenDetector {
names: NameSource::Ruleset(names.iter().map(|name| (*name).to_owned()).collect()),
}
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
fn templated_lookup_path_reference(input: &str, name_start: usize, value: &str) -> bool {
let line_start = input[..name_start].rfind(['\n', '\r']).map_or(0, |i| i + 1);
let before = &input[line_start..name_start];
let inside_template = before
.rfind("{{")
.is_some_and(|open| !before[open..].contains("}}"));
if !inside_template {
return false;
}
let path = value.split_once(':').map_or(value, |(path, _)| path);
let field_ok = value.split_once(':').is_none_or(|(_, field)| {
!field.is_empty()
&& field
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-'))
});
field_ok
&& path.split('/').count() >= 2
&& path.split('/').all(|segment| {
!segment.is_empty()
&& segment.bytes().all(|byte| {
byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-')
})
})
}
fn template_open_reference(input: &str, position: usize) -> bool {
templated_lookup_path_reference(input, position, "kv/app")
}
fn assert_tracker_matches_reference(input: &str) {
let mut tracker = OpenTemplateTracker::default();
for position in (0..=input.len()).filter(|&p| input.is_char_boundary(p)) {
assert_eq!(
tracker.is_open_at(input, position),
template_open_reference(input, position),
"{input:?} at {position}"
);
}
}
#[test]
fn open_template_tracker_matches_the_look_back_on_every_short_brace_string() {
const ALPHABET: [char; 5] = ['{', '}', '\n', '\r', 'a'];
let mut checked = 0usize;
for len in 0..=7u32 {
for mut code in 0..ALPHABET.len().pow(len) {
let mut input = String::new();
for _ in 0..len {
input.push(ALPHABET[code % ALPHABET.len()]);
code /= ALPHABET.len();
}
assert_tracker_matches_reference(&input);
checked += 1;
}
}
assert_eq!(checked, 97_656);
}
#[test]
fn open_template_tracker_matches_the_look_back_on_named_overlap_cases() {
for input in [
"{{{ a",
"{{{}} a",
"{{{}}} a",
"{{ a }}} b {{{ c",
"}}{{ a",
"{{ a }} b {{ c",
"{{ a }}\n{{ b",
"{{ a\r b",
"{{ a\r\n}} b {{",
"{ { a } }",
"x: \"{{ lookup('hashi_vault', 'secret=kv/data/app:token') }}\" y=z",
"é{{ é }} é{{é",
] {
assert_tracker_matches_reference(input);
}
}
#[test]
fn templated_lookup_path_matches_the_look_back_on_generated_lines() {
const PIECES: [&str; 12] = [
"{", "}", "{{", "}}", "\n", "\r\n", " ", "a=", "é", "{{{", "}}}", "'secret=",
];
const VALUES: [&str; 6] = [
"kv/app",
"kv/data/app:token",
"plain",
"kv/",
"a/b:",
"x/y:z-1",
];
let mut state = 0x9e37_79b9_7f4a_7c15u64;
let mut next = |bound: usize| {
state = state
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
usize::try_from(state >> 33).unwrap() % bound
};
for _ in 0..2_000 {
let mut input = String::new();
for _ in 0..next(40) {
input.push_str(PIECES[next(PIECES.len())]);
}
let mut tracker = OpenTemplateTracker::default();
for position in (0..=input.len()).filter(|&p| input.is_char_boundary(p)) {
if next(3) == 0 {
continue;
}
let value = VALUES[next(VALUES.len())];
assert_eq!(
is_templated_lookup_path(&mut tracker, &input, position, value),
templated_lookup_path_reference(&input, position, value),
"{input:?} at {position} with {value:?}"
);
}
}
}
#[test]
fn open_template_tracker_restarts_on_a_backward_query() {
let input = "{{ a\nb }} {{ c";
let mut tracker = OpenTemplateTracker::default();
assert!(tracker.is_open_at(input, input.len()));
assert!(tracker.is_open_at(input, 3));
assert!(!tracker.is_open_at(input, 6));
assert!(tracker.is_open_at(input, input.len()));
}
fn only_range(candidates: &[Candidate]) -> (usize, usize) {
assert_eq!(candidates.len(), 1);
(candidates[0].range().start(), candidates[0].range().end())
}
#[test]
fn nested_assignments_emit_overlapping_contextual_candidates() {
let input = "client_secret=\"SYNTHETIC_REVOKED_OUTER_MARKER; api_key=SYNTHETIC_REVOKED_CONTEXT_OVERLAP_1234\"";
let candidates = detect(input);
assert_eq!(candidates.len(), 2);
assert!(
candidates
.iter()
.all(|candidate| candidate.type_name() == "contextual_secret")
);
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].range(), ByteRange::new(15, 93).unwrap());
assert_eq!(candidates[1].confidence(), Confidence::High);
assert_eq!(candidates[1].range(), ByteRange::new(55, 93).unwrap());
assert!(candidates[0].range().overlaps(candidates[1].range()));
}
const COLON_PREFIX_VALUE: &str = "Synthetic-EXAMPLE-pw-9f3k2";
fn assert_only_value(input: &str, value: &str) {
let start = input.rfind(value).unwrap();
assert_eq!(
only_range(&detect(input)),
(start, start + value.len()),
"{input:?}"
);
}
#[test]
fn a_credential_assignment_after_a_colon_prefix_is_detected() {
for prefix in [
"",
"login failed with ",
"login failed; ",
"user=bob: ",
"login failed: ",
"error: ",
"request failed:\t",
"error: ",
"error = ",
"msg := ",
"[auth] login failed: ",
] {
let input = format!("{prefix}password={COLON_PREFIX_VALUE}");
assert_only_value(&input, COLON_PREFIX_VALUE);
let input = format!("{prefix}api_key: {COLON_PREFIX_VALUE}");
assert_only_value(&input, COLON_PREFIX_VALUE);
}
}
#[test]
fn a_credential_assignment_nested_in_a_credential_colon_value_emits_both_candidates() {
let input = format!("secret: password={COLON_PREFIX_VALUE}");
let candidates = detect(&input);
assert_eq!(candidates.len(), 2, "{candidates:?}");
let inner = input.len() - COLON_PREFIX_VALUE.len();
assert_eq!(
candidates[0].range(),
ByteRange::new(8, input.len()).unwrap()
);
assert_eq!(
candidates[1].range(),
ByteRange::new(inner, input.len()).unwrap()
);
}
#[test]
fn benign_assignments_after_a_colon_prefix_stay_unmatched() {
for input in [
"note: value=hello",
"note: value=Synthetic-EXAMPLE-pw-9f3k2",
"status: ok=true",
"error: user=bob",
"error: token=Synthetic-EXAMPLE-pw-9f3k2",
"login failed: password=",
"login failed: password=********",
"login failed: password=${DB_PASSWORD}",
"login failed: password=<password>",
"url: https://example.test/callback?a=b",
"redirect: https://example.test/cb?state=abc&a=b",
"see https://example.test/?a=b&c=d",
"time: 12:30:45",
"scope: api-key:endpoint:chat",
] {
let candidates = detect(input);
assert!(candidates.is_empty(), "{input:?}: {candidates:?}");
}
}
#[test]
fn a_credential_name_glued_to_a_preceding_operator_stays_unmatched() {
for input in [
format!("error:password={COLON_PREFIX_VALUE}"),
format!("x=password={COLON_PREFIX_VALUE}"),
] {
assert!(detect(&input).is_empty(), "{input:?}");
}
}
#[test]
fn a_high_signal_assignment_wrapped_in_markdown_inline_code_is_still_detected() {
let input = "`api_key=\"SYNTHETIC_REVOKED_CONTEXT_VALUE\"`";
let candidates = detect(input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::High);
let value_start = "`api_key=\"".len();
let value_end = value_start + "SYNTHETIC_REVOKED_CONTEXT_VALUE".len();
assert_eq!(
candidates[0].range(),
ByteRange::new(value_start, value_end).unwrap()
);
}
#[test]
fn a_masked_value_wrapped_in_markdown_inline_code_stays_excluded() {
assert!(detect("`password=********`").is_empty());
}
#[test]
fn an_unquoted_assignment_in_markdown_inline_code_excludes_the_closing_backtick() {
let input = "`api_key=SYNTHETIC_REVOKED_CONTEXT_VALUE`";
let candidates = detect(input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::High);
let value_start = "`api_key=".len();
let value_end = value_start + "SYNTHETIC_REVOKED_CONTEXT_VALUE".len();
assert_eq!(
candidates[0].range(),
ByteRange::new(value_start, value_end).unwrap()
);
}
#[test]
fn high_signal_assignment_with_bounded_entropy_is_high_confidence() {
let input = "api_key=SYNTHETIC_REVOKED_CONTEXT_VALUE";
let candidates = detect(input);
assert_eq!(only_range(&candidates), (8, input.len()));
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].specificity(), Some(Specificity::Contextual));
}
#[test]
fn a_generically_prefixed_high_signal_name_is_high_confidence() {
for name in [
"MYAPP_API_KEY",
"backendSecretKey",
"DB_PASSWORD",
"jwt.secret",
"CI_DEPLOY_TOKEN",
"internal-service-token",
"SMTP_PASSWORD",
"ADMIN_TOKEN",
] {
let input = format!("{name}=SYNTHETIC_REVOKED_CONTEXT_VALUE");
let candidates = detect(&input);
assert_eq!(candidates.len(), 1, "{input}");
assert_eq!(candidates[0].confidence(), Confidence::High, "{input}");
assert_eq!(only_range(&candidates), (name.len() + 1, input.len()));
assert!(
has_open_contextual_assignment(&format!("{name}=")),
"{name}"
);
}
}
#[test]
fn non_secret_prefixes_are_not_generic_names() {
let hex64 = "0123456789abcdef".repeat(4);
for input in [
"publishable_key=SYNTHETIC_REVOKED_CONTEXT_VALUE".to_owned(),
"hashed_token=SYNTHETIC_REVOKED_CONTEXT_VALUE".to_owned(),
format!("masked_api_key=9ctA{}lwCk", "*".repeat(32)),
format!("masked_api_key=abcd{}", "x".repeat(28)),
"redactedApiKey=SYNTHETIC...VALUE_TAIL".to_owned(),
"masked_secret=[REDACTED]-SYNTHETIC-VALUE".to_owned(),
format!("hashed_api_key={hex64}"),
"hash_secret=$2b$12$SYNTHETICsaltSYNTHETIChashvalue0000".to_owned(),
format!("hashed_password=sha256:{hex64}"),
"masked_api_key=Ab3\u{2022}\u{2022}\u{2022}\u{2022}Cd4Ef5Gh6Jk7".to_owned(),
] {
assert!(detect(&input).is_empty(), "{input}");
}
}
#[test]
fn an_unmasked_value_under_a_masking_lead_is_judged_under_the_rest_of_the_name() {
for name in [
"masked_api_key",
"redactedApiKey",
"hashed_password",
"obfuscated_client_secret",
"sanitized_access_token",
] {
let input = format!("{name}=SYNTHETIC_REVOKED_CONTEXT_VALUE");
let candidates = detect(&input);
assert_eq!(
only_range(&candidates),
(name.len() + 1, input.len()),
"{input}"
);
assert_eq!(candidates[0].confidence(), Confidence::High, "{input}");
assert!(
has_open_contextual_assignment(&format!("{name}=")),
"{name}"
);
}
assert!(detect("hashed_token=SYNTHETIC_REVOKED_CONTEXT_VALUE").is_empty());
assert!(!has_open_contextual_assignment("publishable_key="));
}
#[test]
fn provider_prefixed_high_signal_names_are_generic_names() {
for name in [
"POSTMAN_API_KEY",
"GITHUB_TOKEN",
"GH_TOKEN",
"DD_API_KEY",
"NEW_RELIC_API_KEY",
"stripeSecretKey",
"SLACK_BOT_TOKEN",
"OPENAI_API_KEY",
"ANTHROPIC_API_KEY",
"HUGGING_FACE_HUB_TOKEN",
"GITHUB_CLIENT_SECRET",
] {
let input = format!("{name}=SYNTHETIC_REVOKED_CONTEXT_VALUE");
let candidates = detect(&input);
assert_eq!(candidates.len(), 1, "{input}");
assert_eq!(candidates[0].type_name(), "contextual_secret", "{input}");
assert_eq!(candidates[0].confidence(), Confidence::High, "{input}");
assert_eq!(
candidates[0].specificity(),
Some(Specificity::Contextual),
"{input}"
);
}
}
#[test]
fn every_dedicated_provider_prefix_qualifies_for_high_signal_names() {
for prefix in DEDICATED_PROVIDER_SEGMENTS
.iter()
.chain(DEDICATED_PROVIDER_PHRASES)
{
for suffix in [
"api_key",
"token",
"secret_key",
"client_secret",
"password",
] {
let name = format!("{prefix}_{suffix}");
assert!(is_high_signal_name(&name), "{name}");
assert!(is_reserved_name(&name), "{name}");
assert!(
has_open_contextual_assignment(&format!("{name}=")),
"{name}"
);
}
for suffix in [
"credentials",
"auth",
"signing_key",
"csrf_token",
"api_key_id",
] {
let name = format!("{prefix}_{suffix}");
assert!(!is_high_signal_name(&name), "{name}");
assert!(!is_ambiguous_name(&name), "{name}");
}
}
}
#[test]
fn provider_prefixed_ambiguous_request_scoped_and_identifier_names_stay_clean() {
for name in [
"GITHUB_CREDENTIALS",
"OKTA_AUTH",
"SLACK_SIGNING_KEY",
"GITHUB_CSRF_TOKEN",
"STRIPE_NEXT_PAGE_TOKEN",
"SLACK_DEVICE_TOKEN",
"OPENAI_API_KEY_ID",
"STRIPE_API_URL",
"TWILIO_ACCOUNT_SID",
"OPENAI_ORG_ID",
] {
let input = format!("{name}=SYNTHETIC_REVOKED_CONTEXT_VALUE_9f3K");
assert!(detect(&input).is_empty(), "{input}");
}
for name in ["redacted_openai_api_key", "MASKED_STRIPE_SECRET_KEY"] {
let masked = format!("{name}=SYNTHETIC{}9f3K", "*".repeat(16));
assert!(detect(&masked).is_empty(), "{masked}");
let unmasked = format!("{name}=SYNTHETIC_REVOKED_CONTEXT_VALUE_9f3K");
assert_eq!(detect(&unmasked).len(), 1, "{unmasked}");
}
}
#[test]
fn a_prefixed_ambiguous_name_stays_medium_at_the_ambiguous_entropy_bar() {
let input = "SERVICE_CREDENTIALS=SYNTHETIC_REVOKED_CONTEXT_VALUE_9f3K";
let candidates = detect(input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::Medium);
}
#[test]
fn request_scoped_token_names_and_unprefixed_suffix_lookalikes_stay_clean() {
for name in [
"csrf_token",
"X_CSRF_TOKEN",
"next_page_token",
"nextPageToken",
"cancellation_token",
"device_token",
"token",
"tokens",
"api_keys_count",
"passwordless",
"secretary",
"_token",
] {
let input = format!("{name}=SYNTHETIC_REVOKED_CONTEXT_VALUE");
assert!(detect(&input).is_empty(), "{input}");
}
}
#[test]
fn a_vendor_prefixed_placeholder_is_not_a_secret() {
for input in [
"api_key=pplx-your-api-key-here",
"app_token: xapp-<your-app-level-token>",
"api_key=lsv2_pt_your_key_here",
"api_key=pcsk_***",
"access_token=pul-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"api_key=sk-proj-YOUR_API_KEY",
"api_key=sk-placeholder",
"access_token=dapixxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"api_key=PMAK-xxxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"api_key=00000000-0000-0000-0000-000000000000",
"client_token=hmac-sha256:3122799486cdfa0be2445049d8a1f0c2",
"secret=sha256:9f86d081884c7d659a2feaa0c55ad015a3bf4f1b",
] {
assert!(detect(input).is_empty(), "{input}");
}
}
#[test]
fn the_vendor_placeholder_prefix_limit_covers_the_anthropic_admin_prefix() {
assert!(is_vendor_prefixed_placeholder("sk-ant-admin01-<your-key>"));
assert!(is_vendor_prefixed_placeholder("sk-ant-admin01-YOUR_KEY"));
assert!(is_vendor_prefixed_placeholder("sk-ant-admin01-..."));
assert!(!is_vendor_prefixed_placeholder("sk-ant-admin02-<your-key>"));
assert!(!is_vendor_prefixed_placeholder("abcdefghijklmn-<your-key>"));
assert!(!is_vendor_prefixed_placeholder(
"sk-ant-admin01-Ab3Cd4Ef5Gh6"
));
}
#[test]
fn issue_1042_placeholder_shapes_are_excluded_and_their_twins_are_not() {
assert!(is_vendor_prefixed_placeholder(
"rpa_your_key_for_ci_pipeline_test_fixture_only"
));
assert!(is_lead_word_phrase_placeholder("YOUR_TOKEN_FOR_STAGING"));
for twin in [
"your_key_for_ci_7",
"your_Key_for_ci",
"my_key_for_ci",
"your_for_ci",
"your",
] {
assert!(!is_lead_word_phrase_placeholder(twin), "{twin}");
}
for value in [
"pdl_sdbx_apikey_...",
"pdl_live_apikey_\u{2026}",
"wandb_v1_...",
] {
assert!(is_ellipsis_truncated_display(value), "{value}");
}
for twin in [
"pdl_sdbx_apikey_01hq7zyx9...",
"pdl_sdbx_apikeyzz...",
"pdl_sdbx_verylongsegment_...",
"PDL_SDBX_APIKEY_...",
"pdl_sdbx_apikey_",
] {
assert!(!is_ellipsis_truncated_display(twin), "{twin}");
}
let x = |n: usize| "x".repeat(n);
let bitwarden = format!("0.{}-{}.{}:{}==", x(8), x(4), x(30), x(22));
assert!(is_prefixed_filler(&bitwarden));
assert!(!is_prefixed_filler(&format!("0.{}:{}y==", x(8), x(22))));
assert!(!is_prefixed_filler(&format!("0.{}=={}", x(8), x(22))));
for value in ["mykeysecret", "mykeyid", "myapikey", "mysecretaccesskey"] {
assert!(is_glued_my_placeholder(value), "{value}");
}
for twin in [
"mysecret",
"mykey",
"mykeysecret7",
"myKeySecret",
"mykeysecretq",
"keysecret",
] {
assert!(!is_glued_my_placeholder(twin), "{twin}");
}
}
#[test]
fn a_phrase_led_by_a_distinctive_placeholder_word_is_a_placeholder() {
for value in [
"placeholder-not-a-key",
"placeholder-value",
"PLACEHOLDER_API_KEY",
"example-token",
"sample.secret.value",
"changeme-only",
] {
assert!(is_placeholder_led_phrase(value), "{value}");
assert!(
is_generic_placeholder_word(&value.to_ascii_lowercase()),
"{value}"
);
}
for value in [
"placeholder",
"placeholder-",
"placeholder--key",
"placeholder-key9",
"placeholder-hunter",
"secret-not-a-key",
"password-value",
"not-a-real-key",
"key-placeholder",
] {
assert!(!is_placeholder_led_phrase(value), "{value}");
}
}
#[test]
fn a_counting_digit_run_or_glued_your_word_behind_a_vendor_prefix_is_a_placeholder() {
for value in [
"signkey-test-12345",
"re_123456789",
"re_1234567890",
"re_7890123",
"re_yourkey",
"re_YourApiKeyHere",
"signkey-prod-yoursigningkey",
] {
assert!(is_vendor_prefixed_placeholder(value), "{value}");
}
for value in [
"re_123",
"re_12346",
"re_98765",
"re_193847562",
"re_yourkeyq",
"re_yourkey7",
"re_yourdog",
"re_your",
"RE_yourkey",
"longvendorname_12345",
] {
assert!(!is_vendor_prefixed_placeholder(value), "{value}");
}
assert!(!is_ascending_digit_run("123"));
assert!(is_ascending_digit_run("8901"));
assert!(!is_glued_instructional_placeholder("your"));
assert!(!is_glued_instructional_placeholder("your_key"));
}
#[test]
fn a_vendor_prefix_before_random_material_stays_detected() {
for input in [
"api_key=pplx-9f2cQ7xLm4Rt8Wz3Nc6Bh1Jd",
"access_token=pul-xxxx9f2cQ7xLm4Rt8Wz3Nc6Bh1Jd",
"api_key=verylongvendorprefix_your_api_key_here",
"access_token=dapixxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx9",
"secret=sha256x9f86d081884c7d659a2feaa0c55ad015",
"api_key=abcdefghixxxxxxxxxxxxxxx",
] {
assert_eq!(detect(input).len(), 1, "{input}");
}
}
#[test]
fn a_prefixed_name_keeps_every_non_secret_value_exclusion() {
for input in [
"MYAPP_API_KEY=${MYAPP_API_KEY}",
"DB_PASSWORD=<your-db-password>",
"CI_DEPLOY_TOKEN=YOUR_ACCESS_TOKEN",
"ADMIN_TOKEN=short",
] {
assert!(detect(input).is_empty(), "{input}");
}
}
#[test]
fn high_signal_names_warn_on_ordinary_prose_as_an_accepted_precision_tradeoff() {
for (input, captured) in [
(
"The otpauth URI format includes a secret= parameter holding the shared seed.",
"parameter",
),
(
"Set password= followed by your chosen passphrase.",
"followed",
),
(
"The api_key: parameter is required for all authenticated endpoints.",
"parameter",
),
(
"Use client_secret: obtained from the developer console.",
"obtained",
),
(
"Each request needs an access_token: retrieved during the OAuth exchange.",
"retrieved",
),
(
"The private_key: argument accepts a PEM-encoded string.",
"argument",
),
(
"Pass secret: whichever value your provider issued.",
"whichever",
),
(
"Configure password: something memorable but strong.",
"something",
),
(
"The webhook_secret= configuration determines signature validation.",
"configuration",
),
(
"Note that api_key= supports environment interpolation.",
"supports",
),
] {
let candidates = detect(input);
assert_eq!(candidates.len(), 1, "{input:?}");
assert_eq!(candidates[0].type_name(), "contextual_secret");
assert_eq!(candidates[0].confidence(), Confidence::Medium);
let (start, end) = only_range(&candidates);
assert_eq!(&input[start..end], captured, "{input:?}");
}
let input = "password=hunter2xyz";
let candidates = detect(input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::Medium);
}
#[test]
fn escaped_quote_stays_inside_one_structured_value_span() {
let input = "{\"api_key\":\"SYNTHETIC_REVOKED_\\\"QUOTED_VALUE\"}";
let candidates = detect(input);
assert_eq!(only_range(&candidates), (12, 44));
}
#[test]
fn a_nested_assignment_with_no_separator_inside_an_enclosing_quote_is_detected() {
for (input, start, end) in [
(
"value=\"api_key=\"I9RBasVzoPPDPIErHTQcrdjnmKvu\"\"\n",
16,
44,
),
(
"value=\"password=\"yrdhd5QrRabaY9e8KnFuTTALQClH\"\"\n",
17,
45,
),
(
"value=\"client_secret=\"rs06I0rFoRw0mKTRs9hZIDfyQqXw\"\"\n",
22,
50,
),
] {
let candidates = detect(input);
assert_eq!(only_range(&candidates), (start, end), "input: {input:?}");
assert_eq!(candidates[0].confidence(), Confidence::High);
}
}
#[test]
fn a_single_quoted_nested_assignment_with_no_separator_is_detected() {
let input = "value='api_key='SYNTHETIC_REVOKED_NESTED_SINGLE_QUOTE_1234''\n";
let candidates = detect(input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::High);
}
#[test]
fn a_plain_quoted_assignment_with_no_nesting_is_unaffected() {
let input = "api_key=\"SYNTHETIC_REVOKED_PLAIN_QUOTED_VALUE_1234\"";
let candidates = detect(input);
assert_eq!(only_range(&candidates), (9, input.len() - 1));
}
fn only_value(input: &str) -> &str {
let candidates = detect(input);
let (start, end) = only_range(&candidates);
&input[start..end]
}
#[test]
fn an_assignment_inside_an_escaped_json_string_is_detected() {
let input = r#"{"level":"debug","body":"{\"access_token\":\"SYNTHETICq8vN3xR7tLm2Kp9Wd\",\"expires_in\":3600}"}"#;
assert_eq!(only_value(input), "SYNTHETICq8vN3xR7tLm2Kp9Wd");
let nested = r#"{"body":"{\"password\":\"SYNTHETIC\\\"q8vN3xR7tLm2Kp9Wd\",\"x\":1}"}"#;
assert_eq!(only_value(nested), r#"SYNTHETIC\\\"q8vN3xR7tLm2Kp9Wd"#);
assert!(detect(r#"{"body":"{\"password\":\"${DB_PASSWORD}\"}"}"#).is_empty());
}
#[test]
fn url_query_fragment_and_form_body_parameters_are_detected() {
const V: &str = "SYNTHETICq8vN3xR7tLm2Kp9Wd";
for input in [
format!("https://api.example.test/r?access_token={V}&p=q"),
format!("GET /resource?access_token={V} HTTP/1.1"),
format!("Location: https://client.example.test/cb#access_token={V}&state=xyz"),
format!("grant_type=refresh_token&refresh_token={V}"),
format!("&client_secret={V}"),
format!("[docs](https://api.example.test/r?access_token={V})"),
] {
assert_eq!(only_value(&input), V, "{input}");
}
assert_eq!(only_value(&format!("refresh_token={V}&client_id=s6Bhd")), V);
let verifier = format!("code_verifier={V}{V}");
assert_eq!(only_value(&verifier), format!("{V}{V}"));
}
#[test]
fn the_authorization_code_is_ambiguous_and_only_as_a_query_parameter() {
let input = "https://client.example.test/cb?code=SYNTHETICq8vN3xR7tLm2Kp9Wd&state=xyz";
let candidates = detect(input);
assert_eq!(&input[36..62], "SYNTHETICq8vN3xR7tLm2Kp9Wd");
assert_eq!(only_range(&candidates), (36, 62));
assert_eq!(candidates[0].confidence(), Confidence::Medium);
for clean in [
"https://x.example.test/?code=200",
"https://x.example.test/?code=US&lang=en",
"code = SYNTHETICq8vN3xR7tLm2Kp9Wd",
"error code=SYNTHETICq8vN3xR7tLm2Kp9Wd",
"code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
"access_token_type=Bearer&refresh_token_expires_in=3600",
"see docs?password=hunter",
] {
assert!(detect(clean).is_empty(), "{clean}");
}
}
#[test]
fn query_parameters_inside_an_otpauth_uri_are_left_to_otpauth_uri() {
for input in [
"otpauth://push/Example:alice@example.com?secret=SYNTHETICOTPAUTHSEEDVALUEQPWKYV",
"OTPAUTH://TOTP/Example:alice@example.com?secret=SYNTHETICOTPAUTHSEEDVALUEQPWKYV",
"otpauth://totp/Example Label:alice?issuer=x&secret=SYNTHETICOTPAUTHSEEDVALUEQPWKYV",
] {
assert!(detect(input).is_empty(), "{input}");
}
let input = "otpauth://totp/x?secret=SYNTHETICOTPAUTHSEEDVALUEQPWKYV\nhttps://api.example.test/r?access_token=SYNTHETICq8vN3xR7tLm2Kp9Wd";
assert_eq!(only_value(input), "SYNTHETICq8vN3xR7tLm2Kp9Wd");
}
#[test]
fn escaped_placeholders_quoted_references_env_lookups_seams_and_arns_are_not_secrets() {
const V: &str = "SYNTHETICq8vN3xR7tLm2Kp9Wd";
for clean in [
"\"password\": \"<YOUR_PASSWORD>\"",
"- echo 'export DB_PASSWORD=\"'$DEPLOY_PASSWORD'\"' >> .env",
"password = env.DEPLOY_TEST_PASSWORD",
"sb.append(\"UserPassword: \" + getUserPassword() + \",\");",
"$msg = \"password: \" . $password . \"\\n\";",
"ChangePassword = \"arn:aws:iam::aws:policy/ChangePassword\"",
"secret_arn: arn:aws-us-gov:kms:us-gov-west-1:123456789012:key/SYNTHETIC-key-id",
] {
assert!(detect(clean).is_empty(), "{clean}");
}
for (input, value) in [
(
format!("\"password\": \"<x>{V}\""),
format!("<x>{V}"),
),
(format!("DB_PASSWORD=\"'{V}'\""), format!("'{V}'")),
(format!("password = envx{V}"), format!("envx{V}")),
(format!("password = \"{V}+ x +\""), format!("{V}+ x +")),
(format!("password = \"arn:{V}\""), format!("arn:{V}")),
] {
assert_eq!(only_value(&input), value, "{input}");
}
}
#[test]
fn jwk_secret_members_are_detected_only_on_a_kty_line() {
let symmetric = r#"{"kty":"oct","k":"U1lOVEhFVElDX1JFVk9LRURfSldLX1NZTU1FVFJJQ19LRVk"}"#;
assert_eq!(
only_value(symmetric),
"U1lOVEhFVElDX1JFVk9LRURfSldLX1NZTU1FVFJJQ19LRVk"
);
let rsa = r#"{"kty":"RSA","n":"U1lOVEhFVElDX1BVQkxJQ19NT0RVTFVT","e":"AQAB","d":"U1lOVEhFVElDX1JFVk9LRURfUlNBX0Q","qi":"U1lOVEhFVElDX1JFVk9LRURfUlNBX1FJ"}"#;
let values: Vec<&str> = detect(rsa)
.iter()
.map(|candidate| &rsa[candidate.range().start()..candidate.range().end()])
.collect();
assert_eq!(
values,
[
"U1lOVEhFVElDX1JFVk9LRURfUlNBX0Q",
"U1lOVEhFVElDX1JFVk9LRURfUlNBX1FJ"
]
);
for clean in [
r#"{"k":"U1lOVEhFVElDX1JFVk9LRURfSldLX1NZTU1FVFJJQ19LRVk"}"#,
r#"{"kty":"RSA","n":"U1lOVEhFVElDX1BVQkxJQ19NT0RVTFVT","e":"AQAB"}"#,
"{\"kty\":\"oct\",\n\"k\":\"U1lOVEhFVElDX1JFVk9LRURfSldLX1NZTU1FVFJJQ19LRVk\"}",
r#"{"kty":"oct","k":"placeholder"}"#,
] {
assert!(detect(clean).is_empty(), "{clean}");
}
}
#[test]
fn go_short_assignment_and_objective_c_string_literals_are_detected() {
assert_eq!(
only_value("apikey := \"SYNTHETICq8vN3xR7tLm2Kp9Wd\""),
"SYNTHETICq8vN3xR7tLm2Kp9Wd"
);
assert_eq!(
only_value("password := SYNTHETICq8vN3xR7tLm2Kp9Wd"),
"SYNTHETICq8vN3xR7tLm2Kp9Wd"
);
assert_eq!(
only_value("password = @\"SYNTHETICq8vN3xR7tLm2Kp9Wd\";"),
"SYNTHETICq8vN3xR7tLm2Kp9Wd"
);
assert!(detect("password := os.Getenv(\"DB_PASSWORD\")").is_empty());
}
#[test]
fn a_value_containing_braces_and_brackets_is_literal_material() {
let quoted = "apikey = \"SYN{{t}h)e${t]ic(al[value>-_$#x}}\"";
assert_eq!(only_value(quoted), "SYN{{t}h)e${t]ic(al[value>-_$#x}}");
let unquoted = "apikey = SYN{{t}h)e${t]ic(al[value>-_$#x}}";
assert_eq!(only_value(unquoted), "SYN{{t}h)e${t]ic(al[value>-_$#x}}");
for input in [
"password: Option<String>",
"password: \"Optional[SecretStr]\"",
"token: HashMap<String, Vec<u8>>",
"api_key: settings[API_KEY_NAME]",
"secret: {secretName: web-tls-cert}",
"password: {{ vault_db_password }}",
"password = ${DB_PASSWORD}",
"secret = request.headers[\"apikey\"]",
] {
assert!(detect(input).is_empty(), "{input}");
}
}
#[test]
fn a_masked_value_nested_with_no_separator_inside_an_enclosing_quote_stays_excluded() {
let input = "value=\"password=\"********\"\"\n";
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
#[test]
fn a_template_reference_nested_with_no_separator_inside_an_enclosing_quote_stays_excluded() {
let input = "value=\"password=\"{{ vault_db_password }}\"\"\n";
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
#[test]
fn nested_assignment_with_no_separator_is_detected_across_crlf_and_unicode_prefix() {
for input in [
"value=\"api_key=\"SYNTHETIC_REVOKED_NESTED_QUOTE_CRLF_1234\"\"\r\n",
"note: caf\u{e9} \u{2014} value=\"api_key=\"SYNTHETIC_REVOKED_NESTED_QUOTE_UNICODE_1234\"\"\n",
] {
assert!(
!detect(input).is_empty(),
"expected a finding for {input:?}"
);
}
}
#[test]
fn documented_aws_secret_access_key_name_is_high_signal() {
let input = "AWS_SECRET_ACCESS_KEY=SYNTHETIC_REVOKED_AWS_CONTEXT_VALUE";
let candidates = detect(input);
assert_eq!(only_range(&candidates), (22, 57));
}
#[test]
fn documented_aws_session_token_name_is_high_signal() {
let input = "aws_session_token=SYNTHETIC_REVOKED_AWS_CONTEXT_VALUE";
let candidates = detect(input);
assert_eq!(only_range(&candidates), (18, 53));
}
#[test]
fn db_pass_is_a_high_signal_name_only_as_the_whole_name() {
for input in [
"db_pass: 'SYNTHETIC_REVOKED_DB_PASS_VALUE'",
"DB_PASS=SYNTHETIC_REVOKED_DB_PASS_VALUE",
"dbPass = \"SYNTHETIC_REVOKED_DB_PASS_VALUE\"",
] {
let candidates = detect(input);
assert_eq!(candidates.len(), 1, "{input}");
assert_eq!(candidates[0].confidence(), Confidence::High, "{input}");
}
assert_eq!(detect("db_passwd=SYNTHETIC_REVOKED_DB_PASS_VALUE").len(), 1);
assert_eq!(
detect("db_password=SYNTHETIC_REVOKED_DB_PASS_VALUE").len(),
1
);
}
#[test]
fn fal_and_convex_credential_variables_are_exact_high_signal_names() {
const FAL: &str = "5e7c0ded-feed-4bad-9ace-0ddba11c0de5:5a1ed0ff5e7c0dedfeedbadacef00d42";
const CONVEX: &str = "prod:happy-otter-123|01SYNTHETICrevokedCONVEXdeployKEY0042";
for (input, value) in [
(format!("FAL_KEY={FAL}"), FAL),
(format!("export FAL_KEY=\"{FAL}\""), FAL),
(format!("falKey: '{FAL}'"), FAL),
(format!("{{\"FAL_KEY\": \"{FAL}\"}}"), FAL),
(format!("CONVEX_DEPLOY_KEY={CONVEX}"), CONVEX),
(format!("CONVEX_SELF_HOSTED_ADMIN_KEY={CONVEX}"), CONVEX),
(
format!(" CONVEX_SELF_HOSTED_ADMIN_KEY: \"{CONVEX}\""),
CONVEX,
),
(
"FAL_KEY=SYNTHETICrevokedNEUTRALvalue0042xyzw".to_owned(),
"SYNTHETICrevokedNEUTRALvalue0042xyzw",
),
] {
let candidates = detect(&input);
let (start, end) = only_range(&candidates);
assert_eq!(&input[start..end], value, "{input}");
assert_eq!(candidates[0].type_name(), "contextual_secret");
assert_eq!(candidates[0].confidence(), Confidence::High, "{input}");
}
}
#[test]
fn a_composite_value_with_a_placeholder_or_reference_secret_part_is_excluded() {
for input in [
"CONVEX_DEPLOY_KEY=prod:your-deployment-name|your-admin-key",
"CONVEX_DEPLOY_KEY=prod:adjective-animal-123|super-secret-key",
"CONVEX_DEPLOY_KEY=prod:happy-otter-123|${CONVEX_BODY}",
"CONVEX_SELF_HOSTED_ADMIN_KEY=convex-self-hosted|$ADMIN_KEY",
"CONVEX_SELF_HOSTED_ADMIN_KEY: \"convex-self-hosted|{{ admin_key }}\"",
"CONVEX_DEPLOY_KEY=preview:acme:web|<DEPLOY_KEY_BODY>",
"CONVEX_DEPLOY_KEY=prod:happy-otter-123|xxxxxxxxxxxxxxxxxxxx",
"FAL_KEY=your-fal-key-id:your-fal-key-secret",
"FAL_KEY=${FAL_KEY_ID}:${FAL_KEY_SECRET}",
"Authorization: Key your-fal-key-id:your-fal-key-secret",
] {
assert!(detect(input).is_empty(), "{input}");
}
let hex: String = (0..76)
.map(|i| char::from(b"0123456789abcdef"[(i * 7 + 3) % 16]))
.collect();
for (input, value) in [
(
format!("CONVEX_DEPLOY_KEY=prod:happy-otter-123|01{hex}"),
format!("prod:happy-otter-123|01{hex}"),
),
(
"CONVEX_DEPLOY_KEY=prod:happy-otter-123|eyJ2SyntheticRevokedGatedCloudBody0Aq7Zx9"
.to_owned(),
"prod:happy-otter-123|eyJ2SyntheticRevokedGatedCloudBody0Aq7Zx9".to_owned(),
),
(
"FAL_KEY=your-fal-key-id:5a1ed0ff5e7c0dedfeedbadacef00d42".to_owned(),
"your-fal-key-id:5a1ed0ff5e7c0dedfeedbadacef00d42".to_owned(),
),
(
"FAL_KEY=super-secret-key:Zx81QpVn4Lk7Tr2Wm9Hs6Dc3".to_owned(),
"super-secret-key:Zx81QpVn4Lk7Tr2Wm9Hs6Dc3".to_owned(),
),
(
"password=Zx81QpVn4Lk7Tr2Wm9Hs6Dc3:5432".to_owned(),
"Zx81QpVn4Lk7Tr2Wm9Hs6Dc3:5432".to_owned(),
),
] {
let candidates = detect(&input);
let (start, end) = only_range(&candidates);
assert_eq!(&input[start..end], value, "{input}");
assert_eq!(candidates[0].confidence(), Confidence::High, "{input}");
}
}
#[test]
fn a_bare_key_suffix_stays_outside_the_vocabulary() {
for input in [
"PRIMARY_KEY=SYNTHETICrevokedNEUTRALvalue0042xyzw",
"SORT_KEY=SYNTHETICrevokedNEUTRALvalue0042xyzw",
"CACHE_KEY=SYNTHETICrevokedNEUTRALvalue0042xyzw",
"PARTITION_KEY=SYNTHETICrevokedNEUTRALvalue0042xyzw",
"IDEMPOTENCY_KEY=SYNTHETICrevokedNEUTRALvalue0042xyzw",
"CONVEX_KEY=SYNTHETICrevokedNEUTRALvalue0042xyzw",
"MY_FAL_KEY=SYNTHETICrevokedNEUTRALvalue0042xyzw",
"FAL_KEY_ID=5e7c0ded-feed-4bad-9ace-0ddba11c0de5",
"CONVEX_DEPLOYMENT=dev:happy-otter-123",
"FAL_KEY=${FAL_KEY}",
"FAL_KEY=your_fal_key",
] {
assert!(detect(input).is_empty(), "{input}");
}
}
#[test]
fn the_key_authorization_scheme_is_detected_whole() {
const FAL: &str = "5e7c0ded-feed-4bad-9ace-0ddba11c0de5:5a1ed0ff5e7c0dedfeedbadacef00d42";
for input in [
format!("Authorization: Key {FAL}"),
format!("authorization: key {FAL}\r\n"),
format!("curl -H \"Authorization: Key {FAL}\" https://example.invalid/run"),
format!("{{\"headers\":{{\"Authorization\":\"Key {FAL}\"}}}}"),
format!("Proxy-Authorization: Key {FAL}"),
format!("Authorization: Key {FAL}: sent"),
] {
let candidates: Vec<Candidate> = detect(&input)
.into_iter()
.filter(|candidate| candidate.type_name() == "authorization_credential")
.collect();
let (start, end) = only_range(&candidates);
assert_eq!(&input[start..end], FAL, "{input}");
assert_eq!(candidates[0].confidence(), Confidence::High, "{input}");
assert!(
candidates[0]
.signals()
.iter()
.any(|signal| signal == "authorization-key-scheme")
);
}
}
#[test]
fn key_as_prose_or_a_short_value_is_not_an_authorization_scheme() {
for input in [
"The Key to authorization is a signed request.",
"Authorization: Key rotation",
"authorization: keyring SYNTHETICrevokedNEUTRALvalue0042xyzw",
"Authorization: Key $FAL_KEY",
"Authorization: Key ${FAL_KEY}",
"X-Authorization: Key 5e7c0ded-feed-4bad-9ace-0ddba11c0de5:5a1ed0ff",
"notAuthorization: Key 5e7c0ded-feed-4bad-9ace-0ddba11c0de5:5a1ed0ff",
] {
assert!(
detect(input)
.iter()
.all(|candidate| candidate.type_name() != "authorization_credential"),
"{input}"
);
}
}
fn random_literal() -> String {
(0..32)
.map(|i| char::from(b"aZ3kQ9xL2mV7pR4tW8nB5cD1fG6hJ0sY"[(i * 11 + 3) % 32]))
.collect()
}
#[test]
fn existing_secret_names_an_object_not_a_secret() {
for input in [
"auth:\n existingSecret: postgres-credentials\n",
" existingSecret: app-db-credentials-v2\n",
"redisAuthExistingSecret: redis-auth-prod\n",
"existingSecretName: postgres-credentials\n",
"secretName: tls-cert-prod\n",
] {
assert!(detect(input).is_empty(), "{input}");
}
let literal = random_literal();
for input in [
format!("webhookSecret: {literal}\n"),
format!("clientSecret: {literal}\n"),
format!("secret: {literal}\n"),
] {
assert_eq!(detect(&input).len(), 1, "{input}");
}
}
#[test]
fn an_unquoted_credential_variable_name_is_a_reference() {
for input in [
" verify(payload, signing_secret=FAKE_SIGNING_SECRET)",
"- secretKey: DB_PASSWORD\n",
" secretKey: STRIPE_WEBHOOK_SECRET\n",
"client = Client(api_key=OPENAI_API_KEY)",
"password=ADMIN_PASSWORD",
] {
assert!(detect(input).is_empty(), "{input}");
}
let literal = random_literal();
for input in [
format!(" verify(payload, signing_secret={literal})"),
format!("- secretKey: {literal}\n"),
"password=\"ADMIN_PASSWORD_2f9QxL7m\"".to_owned(),
"API_KEY=YOUR_ACMECLOUD_API_KEY".to_owned(),
"password=SYNTHETIC_REVOKED_DB_PASS_VALUE".to_owned(),
"password=Admin_Password".to_owned(),
] {
assert!(!detect(&input).is_empty(), "{input}");
}
}
#[test]
fn a_reverse_dns_identifier_is_a_reference() {
for input in [
"case accessToken = \"com.example.app.accessToken\"",
"case clientSecret = \"com.example.app.clientSecret\"",
"userPassword = \"io.example.keychain.user-password\"",
"static let refreshToken = \"dev.example.auth.refresh_token\"",
] {
assert!(detect(input).is_empty(), "{input}");
}
let literal = random_literal();
for input in [
format!("case accessToken = \"{literal}\""),
"accessToken = \"eyJhbGciOi.eyJzdWIiOi.SflKxwRJSMeKKF2QT4\"".to_owned(),
"accessToken = \"com.Zx81QpVn4Lk7Tr2Wm9\"".to_owned(),
"accessToken = \"xq.Zx81QpVn4Lk7.Tr2Wm9Hs6Dc3\"".to_owned(),
] {
assert!(!detect(&input).is_empty(), "{input}");
}
}
#[test]
fn a_lua_or_path_method_call_is_a_source_code_expression() {
for input in [
"local secret = secrets:get(partner)",
"local token = vault:read(\"app/token\")",
"let password = vault::read(path);",
] {
assert!(detect(input).is_empty(), "{input}");
}
let literal = random_literal();
for input in [
format!("local secret = user:{literal}"),
format!("secret = {literal}"),
] {
assert!(!detect(&input).is_empty(), "{input}");
}
}
#[test]
fn a_secret_path_term_inside_a_template_lookup_is_a_reference() {
for input in [
"vault_token: \"{{ lookup('community.hashi_vault.hashi_vault', 'secret=kv/data/app:token') }}\"",
"db_password: \"{{ lookup('hashi_vault', 'secret=secret/data/db:password url=https://vault.example.invalid') }}\"",
"api_key: \"{{ lookup('hashi_vault', 'secret=kv/app') }}\"",
] {
assert!(detect(input).is_empty(), "{input}");
}
let literal = random_literal();
for input in [
format!("vault: \"{{{{ lookup('hashi_vault', 'secret={literal}') }}}}\""),
format!("secret=kv/data/{literal}"),
format!("{{{{ x }}}} secret=kv/data/{literal}"),
] {
assert!(!detect(&input).is_empty(), "{input}");
}
}
#[test]
fn pass_is_not_a_name_token() {
for input in [
"pass=SYNTHETIC_REVOKED_DB_PASS_VALUE",
"render_pass = \"SYNTHETIC_REVOKED_DB_PASS_VALUE\"",
"first_pass: SYNTHETIC_REVOKED_DB_PASS_VALUE",
"second_pass=SYNTHETIC_REVOKED_DB_PASS_VALUE",
"shadowPass = 'SYNTHETIC_REVOKED_DB_PASS_VALUE'",
"app_db_pass=SYNTHETIC_REVOKED_DB_PASS_VALUE",
] {
assert!(detect(input).is_empty(), "{input}");
}
}
#[test]
fn generic_token_name_is_an_explicit_exclusion() {
assert!(detect("token=SYNTHETIC_REVOKED_CONTEXT_VALUE").is_empty());
}
#[test]
fn value_below_the_minimum_length_is_ignored() {
assert!(detect("api_key=abcdefg").is_empty());
}
#[test]
fn value_above_the_detector_bound_is_ignored_deterministically() {
let input = format!("api_key={}", "A".repeat(100_008));
assert!(detect(&input).is_empty());
}
#[test]
fn common_high_entropy_or_identifier_like_values_stay_unchanged() {
for input in [
"sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
"checksum=9e107d9d372bb6826bd81d3542a419d6",
"550e8400-e29b-41d4-a716-446655440000",
"01ARZ3NDEKTSV4RRFFQ69G5FAV",
"request_01_SYNTHETIC_GENERATED_IDENTIFIER_987654321",
"styles.module.css?hash=7f3a9c2d1e",
"//# sourceMappingURL=app.7f3a9c2d1e.js.map",
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB",
"header.payload.signature",
"sha512-SYNTHETICPACKAGEINTEGRITYBASE64VALUE==",
"model=gpt-5.6-codex-2026-08-31",
] {
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
}
fn synthetic_sid(prefix: &str, body_half: &str) -> String {
format!("{prefix}{body_half}{body_half}")
}
#[test]
fn twilio_account_and_api_key_sids_are_public_identifiers() {
let api_key_sid = synthetic_sid("SK", "0123456789abcdef");
let account_sid = "AC0123456789abcdef0123456789abcde0";
for input in [
format!("twilio credentials: {api_key_sid} {account_sid}"),
format!("credentials: {account_sid}"),
format!("credentials: {api_key_sid}"),
format!("api_key={api_key_sid}"),
format!("secret: \"{account_sid}\""),
] {
assert!(detect(&input).is_empty(), "{input}");
}
}
#[test]
fn values_near_a_twilio_sid_shape_stay_detected() {
let full = synthetic_sid("SK", "0123456789abcdef");
for value in [
synthetic_sid("SK", "0123456789ABCDEF"),
"AC0123456789ABCDEF0123456789ABCDEF".to_owned(),
full[..full.len() - 1].to_owned(),
format!("{full}0"),
synthetic_sid("XK", "0123456789abcdef"),
] {
let input = format!("credentials: {value}");
assert_eq!(only_range(&detect(&input)), (13, input.len()), "{input}");
}
}
#[test]
fn instructional_placeholders_in_key_assignments_are_excluded() {
for input in [
"mailchimp.setConfig({ apiKey: \"YOUR_API_KEY\", server: \"us19\" });",
"apiKey: \"YOUR_API_KEY\"",
"const apiKey = \"YOUR_API_KEY\";",
"api_key = \"YOUR_API_KEY\"",
"API_KEY=YOUR_API_KEY",
"apiKey: \"your_api_key\"",
"apiKey: \"YOUR_KEY\"",
"client_secret: 'YOUR_CLIENT_SECRET'",
"access_token=YOUR_ACCESS_TOKEN",
"API_KEY=your-api-key-here",
"SECRET_KEY=INSERT_SECRET_KEY_HERE",
"api_key: ENTER_YOUR_API_KEY",
"Authorization: Token YOUR_API_TOKEN",
] {
assert!(detect(input).is_empty(), "{input}");
}
}
#[test]
fn real_values_in_placeholder_style_assignments_stay_detected() {
for (prefix, value, suffix) in [
("apiKey: \"", "YOUR_API_KEY_9f2cQ7xLm4Rt", "\""),
("apiKey: \"", "YOUR_API_KEY9f2cQ7xLm4Rt", "\""),
("API_KEY=", "YOUR_ACMECLOUD_API_KEY", ""),
("API_KEY=", "KEY_YOUR_API_KEY", ""),
(
"mailchimp.setConfig({ apiKey: \"",
"q7Lm2Xv9Rt4Kp8Wz3Nc6Bh1Jd5Fs0GyTa",
"\", server: \"us19\" });",
),
(
"const apiKey = \"",
"Zx81QpVn4Lk7Tr2Wm9Hs6Dc3Jf0Gb5Ye8Ua1Io4",
"\";",
),
] {
let input = format!("{prefix}{value}{suffix}");
let start = prefix.len();
assert_eq!(
only_range(&detect(&input)),
(start, start + value.len()),
"{input}"
);
}
}
#[test]
fn a_bounded_entropy_value_never_overrides_an_unrecognized_name() {
for input in [
"id=SYNTHETIC_UNQUALIFIED_HIGH_ENTROPY_VALUE",
"note=SYNTHETIC_REVOKED_CONTEXT_VALUE",
"Reminder: SYNTHETIC_REVOKED_CONTEXT_VALUE was already rotated last week.",
] {
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn additional_placeholder_words_are_excluded_at_the_minimum_length() {
for input in ["webhook_secret=redacted", "client_secret=replaceme"] {
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn masked_values_are_excluded_as_repeated_character_filler() {
for input in [
"Password: ********",
"Password: \u{2022}\u{2022}\u{2022}\u{2022}\u{2022}\u{2022}\u{2022}\u{2022}",
] {
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn a_near_miss_of_repeated_character_filler_is_still_detected() {
assert!(!detect("Password: ********x").is_empty());
}
#[test]
fn a_leading_separator_inside_the_value_does_not_defeat_the_exclusion() {
assert!(detect("secret=\" changeme\"").is_empty());
}
#[test]
fn an_appended_digit_does_not_defeat_the_exclusion() {
assert!(detect("secret_key=\"changeme2\"").is_empty());
}
#[test]
fn hyphenating_two_listed_words_does_not_defeat_the_exclusion() {
assert!(detect("secret_key: \"REDACTED-EXAMPLE\"").is_empty());
}
#[test]
fn a_placeholder_word_embedded_in_a_larger_high_entropy_value_is_still_detected() {
let input = "api_key=SecretSyntheticRevokedContextValue9fQ";
assert!(
!detect(input).is_empty(),
"expected a finding for {input:?}"
);
}
#[test]
fn a_listed_word_followed_by_unrelated_tokens_is_still_detected() {
assert!(!detect("client_secret=password_over_there").is_empty());
}
#[test]
fn documented_aws_names_retain_classification_with_a_colon_separator_and_quoting() {
let input = "AWS_SECRET_ACCESS_KEY: \"SYNTHETIC_REVOKED_AWS_CONTEXT_VALUE\"";
let candidates = detect(input);
assert_eq!(only_range(&candidates), (24, 59));
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].specificity(), Some(Specificity::Contextual));
}
#[test]
fn basic_and_token_authorization_schemes_are_detected() {
let basic_input = "Authorization: Basic U1lOVEhFVElDX1JFVk9LRUQ=";
let basic = detect(basic_input);
let (start, end) = only_range(&basic);
assert_eq!(&basic_input[start..end], "U1lOVEhFVElDX1JFVk9LRUQ=");
assert_eq!(basic[0].type_name(), "authorization_credential");
assert_eq!(basic[0].confidence(), Confidence::High);
assert_eq!(basic[0].specificity(), Some(Specificity::Structural));
let token_input = "Authorization: Token SYNTHETIC_REVOKED_TOKEN_VALUE_1234";
let token = detect(token_input);
let (start, end) = only_range(&token);
assert_eq!(
&token_input[start..end],
"SYNTHETIC_REVOKED_TOKEN_VALUE_1234"
);
assert_eq!(token[0].type_name(), "authorization_credential");
assert_eq!(token[0].confidence(), Confidence::High);
assert_eq!(token[0].specificity(), Some(Specificity::Structural));
}
#[test]
fn token_authorization_and_nested_assignment_emit_overlapping_candidates() {
let input = "Authorization: Token api_key=SYNTHETIC_REVOKED_AUTHORIZATION_OVERLAP_1234";
let candidates = detect(input);
assert_eq!(candidates.len(), 2);
assert_eq!(candidates[0].type_name(), "contextual_secret");
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].specificity(), Some(Specificity::Contextual));
assert_eq!(candidates[0].range(), ByteRange::new(29, 73).unwrap());
assert_eq!(candidates[1].type_name(), "authorization_credential");
assert_eq!(candidates[1].confidence(), Confidence::High);
assert_eq!(candidates[1].specificity(), Some(Specificity::Structural));
assert_eq!(candidates[1].range(), ByteRange::new(21, 73).unwrap());
assert!(candidates[0].range().overlaps(candidates[1].range()));
}
#[test]
fn authorization_value_at_the_minimum_accepted_length_is_medium_confidence() {
let input = "Authorization: Token TOKENVALUE12";
let candidates = detect(input);
let (start, end) = only_range(&candidates);
assert_eq!(&input[start..end], "TOKENVALUE12");
assert_eq!(candidates[0].type_name(), "authorization_credential");
assert_eq!(candidates[0].confidence(), Confidence::Medium);
assert_eq!(candidates[0].specificity(), Some(Specificity::Structural));
}
#[test]
fn authorization_value_below_the_minimum_accepted_length_is_ignored() {
assert!(detect("Authorization: Basic short-value").is_empty());
}
#[test]
fn authorization_scheme_other_than_basic_or_token_is_ignored() {
assert!(detect("Authorization: Digest SYNTHETIC_REVOKED_DIGEST_VALUE_1234").is_empty());
}
#[test]
fn proxy_authorization_and_mid_line_basic_headers_are_detected() {
const BASIC: &str = "U1lOVEhFVElDOmZpeHR1cmU=";
for input in [
format!("Proxy-Authorization: Basic {BASIC}"),
format!("curl -H 'Authorization: Basic {BASIC}' https://api.example.test"),
format!("{{\"headers\":{{\"authorization\":\"Basic {BASIC}\"}}}}"),
format!("[req] authorization: basic {BASIC}"),
] {
let candidates: Vec<Candidate> = detect(&input)
.into_iter()
.filter(|candidate| candidate.type_name() == "authorization_credential")
.collect();
let (start, end) = only_range(&candidates);
assert_eq!(&input[start..end], BASIC, "{input}");
}
for input in [
format!("notAuthorization: Basic {BASIC}"),
format!("X-Authorization: Basic {BASIC}"),
format!("reverse_proxy-authorization: Basic {BASIC}"),
format!("curl -H \"Authorization: token {BASIC}\""),
] {
assert!(
detect(&input)
.iter()
.all(|candidate| candidate.type_name() != "authorization_credential"),
"{input}"
);
}
}
#[test]
fn a_quoted_jinja_template_reference_is_excluded() {
for input in [
"password: \"{{ vault_db_password }}\"",
"password: \"{{ lookup('env', 'DB_PASSWORD') }}\"",
"password: '{{ pillar[\"postgres\"][\"password\"] }}'",
"\"password\": \"{{ vault_db_password }}\"",
] {
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn a_quoted_helm_or_go_template_reference_is_excluded() {
for input in [
"password: \"{{ .Values.postgresql.auth.password }}\"",
"client_secret: \"{{ .ClientSecretRef }}\"",
] {
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn a_value_only_starting_with_a_template_delimiter_is_still_detected() {
let input = "password=\"{{ SYNTHETIC_REVOKED_CONTEXT_VALUE\"";
assert!(
!detect(input).is_empty(),
"expected a finding for {input:?}"
);
}
#[test]
fn a_template_delimiter_pair_embedded_in_a_larger_value_is_still_detected() {
let input = "password=SYNTHETIC_REVOKED_{{ x }}_CONTEXT_VALUE";
assert!(
!detect(input).is_empty(),
"expected a finding for {input:?}"
);
}
#[test]
fn interpolation_and_command_substitution_references_are_excluded() {
for input in [
"password: $(registryPassword)",
"PASSWORD=\"$(pass show db/prod)\"",
"password: \"#{ENV['DB_PASSWORD']}\"",
"\"apiKey\": \"{env:ANTHROPIC_API_KEY}\"",
"\"apiKey\": \"{file:./secrets/api-key}\"",
"password: $[variables.x]",
"password: `${process.env.X}`",
"password=`date +%s`",
"password=$(echo $(date))",
] {
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn a_value_only_starting_with_an_interpolation_delimiter_is_still_detected() {
for input in [
"password=$(SYNTHETIC_REVOKED_CONTEXT_VALUE",
"password=$[SYNTHETIC_REVOKED_CONTEXT_VALUE",
"password=\"#{SYNTHETIC_REVOKED_CONTEXT_VALUE\"",
"password=\"{env:SYNTHETIC_REVOKED_CONTEXT_VALUE\"",
"password=`SYNTHETIC_REVOKED_CONTEXT_VALUE",
] {
assert!(
!detect(input).is_empty(),
"expected a finding for {input:?}"
);
}
}
#[test]
fn an_interpolation_delimiter_pair_embedded_in_a_larger_value_is_still_detected() {
for input in [
"password=SYNTHETIC_REVOKED_$(x)_CONTEXT_VALUE",
"password=SYNTHETIC_REVOKED_#{x}_CONTEXT_VALUE",
"password=SYNTHETIC_REVOKED_`x`_CONTEXT_VALUE",
"password={env:ANTHROPIC_API_KEY}_SYNTHETIC_REVOKED_CONTEXT_VALUE",
"password={file:SYNTHETIC_REVOKED_PATH}_CONTEXT_VALUE",
] {
assert!(
!detect(input).is_empty(),
"expected a finding for {input:?}"
);
}
}
#[test]
fn interpolation_references_are_excluded_across_crlf_tab_operator_and_json_escaping() {
for input in [
"password: $(registryPassword)\r\n",
"password:\t$(registryPassword)",
"{\"password\": \"#{ENV[\\\"DB_PASSWORD\\\"]}\"}",
] {
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn windows_env_and_sql_bind_parameter_references_are_excluded() {
for input in [
"PASSWORD=%DB_PASSWORD%",
"PASSWORD=\"%DB_PASSWORD%\"",
"password = :new_password_hash",
"password: ':new_password_hash'",
] {
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn a_windows_env_reference_missing_either_delimiter_is_still_detected() {
for input in [
"PASSWORD=%DB_PASSWORD_SYNTHETIC_REVOKED",
"PASSWORD=DB_PASSWORD_SYNTHETIC_REVOKED%",
] {
assert!(
!detect(input).is_empty(),
"expected a finding for {input:?}"
);
}
}
#[test]
fn a_windows_env_reference_pair_embedded_in_a_larger_value_is_still_detected() {
assert!(
!detect("PASSWORD=SYNTHETIC_%DB_PASSWORD%_REVOKED_CONTEXT_VALUE").is_empty(),
"expected a finding for an embedded %VAR% pair"
);
}
#[test]
fn a_windows_env_reference_whose_content_is_not_an_identifier_is_still_detected() {
assert!(
!detect("PASSWORD=\"%not an identifier%\"").is_empty(),
"expected a finding when the %...% content is not identifier-shaped"
);
}
#[test]
fn a_sql_bind_parameter_missing_its_colon_is_still_detected() {
assert!(
!detect("password = new_password_hash_SYNTHETIC_REVOKED").is_empty(),
"expected a finding for a bare identifier with no leading colon"
);
}
#[test]
fn a_sql_bind_parameter_embedded_in_a_larger_value_is_still_detected() {
assert!(
!detect("password=SYNTHETIC_:new_password_hash_REVOKED_CONTEXT_VALUE").is_empty(),
"expected a finding for an embedded :identifier pair"
);
}
#[test]
fn windows_env_and_sql_bind_parameter_references_are_excluded_across_crlf_and_unicode_prefix() {
for input in [
"PASSWORD=%DB_PASSWORD%\r\n",
"PASSWORD=\t%DB_PASSWORD%",
"note: caf\u{e9} \u{2014} PASSWORD=%DB_PASSWORD%",
"note: caf\u{e9} \u{2014} password = :new_password_hash",
] {
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn secret_manager_references_are_excluded() {
for input in [
"PASSWORD=op://Engineering/db-prod/password",
"api_key: os.environ/ANTHROPIC_API_KEY",
"secret: projects/example-project/secrets/api-key/versions/latest",
"secret: projects/example-project/secrets/api-key",
"secret: projects/123456789012/secrets/api-key",
"password=ref+vault://secret/data/db-prod#/password",
"password=vault:secret/data/db-prod#password",
"secret=arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/db/password-Ab12Cd",
"password=@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/abc123)",
"password=\"@Microsoft.KeyVault(VaultName=myvault;SecretName=mysecret;SecretVersion=abc123)\"",
] {
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn a_secret_manager_scheme_prefix_that_does_not_satisfy_its_grammar_is_still_detected() {
for input in [
"password=op://SYNTHETIC_REVOKED_NO_SLASH_CONTEXT_VALUE",
"api_key=os.environ/SYNTHETIC-REVOKED-CONTEXT-VALUE!!!",
"secret: projects/SYNTHETIC_REVOKED_MISSING_SECRETS_SEGMENT_CONTEXT_VALUE",
"password=ref+SYNTHETIC_REVOKED_NO_SCHEME_DELIMITER_CONTEXT_VALUE",
"password=vault:SYNTHETIC_REVOKED_NO_FRAGMENT_CONTEXT_VALUE",
"secret=arn:aws:secretsmanager:us-east-1:SYNTHETIC_REVOKED_NOT_TWELVE_DIGITS:secret:name",
"password=@Microsoft.KeyVault(SYNTHETIC_REVOKED_CONTEXT_VALUE)",
] {
assert!(
!detect(input).is_empty(),
"expected a finding for {input:?}"
);
}
}
#[test]
fn azure_keyvault_secreturi_is_excluded_for_any_well_formed_https_host() {
for input in [
"password: @Microsoft.KeyVault(SecretUri=https://example.invalid/secrets/benchmark)",
"password=@Microsoft.KeyVault(SecretUri=https://myvault.vault.usgovcloudapi.net/secrets/mysecret)",
"password=@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.cn/secrets/mysecret/abc123)",
] {
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn azure_keyvault_secreturi_with_a_malformed_host_is_still_detected() {
for input in [
"password=@Microsoft.KeyVault(SecretUri=https://localhost/secrets/SYNTHETIC_REVOKED)",
"password=@Microsoft.KeyVault(SecretUri=https:///secrets/SYNTHETIC_REVOKED)",
"password=@Microsoft.KeyVault(SecretUri=https://my_vault.vault.azure.net/secrets/SYNTHETIC_REVOKED)",
] {
assert!(
!detect(input).is_empty(),
"expected a finding for {input:?}"
);
}
}
#[test]
fn azure_keyvault_reference_is_excluded_across_crlf_and_unicode_prefix() {
for input in [
"password: @Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret)\r\n",
"password: @Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret)\n",
"note: caf\u{e9} \u{2014} password=\"@Microsoft.KeyVault(VaultName=myvault;SecretName=mysecret)\"",
] {
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn a_known_reference_root_member_access_is_excluded() {
for input in [
"password=settings.DATABASE_PASSWORD",
" apiKey: config.anthropicApiKey,",
"this.configService.get(user.id)",
"cfg.RedisPassword",
] {
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn a_snake_case_attribute_reference_chain_is_excluded() {
for input in [
"password = random_password.db.result",
"password=data.aws_secretsmanager_secret_version.db.secret_string",
] {
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn a_generic_type_or_subscript_value_is_excluded() {
for input in ["pub api_key: Option<String>,", "api_key: Optional[str]"] {
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn a_call_or_subscript_truncated_at_a_string_literal_is_excluded() {
let input = "api_key=os.environ[\"OPENAI_API_KEY\"],";
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
#[test]
fn a_dotted_value_with_no_underscore_and_no_known_root_is_still_detected() {
let input = "password: SYNTHETIC.REVOKED.CONTEXT_VALUE";
assert!(
!detect(input).is_empty(),
"expected a finding for {input:?}"
);
}
#[test]
fn an_underscore_separated_value_with_no_dot_is_still_detected_at_high_confidence() {
let input = "password: SYNTHETIC_REVOKED_CONTEXT_VALUE";
let candidates = detect(input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::High);
}
#[test]
fn a_closed_call_expression_is_excluded() {
for input in [
"secret = SecretManagerServiceClient.access_secret_version(req)",
"secret = getSecretOrThrow(SECRET_NAME_CONSTANT)",
"secret = django.core.signing.get_cookie_signer(salt=SALT)",
"api_key = rsa.generate_private_key(public_exponent=65537)",
] {
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn a_call_expression_cut_short_inside_its_arguments_is_excluded() {
for input in [
"secret = crypto.createPrivateKey({ key: pem })",
"secret = helper(FIRST_ARGUMENT, SECOND_ARGUMENT)",
] {
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn redaction_of_a_truncated_call_expression_strands_nothing() {
let input = "secret = crypto.createPrivateKey({ key: pem })";
assert!(
detect(input).is_empty(),
"a partially matched call expression would strand the rest of its argument group",
);
}
#[test]
fn a_value_that_merely_embeds_parentheses_is_still_detected() {
let input = "password: SYNTHETIC(REVOKED)_CONTEXT_VALUE";
let candidates = detect(input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::High);
}
#[test]
fn a_quoted_value_with_an_unbalanced_parenthesis_is_still_detected() {
let input = "password: \"SYNTHETIC(REVOKED_CONTEXT_VALUE\"";
let candidates = detect(input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::High);
}
#[test]
fn a_bracket_group_opened_by_a_non_identifier_is_not_truncated_code() {
for input in [
"password=$(SYNTHETIC_REVOKED_CONTEXT_VALUE",
"password=SYNTHETIC_REVOKED_{{ x }}_CONTEXT_VALUE",
"password=SYNTHETIC_REVOKED_#{x}_CONTEXT_VALUE",
] {
assert!(
!detect(input).is_empty(),
"expected a finding for {input:?}"
);
}
}
#[test]
fn operator_with_no_value_before_end_of_line_does_not_cross_into_the_next_line() {
for input in [
"secret:\n secretName: web-tls-cert",
"Password:\nPermission denied, please try again.",
"fixture@db.example.test's password:\nfixture@db.example.test: Permission denied (publickey,password).",
] {
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
}
#[test]
fn password_value_on_the_same_line_is_still_detected() {
let input = "password: SYNTHETIC_REVOKED_CONTEXT_VALUE";
let candidates = detect(input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].specificity(), Some(Specificity::Contextual));
}
#[test]
fn a_nested_credential_under_an_unrelated_parent_key_is_still_detected() {
let input = "database:\n password: SYNTHETIC_REVOKED_FIXTURE_VALUE";
let candidates = detect(input);
let (start, end) = only_range(&candidates);
assert_eq!(&input[start..end], "SYNTHETIC_REVOKED_FIXTURE_VALUE");
assert_eq!(candidates[0].confidence(), Confidence::High);
}
#[test]
fn a_yaml_flow_mapping_key_is_not_captured_as_the_assignment_value() {
let input = "volumes: [{name: tls, secret: {secretName: web-tls-cert}}]";
assert!(
detect(input).is_empty(),
"expected no findings for {input:?}"
);
}
#[test]
fn a_block_style_secret_value_is_still_detected() {
let input = "secret: SYNTHETIC_REVOKED_CONTEXT_VALUE";
let candidates = detect(input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].specificity(), Some(Specificity::Contextual));
}
#[test]
fn open_contextual_assignment_hint_recognizes_a_pending_high_signal_or_ambiguous_name() {
for open in [
"api_key",
"api_key=",
"api_key: ",
"\"api_key\"=",
"'api_key' = ",
"{api_key=",
"Client(api_key=",
"line one\napi_key:",
"AWS_SECRET_ACCESS_KEY=",
"auth",
"credential:",
"`password\n",
"x\"password\"\n",
"x'secret'\n \n",
"{\\\"password\\\"\n",
"{\"kty\":\"oct\",\"k\"\n",
"{\"kty\":\"RSA\",\"qi\"\r\n",
"{\"kty\":\"oct\",\"k\":",
] {
assert!(has_open_contextual_assignment(open), "{open:?}");
}
}
#[test]
fn open_jwk_member_hint_reads_only_the_members_own_line() {
for closed in [
"{\"k\"\n",
"{\"kty\":\"oct\"}\n{\"k\"\n",
"{\"kty\":\"oct\"}\r{\"k\"\n",
"{\"kty\":\"oct\",k\n",
"{\"kty\":\"RSA\",\"n\"\n",
] {
assert!(!has_open_contextual_assignment(closed), "{closed:?}");
}
}
#[test]
fn open_contextual_assignment_hint_rejects_resolved_or_low_signal_text() {
for closed in [
"",
"token=",
"xapi_key=",
"api_key=SYNTHETIC_REVOKED_CONTEXT_VALUE",
"plain text",
] {
assert!(!has_open_contextual_assignment(closed), "{closed:?}");
}
}
#[test]
fn a_ruleset_supplied_ambiguous_name_is_medium_confidence_at_the_ambiguous_threshold() {
let input = "corp_passphrase=SYNTHETIC_REVOKED_RULESET_AMBIGUOUS_1234";
let candidates = detect_with_ruleset_names(input, &["corp_passphrase"]);
assert_eq!(only_range(&candidates), (16, input.len()));
assert_eq!(candidates[0].confidence(), Confidence::Medium);
assert_eq!(candidates[0].specificity(), Some(Specificity::Contextual));
}
#[test]
fn a_ruleset_supplied_name_never_reaches_high_confidence_regardless_of_entropy() {
let input = "corp_passphrase=SYNTHETIC_REVOKED_CONTEXT_VALUE";
let candidates = detect_with_ruleset_names(input, &["corp_passphrase"]);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::Medium);
}
#[test]
fn a_ruleset_supplied_name_below_the_ambiguous_entropy_threshold_is_ignored() {
let input = "corp_passphrase=aaaaaaaaaaaaaaaaaaaa";
let candidates = detect_with_ruleset_names(input, &["corp_passphrase"]);
assert!(candidates.is_empty());
}
#[test]
fn an_unlisted_name_produces_no_ruleset_candidate() {
let input = "unrelated_field=SYNTHETIC_REVOKED_RULESET_AMBIGUOUS_1234";
let candidates = detect_with_ruleset_names(input, &["corp_passphrase"]);
assert!(candidates.is_empty());
}
#[test]
fn the_ruleset_names_detector_never_matches_a_built_in_high_signal_name() {
let input = "api_key=SYNTHETIC_REVOKED_CONTEXT_VALUE";
let candidates = detect_with_ruleset_names(input, &["corp_passphrase"]);
assert!(candidates.is_empty());
}
#[test]
fn the_ruleset_names_detector_does_not_match_authorization_schemes() {
let input = "Authorization: Basic aGVsbG86d29ybGQtc3ludGhldGljLXJldm9rZWQ=";
let candidates = detect_with_ruleset_names(input, &["corp_passphrase"]);
assert!(candidates.is_empty());
}
#[test]
fn the_ruleset_names_detector_claims_the_fixed_reserved_id() {
let detector = generic_token_ruleset_names_detector(vec!["corp_passphrase".to_owned()]);
assert_eq!(detector.id(), RULESET_NAMES_DETECTOR_ID);
}
#[test]
fn is_reserved_name_covers_both_built_in_buckets() {
for name in HIGH_SIGNAL_NAMES.iter().chain(AMBIGUOUS_NAMES.iter()) {
assert!(is_reserved_name(name), "{name}");
}
assert!(!is_reserved_name("corp_passphrase"));
}
#[test]
fn auth_token_is_a_high_signal_name_and_its_neighbours_are_unchanged() {
for name in ["auth_token", "authToken", "AUTH_TOKEN", "app_auth_token"] {
assert!(is_high_signal_name(&normalize_name(name)), "{name}");
assert!(!is_ambiguous_name(&normalize_name(name)), "{name}");
}
assert!(is_high_signal_name("oauth_token"));
assert!(is_ambiguous_name("auth"));
assert!(!is_high_signal_name("auth"));
assert!(!is_high_signal_name("csrf_token"));
}
#[test]
fn an_auth_token_literal_is_high_and_placeholders_stay_silent() {
let value = "Rk7vQ2mX9pL4tW8nB5cD1fG6hJ3sY0aZ";
let input = format!("auth_token={value}");
let candidates = detect(&input);
assert_eq!(candidates.len(), 1, "{candidates:?}");
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(
&input[candidates[0].range().start()..candidates[0].range().end()],
value
);
for silent in [
"auth_token=your_auth_token",
"auth_token=<AUTH_TOKEN>",
"auth_token=${AUTH_TOKEN}",
"auth_token=TWILIO_AUTH_TOKEN",
"auth_token: {{ auth_token }}",
"auth_token=xxxxxxxxxxxxxxxxxxxxxxxx",
] {
assert!(detect(silent).is_empty(), "{silent}");
}
}
const VENDOR_PREFIX_LEGACY_BODY: &str = "SYNTHETICrevoked0001aaaaBBBBccccDDDD1234wxyzEFGH";
const VENDOR_PREFIX_PROJ_BODY: &str = "SYNTHETICrevoked0002bbbbCCCCddddEEEE5678uvwxIJKL";
#[test]
fn a_bare_sk_legacy_value_is_a_medium_confidence_entropy_specificity_candidate() {
let input = format!("sk-{VENDOR_PREFIX_LEGACY_BODY}");
let candidates = detect(&input);
assert_eq!(only_range(&candidates), (0, input.len()));
assert_eq!(candidates[0].type_name(), "vendor_prefixed_credential");
assert_eq!(candidates[0].confidence(), Confidence::Medium);
assert_eq!(candidates[0].specificity(), Some(Specificity::Entropy));
}
#[test]
fn every_documented_namespace_is_detected_independently() {
for prefix in ["sk-", "sk-proj-", "sk-svcacct-", "sk-admin-"] {
let input = format!("{prefix}{VENDOR_PREFIX_LEGACY_BODY}");
let candidates = detect(&input);
assert_eq!(only_range(&candidates), (0, input.len()), "{prefix}");
assert_eq!(
candidates[0].type_name(),
"vendor_prefixed_credential",
"{prefix}"
);
}
}
#[test]
fn a_low_entropy_bare_vendor_prefixed_body_is_not_detected() {
let input = format!("sk-{}", "A".repeat(48));
assert!(detect(&input).is_empty());
}
#[test]
fn a_bare_vendor_prefixed_body_one_byte_short_is_not_detected() {
let short_body = &VENDOR_PREFIX_LEGACY_BODY[..47];
let input = format!("sk-{short_body} end");
assert!(detect(&input).is_empty());
}
#[test]
fn a_bare_vendor_prefixed_value_embedded_in_a_wider_identifier_is_not_detected() {
let input = format!("sk-{VENDOR_PREFIX_LEGACY_BODY}9");
assert!(detect(&input).is_empty());
}
#[test]
fn anthropic_and_openrouter_lookalike_prefixes_are_not_claimed() {
for prefix in ["sk-ant-", "sk-or-v1-"] {
let input = format!("{prefix}{}", "A".repeat(60));
assert!(detect(&input).is_empty(), "{prefix}");
}
}
#[test]
fn a_bare_vendor_prefixed_value_is_detected_quoted_and_across_unicode_crlf() {
let value = format!("sk-proj-{VENDOR_PREFIX_PROJ_BODY}");
let quoted = format!("{{\"value\": \"{value}\"}}");
let quoted_candidates = detect("ed);
let (start, end) = only_range("ed_candidates);
assert_eq!("ed[start..end], value);
assert_eq!(
quoted_candidates[0].type_name(),
"vendor_prefixed_credential"
);
let unicode_crlf = format!("# \u{1F511} reviewed format\r\n{value}\n");
let unicode_candidates = detect(&unicode_crlf);
let (start, end) = only_range(&unicode_candidates);
assert_eq!(&unicode_crlf[start..end], value);
assert_eq!(
unicode_candidates[0].type_name(),
"vendor_prefixed_credential"
);
}
#[test]
fn the_ruleset_names_detector_does_not_match_bare_vendor_prefixed_values() {
let input = format!("sk-{VENDOR_PREFIX_LEGACY_BODY}");
let candidates = detect_with_ruleset_names(&input, &["corp_passphrase"]);
assert!(candidates.is_empty());
}
#[test]
fn a_keychain_secret_store_reference_is_excluded() {
for input in [
"{\n \"apiKey\": \"{keychain:fireworks-api-key}\"\n}\n",
"api_key='{keychain:synthetic.item_name}'",
"apiKey: {keychain:fireworks-api-key}",
] {
assert!(detect(input).is_empty(), "{input:?}");
}
}
#[test]
fn a_malformed_or_embedded_keychain_reference_is_still_detected() {
for input in [
"\"apiKey\": \"{keychain:}SYNTHETIC0REVOKED\"",
"\"apiKey\": \"{keychain:a b SYNTHETIC0REVOKED}\"",
"\"apiKey\": \"{keychain:item}SYNTHETIC0REVOKED\"",
"\"apiKey\": \"{keychain:vault/item#SYNTHETIC0REVOKED}\"",
"\"apiKey\": \"{keyring:SYNTHETIC0REVOKED}\"",
] {
assert!(!detect(input).is_empty(), "{input:?}");
}
}
#[test]
fn a_partially_masked_console_display_is_excluded() {
let groq = format!("Secret: gsk_{}Tn4q Created: 2026-09-01", "*".repeat(48));
let xai = format!("password: xai-AbCd{}WxYz", "*".repeat(72));
let bullets = format!("secret: sk-{}Ab12", "\u{2022}".repeat(8));
for input in [
groq.as_str(),
xai.as_str(),
bullets.as_str(),
"api_key=ab****cd",
] {
assert!(detect(input).is_empty(), "{input:?}");
}
}
#[test]
fn values_near_a_partially_masked_display_are_still_detected() {
for input in [
"Password: ********x".to_owned(),
"Password: x********".to_owned(),
"secret: SYNTHETIC***REVOKED".to_owned(),
"secret: SYNTHETIC0R****EVOKED0VALUE".to_owned(),
format!("secret: SYNTHETIC0REVOKED0{}Tn4q", "*".repeat(64)),
format!("secret: gsk_{}Tn{}4q", "*".repeat(20), "*".repeat(20)),
format!(
"secret: gsk_{}{}Tn4q",
"*".repeat(20),
"\u{2022}".repeat(20)
),
format!("secret: gsk+{}Tn4q", "*".repeat(48)),
] {
assert!(!detect(&input).is_empty(), "{input:?}");
}
}
#[test]
fn a_colon_namespaced_acl_scope_is_not_an_assignment() {
for input in [
"{\n \"acls\": [\"api-key:endpoint:chat\", \"api-key:model:*\"]\n}\n",
"scopes: api_key:models:read-write",
"secret:rotate:all_regions",
] {
assert!(detect(input).is_empty(), "{input:?}");
}
}
#[test]
fn a_credential_assignment_near_a_scope_identifier_is_still_detected() {
for input in [
"api_key: endpoint:chatSYNTHETIC",
"api-key: endpoint:chat",
"Api-Key:SYNTHETIC0REVOKED0VALUE",
"api_key=endpoint:chat",
"\"api_key\":\"endpoint:chat\"",
"api_key:endpoint:SYNTHETIC0REVOKED",
"api_key:endpoint:0synthetic",
] {
assert!(!detect(input).is_empty(), "{input:?}");
}
}
fn npmrc_spans(input: &str) -> Vec<(usize, usize)> {
npmrc_credential_candidates(input)
.iter()
.map(|candidate| {
assert_eq!(candidate.confidence(), Confidence::High);
(candidate.range().start(), candidate.range().end())
})
.collect()
}
#[test]
fn npmrc_credential_keys_report_their_value() {
let value = "Synthetic0Revoked1Registry2Token3";
for input in [
format!("//registry.npmjs.org/:_authToken={value}\n"),
format!("//npm.example.invalid/repo/npm/:_auth = \"{value}\"\n"),
format!("//npm.example.invalid/:_password={value}"),
format!("_authToken={value}\n"),
format!(" _auth={value}\r\n"),
] {
let start = input.find(value).unwrap();
assert_eq!(
npmrc_spans(&input),
vec![(start, start + value.len())],
"{input}"
);
}
}
#[test]
fn npmrc_references_placeholders_and_other_keys_stay_silent() {
for input in [
"//registry.npmjs.org/:_authToken=${NPM_TOKEN}\n",
"//registry.npmjs.org/:_authToken=<your-token>\n",
"//registry.npmjs.org/:_authToken=\n",
"//registry.npmjs.org/:username=synthetic-user\n",
"//registry.npmjs.org/:email=someone@example.invalid\n",
"registry=https://registry.npmjs.org/\n",
"the _authToken=Synthetic0Revoked1Registry2Token3 in prose\n",
"x:_authToken=Synthetic0Revoked1Registry2Token3\n",
"//registry.npmjs.org/:_authorization=Synthetic0Revoked1Registry2Token3\n",
"//registry.npmjs.org/:_authToken=short\n",
] {
assert!(npmrc_spans(input).is_empty(), "{input}");
}
}
fn value_line_reads() -> usize {
VALUE_LINE_READS.with(std::cell::Cell::get)
}
#[test]
fn value_names_on_one_long_line_read_that_line_once() {
let input = " value=x".repeat(8192);
let before = value_line_reads();
detect(&input);
assert_eq!(value_line_reads() - before, 1);
let lines = format!("{input}\n{input}\r\n{input}\r{input}");
let before = value_line_reads();
detect(&lines);
assert_eq!(value_line_reads() - before, 4);
}
#[test]
fn value_line_pairing_matches_reading_each_line_afresh() {
const PIECES: &[&str] = &[
"value",
"value",
"name",
":",
": ",
"=",
" ",
" ",
"- ",
"-",
"\t",
"\r",
"\n",
"\r\n",
"DEEPGRAM_API_KEY",
"x",
"\u{e9}",
"\u{200b}",
"# c",
"{",
"valueFrom",
"\"",
"'",
];
let mut state = 0x2545_f491_4f6c_dd1du64;
let mut next = move |bound: usize| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
usize::try_from(state % bound as u64).unwrap()
};
let mut inputs: Vec<String> = vec![
"env:\n - name: DEEPGRAM_API_KEY\n value: x\n".into(),
"env:\n - value: x value: y\n name: A_KEY\n".into(),
"value: x value=y\r\n- name: A\r".into(),
];
for _ in 0..20_000 {
let len = 1 + next(14);
inputs.push((0..len).map(|_| PIECES[next(PIECES.len())]).collect());
}
let mut paired = 0usize;
for input in &inputs {
let spans: Vec<(usize, usize)> = input
.match_indices("value")
.map(|(at, name)| (at, at + name.len()))
.collect();
let mut orders = vec![spans.clone()];
let mut scrambled = spans.clone();
for index in (1..scrambled.len()).rev() {
scrambled.swap(index, next(index + 1));
}
orders.push(scrambled);
for order in orders {
let mut memo = ValueLinePairing::default();
for (start, end) in order {
let expected = super::super::text::list_item_paired_name(
input,
super::super::text::line_around(input, start, end),
);
assert_eq!(
memo.paired_name(input, start, end),
expected,
"{input:?} at {start}"
);
paired += usize::from(expected.is_some());
}
}
}
assert!(paired > 0, "the generated inputs never pair a name");
}
fn value_scan_bytes() -> usize {
VALUE_WALK_BYTES.with(std::cell::Cell::get) + VALUE_REACH_BYTES.with(std::cell::Cell::get)
}
#[test]
fn prefixes_inside_a_value_do_not_rescan_it() {
for unit in [
"?a=",
"{a=x",
"(a=",
"&a=",
"a={a=",
"a=[a=",
"{a=x".repeat(900).as_str(),
] {
let unit = if unit.len() > 100 {
format!("{unit} ")
} else {
unit.to_owned()
};
let input = unit.repeat(65_536 / unit.len());
let before = value_scan_bytes();
detect(&input);
let scanned = value_scan_bytes() - before;
assert!(
scanned <= 4 * input.len(),
"{:?}: {scanned} bytes read for {} bytes",
&unit[..unit.len().min(12)],
input.len()
);
}
}
fn reach_inputs() -> Vec<String> {
const PIECES: &[&str] = &[
"a=", "?a=", "&a=", "#a=", "{", "}", "[", "]", "(", ")", "<", ">", " ", "\t", "\r",
"\n", ",", ";", "\"", "'", "`", "&", "\u{e9}", "\u{200b}", "x", "xy", "value:", "=",
];
let mut state = 0x9e37_79b9_7f4a_7c15u64;
let mut next = move |bound: usize| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
usize::try_from(state % bound as u64).unwrap()
};
let mut inputs: Vec<String> = vec![
String::new(),
"a=".into(),
"?a=x&b=y#c=z)".into(),
"a=x&b=1 a=x&1=2".into(),
];
for fill in [
MAX_CONTEXT_VALUE_LENGTH - 2,
MAX_CONTEXT_VALUE_LENGTH - 1,
MAX_CONTEXT_VALUE_LENGTH,
MAX_CONTEXT_VALUE_LENGTH + 1,
MAX_CONTEXT_VALUE_LENGTH + 2,
] {
for stop in ["", " ", "}", "&a=", "#", ")"] {
inputs.push(format!("a={}{stop}", "x".repeat(fill)));
inputs.push(format!("?a={}{stop}", "x".repeat(fill)));
inputs.push(format!("?a=?a={}{stop}", "x".repeat(fill)));
inputs.push(format!("a={{a={}{stop}a=x", "x".repeat(fill)));
}
}
for _ in 0..3_000 {
let len = 1 + next(16);
let mut text: String = (0..len).map(|_| PIECES[next(PIECES.len())]).collect();
if next(16) == 0 {
let at = (0..=text.len()).rev().find(|&at| text.is_char_boundary(at));
text.insert_str(
at.unwrap_or(0),
&"x".repeat(MAX_CONTEXT_VALUE_LENGTH - 3 + next(7)),
);
}
inputs.push(text);
}
inputs
}
fn start_orders(input: &str, mut swap: impl FnMut(usize) -> usize) -> [Vec<usize>; 2] {
let long = input.len() > 512;
let forward: Vec<usize> = (0..=input.len())
.filter(|&at| input.is_char_boundary(at))
.filter(|&at| !long || at % 61 == 0 || at < 40 || input.len() - at < 40)
.collect();
let mut scrambled = forward.clone();
for index in (1..scrambled.len()).rev() {
scrambled.swap(index, swap(index + 1));
}
[forward, scrambled]
}
#[test]
fn query_parameter_value_matches_the_full_walk() {
let mut state = 0x2545_f491_4f6c_dd1du64;
for input in reach_inputs() {
let orders = start_orders(&input, |bound| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
usize::try_from(state % bound as u64).unwrap()
});
for order in orders {
let mut reach = ValueReach::default();
for start in order {
assert_eq!(
query_parameter_value(&input, start, &mut reach),
query_parameter_value_walk(&input, start),
"{:?} at {start}",
&input[..input.len().min(40)]
);
}
}
}
}
#[test]
fn unquoted_assignment_value_matches_the_full_walk() {
let mut state = 0x1234_5678_9abc_def1u64;
for input in reach_inputs() {
let orders = start_orders(&input, |bound| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
usize::try_from(state % bound as u64).unwrap()
});
for order in orders {
let mut reach = ValueReach::default();
for start in order {
assert_eq!(
unquoted_assignment_value(&input, start, &mut reach),
unquoted_assignment_value_with(&input, start, None),
"{:?} at {start}",
&input[..input.len().min(40)]
);
}
}
}
}
}
#[cfg(test)]
mod case_insensitive_differential_tests {
use super::*;
use crate::test_rng::{BOUNDARY_PIECES, XorShift32};
fn old_value_shows_masking_or_hashing(lead: &str, value: &str) -> bool {
let bytes = value.as_bytes();
let lower = value.to_ascii_lowercase();
let x_run = bytes
.chunk_by(|left, right| left == right)
.any(|run| matches!(run[0], b'x' | b'X') && run.len() >= MIN_X_MASK_RUN);
let shows_mask = value.contains(['*', '\u{2022}', '\u{2026}'])
|| value.contains("...")
|| x_run
|| lower.contains("redacted")
|| lower.contains("masked")
|| starts_with_digest_label(value);
if shows_mask {
return true;
}
HASH_NAME_LEADS.contains(&lead)
&& ((HEX_DIGEST_LENGTHS.contains(&value.len())
&& bytes.iter().all(u8::is_ascii_hexdigit))
|| (value.starts_with('$') && value[1..].contains('$')))
}
fn old_is_boolean_null_or_digits(lower: &str) -> bool {
matches!(lower, "true" | "false" | "null" | "undefined")
|| (!lower.is_empty() && lower.bytes().all(|byte| byte.is_ascii_digit()))
}
const WORDS: &[&str] = &[
"redacted",
"REDACTED",
"Masked",
"mAsKeD",
"true",
"FALSE",
"Null",
"UNDEFINED",
"changeme",
"CHANGE_ME",
"placeholder",
"Example",
"your",
"API",
"key",
"token",
"password",
"secret",
"sha256:",
"$2b$12$",
"deadbeef",
"123456",
"0000",
"\u{212a}ey",
"tru\u{e9}",
];
fn inputs() -> Vec<String> {
let mut rng = XorShift32::new(0x1086_0001);
let mut out: Vec<String> = vec![String::new()];
out.extend(WORDS.iter().map(|word| (*word).to_owned()));
let mut pieces: Vec<&str> = BOUNDARY_PIECES.to_vec();
pieces.extend_from_slice(WORDS);
for _ in 0..4000 {
out.push(rng.text(&pieces, 6));
}
out
}
#[test]
fn masking_check_matches_the_lowercasing_implementation() {
for value in inputs() {
for lead in ["masked", "hashed", "redacted", "api"] {
assert_eq!(
value_shows_masking_or_hashing(lead, &value),
old_value_shows_masking_or_hashing(lead, &value),
"{value:?} under {lead}"
);
}
}
}
#[test]
fn placeholder_and_literal_checks_match_the_lowercasing_implementation() {
for value in inputs() {
let lower = value.to_ascii_lowercase();
assert_eq!(
is_generic_placeholder_word(&value),
is_generic_placeholder_word(&lower),
"{value:?}"
);
assert_eq!(
is_boolean_null_or_digits(&value),
old_is_boolean_null_or_digits(&lower),
"{value:?}"
);
}
}
}
#[cfg(test)]
mod assignment_anchor_tests {
use super::*;
use crate::test_rng::XorShift32;
const PIECES: &[&str] = &[
"password",
"=",
":",
" ",
" ",
"\t",
"\n",
"\r",
"\r\n",
"\u{2028}",
"\u{2029}",
"\u{00A0}",
"\u{3000}",
"\u{FEFF}",
"\u{200B}",
"{",
",",
";",
"\"",
"'",
"`",
"[",
"(",
"?",
"&",
"#",
"x",
"Z9",
"-",
"_",
".",
"é",
"😀",
"\u{E2}",
"k",
"os.environ[",
"otpauth://",
"abc",
"\\",
")",
"]",
"\u{0B}",
"\u{0C}",
"\u{85}",
];
fn old_next_match(input: &str, from: usize) -> usize {
let mut pos = from;
while pos < input.len() {
if try_match_assignment_prefix(input, pos).is_some() {
return pos;
}
pos += char_at(input, pos).map_or(1, char::len_utf8);
}
input.len()
}
#[test]
fn anchor_never_skips_a_matching_position() {
let mut rng = XorShift32::new(0x1091_0001);
for _ in 0..4000 {
let input = rng.text(PIECES, 14);
let mut from = 0usize;
while from <= input.len() {
let anchored = next_assignment_position(&input, from);
assert!(input.is_char_boundary(anchored), "{input:?} {from}");
assert!(anchored >= from, "{input:?} {from}");
let expected = old_next_match(&input, from);
assert!(anchored <= expected, "{input:?} from {from}");
assert_eq!(old_next_match(&input, anchored), expected, "{input:?}");
from += char_at(&input, from).map_or(1, char::len_utf8);
}
}
}
#[test]
fn anchor_handles_empty_and_boundary_inputs() {
assert_eq!(next_assignment_position("", 0), 0);
assert_eq!(next_assignment_position("abc", 0), 0);
assert_eq!(next_assignment_position("abc", 1), 3);
assert_eq!(next_assignment_position("abc d", 1), 3);
assert_eq!(next_assignment_position("abc\nxyz", 1), 3);
assert_eq!(next_assignment_position("abc\nxyz", 4), 4);
assert_eq!(next_assignment_position("a\u{2028}b", 1), 1);
assert_eq!(next_assignment_position("a\u{2028}b c", 4), 4);
}
}
#[cfg(test)]
mod residual_allocation_tests {
use super::*;
use crate::test_rng::XorShift32;
const PIECES: &[&str] = &[
"projects",
"secrets",
"versions",
"latest",
"3",
"arn",
"aws",
"aws-cn",
"secretsmanager",
"secret",
"us-east-1",
"123456789012",
"12345",
"vault",
"ref+",
"://",
"#",
"/",
":",
"|",
".",
"-",
"_",
"=",
"x",
"xx",
"xxxxxxxx",
"XXXXXXXX",
"0",
"00000000",
"ab",
"key",
"your",
"super",
"https://",
"kv",
"vault.azure.net",
"name",
" ",
"\u{e9}",
"+",
"@",
];
fn old_gcp(value: &str) -> bool {
let segments: Vec<&str> = value.split('/').collect();
let (project, name) = match segments.as_slice() {
["projects", project, "secrets", name] => (project, name),
["projects", project, "secrets", name, "versions", version]
if is_gcp_secret_version(version) =>
{
(project, name)
}
_ => return false,
};
is_gcp_project_id(project) && is_segment(name)
}
fn old_bank_vaults(value: &str) -> bool {
let Some(rest) = value.strip_prefix("vault:") else {
return false;
};
let parts: Vec<&str> = rest.split('#').collect();
if !(2..=3).contains(&parts.len()) {
return false;
}
is_path(parts[0]) && parts[1..].iter().all(|part| is_segment(part))
}
fn old_sm_arn(value: &str) -> bool {
let segments: Vec<&str> = value.splitn(7, ':').collect();
let [
arn,
partition,
service,
region,
account,
secret_literal,
name,
] = segments.as_slice()
else {
return false;
};
*arn == "arn"
&& is_aws_secretsmanager_partition(partition)
&& *service == "secretsmanager"
&& is_aws_region(region)
&& is_aws_account_id(account)
&& *secret_literal == "secret"
&& is_secretsmanager_secret_name(name)
}
fn old_aws_arn(value: &str) -> bool {
let segments: Vec<&str> = value.splitn(6, ':').collect();
let [arn, partition, service, region, account, resource] = segments.as_slice() else {
return false;
};
*arn == "arn"
&& is_aws_secretsmanager_partition(partition)
&& !service.is_empty()
&& service
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
&& (region.is_empty() || is_aws_region(region))
&& (account.is_empty() || *account == "aws" || is_aws_account_id(account))
&& !resource.is_empty()
&& !resource.bytes().any(|byte| byte.is_ascii_whitespace())
}
fn old_hostname(host: &str) -> bool {
if host.is_empty() || host.len() > 255 {
return false;
}
let labels: Vec<&str> = host.split('.').collect();
labels.len() >= 2 && labels.into_iter().all(is_dns_label)
}
fn old_noun_phrase(value: &str) -> bool {
let words: Vec<&str> = value.split(['-', '_']).collect();
words.len() >= 2
&& words
.iter()
.all(|word| !word.is_empty() && word.bytes().all(|byte| byte.is_ascii_lowercase()))
&& words
.last()
.is_some_and(|tail| CREDENTIAL_PHRASE_TAIL_WORDS.contains(tail))
}
fn old_filler_body(value: &str) -> bool {
let body: Vec<u8> = value
.trim_end_matches('=')
.bytes()
.filter(|byte| !matches!(byte, b'-' | b'_' | b'.' | b':'))
.collect();
if !body.iter().all(u8::is_ascii_alphanumeric) {
return false;
}
(0..=MAX_FILLER_PREFIX_LEN.min(body.len())).any(|split| {
let filler = &body[split..];
filler.len() >= MIN_FILLER_LEN && filler.iter().all(|&byte| byte == filler[0])
})
}
fn compare(name: &str, seed: u32, prefix: &str, new: fn(&str) -> bool, old: fn(&str) -> bool) {
let mut rng = XorShift32::new(seed);
let mut rejected = 0;
for round in 0..40_000 {
let tail = rng.text(PIECES, 12);
let value = if round % 2 == 0 {
tail
} else {
format!("{prefix}{tail}")
};
let expected = old(&value);
rejected += usize::from(!expected);
assert_eq!(new(&value), expected, "{name}: {value:?}");
}
assert!(rejected > 100, "{name}: generator never rejects");
}
#[test]
fn gcp_matches_collecting_form() {
compare(
"gcp",
0x1121_0011,
"projects/",
is_gcp_secret_manager_reference,
old_gcp,
);
for ok in [
"projects/my-proj/secrets/db",
"projects/my-proj/secrets/db/versions/3",
"projects/my-proj/secrets/db/versions/latest",
] {
assert!(is_gcp_secret_manager_reference(ok) && old_gcp(ok), "{ok}");
}
for bad in [
"",
"projects/my-proj/secrets",
"projects/my-proj/secrets/db/",
"projects/my-proj/secrets/db/versions",
"projects/my-proj/secrets/db/versions/x",
"projects/my-proj/secrets/db/versions/3/",
"projects/my-proj/secrets/db/other/3",
"x/my-proj/secrets/db",
"projects//secrets/db",
] {
assert_eq!(is_gcp_secret_manager_reference(bad), old_gcp(bad), "{bad}");
}
}
#[test]
fn bank_vaults_matches_collecting_form() {
compare(
"vault",
0x1121_0012,
"vault:",
is_bank_vaults_reference,
old_bank_vaults,
);
for fixed in [
"vault:secret/data/db#password",
"vault:secret/data/db#password#3",
"vault:secret/data/db#password#3#4",
"vault:secret/data/db",
"vault:#",
"vault:a#b#",
"vault:",
] {
assert_eq!(
is_bank_vaults_reference(fixed),
old_bank_vaults(fixed),
"{fixed}"
);
}
assert!(is_bank_vaults_reference("vault:secret/data/db#password#3"));
}
#[test]
fn arns_match_collecting_forms() {
compare(
"sm-arn",
0x1121_0013,
"arn:aws:secretsmanager:",
is_aws_secretsmanager_arn,
old_sm_arn,
);
compare("arn", 0x1121_0014, "arn:aws:", is_aws_arn, old_aws_arn);
for fixed in [
"arn:aws:secretsmanager:us-east-1:123456789012:secret:db/pass-AbCdEf",
"arn:aws:secretsmanager:us-east-1:123456789012:secret:a:b:c",
"arn:aws:secretsmanager:us-east-1:123456789012:secret:",
"arn:aws:secretsmanager:us-east-1:123456789012:secret",
"arn:aws:iam::aws:policy/IAMUserChangePassword",
"arn:aws:iam::aws:policy/a:b:c",
"arn:aws:iam::123456789012:",
"arn:aws:iam:::x",
"arn:aws:iam:::x y",
"arn:aws:iam::aws",
"",
] {
assert_eq!(
is_aws_secretsmanager_arn(fixed),
old_sm_arn(fixed),
"{fixed}"
);
assert_eq!(is_aws_arn(fixed), old_aws_arn(fixed), "{fixed}");
}
assert!(is_aws_secretsmanager_arn(
"arn:aws:secretsmanager:us-east-1:123456789012:secret:db/pass-AbCdEf"
));
assert!(!is_aws_secretsmanager_arn(
"arn:aws:secretsmanager:us-east-1:123456789012:secret:a:b:c"
));
assert!(is_aws_arn("arn:aws:iam::aws:policy/a:b:c"));
}
#[test]
fn hostname_noun_phrase_and_filler_match_collecting_forms() {
compare("host", 0x1121_0015, "", is_https_hostname, old_hostname);
compare(
"noun",
0x1121_0016,
"your-",
is_credential_noun_phrase,
old_noun_phrase,
);
compare(
"filler",
0x1121_0017,
"",
is_prefixed_filler_body,
old_filler_body,
);
for fixed in ["", ".", "a.", ".a", "a.b", "a..b", "a.b.c", "-a.b"] {
assert_eq!(is_https_hostname(fixed), old_hostname(fixed), "{fixed}");
}
for fixed in [
"",
"-",
"key",
"your-key",
"your--key",
"your-key-",
"a_b_secret",
"A-key",
] {
assert_eq!(
is_credential_noun_phrase(fixed),
old_noun_phrase(fixed),
"{fixed}"
);
}
for fixed in [
"",
"xxxxxxxx",
"xxxxxxx",
"abcdefghxxxxxxxx",
"abcdefghixxxxxxxx",
"abcdefghxxxxxxxxy",
"0.xxxxxxxx-xxxx:xxxx==",
"xxxxxxxx==",
"xxxxxxxx=x",
"xxxxxxxx!",
"aaaaaaaaaaaaaaaaaaaa",
"abcdefgh00000000",
"abcdefghi00000000",
"-_.:=",
] {
assert_eq!(
is_prefixed_filler_body(fixed),
old_filler_body(fixed),
"{fixed}"
);
}
for lead in 0..=11usize {
for run in 0..=11usize {
let value = format!(
"{}{}",
"abcdefghijk".get(..lead).unwrap_or(""),
"z".repeat(run)
);
assert_eq!(
is_prefixed_filler_body(&value),
old_filler_body(&value),
"{value}"
);
}
}
assert!(is_prefixed_filler_body("abcdefghzzzzzzzz"));
assert!(!is_prefixed_filler_body("abcdefghizzzzzzzz"));
}
}