use crate::detectors::pattern;
use crate::detectors::prefilter::Literals;
use crate::error::DetectorFailure;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};
const ANCHOR: &str = "Q~";
const PREFIX_LEN: usize = 3;
const MIN_SUFFIX_LEN: usize = 31;
const MAX_SUFFIX_LEN: usize = 34;
fn is_secret_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'~' | b'-')
}
pub(super) struct MicrosoftEntraClientSecretDetector;
impl Detector for MicrosoftEntraClientSecretDetector {
fn id(&self) -> &'static str {
"microsoft-entra-client-secret"
}
fn detect(
&self,
input: &str,
_context: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
let mut candidates = Vec::new();
for (start, end) in scan(input) {
let Some(range) = ByteRange::new(start, end) else {
continue;
};
candidates.push(
Candidate::built_in("microsoft_entra_client_secret", Confidence::High, range)
.with_specificity(Specificity::Provider)
.with_signal_pack(crate::types::signal_pack!(
"entra-digit-q-tilde-marker",
"bounded-opaque-suffix"
)),
);
}
Ok(candidates)
}
}
fn scan(input: &str) -> Vec<(usize, usize)> {
let bytes = input.as_bytes();
let Some(first) = pattern::find_literal(bytes, ANCHOR.as_bytes(), 0) else {
return Vec::new();
};
let mut ends = pattern::RunCursor::new(bytes, is_secret_byte);
let mut matches = Vec::new();
let mut anchor = first;
while anchor < bytes.len() {
if !bytes[anchor..].starts_with(ANCHOR.as_bytes()) {
anchor += 1;
continue;
}
let Some((start, end)) = match_at(bytes, &mut ends, anchor) else {
anchor += 1;
continue;
};
matches.push((start, end));
anchor = end;
}
matches
}
fn match_at(
bytes: &[u8],
ends: &mut pattern::RunCursor<'_>,
anchor: usize,
) -> Option<(usize, usize)> {
let digit_at = anchor.checked_sub(1)?;
let start = anchor.checked_sub(PREFIX_LEN + 1)?;
if !bytes[digit_at].is_ascii_digit() {
return None;
}
if !bytes[start..digit_at].iter().copied().all(is_secret_byte) {
return None;
}
let suffix_start = anchor + ANCHOR.len();
let available = ends.end(suffix_start) - suffix_start;
if !(MIN_SUFFIX_LEN..=MAX_SUFFIX_LEN).contains(&available) {
return None;
}
let end = suffix_start + available;
pattern::boundary_ok(bytes, start, end, is_secret_byte).then_some((start, end))
}
pub(super) const REQUIRED_LITERALS: &[Literals] = &[Literals::Strs(&[ANCHOR])];
#[cfg(test)]
mod tests {
use super::*;
const SUFFIX_32: &str = "SYNTHETIC_REVOKED_ENTRA_SECRET_V";
fn detect(input: &str) -> Vec<Candidate> {
MicrosoftEntraClientSecretDetector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
#[test]
fn detects_the_synthetic_fixture() {
let input = format!("abc8Q~{SUFFIX_32}");
let candidates = detect(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "microsoft_entra_client_secret");
assert_eq!(candidates[0].confidence(), Confidence::High);
assert_eq!(candidates[0].effective_specificity(), Specificity::Provider);
assert_eq!(
candidates[0].range(),
ByteRange::new(0, input.len()).unwrap()
);
}
#[test]
fn detects_at_the_minimum_and_maximum_suffix_length() {
for len in [31usize, 34] {
let suffix = "SYNTHETIC_REVOKED_ENTRA_SECRET_VALUE_PADDING_Z"
.chars()
.take(len)
.collect::<String>();
assert_eq!(suffix.len(), len);
let input = format!("abc8Q~{suffix}");
let candidates = detect(&input);
assert_eq!(candidates.len(), 1, "len={len}");
assert_eq!(
candidates[0].range(),
ByteRange::new(0, input.len()).unwrap(),
"len={len}"
);
}
}
#[test]
fn rejects_a_suffix_one_byte_below_the_minimum() {
let suffix = "SYNTHETIC_REVOKED_ENTRA_SECRET";
assert_eq!(suffix.len(), 30);
assert_eq!(detect(&format!("abc8Q~{suffix}")).len(), 0);
}
#[test]
fn rejects_a_suffix_one_byte_above_the_maximum_rather_than_truncating() {
let suffix = "SYNTHETIC_REVOKED_ENTRA_SECRET_VALUE_PADDING_Z"
.chars()
.take(35)
.collect::<String>();
assert_eq!(suffix.len(), 35);
assert_eq!(detect(&format!("abc8Q~{suffix}")).len(), 0);
}
#[test]
fn detects_a_secret_whose_leading_run_starts_or_contains_a_dash() {
for lead in ["-bc", "a-c", "--c"] {
let input = format!("{lead}8Q~{SUFFIX_32}");
let candidates = detect(&input);
assert_eq!(candidates.len(), 1, "lead={lead}");
assert_eq!(
candidates[0].range(),
ByteRange::new(0, input.len()).unwrap(),
"lead={lead}"
);
}
}
#[test]
fn finds_a_leading_dash_secret_after_an_assignment_or_quote() {
for prefix in ["AZURE_CLIENT_SECRET=", "secret: \"", "secret '"] {
let input = format!("{prefix}-bc8Q~{SUFFIX_32}");
let candidates = detect(&input);
assert_eq!(candidates.len(), 1, "prefix={prefix}");
assert_eq!(
candidates[0].range(),
ByteRange::new(prefix.len(), input.len()).unwrap(),
"prefix={prefix}"
);
}
}
#[test]
fn rejects_a_leading_run_joined_to_a_wider_dash_or_alphanumeric_token() {
for joined in ["x-bc8Q~", "--bc8Q~", "xabc8Q~"] {
assert_eq!(
detect(&format!("{joined}{SUFFIX_32}")).len(),
0,
"joined={joined}"
);
}
}
#[test]
fn rejects_a_non_digit_immediately_before_the_marker() {
assert_eq!(detect(&format!("abcXQ~{SUFFIX_32}")).len(), 0);
}
#[test]
fn rejects_an_anchor_too_close_to_the_start_of_input() {
assert_eq!(detect(&format!("8Q~{SUFFIX_32}")).len(), 0);
}
#[test]
fn rejects_a_suffix_broken_by_an_out_of_alphabet_byte() {
let broken = format!("{} {}", &SUFFIX_32[..10], &SUFFIX_32[11..]);
assert_eq!(detect(&format!("abc8Q~{broken}")).len(), 0);
}
#[test]
fn rejects_the_literal_q_tilde_with_no_preceding_digit() {
assert_eq!(detect("the Q~ notation is unrelated").len(), 0);
}
#[test]
fn rejects_a_digit_followed_by_q_without_the_tilde() {
assert_eq!(detect("build revision 8Qa2 shipped").len(), 0);
}
#[test]
fn finds_a_qualified_match_inside_surrounding_context() {
let input = format!("client_secret=abc8Q~{SUFFIX_32}");
let candidates = detect(&input);
assert_eq!(candidates.len(), 1);
let start = input.find("abc8Q~").unwrap();
assert_eq!(
candidates[0].range(),
ByteRange::new(start, input.len()).unwrap()
);
}
#[test]
fn finds_deterministic_findings_across_repeated_calls() {
let input = format!("abc8Q~{SUFFIX_32}");
assert_eq!(detect(&input), detect(&input));
}
#[test]
fn stays_bounded_over_a_long_run_of_rejected_anchors() {
let input = format!("abc8Q~{SUFFIX_32}!{}", "Q~".repeat(10_000));
let candidates = detect(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(
candidates[0].range(),
ByteRange::new(0, 6 + SUFFIX_32.len()).unwrap()
);
}
}