use crate::detectors::pattern::{self, Alphabet, PrefixShape};
use crate::error::DetectorFailure;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};
pub(super) struct KnownFormatProviderDetector {
id: &'static str,
type_name: &'static str,
shapes: &'static [PrefixShape<'static>],
boundary: Alphabet,
}
impl KnownFormatProviderDetector {
pub(super) const fn new(
id: &'static str,
type_name: &'static str,
shapes: &'static [PrefixShape<'static>],
boundary: Alphabet,
) -> Self {
Self {
id,
type_name,
shapes,
boundary,
}
}
pub(super) const fn detector_id(&self) -> &'static str {
self.id
}
pub(super) const fn shapes(&self) -> &'static [PrefixShape<'static>] {
self.shapes
}
}
impl Detector for KnownFormatProviderDetector {
fn id(&self) -> &str {
self.id
}
fn detect(
&self,
input: &str,
_context: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
let mut candidates = Vec::new();
for (start, end, signals) in
pattern::scan_prefixed_shapes(input, self.shapes, self.boundary)
{
let Some(range) = ByteRange::new(start, end) else {
continue;
};
candidates.push(
Candidate::built_in(self.type_name, Confidence::High, range)
.with_specificity(Specificity::Provider)
.with_signals(signals.iter().copied()),
);
}
Ok(candidates)
}
}
pub(super) struct TypedKnownFormatProviderDetector {
id: &'static str,
shapes: &'static [PrefixShape<'static>],
types: &'static [&'static str],
boundary: Alphabet,
}
impl TypedKnownFormatProviderDetector {
pub(super) const fn new(
id: &'static str,
shapes: &'static [PrefixShape<'static>],
types: &'static [&'static str],
boundary: Alphabet,
) -> Self {
assert!(shapes.len() == types.len());
Self {
id,
shapes,
types,
boundary,
}
}
pub(super) const fn detector_id(&self) -> &'static str {
self.id
}
pub(super) const fn shapes(&self) -> &'static [PrefixShape<'static>] {
self.shapes
}
fn type_at(&self, bytes: &[u8], start: usize) -> Option<&'static str> {
self.shapes
.iter()
.zip(self.types)
.filter(|(shape, _)| bytes[start..].starts_with(shape.prefix.as_bytes()))
.max_by_key(|(shape, _)| shape.prefix.len())
.map(|(_, type_name)| *type_name)
}
}
impl Detector for TypedKnownFormatProviderDetector {
fn id(&self) -> &str {
self.id
}
fn detect(
&self,
input: &str,
_context: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
let bytes = input.as_bytes();
let mut candidates = Vec::new();
for (start, end, signals) in
pattern::scan_prefixed_shapes(input, self.shapes, self.boundary)
{
let (Some(range), Some(type_name)) =
(ByteRange::new(start, end), self.type_at(bytes, start))
else {
continue;
};
candidates.push(
Candidate::built_in(type_name, Confidence::High, range)
.with_specificity(Specificity::Provider)
.with_signals(signals.iter().copied()),
);
}
Ok(candidates)
}
}
const STRIPE_SIGNALS: [&str; 2] = ["stripe-documented-prefix", "opaque-suffix"];
pub(super) const STRIPE: KnownFormatProviderDetector = KnownFormatProviderDetector {
id: "stripe-token",
type_name: "stripe_credential",
shapes: &[
PrefixShape::at_least("sk_test_", 20, pattern::is_alnum, &STRIPE_SIGNALS),
PrefixShape::at_least("sk_live_", 20, pattern::is_alnum, &STRIPE_SIGNALS),
PrefixShape::at_least("rk_test_", 20, pattern::is_alnum, &STRIPE_SIGNALS),
PrefixShape::at_least("rk_live_", 20, pattern::is_alnum, &STRIPE_SIGNALS),
PrefixShape::at_least("sk_org_", 20, pattern::is_alnum, &STRIPE_SIGNALS),
PrefixShape::at_least("sk_org_live_", 20, pattern::is_alnum, &STRIPE_SIGNALS),
PrefixShape::at_least("sk_org_test_", 20, pattern::is_alnum, &STRIPE_SIGNALS),
],
boundary: pattern::is_alnum_dash,
};
const PYPI_SIGNALS: [&str; 2] = ["pypi-documented-prefix", "macaroon-minimum-length"];
pub(super) const PYPI: KnownFormatProviderDetector = KnownFormatProviderDetector {
id: "pypi-token",
type_name: "pypi_api_token",
shapes: &[PrefixShape::at_least(
"pypi-",
85,
pattern::is_alnum_dash,
&PYPI_SIGNALS,
)],
boundary: pattern::is_alnum_dash,
};
const HUGGING_FACE_SIGNALS: [&str; 2] = ["huggingface-documented-prefix", "base62-exact-length"];
const HUGGING_FACE_ORGANIZATION_SIGNALS: [&str; 2] = [
"huggingface-organization-documented-prefix",
"base62-exact-length",
];
pub(super) const HUGGING_FACE: KnownFormatProviderDetector = KnownFormatProviderDetector {
id: "huggingface-token",
type_name: "huggingface_token",
shapes: &[
PrefixShape::exact("hf_", 34, pattern::is_alnum, &HUGGING_FACE_SIGNALS),
PrefixShape::exact(
"api_org_",
34,
pattern::is_alnum,
&HUGGING_FACE_ORGANIZATION_SIGNALS,
),
],
boundary: pattern::is_alnum_dash,
};
const DOCKER_SIGNALS: [&str; 2] = ["docker-documented-prefix", "exact-length-suffix"];
pub(super) const DOCKER: KnownFormatProviderDetector = KnownFormatProviderDetector {
id: "docker-token",
type_name: "docker_token",
shapes: &[
PrefixShape::exact(
"dckr_pat_",
DOCKER_PAT_SUFFIX_LEN,
pattern::is_alnum_dash,
&DOCKER_SIGNALS,
),
PrefixShape::one_of(
"dckr_oat_",
&DOCKER_OAT_SUFFIX_LENS,
pattern::is_alnum_dash,
&DOCKER_SIGNALS,
),
],
boundary: pattern::is_alnum_dash,
};
pub(super) const DOCKER_PAT_SUFFIX_LEN: usize = 27;
pub(super) const DOCKER_OAT_SUFFIX_LEN: usize = 32;
pub(super) const DOCKER_OAT_SUFFIX_LENS: [usize; 2] =
[DOCKER_PAT_SUFFIX_LEN, DOCKER_OAT_SUFFIX_LEN];
const DIGITALOCEAN_SIGNALS: [&str; 2] =
["digitalocean-documented-prefix", "fixed-length-hex-suffix"];
pub(super) const DIGITALOCEAN: KnownFormatProviderDetector = KnownFormatProviderDetector {
id: "digitalocean-token",
type_name: "digitalocean_token",
shapes: &[
PrefixShape::exact("dop_v1_", 64, pattern::is_lower_hex, &DIGITALOCEAN_SIGNALS),
PrefixShape::exact("doo_v1_", 64, pattern::is_lower_hex, &DIGITALOCEAN_SIGNALS),
PrefixShape::exact("dor_v1_", 64, pattern::is_lower_hex, &DIGITALOCEAN_SIGNALS),
],
boundary: pattern::is_alnum_dash,
};
const SUPABASE_SIGNALS: [&str; 3] = [
"supabase-secret-prefix",
"elevated-access-key",
"documented-random-checksum-layout",
];
const SUPABASE_BODY_LEN: usize = 22 + 1 + 8;
const SUPABASE_DELIMITER_OFFSET: usize = 22;
const SUPABASE_PREFIX: &str = "sb_secret_";
fn supabase_delimiter_ok(bytes: &[u8], start: usize, _end: usize) -> bool {
bytes.get(start + SUPABASE_PREFIX.len() + SUPABASE_DELIMITER_OFFSET) == Some(&b'_')
}
pub(super) const SUPABASE: KnownFormatProviderDetector = KnownFormatProviderDetector {
id: "supabase-token",
type_name: "supabase_secret_key",
shapes: &[PrefixShape::exact(
SUPABASE_PREFIX,
SUPABASE_BODY_LEN,
pattern::is_alnum_dash,
&SUPABASE_SIGNALS,
)
.with_post_check(supabase_delimiter_ok)],
boundary: pattern::is_alnum_dash,
};
const SUPABASE_PAT_SIGNALS: [&str; 2] =
["supabase-pat-documented-prefix", "tool-corroborated-length"];
pub(super) const SUPABASE_PAT: KnownFormatProviderDetector = KnownFormatProviderDetector {
id: "supabase-management-token",
type_name: "supabase_personal_access_token",
shapes: &[
PrefixShape::exact(
"sbp_v0_",
40,
pattern::is_lower_alnum,
&SUPABASE_PAT_SIGNALS,
),
PrefixShape::exact("sbp_", 40, pattern::is_lower_alnum, &SUPABASE_PAT_SIGNALS),
],
boundary: pattern::is_alnum_dash,
};
const NPM_SIGNALS: [&str; 2] = ["npm-documented-prefix", "base62-exact-length"];
pub(super) const NPM: KnownFormatProviderDetector = KnownFormatProviderDetector {
id: "npm-token",
type_name: "npm_access_token",
shapes: &[PrefixShape::exact(
"npm_",
36,
pattern::is_alnum,
&NPM_SIGNALS,
)],
boundary: pattern::is_alnum_dash,
};
const GOOGLE_SIGNALS: [&str; 2] = ["google-documented-prefix", "exact-length-suffix"];
pub(super) const GOOGLE: KnownFormatProviderDetector = KnownFormatProviderDetector {
id: "google-api-key",
type_name: "google_api_key",
shapes: &[PrefixShape::exact(
"AIza",
35,
pattern::is_alnum_dash,
&GOOGLE_SIGNALS,
)],
boundary: pattern::is_alnum_dash,
};
const GRAFANA_CLOUD_SIGNALS: [&str; 2] =
["grafana-cloud-documented-prefix", "base64-opaque-suffix"];
pub(super) const GRAFANA_CLOUD: KnownFormatProviderDetector = KnownFormatProviderDetector {
id: "grafana-cloud-access-policy-token",
type_name: "grafana_cloud_access_policy_token",
shapes: &[PrefixShape::at_least(
"glc_",
32,
pattern::is_base64_body,
&GRAFANA_CLOUD_SIGNALS,
)],
boundary: pattern::is_alnum_dash,
};
const PULUMI_SIGNALS: [&str; 2] = ["pulumi-documented-prefix", "tool-corroborated-length"];
pub(super) const PULUMI: KnownFormatProviderDetector = KnownFormatProviderDetector {
id: "pulumi-access-token",
type_name: "pulumi_access_token",
shapes: &[PrefixShape::exact(
"pul-",
40,
pattern::is_lower_hex,
&PULUMI_SIGNALS,
)],
boundary: pattern::is_alnum_dash,
};
#[cfg(test)]
mod tests {
use super::*;
const BODY: &str = "SYNTHETICREVOKEDPROVIDERVALUE";
const HUGGING_FACE_BODY: &str = "SYNTHETICREVOKEDHUGGINGFACETOKEN01";
const _: () = assert!(HUGGING_FACE_BODY.len() == 34);
const NPM_BODY: &str = "SYNTHETICREVOKEDNPMACCESSTOKENVALUE1";
const GOOGLE_BODY: &str = "SYNTHETIC_REVOKED_GOOGLE_API_KEY012";
const GRAFANA_CLOUD_BODY: &str = "SYNTHETICREVOKEDGRAFANACLOUDACCESSPOLICYTOKEN";
const DOCKER_PAT_BODY: &str = "SYNTHETICREVOKEDDOCKERPAT00";
const DOCKER_OAT_BODY: &str = "SYNTHETICREVOKEDDOCKERORGTOKEN00";
const _: () = assert!(DOCKER_PAT_BODY.len() == DOCKER_PAT_SUFFIX_LEN);
const _: () = assert!(DOCKER_OAT_BODY.len() == DOCKER_OAT_SUFFIX_LEN);
const DIGITALOCEAN_BODY: &str =
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
const DIGITALOCEAN_OAUTH_BODY: &str =
"fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210";
const SUPABASE_PAT_BODY: &str = "synthetic0revoked1provider2value3padding";
const SUPABASE_BODY: &str = "SYNTHETIC_REVOKED_SUPA_CHECKSUM";
const _: () = assert!(SUPABASE_BODY.len() == SUPABASE_BODY_LEN);
const _: () = assert!(SUPABASE_PAT_BODY.len() == 40);
const DIGITALOCEAN_REFRESH_BODY: &str =
"123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0";
const PULUMI_BODY: &str = "0123456789abcdef0123456789abcdef01234567";
const _: () = assert!(PULUMI_BODY.len() == 40);
fn detect(detector: &KnownFormatProviderDetector, input: &str) -> Vec<Candidate> {
detector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
struct Family {
detector: KnownFormatProviderDetector,
value: String,
broken: String,
short: &'static str,
}
fn family(
detector: KnownFormatProviderDetector,
prefix: &str,
body: &str,
short: &'static str,
) -> Family {
Family {
detector,
value: format!("{prefix}{body}"),
broken: format!("{prefix}{}!{}", &body[..4], &body[4..]),
short,
}
}
fn families() -> Vec<Family> {
vec![
family(STRIPE, "sk_live_", BODY, "sk_live_SYNTHETICSHORT"),
family(
PYPI,
"pypi-",
&"SYNTHETIC_REVOKED_".repeat(5),
"pypi-SYNTHETICSHORT",
),
family(HUGGING_FACE, "hf_", HUGGING_FACE_BODY, "hf_SYNTHETIC_SHORT"),
family(
DOCKER,
"dckr_pat_",
DOCKER_PAT_BODY,
"dckr_pat_SYNTHETIC_SHORT",
),
family(
DIGITALOCEAN,
"dop_v1_",
DIGITALOCEAN_BODY,
"dop_v1_SYNTHETIC_SHORT",
),
family(
SUPABASE,
"sb_secret_",
SUPABASE_BODY,
"sb_secret_SYNTHETIC_SHORT",
),
family(
SUPABASE_PAT,
"sbp_",
SUPABASE_PAT_BODY,
"sbp_synthetic0short",
),
family(NPM, "npm_", NPM_BODY, "npm_SYNTHETICSHORT"),
family(GOOGLE, "AIza", GOOGLE_BODY, "AIzaSYNTHETICSHORT"),
family(
GRAFANA_CLOUD,
"glc_",
GRAFANA_CLOUD_BODY,
"glc_SYNTHETICSHORT",
),
family(PULUMI, "pul-", PULUMI_BODY, "pul-0123456789abcdef"),
]
}
#[test]
fn detects_a_synthetic_credential_with_provider_specificity() {
for family in families() {
let candidates = detect(&family.detector, &family.value);
assert_eq!(candidates.len(), 1, "{}", family.detector.id());
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
assert_eq!(
candidates[0].range(),
ByteRange::new(0, family.value.len()).unwrap()
);
}
}
#[test]
fn rejects_short_invalid_alphabet_and_embedded_lookalikes() {
for family in families() {
let embedded = format!("X{}Y", family.value);
for input in [family.short, family.broken.as_str(), embedded.as_str()] {
assert_eq!(
detect(&family.detector, input).len(),
0,
"{} {input}",
family.detector.id()
);
}
}
}
#[test]
fn accepts_punctuation_boundaries() {
for family in families() {
let input = format!("({}).", family.value);
let candidates = detect(&family.detector, &input);
assert_eq!(candidates.len(), 1, "{}", family.detector.id());
assert_eq!(
candidates[0].range(),
ByteRange::new(1, family.value.len() + 1).unwrap(),
"{}",
family.detector.id()
);
}
}
#[test]
fn detects_every_documented_prefix_variant() {
let cases: [(&KnownFormatProviderDetector, &str); 10] = [
(&STRIPE, "sk_test_"),
(&STRIPE, "sk_live_"),
(&STRIPE, "rk_test_"),
(&STRIPE, "rk_live_"),
(&STRIPE, "sk_org_"),
(&STRIPE, "sk_org_live_"),
(&STRIPE, "sk_org_test_"),
(&DIGITALOCEAN, "dop_v1_"),
(&DIGITALOCEAN, "doo_v1_"),
(&DIGITALOCEAN, "dor_v1_"),
];
for (detector, prefix) in cases {
let body = if detector.id() == DIGITALOCEAN.id() {
DIGITALOCEAN_BODY
} else {
BODY
};
let value = format!("{prefix}{body}");
let candidates = detect(detector, &value);
assert_eq!(candidates.len(), 1, "{prefix}");
assert_eq!(
candidates[0].range(),
ByteRange::new(0, value.len()).unwrap(),
"{prefix}"
);
}
}
#[test]
fn does_not_classify_neighboring_public_or_identifier_only_formats() {
for input in [
format!("pk_live_{BODY}"),
format!("pk_test_{BODY}"),
format!("sb_publishable_{SUPABASE_BODY}"),
format!("SK{}", "0".repeat(32)),
format!("sk_liv_{BODY}"),
format!("sb_secrets_{SUPABASE_BODY}"),
] {
assert_eq!(detect(&STRIPE, &input).len(), 0, "{input}");
assert_eq!(detect(&SUPABASE, &input).len(), 0, "{input}");
}
}
#[test]
fn supabase_accepts_only_the_documented_random_checksum_layout() {
let random = &SUPABASE_BODY[..SUPABASE_DELIMITER_OFFSET];
let checksum = &SUPABASE_BODY[SUPABASE_DELIMITER_OFFSET + 1..];
assert_eq!((random.len(), checksum.len()), (22, 8));
for body in [
SUPABASE_BODY.to_string(),
"a-b_c-d_e-f_g-h_i-j_k-_l-m_n-o_".to_string(),
format!("{}_{}", "_-".repeat(11), "-_".repeat(4)),
] {
assert_eq!(body.len(), SUPABASE_BODY_LEN, "{body}");
let input = format!("SUPABASE_SECRET_KEY=sb_secret_{body}\n");
let candidates = detect(&SUPABASE, &input);
assert_eq!(candidates.len(), 1, "{input}");
assert_eq!(
candidates[0].range(),
ByteRange::new(20, 20 + 10 + SUPABASE_BODY_LEN).unwrap(),
"{input}"
);
}
for body in [
format!("{}_{checksum}", &random[..21]),
format!("{random}X_{checksum}"),
format!("{random}_{checksum}X"),
format!("{random}_{}", &checksum[..7]),
format!("{random}-{checksum}"),
format!("{random}X{checksum}"),
"SYNTHETICREVOKEDSYNTHETICREVOKEDSYNTHETI".to_string(),
] {
for input in [
format!("sb_secret_{body}"),
format!("SUPABASE_SECRET_KEY=sb_secret_{body}\n"),
] {
assert_eq!(detect(&SUPABASE, &input).len(), 0, "{input}");
}
}
}
#[test]
fn rejects_organization_and_webhook_documented_absence_and_separator_near_misses() {
for input in [
format!("rk_org_{BODY}"),
format!("sk_org{BODY}"),
format!("sk_org-{BODY}"),
format!("whsec{BODY}"),
format!("whsec-{BODY}"),
format!("wh_sec_{BODY}"),
] {
assert_eq!(detect(&STRIPE, &input).len(), 0, "{input}");
}
}
#[test]
fn claims_organization_mode_segment_with_the_same_floor_as_sk_org() {
for mode in ["live", "test"] {
let prefix = format!("sk_org_{mode}_");
for len in [20usize, 21, 32, 64, 120] {
let body = "A".repeat(len);
let value = format!("{prefix}{body}");
for input in [
value.clone(),
format!("KEY={value}\n"),
format!("\"{value}\""),
format!("\u{ac00}{value}\u{ac00}"),
format!("x {value}."),
] {
let c = detect(&STRIPE, &input);
assert_eq!(c.len(), 1, "{mode} {len}");
let start = input.find("sk_org_").unwrap();
assert_eq!(
c[0].range(),
ByteRange::new(start, start + value.len()).unwrap(),
"{mode} {len}"
);
}
}
let mixed = format!("{prefix}{}", "aZ09".repeat(6));
assert_eq!(detect(&STRIPE, &mixed).len(), 1, "{mixed}");
for input in [
prefix.clone(),
format!("{prefix}{}", "A".repeat(19)),
format!("{prefix}{}_{}", "A".repeat(10), "A".repeat(10)),
format!("{prefix}{}-{}", "A".repeat(10), "A".repeat(10)),
format!("{prefix}{}", "A".repeat(10)),
] {
let c = detect(&STRIPE, &input);
assert!(c.iter().all(|x| x.range().end() <= input.len()), "{input}");
assert_eq!(c.len(), 0, "{input}");
}
for lead in ["a", "9", "_", "-"] {
let input = format!("{lead}{prefix}{}", "A".repeat(24));
assert_eq!(detect(&STRIPE, &input).len(), 0, "{input}");
}
for tail in ["_", "-"] {
let input = format!("{prefix}{}{tail}", "A".repeat(24));
assert_eq!(detect(&STRIPE, &input).len(), 0, "{input}");
}
}
for mode in ["prod", "Live", "LIVE", "lives", "li", ""] {
let input = format!("sk_org_{mode}_{}", "A".repeat(24));
assert_eq!(detect(&STRIPE, &input).len(), 0, "{input}");
}
for prefix in ["sk_org_", "sk_live_", "sk_test_"] {
let input = format!("{prefix}{}", "A".repeat(24));
assert_eq!(detect(&STRIPE, &input).len(), 1, "{input}");
}
let two = format!("sk_org_live_{0} sk_org_test_{0}", "A".repeat(24));
assert_eq!(detect(&STRIPE, &two).len(), 2);
}
#[test]
fn rejects_masked_interpolated_and_contextualized_near_misses() {
for input in [
format!("(pk_live_{BODY})."),
format!("(sb_publishable_{SUPABASE_BODY})."),
format!("# \u{1F511} caf\u{e9}\r\npk_live_{BODY}\r\n"),
format!("# \u{1F511} caf\u{e9}\r\nsb_publishable_{SUPABASE_BODY}\r\n"),
"sk_live_********************".to_string(),
"sb_secret_********************".to_string(),
"sk_live_${STRIPE_SECRET_KEY}".to_string(),
"sb_secret_${SUPABASE_SERVICE_ROLE_KEY}".to_string(),
] {
assert_eq!(detect(&STRIPE, &input).len(), 0, "{input}");
assert_eq!(detect(&SUPABASE, &input).len(), 0, "{input}");
}
}
#[test]
fn classifies_only_the_secret_half_of_a_mixed_public_and_secret_input() {
let input = format!("pk_live_SYNTHETICREVOKEDSYNT\nsk_live_{BODY}");
let candidates = detect(&STRIPE, &input);
assert_eq!(candidates.len(), 1);
let expected_start = input.find("sk_live_").unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(expected_start, input.len()).unwrap()
);
}
#[test]
fn classifies_only_the_secret_half_of_a_mixed_public_and_secret_input_in_sandbox_mode() {
let input = format!("pk_test_SYNTHETICREVOKEDSYNT\nsk_test_{BODY}");
let candidates = detect(&STRIPE, &input);
assert_eq!(candidates.len(), 1);
let expected_start = input.find("sk_test_").unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(expected_start, input.len()).unwrap()
);
}
const INFRA_SUFFIX: &str = "SYNTHETIC_REVOKED_KEY_VALUE";
const DOCKER_OAT_SUFFIX: &str = "SYNTHETIC_REVOKED_OAT_KEY_VALUE3";
const _: () = assert!(INFRA_SUFFIX.len() == DOCKER_PAT_SUFFIX_LEN);
const _: () = assert!(DOCKER_OAT_SUFFIX.len() == DOCKER_OAT_SUFFIX_LEN);
struct InfraVariant {
detector: &'static KnownFormatProviderDetector,
prefix: &'static str,
body: &'static str,
placeholder: String,
}
fn digitalocean_variant(prefix: &'static str, body: &'static str) -> InfraVariant {
InfraVariant {
detector: &DIGITALOCEAN,
prefix,
body,
placeholder: "a".repeat(64),
}
}
fn docker_variant(prefix: &'static str, body: &'static str) -> InfraVariant {
InfraVariant {
detector: &DOCKER,
prefix,
body,
placeholder: "x".repeat(body.len()),
}
}
fn infra_provider_variants() -> Vec<InfraVariant> {
vec![
docker_variant("dckr_pat_", INFRA_SUFFIX),
docker_variant("dckr_oat_", DOCKER_OAT_SUFFIX),
digitalocean_variant("dop_v1_", DIGITALOCEAN_BODY),
digitalocean_variant("doo_v1_", DIGITALOCEAN_OAUTH_BODY),
digitalocean_variant("dor_v1_", DIGITALOCEAN_REFRESH_BODY),
]
}
#[test]
fn infra_providers_accept_a_doc_style_placeholder_built_from_valid_alphabet_characters() {
for variant in infra_provider_variants() {
let input = format!("{}{}", variant.prefix, variant.placeholder);
assert_eq!(
detect(variant.detector, &input).len(),
1,
"{}",
variant.detector.id()
);
}
}
#[test]
fn infra_providers_reject_a_prefix_embedded_in_a_wider_benign_identifier() {
for variant in infra_provider_variants() {
let input = format!("legacy{}{}", variant.prefix, variant.body);
assert_eq!(
detect(variant.detector, &input).len(),
0,
"{}",
variant.detector.id()
);
}
}
#[test]
fn infra_providers_reject_every_shape_embedded_in_a_wider_identifier_leading_trailing_or_dash_joined()
{
for variant in infra_provider_variants() {
let value = format!("{}{}", variant.prefix, variant.body);
assert!(
detect(variant.detector, &format!("legacy{value}")).is_empty(),
"{} leading",
variant.detector.id()
);
assert!(
detect(variant.detector, &format!("{value}_backup")).is_empty(),
"{} trailing",
variant.detector.id()
);
assert!(
detect(variant.detector, &format!("{value}-1")).is_empty(),
"{} dash",
variant.detector.id()
);
}
}
#[test]
fn infra_providers_reject_case_changed_wrong_prefixes() {
for variant in infra_provider_variants() {
let input = format!("{}{}", variant.prefix.to_ascii_uppercase(), variant.body);
assert_eq!(
detect(variant.detector, &input).len(),
0,
"{}",
variant.detector.id()
);
}
}
#[test]
fn infra_providers_reject_masked_and_interpolated_near_misses() {
for variant in infra_provider_variants() {
for input in [
format!("{}{}", variant.prefix, "*".repeat(variant.body.len())),
format!("{}${{ENV_VAR}}", variant.prefix),
] {
assert_eq!(
detect(variant.detector, &input).len(),
0,
"{} {input}",
variant.detector.id()
);
}
}
}
#[test]
fn infra_providers_bound_a_match_against_trailing_prose_punctuation() {
for variant in infra_provider_variants() {
let token = format!("{}{}", variant.prefix, variant.body);
let input = format!("Rotate {token}, then redeploy.");
let candidates = detect(variant.detector, &input);
assert_eq!(candidates.len(), 1, "{}", variant.detector.id());
let start = "Rotate ".len();
let end = start + token.len();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, end).unwrap(),
"{}",
variant.detector.id()
);
}
}
#[test]
fn docker_rejects_an_ordinary_registry_image_digest_reference() {
let input = "docker pull registry.example.com/myorg/app@sha256:\
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b85";
assert_eq!(detect(&DOCKER, input).len(), 0);
}
#[test]
fn docker_accepts_each_segment_at_exactly_its_own_length() {
for (prefix, body) in [
("dckr_pat_", DOCKER_PAT_BODY),
("dckr_oat_", DOCKER_OAT_BODY),
] {
let value = format!("{prefix}{body}");
let candidates = detect(&DOCKER, &value);
assert_eq!(candidates.len(), 1, "{prefix}");
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
assert_eq!(
candidates[0].range(),
ByteRange::new(0, value.len()).unwrap(),
"{prefix}"
);
}
}
#[test]
fn docker_rejects_a_suffix_one_byte_off_either_documented_length() {
for (prefix, body) in [
("dckr_pat_", DOCKER_PAT_BODY),
("dckr_oat_", DOCKER_OAT_BODY),
] {
let one_short = format!("{prefix}{}", &body[..body.len() - 1]);
let one_long = format!("{prefix}{body}0");
for input in [one_short, one_long] {
assert_eq!(detect(&DOCKER, &input).len(), 0, "{input}");
}
}
}
#[test]
fn docker_does_not_accept_the_oat_width_under_the_pat_prefix() {
let input = format!("dckr_pat_{DOCKER_OAT_BODY}");
assert_eq!(detect(&DOCKER, &input).len(), 0, "{input}");
}
#[test]
fn docker_oat_accepts_exactly_the_27_and_32_byte_widths() {
for body in [DOCKER_PAT_BODY, DOCKER_OAT_BODY] {
let input = format!("DOCKER_TOKEN=dckr_oat_{body}");
let candidates = detect(&DOCKER, &input);
assert_eq!(candidates.len(), 1, "len={}", body.len());
assert_eq!(
candidates[0].range(),
ByteRange::new("DOCKER_TOKEN=".len(), input.len()).unwrap(),
"len={}",
body.len()
);
}
let padding = "SYNTHETICREVOKEDDOCKERORGTOKEN0000";
for len in [26usize, 28, 29, 30, 31, 33] {
let input = format!("dckr_oat_{}", &padding[..len]);
assert_eq!(detect(&DOCKER, &input).len(), 0, "len={len}");
}
}
#[test]
fn docker_distinguishes_unicode_crlf_twins_from_their_paired_positives() {
const COMMENT: &str = "# \u{1F511} reviewed format\r\n";
assert_eq!(COMMENT.len(), 24);
for (prefix, body) in [
("dckr_pat_", DOCKER_PAT_BODY),
("dckr_oat_", DOCKER_OAT_BODY),
] {
let positive = format!("{COMMENT}{prefix}{body}\n\r\n");
let candidates = detect(&DOCKER, &positive);
assert_eq!(candidates.len(), 1, "{prefix}");
assert_eq!(
candidates[0].range(),
ByteRange::new(COMMENT.len(), COMMENT.len() + prefix.len() + body.len()).unwrap(),
"{prefix}"
);
let twin = format!("{COMMENT}{prefix}{}\n\r\n", &body[..body.len() - 1]);
assert_eq!(detect(&DOCKER, &twin).len(), 0, "{prefix}");
}
}
#[test]
fn docker_discriminates_adjacent_twins_and_bounds_delimited_values() {
let pat = format!("dckr_pat_{DOCKER_PAT_BODY}");
let oat = format!("dckr_oat_{DOCKER_OAT_BODY}");
let pat_twin = &pat[..pat.len() - 1];
let oat_twin = &oat[..oat.len() - 1];
let input = format!("{pat}\n{pat_twin}\n{oat}\n{oat_twin}\n");
let candidates = detect(&DOCKER, &input);
let ranges: Vec<(usize, usize)> = candidates
.iter()
.map(|candidate| (candidate.range().start(), candidate.range().end()))
.collect();
let oat_start = pat.len() + 1 + pat_twin.len() + 1;
assert_eq!(
ranges,
vec![(0, pat.len()), (oat_start, oat_start + oat.len())]
);
for (input, start, len) in [
(format!("\"{pat}\""), 1, pat.len()),
(format!("`{oat}`"), 1, oat.len()),
(
format!("DOCKER_TOKEN={pat}"),
"DOCKER_TOKEN=".len(),
pat.len(),
),
] {
let candidates = detect(&DOCKER, &input);
assert_eq!(candidates.len(), 1, "{input}");
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + len).unwrap(),
"{input}"
);
}
}
#[test]
fn digitalocean_rejects_an_ordinary_deployment_resource_id() {
let input = "resource: do:app:3f900b88-8eb1-4de4-b7a3-93c1fb2f8b1d";
assert_eq!(detect(&DIGITALOCEAN, input).len(), 0);
}
#[test]
fn infra_providers_report_a_repeated_identical_value_once_per_occurrence() {
for variant in infra_provider_variants() {
let value = format!("{}{}", variant.prefix, variant.body);
let input = format!("{value} {value}");
let candidates = detect(variant.detector, &input);
assert_eq!(candidates.len(), 2, "{}", variant.detector.id());
}
}
#[test]
fn application_providers_accept_an_all_valid_alphabet_documentation_placeholder() {
let value = format!("hf_{}", "x".repeat(34));
let candidates = detect(&HUGGING_FACE, &value);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].confidence(), Confidence::High);
}
#[test]
fn application_providers_reject_the_prefix_embedded_in_a_wider_identifier() {
let value = format!("legacyhf_{HUGGING_FACE_BODY}");
assert_eq!(detect(&HUGGING_FACE, &value).len(), 0);
}
#[test]
fn hf_rejects_every_embedding_shape_leading_trailing_or_dash_joined() {
let value = format!("hf_{HUGGING_FACE_BODY}");
assert!(detect(&HUGGING_FACE, &format!("legacy{value}")).is_empty());
assert!(detect(&HUGGING_FACE, &format!("{value}_backup")).is_empty());
assert!(detect(&HUGGING_FACE, &format!("{value}-1")).is_empty());
}
#[test]
fn application_providers_reject_a_percent_encoded_delimiter_lookalike() {
assert_eq!(
detect(&HUGGING_FACE, "hf%5FSYNTHETIC_REVOKED_CONFORMANCE_KEY").len(),
0
);
}
#[test]
fn application_providers_report_a_repeated_identical_value_once_per_occurrence() {
let value = format!("hf_{HUGGING_FACE_BODY}");
let input = format!("{value} {value}");
assert_eq!(detect(&HUGGING_FACE, &input).len(), 2);
}
#[test]
fn huggingface_rejects_a_body_one_byte_off_the_documented_length() {
for body in [
&HUGGING_FACE_BODY[..HUGGING_FACE_BODY.len() - 1],
&format!("{HUGGING_FACE_BODY}A"),
] {
let value = format!("hf_{body}");
assert_eq!(detect(&HUGGING_FACE, &value).len(), 0, "{value}");
}
}
#[test]
fn huggingface_rejects_a_documented_length_body_containing_underscore_or_dash() {
for byte in ['_', '-'] {
let mut body = HUGGING_FACE_BODY.to_string();
body.replace_range(4..5, &byte.to_string());
let value = format!("hf_{body}");
assert_eq!(detect(&HUGGING_FACE, &value).len(), 0, "{value}");
}
}
#[test]
fn huggingface_accepts_a_digit_bearing_documented_length_body() {
let mut body = HUGGING_FACE_BODY.to_string();
body.replace_range(0..2, "42");
let value = format!("hf_{body}");
assert_eq!(detect(&HUGGING_FACE, &value).len(), 1, "{value}");
}
#[test]
fn huggingface_organization_token_detects_the_api_org_prefix_at_the_documented_shape() {
let value = format!("api_org_{HUGGING_FACE_BODY}");
let candidates = detect(&HUGGING_FACE, &value);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "huggingface_token");
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
assert_eq!(
candidates[0].range(),
ByteRange::new(0, value.len()).unwrap()
);
let user_value = format!("hf_{HUGGING_FACE_BODY}");
assert_eq!(detect(&HUGGING_FACE, &user_value).len(), 1);
}
#[test]
fn huggingface_organization_token_and_user_token_are_both_reported_independently() {
let user_value = format!("hf_{HUGGING_FACE_BODY}");
let org_value = format!("api_org_{HUGGING_FACE_BODY}");
let input = format!("{user_value} {org_value}");
let candidates = detect(&HUGGING_FACE, &input);
assert_eq!(candidates.len(), 2);
assert_eq!(
candidates[0].range(),
ByteRange::new(0, user_value.len()).unwrap()
);
let org_start = input.find(&org_value).unwrap();
assert_eq!(
candidates[1].range(),
ByteRange::new(org_start, org_start + org_value.len()).unwrap()
);
}
#[test]
fn huggingface_organization_token_rejects_a_body_one_byte_off_the_documented_length() {
for body in [
&HUGGING_FACE_BODY[..HUGGING_FACE_BODY.len() - 1],
&format!("{HUGGING_FACE_BODY}A"),
] {
let value = format!("api_org_{body}");
assert_eq!(detect(&HUGGING_FACE, &value).len(), 0, "{value}");
}
}
#[test]
fn huggingface_organization_token_rejects_an_ordinary_non_conforming_identifier() {
for value in ["api_org_name", "api_org_id", "api_org_12345"] {
assert_eq!(detect(&HUGGING_FACE, value).len(), 0, "{value}");
}
}
#[test]
fn huggingface_organization_token_rejects_embedded_prefix_and_underscore_or_dash_in_body() {
let embedded = format!("legacyapi_org_{HUGGING_FACE_BODY}");
assert_eq!(detect(&HUGGING_FACE, &embedded).len(), 0);
for byte in ['_', '-'] {
let mut body = HUGGING_FACE_BODY.to_string();
body.replace_range(4..5, &byte.to_string());
let value = format!("api_org_{body}");
assert_eq!(detect(&HUGGING_FACE, &value).len(), 0, "{value}");
}
}
#[test]
fn huggingface_organization_token_rejects_every_embedding_shape_leading_trailing_or_dash_joined()
{
let value = format!("api_org_{HUGGING_FACE_BODY}");
assert!(detect(&HUGGING_FACE, &format!("legacy{value}")).is_empty());
assert!(detect(&HUGGING_FACE, &format!("{value}_backup")).is_empty());
assert!(detect(&HUGGING_FACE, &format!("{value}-1")).is_empty());
}
#[test]
fn huggingface_organization_token_accepts_a_digit_bearing_documented_length_body() {
let mut body = HUGGING_FACE_BODY.to_string();
body.replace_range(0..2, "42");
let value = format!("api_org_{body}");
assert_eq!(detect(&HUGGING_FACE, &value).len(), 1, "{value}");
}
fn digitalocean_tokens() -> [String; 3] {
[
format!("dop_v1_{DIGITALOCEAN_BODY}"),
format!("doo_v1_{DIGITALOCEAN_OAUTH_BODY}"),
format!("dor_v1_{DIGITALOCEAN_REFRESH_BODY}"),
]
}
#[test]
fn digitalocean_accepts_exactly_sixty_four_lowercase_hex_bytes_for_every_prefix() {
for token in digitalocean_tokens() {
assert_eq!(token.len(), 71);
let candidates = detect(&DIGITALOCEAN, &token);
assert_eq!(candidates.len(), 1, "{token}");
assert_eq!(candidates[0].type_name(), "digitalocean_token");
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
assert_eq!(candidates[0].range(), ByteRange::new(0, 71).unwrap());
}
}
#[test]
fn digitalocean_never_extracts_a_token_from_a_wider_identifier() {
for token in digitalocean_tokens() {
for input in [
format!("{token}0"),
format!("{token}_backup"),
format!("{token}-1"),
format!("x{token}"),
format!("legacy{token}"),
] {
assert!(detect(&DIGITALOCEAN, &input).is_empty(), "{input}");
}
}
}
#[test]
fn digitalocean_rejects_uppercase_hex_and_non_hex_bytes_inside_the_body() {
let token = format!("dop_v1_{DIGITALOCEAN_BODY}");
let body_at = |index: usize, replacement: &str| {
let at = "dop_v1_".len() + index;
format!("{}{replacement}{}", &token[..at], &token[at + 1..])
};
for input in [
body_at(8, "D"),
body_at(8, "g"),
body_at(8, " "),
body_at(63, "A"),
] {
assert!(detect(&DIGITALOCEAN, &input).is_empty(), "{input}");
}
}
#[test]
fn digitalocean_bounds_the_token_against_quotes_code_spans_and_urls() {
let token = format!("dop_v1_{DIGITALOCEAN_BODY}");
for (input, start) in [
(format!("\"{token}\""), 1),
(format!("`{token}`"), 1),
(format!("token: '{token}',"), 8),
(format!("https://example.test/?token={token}&x=1"), 28),
] {
let candidates = detect(&DIGITALOCEAN, &input);
assert_eq!(candidates.len(), 1, "{input}");
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + 71).unwrap(),
"{input}"
);
}
}
#[test]
fn digitalocean_rejects_wrong_and_encoded_prefixes_with_a_contracted_body() {
for input in [
format!("dov_v1_{DIGITALOCEAN_BODY}"),
format!("dop_v2_{DIGITALOCEAN_BODY}"),
format!("DOP_V1_{DIGITALOCEAN_BODY}"),
format!("dop%5Fv1%5F{DIGITALOCEAN_BODY}"),
] {
assert!(detect(&DIGITALOCEAN, &input).is_empty(), "{input}");
}
}
#[test]
fn pulumi_accepts_exactly_forty_lowercase_hex_bytes() {
let token = format!("pul-{PULUMI_BODY}");
assert_eq!(token.len(), 44);
let candidates = detect(&PULUMI, &token);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "pulumi_access_token");
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
assert_eq!(candidates[0].range(), ByteRange::new(0, 44).unwrap());
}
#[test]
fn pulumi_rejects_a_body_one_hex_byte_short_or_long_of_the_documented_length() {
for body in [
&PULUMI_BODY[..PULUMI_BODY.len() - 1],
&format!("{PULUMI_BODY}0"),
] {
let value = format!("pul-{body}");
assert_eq!(detect(&PULUMI, &value).len(), 0, "{value}");
}
}
#[test]
fn pulumi_rejects_uppercase_hex_and_non_hex_bytes_inside_the_body() {
let token = format!("pul-{PULUMI_BODY}");
let body_at = |index: usize, replacement: &str| {
let at = "pul-".len() + index;
format!("{}{replacement}{}", &token[..at], &token[at + 1..])
};
for input in [
body_at(8, "D"),
body_at(8, "g"),
body_at(8, " "),
body_at(39, "A"),
] {
assert!(detect(&PULUMI, &input).is_empty(), "{input}");
}
}
#[test]
fn pulumi_rejects_undocumented_near_miss_prefixes() {
for input in [
format!("pu-{PULUMI_BODY}"),
format!("pull-{PULUMI_BODY}"),
format!("pul_{PULUMI_BODY}"),
format!("pul{PULUMI_BODY}"),
format!("PUL-{PULUMI_BODY}"),
format!("legacypul-{PULUMI_BODY}"),
format!("pul%2D{PULUMI_BODY}"),
] {
assert!(detect(&PULUMI, &input).is_empty(), "{input}");
}
}
#[test]
fn pulumi_rejects_stack_project_and_version_identifiers_as_benign_controls() {
for input in [
"stack: myorg/my-infra-project/production",
"Updating (dev):\n pulumi:pulumi:Stack my-infra-project-dev running\nResources: 3 unchanged\nUpdate succeeded in 8s",
"Previewing update (staging)\n Type Name\n + pulumi:providers:aws default",
"pulumi version\nv3.142.0",
"PULUMI_ACCESS_TOKEN=pul-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
] {
assert!(detect(&PULUMI, input).is_empty(), "{input}");
}
}
#[test]
fn pulumi_bounds_the_token_against_quotes_code_spans_and_assignments() {
let token = format!("pul-{PULUMI_BODY}");
for (input, start) in [
(format!("\"{token}\""), 1),
(format!("`{token}`"), 1),
(
format!("PULUMI_ACCESS_TOKEN={token}"),
"PULUMI_ACCESS_TOKEN=".len(),
),
] {
let candidates = detect(&PULUMI, &input);
assert_eq!(candidates.len(), 1, "{input}");
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + token.len()).unwrap(),
"{input}"
);
}
}
}