use crate::detectors::pattern::{self, Alphabet};
use crate::detectors::prefilter::Literals;
use crate::detectors::text;
use crate::error::DetectorFailure;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};
const KEY_HEX_LEN: usize = 32;
const DATACENTER_LITERAL: &str = "-us";
const MIN_DATACENTER_DIGITS: usize = 1;
const MAX_DATACENTER_DIGITS: usize = 3;
const CONTEXT_KEYWORD: &str = "mailchimp";
const BOUNDARY: Alphabet = pattern::is_alnum_dash;
fn is_key_hex(byte: u8) -> bool {
byte.is_ascii_hexdigit()
}
fn line_has_context_keyword(line: &str) -> bool {
text::contains_ci(line, CONTEXT_KEYWORD)
}
fn match_datacenter_suffix(bytes: &[u8], hex_end: usize) -> Option<usize> {
let literal = DATACENTER_LITERAL.as_bytes();
let literal_end = hex_end + literal.len();
if literal_end > bytes.len() || &bytes[hex_end..literal_end] != literal {
return None;
}
let mut digits_end = literal_end;
while digits_end < bytes.len() && bytes[digits_end].is_ascii_digit() {
digits_end += 1;
}
let digit_count = digits_end - literal_end;
(MIN_DATACENTER_DIGITS..=MAX_DATACENTER_DIGITS)
.contains(&digit_count)
.then_some(digits_end)
}
fn is_non_credential_structure(bytes: &[u8], start: usize, end: usize) -> bool {
let dns_label =
bytes.get(end) == Some(&b'.') && bytes.get(end + 1).is_some_and(u8::is_ascii_alphanumeric);
let path_segment = start > 0 && bytes[start - 1] == b'/';
dns_label || path_segment
}
pub(super) struct MailchimpMarketingApiKeyDetector;
impl Detector for MailchimpMarketingApiKeyDetector {
fn id(&self) -> &'static str {
"mailchimp-api-key"
}
fn detect(
&self,
input: &str,
_context: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
let mut candidates = Vec::new();
text::for_each_long_run_line(input, |line_start, line_end| {
let line = &input[line_start..line_end];
let has_keyword = line_has_context_keyword(line);
let bytes = line.as_bytes();
let mut start = 0usize;
while start < bytes.len() {
if !is_key_hex(bytes[start]) {
start += 1;
continue;
}
let hex_end = pattern::run_end(bytes, start, is_key_hex);
if hex_end - start == KEY_HEX_LEN
&& let Some(full_end) = match_datacenter_suffix(bytes, hex_end)
&& pattern::boundary_ok(bytes, start, full_end, BOUNDARY)
&& !text::is_repeated_character_filler(&line[start..hex_end])
&& (has_keyword || !is_non_credential_structure(bytes, start, full_end))
&& let Some(range) = ByteRange::new(line_start + start, line_start + full_end)
{
let identifier_position = is_non_credential_structure(bytes, start, full_end);
let (confidence, context_signal) = if has_keyword
&& text::is_provider_named_assignment(line, start, &[CONTEXT_KEYWORD])
{
(Confidence::High, "mailchimp-named-assignment")
} else if !identifier_position {
(Confidence::High, "mailchimp-suffix-shape")
} else {
(Confidence::Medium, "mailchimp-keyword-cooccurrence")
};
candidates.push(
Candidate::built_in("mailchimp_api_key", confidence, range)
.with_specificity(Specificity::Provider)
.with_signals([context_signal, "documented-datacenter-suffix"]),
);
}
start = hex_end;
}
});
Ok(candidates)
}
}
pub(super) const REQUIRED_LITERALS: &[Literals] = &[Literals::Strs(&[DATACENTER_LITERAL])];
#[cfg(test)]
mod tests {
use super::*;
const KEY_HEX: &str = "0123456789abcdef0123456789abcdef";
const _: () = assert!(KEY_HEX.len() == KEY_HEX_LEN);
fn key() -> String {
format!("{KEY_HEX}-us6")
}
fn detect(input: &str) -> Vec<Candidate> {
MailchimpMarketingApiKeyDetector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
#[test]
fn detects_the_key_alongside_a_mailchimp_keyword() {
for input in [
format!("MAILCHIMP_API_KEY={}", key()),
format!("mailchimp.api_key: {}", key()),
format!("# Mailchimp API key: {}", key()),
format!("{{\"mailchimpApiKey\": \"{}\"}}", key()),
] {
let candidates = detect(&input);
assert_eq!(candidates.len(), 1, "{input}");
assert_eq!(candidates[0].type_name(), "mailchimp_api_key");
assert_eq!(candidates[0].confidence(), Confidence::High, "{input}");
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
let start = input.rfind(&key()).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + key().len()).unwrap()
);
}
}
#[test]
fn accepts_a_two_digit_datacenter_suffix() {
let value = format!("{KEY_HEX}-us21");
let input = format!("mailchimp {value}");
let candidates = detect(&input);
assert_eq!(candidates.len(), 1);
let start = input.rfind(&value).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + value.len()).unwrap()
);
}
#[test]
fn reports_the_complete_shape_with_no_keyword_at_high() {
for input in [
key(),
format!("# mailchimp\n{}\n", key()),
format!("auth=(\"anystring\", \"{}\"),", key()),
format!("> Authorization: apikey {}", key()),
format!("The key in the runbook is {}. Revoked?", key()),
] {
let candidates = detect(&input);
assert_eq!(candidates.len(), 1, "{input}");
let range = candidates[0].range();
assert_eq!(&input[range.start()..range.end()], key());
assert_eq!(candidates[0].confidence(), Confidence::High, "{input}");
assert!(
candidates[0]
.signals()
.iter()
.any(|signal| signal == "mailchimp-suffix-shape"),
"{input}"
);
}
}
#[test]
fn keyword_free_benign_twins_stay_silent() {
for input in [
KEY_HEX.to_owned(),
"0123abcd-89ab-cdef-0123-456789abcdef".to_owned(),
format!("request_id={KEY_HEX}"),
format!("{KEY_HEX}-us-east-1"),
format!("bucket {KEY_HEX}-us"),
format!("{KEY_HEX}-us1234"),
format!("https://{}.cdn.example.test/a.png", key()),
format!("GET /v1/objects/{} HTTP/1.1", key()),
format!("x{}", key()),
format!("{}-us6", &KEY_HEX[1..]),
] {
assert!(detect(&input).is_empty(), "{input}");
}
for input in [
format!("mailchimp https://{}.cdn.example.test", key()),
format!("mailchimp GET /v1/objects/{}", key()),
] {
let candidates = detect(&input);
assert_eq!(candidates.len(), 1, "{input}");
assert_eq!(candidates[0].confidence(), Confidence::Medium, "{input}");
}
}
#[test]
fn matches_the_keyword_case_insensitively() {
let input = format!("MailChimp {}", key());
assert_eq!(detect(&input).len(), 1);
}
#[test]
fn rejects_a_bare_hex_body_with_no_datacenter_suffix() {
assert!(detect(&format!("mailchimp {KEY_HEX}")).is_empty());
}
#[test]
fn rejects_a_suffix_with_no_preceding_hex_body() {
assert!(detect("mailchimp -us6").is_empty());
}
#[test]
fn rejects_a_wrong_datacenter_literal() {
assert!(detect(&format!("mailchimp {KEY_HEX}-eu6")).is_empty());
}
#[test]
fn accepts_a_three_digit_datacenter_suffix() {
let value = format!("{KEY_HEX}-us123");
let input = format!("mailchimp {value}");
let candidates = detect(&input);
assert_eq!(candidates.len(), 1);
let start = input.rfind(&value).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + value.len()).unwrap()
);
}
#[test]
fn rejects_a_four_digit_datacenter_suffix() {
assert!(detect(&format!("mailchimp {KEY_HEX}-us1234")).is_empty());
}
#[test]
fn rejects_a_hex_body_one_byte_short_of_the_required_length() {
let short = &KEY_HEX[..KEY_HEX_LEN - 1];
assert!(detect(&format!("mailchimp {short}-us6")).is_empty());
}
#[test]
fn rejects_a_hex_body_one_byte_longer_than_the_required_length_rather_than_truncating() {
let long = format!("{KEY_HEX}0");
assert!(detect(&format!("mailchimp {long}-us6")).is_empty());
}
#[test]
fn accepts_an_uppercase_or_mixed_case_hex_body() {
let upper = KEY_HEX.to_ascii_uppercase();
let mixed = format!("{}{}", &KEY_HEX[..16], &upper[16..]);
for body in [upper, mixed] {
let value = format!("{body}-us6");
let input = format!("mailchimp {value}");
let candidates = detect(&input);
assert_eq!(candidates.len(), 1, "{input}");
let start = input.rfind(&value).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + value.len()).unwrap()
);
}
}
#[test]
fn rejects_a_non_hex_letter_in_the_body() {
let body = format!("{}z{}", &KEY_HEX[..16], &KEY_HEX[17..]);
assert!(detect(&format!("mailchimp {body}-us6")).is_empty());
}
#[test]
fn rejects_a_masked_repeated_character_body() {
assert!(detect(&format!("mailchimp {}-us1", "0".repeat(KEY_HEX_LEN))).is_empty());
}
#[test]
fn rejects_an_environment_variable_reference() {
assert!(detect("mailchimp MAILCHIMP_API_KEY=${MAILCHIMP_API_KEY}").is_empty());
}
#[test]
fn rejects_an_audience_id_reference() {
assert!(detect("mailchimp list_id: a1b2c3d4e5").is_empty());
}
#[test]
fn rejects_a_key_embedded_in_a_wider_identifier() {
let value = key();
assert!(detect(&format!("mailchimp x{value}")).is_empty());
assert!(detect(&format!("mailchimp {value}x")).is_empty());
assert!(detect(&format!("mailchimp {value}-1")).is_empty());
}
#[test]
fn finds_a_match_across_crlf_and_a_unicode_prefix() {
let input = format!("# \u{1F511} caf\u{e9}\r\nmailchimp {}\r\n", key());
let candidates = detect(&input);
assert_eq!(candidates.len(), 1);
let start = input.rfind(&key()).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + key().len()).unwrap()
);
}
#[test]
fn finds_deterministic_findings_across_repeated_calls() {
let input = format!("mailchimp {}", key());
assert_eq!(detect(&input), detect(&input));
}
#[test]
fn every_candidate_on_a_context_bearing_line_is_reported() {
let input = format!("mailchimp {} {}", key(), key());
let candidates = detect(&input);
assert_eq!(candidates.len(), 2);
assert!(
candidates
.iter()
.all(|candidate| candidate.confidence() == Confidence::High)
);
}
#[test]
fn stays_bounded_over_a_long_context_free_line_packed_with_candidates() {
let input = format!("{} ", key()).repeat(10_000);
assert_eq!(detect(&input).len(), 10_000);
let near_misses = format!("{KEY_HEX}-us ").repeat(10_000);
assert!(detect(&near_misses).is_empty());
}
}