use crate::detectors::additional_providers::STRIPE;
use crate::detectors::pattern;
use crate::detectors::prefilter::Literals;
use crate::detectors::text;
use crate::error::DetectorFailure;
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext, Specificity};
const WEBHOOK_PREFIX: &str = "whsec_";
const WEBHOOK_TYPE: &str = "stripe_webhook_signing_secret";
const WEBHOOK_SIGNALS: [&str; 2] = ["stripe-documented-prefix", "webhook-base64-body"];
const WEBHOOK_BODY_MIN: usize = 32;
const WEBHOOK_MAX_PADDING: usize = 2;
const BOUNDARY: pattern::Alphabet = pattern::is_alnum_dash;
fn is_base64_body(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'+' || byte == b'/'
}
pub(super) struct StripeTokenDetector;
impl Detector for StripeTokenDetector {
fn id(&self) -> &str {
STRIPE.id()
}
fn detect(
&self,
input: &str,
context: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
let mut candidates = STRIPE.detect(input, context)?;
candidates.retain(|candidate| {
let range = candidate.range();
!has_filler_body(&input[range.start()..range.end()])
});
for (start, end) in scan_webhook(input) {
if has_filler_body(&input[start..end]) {
continue;
}
let Some(range) = ByteRange::new(start, end) else {
continue;
};
candidates.push(
Candidate::built_in(WEBHOOK_TYPE, Confidence::High, range)
.with_specificity(Specificity::Provider)
.with_signals(WEBHOOK_SIGNALS),
);
}
super::sort_candidates_by_start(&mut candidates);
Ok(candidates)
}
}
fn has_filler_body(value: &str) -> bool {
value
.rsplit_once('_')
.is_some_and(|(_, body)| text::is_repeated_character_filler(body.trim_end_matches('=')))
}
fn scan_webhook(input: &str) -> Vec<(usize, usize)> {
let bytes = input.as_bytes();
let Some(first) = pattern::find_literal(bytes, WEBHOOK_PREFIX.as_bytes(), 0) else {
return Vec::new();
};
let mut body_ends = pattern::RunCursor::new(bytes, is_base64_body);
let mut matches = Vec::new();
let mut start = first;
while start < bytes.len() {
if !bytes[start..].starts_with(WEBHOOK_PREFIX.as_bytes()) {
start += 1;
continue;
}
let body_start = start + WEBHOOK_PREFIX.len();
let body_end = body_ends.end(body_start);
if body_end - body_start < WEBHOOK_BODY_MIN {
start += 1;
continue;
}
let padding = bytes[body_end..]
.iter()
.take(WEBHOOK_MAX_PADDING)
.take_while(|&&byte| byte == b'=')
.count();
let end = body_end + padding;
if pattern::boundary_ok(bytes, start, end, BOUNDARY) {
matches.push((start, end));
}
start = end;
}
matches
}
pub(super) const REQUIRED_LITERALS: &[Literals] = &[
Literals::Shapes(STRIPE.shapes()),
Literals::Strs(&[WEBHOOK_PREFIX]),
];
#[cfg(test)]
mod tests {
use super::*;
const BODY: &str = "SYNTHETICREVOKEDWEBHOOKSECRET012";
const _: () = assert!(BODY.len() == WEBHOOK_BODY_MIN);
fn detect(input: &str) -> Vec<Candidate> {
StripeTokenDetector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
fn ranges(input: &str) -> Vec<(usize, usize)> {
detect(input)
.iter()
.map(|candidate| (candidate.range().start(), candidate.range().end()))
.collect()
}
#[test]
fn detects_a_webhook_secret_with_its_own_type_and_metadata() {
let input = format!("whsec_{BODY}");
let candidates = detect(&input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), WEBHOOK_TYPE);
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 applies_the_thirty_two_byte_floor() {
let one_short = format!("whsec_{}", &BODY[..WEBHOOK_BODY_MIN - 1]);
assert!(ranges(&one_short).is_empty());
let longer = format!("whsec_{BODY}0123456789");
assert_eq!(ranges(&longer), vec![(0, longer.len())]);
}
#[test]
fn admits_base64_symbols_and_up_to_two_padding_bytes() {
for tail in ["+", "/", "+/+/", "=", "=="] {
let input = format!("whsec_{BODY}{tail}");
assert_eq!(ranges(&input), vec![(0, input.len())], "{tail}");
}
let symbolic = format!("whsec_{}+{}/", &BODY[..16], &BODY[16..]);
assert_eq!(ranges(&symbolic), vec![(0, symbolic.len())]);
}
#[test]
fn a_third_padding_byte_is_left_outside_the_match() {
let input = format!("whsec_{BODY}===");
assert_eq!(ranges(&input), vec![(0, input.len() - 1)]);
}
#[test]
fn rejects_a_value_embedded_in_a_wider_identifier() {
for input in [
format!("legacywhsec_{BODY}"),
format!("_whsec_{BODY}"),
format!("whsec_{BODY}_backup"),
format!("whsec_{BODY}-1"),
] {
assert!(ranges(&input).is_empty(), "{input}");
}
}
#[test]
fn rejects_separator_near_misses_masks_and_references() {
for input in [
format!("whsec{BODY}"),
format!("whsec-{BODY}"),
format!("wh_sec_{BODY}"),
"whsec_********************************".to_string(),
"whsec_${STRIPE_WEBHOOK_SECRET}".to_string(),
"whsec_...".to_string(),
] {
assert!(ranges(&input).is_empty(), "{input}");
}
}
#[test]
fn public_identifiers_and_signature_digests_stay_clean() {
for input in [
"we_1SYNTHETICENDPOINTID",
"evt_1SYNTHETICEVENTIDENTIFIER",
"pk_live_SYNTHETICREVOKEDPUBLISHABLE",
"t=1700000000,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd",
] {
assert!(ranges(input).is_empty(), "{input}");
}
}
#[test]
fn key_and_webhook_shapes_stay_distinct_and_ordered_in_one_input() {
let input = format!("whsec_{BODY}\nsk_live_SYNTHETICREVOKEDSYNTHETIC");
let candidates = detect(&input);
let types: Vec<&str> = candidates.iter().map(Candidate::type_name).collect();
assert_eq!(types, vec![WEBHOOK_TYPE, "stripe_credential"]);
let reversed = format!("sk_live_SYNTHETICREVOKEDSYNTHETIC\nwhsec_{BODY}");
let candidates = detect(&reversed);
let types: Vec<&str> = candidates.iter().map(Candidate::type_name).collect();
assert_eq!(types, vec!["stripe_credential", WEBHOOK_TYPE]);
}
#[test]
fn reports_each_rolling_secret_once() {
let input = format!("whsec_{BODY} whsec_{BODY}");
let second = 6 + BODY.len() + 1;
assert_eq!(
ranges(&input),
vec![(0, 6 + BODY.len()), (second, second + 6 + BODY.len())]
);
}
#[test]
fn rejects_a_repeated_filler_body_behind_any_prefix() {
for input in [
format!("sk_test_{}", "x".repeat(24)),
format!("sk_live_{}", "X".repeat(32)),
format!("rk_test_{}", "0".repeat(20)),
format!("whsec_{}", "x".repeat(32)),
format!("whsec_{}==", "A".repeat(32)),
] {
assert!(detect(&input).is_empty(), "{input}");
}
let real = format!("sk_test_{BODY}");
assert_eq!(ranges(&real), vec![(0, real.len())]);
}
}