use std::cell::RefCell;
use std::marker::PhantomData;
use std::rc::Rc;
use super::pattern::PrefixShape;
const PAIR_SET_BITS: usize = 1024;
const PAIR_SLOT_SHIFT: u32 = u32::BITS - PAIR_SET_BITS.trailing_zeros();
const PAIR_TABLE_WORDS: usize = (1 << 16) / 64;
const EXACT_PAIRS_FROM: usize = 4 * 1024;
fn pair_slot(first: u8, second: u8) -> usize {
let pair = u32::from(u16::from_le_bytes([first, second]));
(pair.wrapping_mul(0x9E37_79B1) >> PAIR_SLOT_SHIFT) as usize
}
const fn pair_index(first: u8, second: u8) -> usize {
((first as usize) << 8) | second as usize
}
pub(crate) struct PairSet {
bits: [u64; PAIR_SET_BITS / 64],
}
impl PairSet {
pub(crate) fn of(text: &[u8]) -> Self {
let mut bits = [0u64; PAIR_SET_BITS / 64];
for pair in text.windows(2) {
let slot = pair_slot(pair[0], pair[1]);
bits[slot / 64] |= 1 << (slot % 64);
}
Self { bits }
}
fn may_contain(&self, first: u8, second: u8) -> bool {
let slot = pair_slot(first, second);
self.bits[slot / 64] & (1 << (slot % 64)) != 0
}
fn may_contain_literal(&self, literal: &[u8]) -> bool {
literal
.windows(2)
.all(|pair| self.may_contain(pair[0], pair[1]))
}
}
struct PairTable {
bits: [u64; PAIR_TABLE_WORDS],
}
impl PairTable {
fn of(text: &[u8]) -> Box<Self> {
let mut table = Box::new(Self {
bits: [0; PAIR_TABLE_WORDS],
});
for pair in text.windows(2) {
let index = pair_index(pair[0], pair[1]);
table.bits[index / 64] |= 1 << (index % 64);
}
table
}
const fn contains(&self, first: u8, second: u8) -> bool {
let index = pair_index(first, second);
self.bits[index / 64] & (1 << (index % 64)) != 0
}
fn may_contain_literal(&self, literal: &[u8]) -> bool {
literal
.windows(2)
.all(|pair| self.contains(pair[0], pair[1]))
}
}
enum Pairs {
Hashed(PairSet),
Exact(Box<PairTable>),
}
impl Pairs {
fn of(text: &[u8]) -> Self {
if text.len() < EXACT_PAIRS_FROM {
Self::Hashed(PairSet::of(text))
} else {
Self::Exact(PairTable::of(text))
}
}
fn may_contain_literal(&self, literal: &[u8]) -> bool {
match self {
Self::Hashed(pairs) => pairs.may_contain_literal(literal),
Self::Exact(pairs) => pairs.may_contain_literal(literal),
}
}
}
#[derive(Clone, Copy)]
pub(super) enum Literals {
Bytes(&'static [&'static [u8]]),
Strs(&'static [&'static str]),
Prefixes(&'static [(&'static str, &'static str)]),
Shapes(&'static [PrefixShape<'static>]),
}
impl Literals {
fn for_each(self, visit: &mut dyn FnMut(&'static [u8])) {
match self {
Self::Bytes(literals) => literals.iter().for_each(|literal| visit(literal)),
Self::Strs(literals) => literals
.iter()
.for_each(|literal| visit(literal.as_bytes())),
Self::Prefixes(pairs) => pairs
.iter()
.for_each(|(prefix, _)| visit(prefix.as_bytes())),
Self::Shapes(shapes) => shapes
.iter()
.for_each(|shape| visit(shape.prefix.as_bytes())),
}
}
}
#[derive(Clone, Copy)]
pub(crate) struct RequiredLiterals {
groups: &'static [Literals],
}
impl std::fmt::Debug for RequiredLiterals {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RequiredLiterals").finish_non_exhaustive()
}
}
impl RequiredLiterals {
pub(super) fn any_of(groups: &'static [Literals]) -> Option<Self> {
let mut count = 0usize;
let mut too_short = false;
for group in groups {
group.for_each(&mut |literal| {
count += 1;
too_short |= literal.len() < 2;
});
}
(count > 0 && !too_short).then_some(Self { groups })
}
fn for_each(self, visit: &mut dyn FnMut(&'static [u8])) {
for group in self.groups {
group.for_each(visit);
}
}
#[cfg(test)]
pub(crate) fn literals(self) -> Vec<&'static [u8]> {
let mut literals = Vec::new();
self.for_each(&mut |literal| literals.push(literal));
literals
}
}
const SLOT_WORDS: usize = 4;
const MAX_SLOTS: usize = SLOT_WORDS * 64;
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct SlotSet {
bits: [u64; SLOT_WORDS],
}
impl SlotSet {
fn insert(&mut self, slot: usize) {
self.bits[slot / 64] |= 1 << (slot % 64);
}
pub(crate) fn contains(&self, slot: usize) -> bool {
slot < MAX_SLOTS && self.bits[slot / 64] & (1 << (slot % 64)) != 0
}
fn is_subset_of(&self, other: &Self) -> bool {
self.bits
.iter()
.zip(&other.bits)
.all(|(mine, theirs)| mine & !theirs == 0)
}
fn len(&self) -> u32 {
self.bits.iter().map(|word| word.count_ones()).sum()
}
}
#[derive(Clone, Copy)]
struct Entry {
literal: &'static [u8],
slot: u16,
}
pub(crate) struct LiteralMatcher {
leads: Box<[u64; PAIR_TABLE_WORDS]>,
ranks: Box<[u32; PAIR_TABLE_WORDS]>,
entries: Box<[Entry]>,
groups: Box<[Group]>,
declared: SlotSet,
}
#[derive(Clone, Copy)]
struct Group {
start: u32,
end: u32,
slots: SlotSet,
}
impl std::fmt::Debug for LiteralMatcher {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LiteralMatcher").finish_non_exhaustive()
}
}
impl LiteralMatcher {
pub(crate) fn compile<'a>(
declarations: impl IntoIterator<Item = Option<&'a RequiredLiterals>>,
) -> Option<Self> {
let mut entries = Vec::new();
let mut declared = SlotSet::default();
for (slot, required) in declarations.into_iter().enumerate() {
let Some(required) = required else {
continue;
};
let Ok(slot_id) = u16::try_from(slot) else {
return None;
};
if slot >= MAX_SLOTS {
return None;
}
declared.insert(slot);
required.for_each(&mut |literal| {
entries.push(Entry {
literal,
slot: slot_id,
});
});
}
let lead = |entry: &Entry| pair_index(entry.literal[0], entry.literal[1]);
entries.sort_by_key(|entry| (lead(entry), entry.slot));
let mut leads = Box::new([0u64; PAIR_TABLE_WORDS]);
let mut groups: Vec<Group> = Vec::new();
let mut last_pair = None;
for (index, entry) in entries.iter().enumerate() {
let pair = lead(entry);
let index = u32::try_from(index).ok()?;
if last_pair == Some(pair) {
if let Some(group) = groups.last_mut() {
group.end = index + 1;
group.slots.insert(usize::from(entry.slot));
}
} else {
leads[pair / 64] |= 1 << (pair % 64);
let mut slots = SlotSet::default();
slots.insert(usize::from(entry.slot));
groups.push(Group {
start: index,
end: index + 1,
slots,
});
last_pair = Some(pair);
}
}
let mut ranks = Box::new([0u32; PAIR_TABLE_WORDS]);
let mut seen = 0u32;
for (rank, word) in ranks.iter_mut().zip(leads.iter()) {
*rank = seen;
seen += word.count_ones();
}
Some(Self {
leads,
ranks,
entries: entries.into_boxed_slice(),
groups: groups.into_boxed_slice(),
declared,
})
}
fn group(&self, lead: usize) -> &Group {
let word = lead / 64;
let below = self.leads[word] & ((1u64 << (lead % 64)) - 1);
&self.groups[self.ranks[word] as usize + below.count_ones() as usize]
}
pub(crate) fn present(&self, text: &[u8]) -> SlotSet {
let mut present = SlotSet::default();
let mut remaining = self.declared.len();
if remaining == 0 {
return present;
}
for (offset, pair) in text.windows(2).enumerate() {
let lead = pair_index(pair[0], pair[1]);
if self.leads[lead / 64] & (1 << (lead % 64)) == 0 {
continue;
}
let group = self.group(lead);
if group.slots.is_subset_of(&present) {
continue;
}
let rest = &text[offset..];
for entry in &self.entries[group.start as usize..group.end as usize] {
let slot = usize::from(entry.slot);
if !present.contains(slot) && rest.starts_with(entry.literal) {
present.insert(slot);
remaining -= 1;
if remaining == 0 {
return present;
}
}
}
}
present
}
}
struct ActiveScan {
start: usize,
len: usize,
pairs: Option<Pairs>,
long_run_lines: Option<Rc<[(usize, usize)]>>,
provider_words: Option<u8>,
}
thread_local! {
static ACTIVE_SCAN: RefCell<Option<ActiveScan>> = const { RefCell::new(None) };
}
pub(crate) struct ScanScope {
previous: Option<ActiveScan>,
_not_send: PhantomData<*const ()>,
}
impl ScanScope {
pub(crate) fn enter(scanned: &str) -> Self {
let active = ActiveScan {
start: scanned.as_ptr() as usize,
len: scanned.len(),
pairs: None,
long_run_lines: None,
provider_words: None,
};
let previous = ACTIVE_SCAN
.try_with(|cell| {
cell.try_borrow_mut()
.ok()
.and_then(|mut current| current.replace(active))
})
.ok()
.flatten();
Self {
previous,
_not_send: PhantomData,
}
}
}
impl Drop for ScanScope {
fn drop(&mut self) {
let previous = self.previous.take();
let _ = ACTIVE_SCAN.try_with(|cell| {
if let Ok(mut current) = cell.try_borrow_mut() {
*current = previous;
}
});
}
}
pub(crate) fn ruleset_literal_may_occur(input: &str, literal: &[u8]) -> bool {
if literal.len() < 2 {
return true;
}
ACTIVE_SCAN
.try_with(|cell| {
let Ok(mut current) = cell.try_borrow_mut() else {
return true;
};
match current.as_mut() {
Some(active)
if active.start == input.as_ptr() as usize && active.len == input.len() =>
{
active
.pairs
.get_or_insert_with(|| Pairs::of(input.as_bytes()))
.may_contain_literal(literal)
}
_ => true,
}
})
.unwrap_or(true)
}
#[cfg(test)]
thread_local! {
static FORCE_BYPASS_LONG_RUN_INDEX: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub(super) fn long_run_lines(input: &str) -> Option<Rc<[(usize, usize)]>> {
ACTIVE_SCAN
.try_with(|cell| {
let mut current = cell.try_borrow_mut().ok()?;
let active = current.as_mut()?;
if active.start != input.as_ptr() as usize || active.len != input.len() {
return None;
}
#[cfg(test)]
if FORCE_BYPASS_LONG_RUN_INDEX.with(std::cell::Cell::get) {
return None;
}
let spans = active.long_run_lines.get_or_insert_with(|| {
let spans = super::text::long_run_line_spans(input);
#[cfg(debug_assertions)]
assert_eq!(spans, super::text::long_run_line_spans_by_line(input));
spans.into()
});
Some(Rc::clone(spans))
})
.ok()
.flatten()
}
pub(super) fn provider_word_mask(input: &str, build: fn(&[u8]) -> u8) -> Option<u8> {
ACTIVE_SCAN
.try_with(|cell| {
let mut current = cell.try_borrow_mut().ok()?;
let active = current.as_mut()?;
if active.start != input.as_ptr() as usize || active.len != input.len() {
return None;
}
Some(
*active
.provider_words
.get_or_insert_with(|| build(input.as_bytes())),
)
})
.ok()
.flatten()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_literal_is_possible_exactly_when_all_its_pairs_occur() {
let pairs = PairSet::of(b"xx re_ yy");
assert!(pairs.may_contain_literal(b"re_"));
assert!(!pairs.may_contain_literal(b"ab"));
let split = PairSet::of(b"re e_");
assert!(split.may_contain_literal(b"re_"));
let neither = PairSet::of(b"r e _");
assert!(!neither.may_contain_literal(b"re_"));
}
#[test]
fn every_occurring_literal_is_reported_possible() {
let text = b"prefix ghp_ AKIA sk-proj- xoxb- .atlasv1. 0: \xff\x00 end";
let pairs = PairSet::of(text);
let table = PairTable::of(text);
for start in 0..text.len() {
for end in start + 2..=text.len() {
assert!(pairs.may_contain_literal(&text[start..end]));
assert!(table.may_contain_literal(&text[start..end]));
}
}
}
#[test]
fn the_pair_table_is_exact_for_every_pair() {
let text = b"ab\xff\x00zz";
let table = PairTable::of(text);
for first in 0..=u8::MAX {
for second in 0..=u8::MAX {
let occurs = text.windows(2).any(|pair| pair == [first, second]);
assert_eq!(table.contains(first, second), occurs);
}
}
}
#[test]
fn declarations_refuse_short_or_empty_literal_lists() {
assert!(RequiredLiterals::any_of(&[]).is_none());
assert!(RequiredLiterals::any_of(&[Literals::Strs(&[])]).is_none());
assert!(RequiredLiterals::any_of(&[Literals::Strs(&["ghp_", "x"])]).is_none());
assert!(
RequiredLiterals::any_of(&[Literals::Strs(&["ghp_"]), Literals::Bytes(&[b"x"])])
.is_none()
);
assert!(RequiredLiterals::any_of(&[Literals::Strs(&["ghp_", "gho_"])]).is_some());
}
#[test]
fn a_declaration_matches_exactly_when_a_literal_occurs() {
let github = RequiredLiterals::any_of(&[
Literals::Prefixes(&[("ghp_", "github_token")]),
Literals::Bytes(&[b"glpat-"]),
])
.unwrap();
let separator = RequiredLiterals::any_of(&[Literals::Strs(&["0:", "==", "re_"])]).unwrap();
let matcher =
LiteralMatcher::compile([None, Some(&github), None, Some(&separator)]).unwrap();
let present = |text: &[u8]| {
let found = matcher.present(text);
(0..4)
.filter(|&slot| found.contains(slot))
.collect::<Vec<_>>()
};
assert_eq!(present(b"token glpat-abc"), [1]);
assert_eq!(present(b"plain prose only"), [] as [usize; 0]);
assert_eq!(present(b""), [] as [usize; 0]);
assert_eq!(present(b"g"), [] as [usize; 0]);
assert_eq!(present(b"re e_ glpat"), [] as [usize; 0]);
assert_eq!(present(b"x==ghp_"), [1, 3]);
assert_eq!(present(b"ghp"), [] as [usize; 0]);
assert_eq!(present(b"10:"), [3]);
}
#[test]
fn a_declaration_past_the_slot_limit_compiles_no_matcher() {
let github = RequiredLiterals::any_of(&[Literals::Strs(&["ghp_"])]).unwrap();
let mut declarations = vec![None; MAX_SLOTS];
declarations.push(Some(&github));
assert!(LiteralMatcher::compile(declarations).is_none());
let mut within = vec![None; MAX_SLOTS - 1];
within.push(Some(&github));
let matcher = LiteralMatcher::compile(within).unwrap();
assert!(matcher.present(b"ghp_").contains(MAX_SLOTS - 1));
}
#[test]
fn a_ruleset_literal_is_ruled_out_only_for_the_marked_scan_copy() {
let scanned = String::from("prose with no prefix at all");
assert!(ruleset_literal_may_occur(&scanned, b"ACME_"));
{
let _scope = ScanScope::enter(&scanned);
assert!(!ruleset_literal_may_occur(&scanned, b"ACME_"));
assert!(ruleset_literal_may_occur(&scanned, b"prefix"));
assert!(ruleset_literal_may_occur(&scanned[1..], b"ACME_"));
assert!(ruleset_literal_may_occur(&scanned[..4], b"ACME_"));
let other = String::from("prose with no prefix at all");
assert!(ruleset_literal_may_occur(&other, b"ACME_"));
{
let inner = String::from("ACME_ inner");
let _inner = ScanScope::enter(&inner);
assert!(ruleset_literal_may_occur(&inner, b"ACME_"));
assert!(ruleset_literal_may_occur(&scanned, b"ACME_"));
}
assert!(!ruleset_literal_may_occur(&scanned, b"ACME_"));
}
assert!(ruleset_literal_may_occur(&scanned, b"ACME_"));
}
use crate::detectors::{built_in_entries, common_built_in_entries};
use crate::registry::DetectorRegistry;
use crate::types::DetectorContext;
use crate::{DefaultPolicy, scan};
const SHORT_BASE: &str = "config: value é 漢字 🙂 \u{200B}x\u{FEFF}y end\n";
fn long_base() -> String {
let line = "2026-09-30T12:34:56Z INFO request id=42 path=/v1/items status=200 \
{\"name\":\"value\",\"list\":[1,2,3]} fn main() { let x = y; } \
naïve café 東京 🙂 \u{200B}zero\u{2060}width\n";
let text = line.repeat(EXACT_PAIRS_FROM / line.len() + 2);
assert!(text.len() > EXACT_PAIRS_FROM);
text
}
fn insert_at(text: &str, at: usize, inserted: &str) -> String {
let mut at = at.min(text.len());
while !text.is_char_boundary(at) {
at += 1;
}
format!("{}{inserted}{}", &text[..at], &text[at..])
}
fn variants(base: &str, literal: &str) -> Vec<String> {
let value = format!("{literal}SYNTHETIC0123456789abcdefREVOKED0000");
let mut split = literal.to_owned();
let second = literal
.char_indices()
.nth(1)
.map_or(literal.len(), |(at, _)| at);
split.insert(second, '\u{200B}');
let truncated = &literal[..literal.len() - 1];
vec![
format!("{value}{base}"),
insert_at(base, base.len() / 2, &format!(" {value} ")),
format!("{base}{literal}"),
insert_at(base, base.len() / 3, truncated),
insert_at(base, base.len() / 3, &format!("{split}SYNTHETIC0123456789")),
format!("{base}{truncated}"),
]
}
fn check_exact(registry: &DetectorRegistry, text: &str) {
let matcher = registry.prefilter().unwrap();
let present = matcher.present(text.as_bytes());
let context = DetectorContext::new(text.len());
for (slot, registered) in registry.detectors().iter().enumerate() {
let Some(required) = registered.required_literals() else {
assert!(!present.contains(slot));
continue;
};
let occurs = required.literals().iter().any(|literal| {
text.as_bytes()
.windows(literal.len())
.any(|window| window == *literal)
});
assert_eq!(present.contains(slot), occurs, "{}", registered.id());
if !occurs {
assert!(
registered
.detector()
.detect(text, &context)
.is_ok_and(|candidates| candidates.is_empty()),
"{} would be skipped but proposes a candidate",
registered.id()
);
}
}
let _ = scan(text, registry, &DefaultPolicy);
}
#[test]
fn the_matcher_is_exact_and_never_skips_an_emitting_detector() {
let long = long_base();
for registry in [
DetectorRegistry::with_built_in([]).unwrap(),
DetectorRegistry::with_common_built_in([]).unwrap(),
] {
let literals: Vec<&str> = registry
.detectors()
.iter()
.filter_map(|registered| registered.required_literals())
.flat_map(|required| required.literals())
.map(|literal| std::str::from_utf8(literal).unwrap())
.collect();
check_exact(®istry, "");
check_exact(®istry, SHORT_BASE);
check_exact(®istry, &long);
for literal in &literals {
for text in variants(SHORT_BASE, literal) {
check_exact(®istry, &text);
}
}
for literal in literals.iter().step_by(7) {
for text in variants(&long, literal) {
check_exact(®istry, &text);
}
}
}
}
#[test]
fn ruleset_detectors_find_the_same_with_and_without_the_prefilter() {
let ruleset = "ruleset-revision: 1\n\
detector: acme-internal-token\n\
specificity: contextual\n\
prefix: \"ACME_\"\n\
alphabet: alnum-dash\n\
run: at-least 12\n\
validator: none\n\
detector: acme-checksum-token\n\
specificity: entropy\n\
prefix: \"re_q\"\n\
alphabet: alnum\n\
run: at-least 8\n\
validator: trailing-lower-hex\n\
detector: acme-unicode-token\n\
specificity: contextual\n\
prefix: \"é_k\"\n\
alphabet: alnum\n\
run: exact 10\n\
validator: none\n";
let detectors = crate::load_ruleset(ruleset.as_bytes()).unwrap();
let long = long_base();
for base in [SHORT_BASE, long.as_str()] {
let _scope = ScanScope::enter(base);
assert!(!ruleset_literal_may_occur(base, b"ACME_"));
}
let mut inputs = vec![String::new(), SHORT_BASE.to_owned(), long.clone()];
for base in [SHORT_BASE, long.as_str()] {
for literal in ["ACME_", "re_q", "é_k"] {
inputs.extend(variants(base, literal));
}
inputs.push(format!("{base} re e_ _q"));
}
for input in &inputs {
let context = DetectorContext::new(input.len());
for detector in &detectors {
let unfiltered = detector.detect(input, &context).unwrap();
let filtered = {
let _scope = ScanScope::enter(input);
detector.detect(input, &context).unwrap()
};
assert_eq!(filtered, unfiltered, "{}", detector.id());
}
}
let registry = DetectorRegistry::with_built_in(detectors).unwrap();
for input in &inputs {
let _ = scan(input, ®istry, &DefaultPolicy);
}
}
#[test]
fn full_declares_103_detectors_and_common_4() {
let declared = |entries: Vec<super::super::BuiltIn>| {
entries
.iter()
.filter(|entry| entry.required.is_some())
.count()
};
assert_eq!(declared(built_in_entries()), 103);
assert_eq!(declared(common_built_in_entries()), 4);
}
#[test]
fn only_the_reviewed_built_ins_run_on_every_call() {
let always: Vec<String> = built_in_entries()
.into_iter()
.filter(|entry| entry.required.is_none())
.map(|entry| entry.detector.id().to_owned())
.collect();
assert_eq!(
always,
[
"twilio-auth-token",
"twilio-api-key-secret",
"discord-bot-token",
"datadog-api-key",
"datadog-application-key-legacy",
"new-relic-license-key",
"pinecone-api-key",
"confluent-cloud-api-secret-legacy",
"heroku-api-key-legacy",
"travisci-api-token",
"mistral-api-key",
"cohere-api-key",
"ai21-api-key",
"deepgram-api-key",
"convex-deployment-key",
"bearer-token",
"generic-token",
]
);
}
#[test]
fn bare_shape_detectors_agree_inside_and_outside_a_scan() {
use crate::types::{Detector, DetectorContext};
let detectors: Vec<Box<dyn Detector>> = vec![
Box::new(super::super::twilio::TwilioAuthTokenDetector),
Box::new(super::super::twilio::TwilioApiKeySecretDetector),
Box::new(super::super::datadog::DatadogApiKeyDetector),
Box::new(super::super::datadog::DatadogApplicationKeyLegacyDetector),
Box::new(super::super::new_relic::NewRelicLicenseKeyDetector),
Box::new(super::super::heroku::HerokuApiKeyLegacyDetector),
Box::new(super::super::confluent::ConfluentLegacyApiSecretDetector),
Box::new(super::super::pinecone::PineconeApiKeyDetector),
Box::new(super::super::mailchimp::MailchimpMarketingApiKeyDetector),
];
let hex32 = "0123456789abcdef0123456789abcdef";
let hex40 = "0123456789abcdef0123456789abcdef01234567";
let uuid = "01234567-89ab-cdef-0123-456789abcdef";
let b64 = "AbCdEfGhIjKlMnOpQrStUvWxYz0123456789+/AbCdEfGhIjKlMnOpQrStUvWxYz01";
let alnum32 = "AbCdEfGhIjKlMnOpQrStUvWxYz012345";
let pool: Vec<String> = vec![
format!("TWILIO_AUTH_TOKEN={hex32}"),
format!("AC{hex32} {hex32}"),
format!("SK{alnum32} {alnum32}"),
format!("twilio api {alnum32}"),
"twilio profiles:list --properties authToken".to_owned(),
"ID Auth Token".to_owned(),
format!("pf_one {hex32}"),
format!("DD_API_KEY={hex32}"),
format!("datadog {hex40}"),
format!("DD_APPLICATION_KEY={hex40}"),
format!("NEW_RELIC_LICENSE_KEY={hex40}"),
format!("{}FFFFNRAL", &hex32),
format!("eu01xx{}FFFFNRAL", &hex32[..26]),
format!("HEROKU_API_KEY={uuid}"),
"heroku auth:token".to_owned(),
format!("machine api.heroku.test password {uuid}"),
format!("confluent.api.secret={b64}"),
"schema.registry.url=https://confluent.test".to_owned(),
format!("basic.auth.user.info=key:{b64}"),
format!("pinecone_api_key = {uuid}"),
format!("mailchimp {hex32}-us12"),
format!("{hex32}-us1"),
format!("{hex32}-us1.example.test"),
"short line".to_owned(),
"0123456789abcdef".to_owned(),
String::new(),
"caf\u{e9} \u{597D} 0123".to_owned(),
];
let mut state = 0x9e37_79b9_7f4a_7c15u64;
let mut next = move || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
usize::try_from(state >> 33).unwrap()
};
let mut found = 0usize;
for _ in 0..600 {
let mut input = String::new();
for _ in 0..=(next() % 9) {
input.push_str(&pool[next() % pool.len()]);
input.push_str(["\n", "\r\n", "\r", " ", "\n\n"][next() % 5]);
}
let context = DetectorContext::new(input.len());
for detector in &detectors {
let outside = detector.detect(&input, &context).unwrap();
let inside = {
let _scope = ScanScope::enter(&input);
detector.detect(&input, &context).unwrap()
};
assert_eq!(inside, outside, "{} {input:?}", detector.id());
found += outside.len();
}
}
assert!(found > 500, "the inputs must exercise matches, saw {found}");
}
#[test]
fn bare_shape_detectors_agree_with_the_index_built_or_bypassed() {
struct Reset;
impl Drop for Reset {
fn drop(&mut self) {
FORCE_BYPASS_LONG_RUN_INDEX.with(|force| force.set(false));
}
}
use crate::types::{Detector, DetectorContext};
let detectors: Vec<Box<dyn Detector>> = vec![
Box::new(super::super::twilio::TwilioAuthTokenDetector),
Box::new(super::super::twilio::TwilioApiKeySecretDetector),
Box::new(super::super::datadog::DatadogApiKeyDetector),
Box::new(super::super::datadog::DatadogApplicationKeyLegacyDetector),
Box::new(super::super::new_relic::NewRelicLicenseKeyDetector),
Box::new(super::super::heroku::HerokuApiKeyLegacyDetector),
Box::new(super::super::confluent::ConfluentLegacyApiSecretDetector),
Box::new(super::super::pinecone::PineconeApiKeyDetector),
Box::new(super::super::mailchimp::MailchimpMarketingApiKeyDetector),
];
let _reset = Reset;
let hex32 = "0123456789abcdef0123456789abcdef";
let hex40 = "0123456789abcdef0123456789abcdef01234567";
let uuid = "01234567-89ab-cdef-0123-456789abcdef";
let b64 = "AbCdEfGhIjKlMnOpQrStUvWxYz0123456789+/AbCdEfGhIjKlMnOpQrStUvWxYz01";
let alnum32 = "AbCdEfGhIjKlMnOpQrStUvWxYz012345";
let dense: Vec<String> = vec![
format!("TWILIO_AUTH_TOKEN={hex32}"),
format!("AC{hex32} {hex32}"),
format!("SK{alnum32} {alnum32}"),
format!("DD_API_KEY={hex32}"),
format!("datadog {hex40}"),
format!("NEW_RELIC_LICENSE_KEY={hex40}"),
format!("{hex32}FFFFNRAL"),
format!("HEROKU_API_KEY={uuid}"),
format!("confluent.api.secret={b64}"),
format!("pinecone_api_key = {uuid}"),
format!("mailchimp {hex32}-us12"),
format!("{hex32}-us1.example.test"),
format!("{hex40}{hex40}"),
];
let sparse: Vec<String> = vec![
"twilio profiles:list --properties authToken".to_owned(),
"ID Auth Token".to_owned(),
"heroku auth:token".to_owned(),
"schema.registry.url=https://confluent.test".to_owned(),
"short line".to_owned(),
"0123456789abcdef".to_owned(),
String::new(),
"caf\u{e9} \u{597D} 0123".to_owned(),
];
let mut state = 0x2545_f491_4f6c_dd1du64;
let mut next = move || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
usize::try_from(state >> 33).unwrap()
};
let (mut mostly_indexed, mut mostly_skipped, mut found) = (0usize, 0usize, 0usize);
for round in 0..640 {
let lines = 1 + next() % 80;
let sparse_in_ten = [0, 0, 1, 10][round % 4];
let mut input = String::new();
for _ in 0..lines {
let pool = if next() % 10 < sparse_in_ten {
&sparse
} else {
&dense
};
input.push_str(&pool[next() % pool.len()]);
input.push_str(["\n", "\n", "\n", "\r\n", "\r"][next() % 5]);
}
if super::super::text::long_run_line_spans_by_line(&input).len() * 2
> input.lines().count()
{
mostly_indexed += 1;
} else {
mostly_skipped += 1;
}
let context = DetectorContext::new(input.len());
for detector in &detectors {
let outside = detector.detect(&input, &context).unwrap();
for forced in [false, true] {
FORCE_BYPASS_LONG_RUN_INDEX.with(|force| force.set(forced));
let _scope = ScanScope::enter(&input);
let inside = detector.detect(&input, &context).unwrap();
assert_eq!(inside, outside, "{} {forced:?} {input:?}", detector.id());
}
found += outside.len();
}
}
assert!(
mostly_indexed > 100 && mostly_skipped > 100,
"{mostly_indexed}/{mostly_skipped}"
);
assert!(
found > 5000,
"the inputs must exercise matches, saw {found}"
);
}
#[test]
fn the_long_run_index_is_only_handed_out_for_the_active_scan_copy() {
let input = format!("{}\nshort\n", "a".repeat(40));
assert!(long_run_lines(&input).is_none());
let _scope = ScanScope::enter(&input);
assert_eq!(long_run_lines(&input).as_deref(), Some(&[(0, 40)][..]));
assert!(long_run_lines(&input[..45]).is_none());
assert!(long_run_lines(&input.clone()).is_none());
}
fn present_oracle(matcher: &LiteralMatcher, text: &[u8]) -> Vec<usize> {
let mut slots: Vec<usize> = matcher
.entries
.iter()
.filter(|entry| {
text.windows(entry.literal.len())
.any(|window| window == entry.literal)
})
.map(|entry| usize::from(entry.slot))
.collect();
slots.sort_unstable();
slots.dedup();
slots
}
fn present_slots(matcher: &LiteralMatcher, text: &[u8]) -> Vec<usize> {
let found = matcher.present(text);
(0..MAX_SLOTS)
.filter(|&slot| found.contains(slot))
.collect()
}
#[test]
fn lead_group_lookup_matches_a_substring_oracle() {
use crate::test_rng::XorShift32;
let a =
RequiredLiterals::any_of(&[Literals::Strs(&["ghp_", "gho_", "gh", "ab_cd"])]).unwrap();
let b = RequiredLiterals::any_of(&[Literals::Strs(&["ghp_", "ghx", "zz"])]).unwrap();
let c = RequiredLiterals::any_of(&[Literals::Strs(&["ab_", "ab_cd", "é!", "\u{200B}x"])])
.unwrap();
let matcher = LiteralMatcher::compile([Some(&a), None, Some(&b), Some(&c)]).unwrap();
let pieces = [
"g", "gh", "ghp", "ghp_", "gho", "gho_", "ghx", "ab", "ab_", "ab_c", "ab_cd", "zz",
"z", "é", "é!", "\u{200B}", "x", " ", "~", "_", "漢",
];
let mut rng = XorShift32::new(0x1093);
for _ in 0..4000 {
let text = rng.text(&pieces, 12);
assert_eq!(
present_slots(&matcher, text.as_bytes()),
present_oracle(&matcher, text.as_bytes()),
"{text:?}"
);
}
for registry in [
DetectorRegistry::with_built_in([]).unwrap(),
DetectorRegistry::with_common_built_in([]).unwrap(),
] {
let matcher = registry.prefilter().unwrap();
let literals: Vec<String> = matcher
.entries
.iter()
.map(|entry| String::from_utf8_lossy(entry.literal).into_owned())
.collect();
let pieces: Vec<&str> = literals
.iter()
.flat_map(|literal| {
let cut = literal
.char_indices()
.nth(2)
.map_or(literal.len(), |(i, _)| i);
[literal.as_str(), &literal[..cut]]
})
.chain(["é", " ", "\u{200B}", "~"])
.collect();
for _ in 0..1500 {
let text = rng.text(&pieces, 10);
assert_eq!(
present_slots(matcher, text.as_bytes()),
present_oracle(matcher, text.as_bytes()),
"{text:?}"
);
}
}
}
}