use super::text::lines;
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_LITERAL: &str = "key-";
const BODY_LEN: usize = 32;
const TRIPLET_SEGMENTS: [usize; 3] = [32, 8, 8];
const TRIPLET_LEN: usize = 50;
const TRIPLET_SEPARATOR_PAIRS: [&str; 16] = [
"0-", "1-", "2-", "3-", "4-", "5-", "6-", "7-", "8-", "9-", "a-", "b-", "c-", "d-", "e-", "f-",
];
const CONTEXT_KEYWORD: &str = "mailgun";
const BOUNDARY: Alphabet = pattern::is_alnum_dash;
fn line_has_context_keyword(line: &str) -> bool {
text::contains_ci(line, CONTEXT_KEYWORD)
}
fn is_triplet(run: &[u8]) -> bool {
if run.len() != TRIPLET_LEN {
return false;
}
let mut offset = 0usize;
for (index, width) in TRIPLET_SEGMENTS.iter().enumerate() {
if index > 0 {
if run[offset] != b'-' {
return false;
}
offset += 1;
}
if !run[offset..offset + width]
.iter()
.copied()
.all(pattern::is_lower_hex)
{
return false;
}
offset += width;
}
let first = run[0];
run.iter().any(|&byte| byte != b'-' && byte != first)
}
fn context_confidence(line: &str, start: usize) -> (Confidence, &'static str) {
if text::is_provider_named_assignment(line, start, &[CONTEXT_KEYWORD]) {
(Confidence::High, "mailgun-named-assignment")
} else {
(Confidence::Medium, "mailgun-keyword-cooccurrence")
}
}
pub(super) struct MailgunApiKeyDetector;
impl Detector for MailgunApiKeyDetector {
fn id(&self) -> &'static str {
"mailgun-api-key"
}
fn detect(
&self,
input: &str,
_context: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
let mut candidates = Vec::new();
for (line_start, line_end) in lines(input) {
let line = &input[line_start..line_end];
if !line_has_context_keyword(line) {
continue;
}
let bytes = line.as_bytes();
let literal = KEY_LITERAL.as_bytes();
let mut ends = pattern::RunCursor::new(bytes, pattern::is_lower_alnum);
let mut pos = 0usize;
while pos + literal.len() <= bytes.len() {
if &bytes[pos..pos + literal.len()] != literal {
pos += 1;
continue;
}
let body_start = pos + literal.len();
let body_end = ends.end(body_start);
if body_end - body_start == BODY_LEN
&& pattern::boundary_ok(bytes, pos, body_end, BOUNDARY)
&& !text::is_repeated_character_filler(&line[body_start..body_end])
&& let Some(range) = ByteRange::new(line_start + pos, line_start + body_end)
{
let (confidence, context_signal) = context_confidence(line, pos);
candidates.push(
Candidate::built_in("mailgun_api_key", confidence, range)
.with_specificity(Specificity::Provider)
.with_signals([context_signal, "documented-key-prefix"]),
);
}
pos += literal.len();
}
let mut start = 0usize;
while start < bytes.len() {
if !pattern::is_hex_or_dash(bytes[start]) {
start += 1;
continue;
}
let end = pattern::run_end(bytes, start, pattern::is_hex_or_dash);
if is_triplet(&bytes[start..end])
&& pattern::boundary_ok(bytes, start, end, BOUNDARY)
&& !text::is_non_credential_assignment(line, start)
&& let Some(range) = ByteRange::new(line_start + start, line_start + end)
{
let (confidence, context_signal) = context_confidence(line, start);
candidates.push(
Candidate::built_in("mailgun_api_key", confidence, range)
.with_specificity(Specificity::Provider)
.with_signals([context_signal, "hex-triplet-shape"]),
);
}
start = end;
}
}
Ok(candidates)
}
}
pub(super) const REQUIRED_LITERALS: &[Literals] = &[
Literals::Strs(&[KEY_LITERAL]),
Literals::Strs(&TRIPLET_SEPARATOR_PAIRS),
];
#[cfg(test)]
mod tests {
use super::*;
const BODY: &str = "abcdefghijklmnopqrstuvwxyz012345";
const _: () = assert!(BODY.len() == BODY_LEN);
fn key() -> String {
format!("{KEY_LITERAL}{BODY}")
}
fn detect(input: &str) -> Vec<Candidate> {
MailgunApiKeyDetector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
const TRIPLET: &str = concat!("0123456789abcdef0123456789abcdef", "-01234567", "-89abcdef");
const _: () = assert!(TRIPLET.len() == TRIPLET_LEN);
#[test]
fn detects_the_prefix_less_triplet_alongside_a_mailgun_keyword() {
for (input, confidence) in [
(format!("MAILGUN_API_KEY={TRIPLET}"), Confidence::High),
(format!("mailgun private key {TRIPLET}"), Confidence::Medium),
(
format!("{{\"mailgunSigningKey\": \"{TRIPLET}\"}}"),
Confidence::High,
),
] {
let candidates = detect(&input);
assert_eq!(candidates.len(), 1, "{input}");
assert_eq!(candidates[0].type_name(), "mailgun_api_key");
assert_eq!(candidates[0].confidence(), confidence, "{input}");
let start = input.find(TRIPLET).unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, start + TRIPLET.len()).unwrap()
);
}
}
#[test]
fn rejects_triplet_near_misses() {
let upper = TRIPLET.to_ascii_uppercase();
let short = TRIPLET[1..].to_owned();
let long = format!("{TRIPLET}0");
let shifted = format!("{}-{}", &TRIPLET[..31], &TRIPLET[32..]);
let filler = format!("{}-{}-{}", "0".repeat(32), "0".repeat(8), "0".repeat(8));
for value in [upper, short, long, shifted, filler] {
let input = format!("mailgun {value}");
assert!(detect(&input).is_empty(), "{input}");
}
assert!(detect(TRIPLET).is_empty());
assert!(detect(&format!("MAILGUN_KEY_ID={TRIPLET}")).is_empty());
assert!(detect(&format!("mailgun x-{TRIPLET}")).is_empty());
}
#[test]
fn detects_the_key_alongside_a_mailgun_keyword() {
for input in [
format!("MAILGUN_API_KEY={}", key()),
format!("mailgun.api_key: {}", key()),
format!("# Mailgun private API key: {}", key()),
format!("{{\"mailgunApiKey\": \"{}\"}}", key()),
] {
let candidates = detect(&input);
assert_eq!(candidates.len(), 1, "{input}");
assert_eq!(candidates[0].type_name(), "mailgun_api_key");
let expected = if input.starts_with('#') {
Confidence::Medium
} else {
Confidence::High
};
assert_eq!(candidates[0].confidence(), expected, "{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 detects_a_webhook_signing_key_named_field_alongside_the_keyword() {
let input = format!("mailgun http_signing_key={}", key());
let candidates = detect(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "mailgun_api_key");
}
#[test]
fn rejects_a_bare_value_with_no_context() {
assert!(detect(&key()).is_empty());
}
#[test]
fn rejects_context_on_a_different_line() {
let input = format!("# mailgun\n{}\n", key());
assert!(detect(&input).is_empty());
}
#[test]
fn matches_the_keyword_case_insensitively() {
let input = format!("MailGun {}", key());
assert_eq!(detect(&input).len(), 1);
}
#[test]
fn rejects_a_body_one_byte_short_of_the_required_length() {
let short = &BODY[..BODY_LEN - 1];
assert!(detect(&format!("mailgun {KEY_LITERAL}{short}")).is_empty());
}
#[test]
fn rejects_a_body_one_byte_longer_than_the_required_length_rather_than_truncating() {
let long = format!("{BODY}0");
assert!(detect(&format!("mailgun {KEY_LITERAL}{long}")).is_empty());
}
#[test]
fn rejects_an_uppercase_body() {
let upper = BODY.to_ascii_uppercase();
assert!(detect(&format!("mailgun {KEY_LITERAL}{upper}")).is_empty());
}
#[test]
fn rejects_a_masked_repeated_character_body() {
assert!(detect(&format!("mailgun {KEY_LITERAL}{}", "0".repeat(BODY_LEN))).is_empty());
}
#[test]
fn rejects_an_environment_variable_reference() {
assert!(detect("mailgun MAILGUN_API_KEY=${MAILGUN_API_KEY}").is_empty());
}
#[test]
fn rejects_the_public_validation_key_shape() {
assert!(detect(&format!("mailgun pubkey-{BODY}")).is_empty());
}
#[test]
fn rejects_a_key_embedded_in_a_wider_identifier() {
let value = key();
assert!(detect(&format!("mailgun x{value}")).is_empty());
assert!(detect(&format!("mailgun {value}x")).is_empty());
assert!(detect(&format!("mailgun {value}-1")).is_empty());
}
#[test]
fn finds_a_match_across_crlf_and_a_unicode_prefix() {
let input = format!("# \u{1F511} caf\u{e9}\r\nmailgun {}\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!("mailgun {}", key());
assert_eq!(detect(&input), detect(&input));
}
#[test]
fn every_candidate_on_a_context_bearing_line_is_reported() {
let input = format!("mailgun {} {}", key(), key());
let candidates = detect(&input);
assert_eq!(candidates.len(), 2);
assert!(
candidates
.iter()
.all(|candidate| candidate.confidence() == Confidence::Medium)
);
}
#[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(), 0);
}
}