use std::borrow::Cow;
use std::sync::{Arc, OnceLock};
use crate::composition::Composition;
use crate::detectors::{
BuiltIn, BuiltInDetector, LiteralMatcher, RequiredLiterals, built_in_entries, built_in_ids,
common_built_in_entries,
};
use crate::error::{SecretScanError, SecretScanErrorCode};
use crate::limits::WholeInputLimits;
use crate::pii::{PiiSelection, adapter, is_reserved_detector_id};
use crate::pipeline::{scan_and_redact_in, scan_in};
use crate::selection::{DetectionConfigError, DetectionSelection, PlanEntry, plan_selection};
use crate::types::{Detector, Finding, PlaceholderFormatter, Policy, ScanResult, is_identifier};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Profile {
Full,
Common,
Custom,
}
impl Profile {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Full => "full",
Self::Common => "common",
Self::Custom => "custom",
}
}
#[must_use]
pub fn from_name(name: &str) -> Option<Self> {
match name {
"full" => Some(Self::Full),
"common" => Some(Self::Common),
_ => None,
}
}
}
#[derive(Clone, Debug)]
enum Prefilter {
Shared(&'static LiteralMatcher),
Owned(Arc<LiteralMatcher>),
}
impl Prefilter {
fn matcher(&self) -> &LiteralMatcher {
match self {
Self::Shared(matcher) => matcher,
Self::Owned(matcher) => matcher,
}
}
}
pub(crate) fn compile_matcher(declared: Vec<Option<&RequiredLiterals>>) -> Option<LiteralMatcher> {
LiteralMatcher::compile(declared)
}
fn retain_and_recompile<T>(
entries: &mut Vec<T>,
keep: &[bool],
required: impl Fn(&T) -> Option<&RequiredLiterals>,
) -> Option<Prefilter> {
let mut flags = keep.iter();
entries.retain(|_| flags.next().copied().unwrap_or(true));
compile_matcher(entries.iter().map(required).collect())
.map(|matcher| Prefilter::Owned(Arc::new(matcher)))
}
pub struct RegisteredDetector {
id: Cow<'static, str>,
detector: Held,
required: Option<RequiredLiterals>,
}
impl RegisteredDetector {
#[must_use]
pub fn id(&self) -> &str {
&self.id
}
pub(crate) const fn id_cow(&self) -> &Cow<'static, str> {
&self.id
}
#[must_use]
pub fn detector(&self) -> &dyn Detector {
match &self.detector {
Held::BuiltIn(detector) => *detector,
Held::Pii(detector) => detector.as_ref(),
Held::Custom(detector) => detector.as_ref(),
}
}
pub(crate) const fn required_literals(&self) -> Option<&RequiredLiterals> {
self.required.as_ref()
}
}
enum Held {
BuiltIn(BuiltInDetector),
Pii(Box<dyn Detector + Send + Sync>),
Custom(Box<dyn Detector>),
}
impl std::fmt::Debug for RegisteredDetector {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RegisteredDetector")
.field("id", &self.id)
.finish_non_exhaustive()
}
}
#[derive(Debug, Default)]
pub struct DetectorRegistry {
detectors: Vec<RegisteredDetector>,
profile: Option<Profile>,
activation_identity: String,
detection: DetectionSelection,
pii: PiiSelection,
prefilter: Option<Prefilter>,
}
impl DetectorRegistry {
#[cfg(test)]
pub(crate) fn with_internal_test_detector(detector: Box<dyn Detector>) -> Self {
Self {
detectors: vec![RegisteredDetector {
id: Cow::Owned(detector.id().to_owned()),
detector: Held::Custom(detector),
required: None,
}],
profile: None,
activation_identity: String::new(),
detection: DetectionSelection::all(),
pii: PiiSelection::empty(),
prefilter: None,
}
}
#[must_use]
pub const fn new() -> Self {
Self {
detectors: Vec::new(),
profile: None,
activation_identity: String::new(),
detection: DetectionSelection::all(),
pii: PiiSelection::empty(),
prefilter: None,
}
}
pub fn with_built_in<I>(custom: I) -> Result<Self, SecretScanError>
where
I: IntoIterator<Item = Box<dyn Detector>>,
{
static FULL_PREFILTER: OnceLock<Option<LiteralMatcher>> = OnceLock::new();
let mut registry = Self::new();
for BuiltIn {
id,
detector,
required,
} in built_in_entries()
{
registry.push_validated_built_in(id, detector, required)?;
}
registry.prefilter = registry
.compile_prefilter(&FULL_PREFILTER)
.map(Prefilter::Shared);
for detector in custom {
registry.push_validated_custom(detector, false)?;
}
registry.profile = Some(Profile::Full);
registry.activation_identity = PiiSelection::default().activation_identity(Profile::Full);
Ok(registry)
}
pub fn with_common_built_in<I>(custom: I) -> Result<Self, SecretScanError>
where
I: IntoIterator<Item = Box<dyn Detector>>,
{
static COMMON_PREFILTER: OnceLock<Option<LiteralMatcher>> = OnceLock::new();
let mut registry = Self::new();
for BuiltIn {
id,
detector,
required,
} in common_built_in_entries()
{
registry.push_validated_built_in(id, detector, required)?;
}
registry.prefilter = registry
.compile_prefilter(&COMMON_PREFILTER)
.map(Prefilter::Shared);
for detector in custom {
registry.push_validated_custom(detector, true)?;
}
registry.profile = Some(Profile::Common);
registry.activation_identity = PiiSelection::default().activation_identity(Profile::Common);
Ok(registry)
}
pub fn with_composition<I>(
composition: &Composition,
custom: I,
) -> Result<Self, SecretScanError>
where
I: IntoIterator<Item = Box<dyn Detector>>,
{
let mut registry = Self::new();
for selected in composition.selected() {
registry.push_validated_built_in(selected.id, selected.detector, selected.required)?;
}
registry.prefilter = composition.prefilter().map(Prefilter::Owned);
for detector in custom {
registry.push_validated_custom(detector, true)?;
}
registry.profile = Some(Profile::Custom);
registry.activation_identity = PiiSelection::default().activation_identity(Profile::Custom);
Ok(registry)
}
pub fn with_composition_and_pii<I>(
composition: &Composition,
selection: &PiiSelection,
custom: I,
) -> Result<Self, SecretScanError>
where
I: IntoIterator<Item = Box<dyn Detector>>,
{
Self::with_composition(composition, [])?.with_pii_and_custom(
Profile::Custom,
selection,
custom,
)
}
pub fn with_built_in_and_pii(selection: &PiiSelection) -> Result<Self, SecretScanError> {
Self::with_built_in([])?.with_pii_and_custom(Profile::Full, selection, std::iter::empty())
}
pub fn with_common_built_in_and_pii(selection: &PiiSelection) -> Result<Self, SecretScanError> {
Self::with_common_built_in([])?.with_pii_and_custom(
Profile::Common,
selection,
std::iter::empty(),
)
}
pub fn with_built_in_and_pii_custom<I>(
selection: &PiiSelection,
custom: I,
) -> Result<Self, SecretScanError>
where
I: IntoIterator<Item = Box<dyn Detector>>,
{
Self::with_built_in([])?.with_pii_and_custom(Profile::Full, selection, custom)
}
pub fn with_common_built_in_and_pii_custom<I>(
selection: &PiiSelection,
custom: I,
) -> Result<Self, SecretScanError>
where
I: IntoIterator<Item = Box<dyn Detector>>,
{
Self::with_common_built_in([])?.with_pii_and_custom(Profile::Common, selection, custom)
}
fn with_pii_and_custom<I>(
self,
profile: Profile,
selection: &PiiSelection,
custom: I,
) -> Result<Self, SecretScanError>
where
I: IntoIterator<Item = Box<dyn Detector>>,
{
debug_assert_eq!(self.profile, Some(profile));
let mut registry = self;
if !selection.is_off() {
registry.detectors.push(RegisteredDetector {
id: Cow::Borrowed("pii-domain"),
detector: Held::Pii(adapter(selection)),
required: None,
});
}
for detector in custom {
registry.push_validated_custom(detector, true)?;
}
registry.profile = Some(profile);
registry.activation_identity = selection.activation_identity(profile);
registry.pii = selection.clone();
Ok(registry)
}
fn compile_prefilter(
&self,
cache: &'static OnceLock<Option<LiteralMatcher>>,
) -> Option<&'static LiteralMatcher> {
cache
.get_or_init(|| {
compile_matcher(
self.detectors
.iter()
.map(RegisteredDetector::required_literals)
.collect(),
)
})
.as_ref()
}
pub(crate) fn prefilter(&self) -> Option<&LiteralMatcher> {
self.prefilter.as_ref().map(Prefilter::matcher)
}
#[must_use]
pub const fn profile(&self) -> Option<Profile> {
self.profile
}
#[must_use]
pub fn activation_identity(&self) -> &str {
&self.activation_identity
}
#[must_use]
pub const fn detection(&self) -> &DetectionSelection {
&self.detection
}
pub(crate) const fn pii_selection(&self) -> &PiiSelection {
&self.pii
}
pub(crate) fn built_in_ids(&self) -> impl Iterator<Item = &str> {
self.detectors
.iter()
.filter(|registered| matches!(registered.detector, Held::BuiltIn(_)))
.map(RegisteredDetector::id)
}
pub fn with_detection(
mut self,
selection: &DetectionSelection,
) -> Result<Self, DetectionConfigError> {
if selection.is_all() {
return Ok(self);
}
let plan: Vec<PlanEntry<'_>> = self
.detectors
.iter()
.map(|registered| PlanEntry {
id: registered.id(),
built_in: matches!(registered.detector, Held::BuiltIn(_)),
})
.collect();
let keep = plan_selection(selection, &plan)?;
drop(plan);
self.prefilter = retain_and_recompile(
&mut self.detectors,
&keep,
RegisteredDetector::required_literals,
);
self.detection = selection.clone();
Ok(self)
}
pub fn register(&mut self, detector: Box<dyn Detector>) -> Result<&mut Self, SecretScanError> {
self.push_validated_custom(detector, false)?;
self.profile = None;
Ok(self)
}
fn push_validated_custom(
&mut self,
detector: Box<dyn Detector>,
reject_built_in_ids: bool,
) -> Result<(), SecretScanError> {
let id = detector.id();
self.validate_id(id, reject_built_in_ids)?;
self.detectors.push(RegisteredDetector {
id: Cow::Owned(id.to_owned()),
detector: Held::Custom(detector),
required: None,
});
Ok(())
}
fn push_validated_built_in(
&mut self,
id: &'static str,
detector: BuiltInDetector,
required: Option<RequiredLiterals>,
) -> Result<(), SecretScanError> {
self.validate_id(id, false)?;
self.detectors.push(RegisteredDetector {
id: Cow::Borrowed(id),
detector: Held::BuiltIn(detector),
required,
});
Ok(())
}
fn validate_id(&self, id: &str, reject_built_in_ids: bool) -> Result<(), SecretScanError> {
if !is_identifier(id)
|| is_reserved_detector_id(id)
|| self.contains(id)
|| (reject_built_in_ids && built_in_ids().any(|reserved| reserved == id))
{
return Err(SecretScanErrorCode::InvalidDetector.into());
}
Ok(())
}
#[must_use]
pub fn detectors(&self) -> &[RegisteredDetector] {
&self.detectors
}
pub fn ids(&self) -> impl Iterator<Item = &str> {
self.detectors.iter().map(RegisteredDetector::id)
}
#[must_use]
pub fn len(&self) -> usize {
self.detectors.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.detectors.is_empty()
}
#[must_use]
pub fn contains(&self, id: &str) -> bool {
self.detectors.iter().any(|registered| registered.id == id)
}
}
#[derive(Clone, Copy)]
pub(crate) struct DetectorEntry<'a> {
pub(crate) id: &'a Cow<'static, str>,
pub(crate) detector: &'a dyn Detector,
pub(crate) declares_literals: bool,
}
pub(crate) trait DetectorSet {
fn detector_count(&self) -> usize;
fn detector_entries(&self) -> impl Iterator<Item = DetectorEntry<'_>>;
fn compiled_prefilter(&self) -> Option<&LiteralMatcher>;
}
impl DetectorSet for DetectorRegistry {
fn detector_count(&self) -> usize {
self.len()
}
fn detector_entries(&self) -> impl Iterator<Item = DetectorEntry<'_>> {
self.detectors.iter().map(|registered| DetectorEntry {
id: registered.id_cow(),
detector: registered.detector(),
declares_literals: registered.required_literals().is_some(),
})
}
fn compiled_prefilter(&self) -> Option<&LiteralMatcher> {
Self::prefilter(self)
}
}
enum SharedHeld {
BuiltIn(BuiltInDetector),
Pii(Box<dyn Detector + Send + Sync>),
}
struct SharedDetector {
id: Cow<'static, str>,
detector: SharedHeld,
required: Option<RequiredLiterals>,
}
impl SharedDetector {
fn detector(&self) -> &dyn Detector {
match &self.detector {
SharedHeld::BuiltIn(detector) => *detector,
SharedHeld::Pii(detector) => detector.as_ref(),
}
}
}
pub struct BuiltInRegistry {
detectors: Vec<SharedDetector>,
profile: Profile,
activation_identity: String,
detection: DetectionSelection,
prefilter: Option<Prefilter>,
}
impl BuiltInRegistry {
fn from_built_in_only(registry: DetectorRegistry) -> Result<Self, SecretScanError> {
let invalid = || SecretScanError::from(SecretScanErrorCode::InvalidDetector);
let profile = registry.profile.ok_or_else(invalid)?;
let mut detectors = Vec::with_capacity(registry.detectors.len());
for registered in registry.detectors {
let held = match registered.detector {
Held::BuiltIn(detector) => SharedHeld::BuiltIn(detector),
Held::Pii(detector) => SharedHeld::Pii(detector),
Held::Custom(_) => return Err(invalid()),
};
detectors.push(SharedDetector {
id: registered.id,
detector: held,
required: registered.required,
});
}
Ok(Self {
detectors,
profile,
activation_identity: registry.activation_identity,
detection: registry.detection,
prefilter: registry.prefilter,
})
}
pub fn with_built_in() -> Result<Self, SecretScanError> {
Self::from_built_in_only(DetectorRegistry::with_built_in([])?)
}
pub fn with_common_built_in() -> Result<Self, SecretScanError> {
Self::from_built_in_only(DetectorRegistry::with_common_built_in([])?)
}
pub fn with_built_in_and_pii(selection: &PiiSelection) -> Result<Self, SecretScanError> {
Self::from_built_in_only(DetectorRegistry::with_built_in_and_pii(selection)?)
}
pub fn with_common_built_in_and_pii(selection: &PiiSelection) -> Result<Self, SecretScanError> {
Self::from_built_in_only(DetectorRegistry::with_common_built_in_and_pii(selection)?)
}
#[must_use]
pub const fn profile(&self) -> Profile {
self.profile
}
#[must_use]
pub fn activation_identity(&self) -> &str {
&self.activation_identity
}
#[must_use]
pub const fn detection(&self) -> &DetectionSelection {
&self.detection
}
pub fn with_detection(
mut self,
selection: &DetectionSelection,
) -> Result<Self, DetectionConfigError> {
if selection.is_all() {
return Ok(self);
}
let plan: Vec<PlanEntry<'_>> = self
.detectors
.iter()
.map(|registered| PlanEntry {
id: registered.id.as_ref(),
built_in: matches!(registered.detector, SharedHeld::BuiltIn(_)),
})
.collect();
let keep = plan_selection(selection, &plan)?;
drop(plan);
self.prefilter = retain_and_recompile(&mut self.detectors, &keep, |registered| {
registered.required.as_ref()
});
self.detection = selection.clone();
Ok(self)
}
pub fn ids(&self) -> impl Iterator<Item = &str> {
self.detectors
.iter()
.map(|registered| registered.id.as_ref())
}
#[must_use]
pub fn len(&self) -> usize {
self.detectors.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.detectors.is_empty()
}
#[must_use]
pub fn contains(&self, id: &str) -> bool {
self.detectors.iter().any(|registered| registered.id == id)
}
pub fn scan(&self, input: &str, policy: &dyn Policy) -> Result<Vec<Finding>, SecretScanError> {
self.scan_with_limits(input, policy, &WholeInputLimits::default())
}
pub fn scan_with_limits(
&self,
input: &str,
policy: &dyn Policy,
limits: &WholeInputLimits,
) -> Result<Vec<Finding>, SecretScanError> {
scan_in(input, self, policy, limits)
}
pub fn scan_and_redact(
&self,
input: &str,
policy: &dyn Policy,
formatter: &dyn PlaceholderFormatter,
) -> Result<ScanResult, SecretScanError> {
self.scan_and_redact_with_limits(input, policy, formatter, &WholeInputLimits::default())
}
pub fn scan_and_redact_with_limits(
&self,
input: &str,
policy: &dyn Policy,
formatter: &dyn PlaceholderFormatter,
limits: &WholeInputLimits,
) -> Result<ScanResult, SecretScanError> {
scan_and_redact_in(input, self, policy, formatter, limits)
}
}
impl DetectorSet for BuiltInRegistry {
fn detector_count(&self) -> usize {
self.detectors.len()
}
fn detector_entries(&self) -> impl Iterator<Item = DetectorEntry<'_>> {
self.detectors.iter().map(|registered| DetectorEntry {
id: ®istered.id,
detector: registered.detector(),
declares_literals: registered.required.is_some(),
})
}
fn compiled_prefilter(&self) -> Option<&LiteralMatcher> {
self.prefilter.as_ref().map(Prefilter::matcher)
}
}
impl std::fmt::Debug for BuiltInRegistry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BuiltInRegistry")
.field("profile", &self.profile)
.field("detectors", &self.detectors.len())
.finish_non_exhaustive()
}
}
const _: () = {
const fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<BuiltInRegistry>();
};
#[cfg(test)]
mod tests {
use super::*;
use crate::detectors::{built_in_detectors, common_built_in_detectors};
use crate::error::DetectorFailure;
use crate::types::{Candidate, DetectorContext};
struct Named(&'static str);
impl Detector for Named {
fn id(&self) -> &str {
self.0
}
fn detect(&self, _: &str, _: &DetectorContext) -> Result<Vec<Candidate>, DetectorFailure> {
Ok(Vec::new())
}
}
#[test]
fn only_crate_built_ins_carry_prefilter_declarations() {
let full =
DetectorRegistry::with_built_in([Box::new(Named("custom")) as Box<dyn Detector>])
.unwrap();
let declared = |registry: &DetectorRegistry, id: &str| {
registry
.detectors()
.iter()
.find(|registered| registered.id() == id)
.unwrap()
.required_literals()
.is_some()
};
assert!(declared(&full, "github-token"));
assert!(!declared(&full, "generic-token"));
assert!(!declared(&full, "custom"));
let mut low_level = DetectorRegistry::new();
low_level.register(Box::new(Named("github-token"))).unwrap();
assert!(!declared(&low_level, "github-token"));
let pii = DetectorRegistry::with_built_in_and_pii(&PiiSelection::default()).unwrap();
assert!(pii.detectors().iter().all(|registered| {
registered.id() != "pii-domain" || registered.required_literals().is_none()
}));
}
#[test]
fn preserves_registration_order() {
let mut registry = DetectorRegistry::new();
registry
.register(Box::new(Named("zeta")))
.unwrap()
.register(Box::new(Named("alpha")))
.unwrap()
.register(Box::new(Named("mid.point-1_a")))
.unwrap();
assert_eq!(
registry.ids().collect::<Vec<_>>(),
["zeta", "alpha", "mid.point-1_a"]
);
assert_eq!(registry.len(), 3);
assert!(!registry.is_empty());
assert!(registry.contains("alpha"));
assert!(!registry.contains("beta"));
assert_eq!(registry.detectors()[1].detector().id(), "alpha");
}
#[test]
fn rejects_malformed_and_duplicate_ids() {
let mut registry = DetectorRegistry::new();
registry.register(Box::new(Named("dup"))).unwrap();
for id in ["", "Dup", "dup", "1x", "a--b", "a-", " a"] {
let error = registry.register(Box::new(Named(id))).unwrap_err();
assert_eq!(error.code(), SecretScanErrorCode::InvalidDetector);
assert_eq!(error.to_string(), "Invalid detector registration.");
}
assert_eq!(registry.len(), 1);
}
#[test]
fn rejects_ids_over_the_length_limit() {
let long = "a".repeat(crate::MAX_IDENTIFIER_LENGTH + 1).leak();
let mut registry = DetectorRegistry::new();
let error = registry.register(Box::new(Named(long))).unwrap_err();
assert_eq!(error.code(), SecretScanErrorCode::InvalidDetector);
}
#[test]
fn built_in_come_first() {
let registry =
DetectorRegistry::with_built_in([Box::new(Named("custom")) as Box<dyn Detector>])
.unwrap();
let built_in: Vec<String> = built_in_detectors()
.iter()
.map(|d| d.id().to_owned())
.collect();
let ids: Vec<&str> = registry.ids().collect();
assert_eq!(ids.len(), built_in.len() + 1);
assert_eq!(ids[..built_in.len()], built_in);
assert_eq!(ids[built_in.len()], "custom");
}
#[test]
fn common_built_in_come_first() {
let registry =
DetectorRegistry::with_common_built_in(
[Box::new(Named("custom")) as Box<dyn Detector>],
)
.unwrap();
let common: Vec<String> = common_built_in_detectors()
.iter()
.map(|d| d.id().to_owned())
.collect();
let ids: Vec<&str> = registry.ids().collect();
assert_eq!(ids.len(), common.len() + 1);
assert_eq!(ids[..common.len()], common);
assert_eq!(ids[common.len()], "custom");
}
#[test]
fn profile_identity_matches_how_the_registry_was_built() {
assert_eq!(DetectorRegistry::new().profile(), None);
assert_eq!(
DetectorRegistry::with_built_in([]).unwrap().profile(),
Some(Profile::Full)
);
assert_eq!(
DetectorRegistry::with_common_built_in([])
.unwrap()
.profile(),
Some(Profile::Common)
);
}
#[test]
fn extending_a_profile_registry_clears_its_profile_identity() {
let mut registry = DetectorRegistry::with_common_built_in([]).unwrap();
registry.register(Box::new(Named("github-token"))).unwrap();
assert_eq!(registry.profile(), None);
let mut rejected = DetectorRegistry::with_common_built_in([]).unwrap();
rejected.register(Box::new(Named("Bad"))).unwrap_err();
assert_eq!(rejected.profile(), Some(Profile::Common));
}
#[test]
fn a_profile_constructor_reads_a_custom_id_once() {
struct Flipping(std::sync::atomic::AtomicUsize);
impl Detector for Flipping {
fn id(&self) -> &str {
if self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed) == 0 {
"github-token"
} else {
"custom-token"
}
}
fn detect(
&self,
_: &str,
_: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
Ok(Vec::new())
}
}
let error = DetectorRegistry::with_common_built_in([Box::new(Flipping(
std::sync::atomic::AtomicUsize::new(0),
)) as Box<dyn Detector>])
.unwrap_err();
assert_eq!(error.code(), SecretScanErrorCode::InvalidDetector);
}
#[test]
fn profile_wire_names_round_trip() {
for (profile, name) in [(Profile::Full, "full"), (Profile::Common, "common")] {
assert_eq!(profile.as_str(), name);
assert_eq!(Profile::from_name(name), Some(profile));
}
assert_eq!(Profile::from_name("tiny"), None);
}
#[test]
fn common_detectors_produce_the_same_candidates_as_in_full() {
let full = DetectorRegistry::with_built_in([]).unwrap();
let common = DetectorRegistry::with_common_built_in([]).unwrap();
let inputs = [
"-----BEGIN PRIVATE KEY-----\nU1lOVEhFVElDX1JFVk9LRUQ=\n-----END PRIVATE KEY-----",
"eyJhbGciOiJIUzI1NiJ9.SYNTHETIC_REVOKED_PAYLOAD.SYNTHETIC_REVOKED_SIGNATURE",
"Authorization: Bearer SYNTHETIC_REVOKED_BEARER_TOKEN_VALUE_0001",
"postgres://user:SYNTHETIC_REVOKED_PASSWORD@example.test:5432/db",
"otpauth://totp/Example:alice@example.test?secret=SYNTHETICREVOKEDSECRET&issuer=Example",
"API_KEY=SYNTHETIC_REVOKED_GENERIC_TOKEN_VALUE_0001234567890",
];
for input in inputs {
let context = DetectorContext::new(input.len());
for id in common.ids() {
let full_detector = full
.detectors()
.iter()
.find(|registered| registered.id() == id)
.unwrap();
let common_detector = common
.detectors()
.iter()
.find(|registered| registered.id() == id)
.unwrap();
assert_eq!(
full_detector.detector().detect(input, &context).unwrap(),
common_detector.detector().detect(input, &context).unwrap(),
"{id}: {input}",
);
}
}
}
#[test]
fn debug_output_shows_only_ids() {
let mut registry = DetectorRegistry::new();
registry.register(Box::new(Named("only"))).unwrap();
let rendered = format!("{registry:?}");
assert!(rendered.contains("only"));
assert!(rendered.contains(".."));
}
#[test]
fn pii_adapter_has_one_fixed_slot_and_reserved_identity() {
let selection = PiiSelection::parse(&["pii"]).unwrap();
let mut full = DetectorRegistry::with_built_in_and_pii(&selection).unwrap();
assert_eq!(full.ids().collect::<Vec<_>>().last(), Some(&"pii-domain"));
assert_eq!(full.profile(), Some(Profile::Full));
assert_eq!(
full.activation_identity(),
"credentials=full;selectors=pii:global;families=pii:global:email,pii:global:iban,pii:global:network-address,pii:global:payment-card,pii:global:phone;vocabulary=pii-context/v2"
);
assert_eq!(
full.register(Box::new(Named("pii-domain")))
.unwrap_err()
.code(),
SecretScanErrorCode::InvalidDetector
);
assert_eq!(full.profile(), Some(Profile::Full));
}
#[test]
fn legacy_profile_constructors_remain_pii_off() {
let full = DetectorRegistry::with_built_in([]).unwrap();
assert!(!full.contains("pii-domain"));
assert_eq!(
full.activation_identity(),
"credentials=full;selectors=off;families=;vocabulary=pii-context/v2"
);
}
}