use crate::filetype::FileType;
use crate::finding::VerifiedResult;
use std::path::Path;
use std::sync::Arc;
#[derive(Debug, Clone, Copy)]
pub struct DetectorContext<'a> {
pub file: &'a Path,
pub filetype: FileType,
pub line_number: u32,
pub enable_eager_search: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RawFinding {
pub secret: String,
pub col_start: usize,
pub col_end: usize,
}
impl RawFinding {
pub fn new(secret: String, col_start: usize, col_end: usize) -> Self {
Self {
secret,
col_start,
col_end,
}
}
}
pub trait Detector: Send + Sync + std::fmt::Debug {
fn name(&self) -> &'static str;
fn secret_type(&self) -> &str;
fn detect(&self, line: &str, ctx: &DetectorContext) -> Vec<RawFinding>;
fn prefilter_patterns(&self, _enable_eager_search: bool) -> Vec<&str> {
Vec::new()
}
fn verify(&self, _secret: &str, _ctx: &DetectorContext) -> VerifiedResult {
VerifiedResult::Unverified
}
}
#[derive(Debug, Clone, Default)]
pub struct DetectorRegistry {
detectors: Vec<Arc<dyn Detector>>,
}
impl DetectorRegistry {
pub fn new() -> Self {
Self {
detectors: Vec::new(),
}
}
pub fn register<D: Detector + 'static>(&mut self, detector: D) -> &mut Self {
self.detectors.push(Arc::new(detector));
self
}
pub fn register_arc(&mut self, detector: Arc<dyn Detector>) -> &mut Self {
self.detectors.push(detector);
self
}
pub fn detectors(&self) -> &[Arc<dyn Detector>] {
&self.detectors
}
pub fn names(&self) -> Vec<String> {
self.detectors
.iter()
.map(|d| d.name().to_string())
.collect()
}
pub fn get(&self, name: &str) -> Option<Arc<dyn Detector>> {
self.detectors.iter().find(|d| d.name() == name).cloned()
}
pub fn len(&self) -> usize {
self.detectors.len()
}
pub fn is_empty(&self) -> bool {
self.detectors.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug)]
struct Stub;
impl Detector for Stub {
fn name(&self) -> &'static str {
"Stub"
}
fn secret_type(&self) -> &str {
"Stub"
}
fn detect(&self, _line: &str, _ctx: &DetectorContext) -> Vec<RawFinding> {
vec![]
}
}
#[test]
fn registry_register_and_names() {
let mut r = DetectorRegistry::new();
r.register(Stub);
assert_eq!(r.names(), vec!["Stub".to_string()]);
assert!(r.get("Stub").is_some());
assert!(r.get("Missing").is_none());
}
}