truman-core 0.1.0

Core types, filters, and parallel scanner for Truman secret detection
Documentation
use crate::filetype::FileType;
use crate::finding::VerifiedResult;
use std::path::Path;
use std::sync::Arc;

/// Per-line context handed to every detector.
#[derive(Debug, Clone, Copy)]
pub struct DetectorContext<'a> {
    /// File being scanned.
    pub file: &'a Path,
    /// File type derived from the file extension.
    pub filetype: FileType,
    /// 1-indexed line number within the file.
    pub line_number: u32,
    /// Whether eager (quote-less) searching is enabled (adhoc scans).
    pub enable_eager_search: bool,
}

/// A raw (unfiltered, unhashed) detector hit within a single line.
///
/// `col_start` / `col_end` are byte indices into the detection line
/// (`col_end` end-exclusive). They must denote exact match positions so
/// the scanner can build a precise [`crate::finding::Span`].
#[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,
        }
    }
}

/// The core extension point of truman.
///
/// Implement this trait to add a new secret detector. Detectors must be
/// pure line-scanners: given one line plus context, return zero or more
/// raw findings with exact byte positions.
///
/// Example (10 lines):
/// ```rust
/// use truman_core::{Detector, DetectorContext, RawFinding};
/// #[derive(Debug)]
/// struct MyDetector;
/// impl Detector for MyDetector {
///     fn name(&self) -> &'static str { "MyDetector" }
///     fn secret_type(&self) -> &str { "My Secret" }
///     fn detect(&self, line: &str, _ctx: &DetectorContext) -> Vec<RawFinding> {
///         // ... regex find_iter -> RawFinding { secret, col_start, col_end }
///         vec![]
///     }
/// }
/// ```
pub trait Detector: Send + Sync + std::fmt::Debug {
    /// Stable detector name (e.g. `"StripeDetector"`).
    fn name(&self) -> &'static str;

    /// Human-readable secret type (e.g. `"Stripe Access Key"`).
    fn secret_type(&self) -> &str;

    /// Scan a single (rstripped) line; return raw findings with exact columns.
    fn detect(&self, line: &str, ctx: &DetectorContext) -> Vec<RawFinding>;

    /// Regex patterns covering every possible hit of `detect` in this search mode.
    ///
    /// The scanner derives required literals from these patterns and checks them
    /// together before running detectors. Return all detection patterns, including
    /// alternative/legacy forms; extra patterns are safe but may reduce pruning.
    /// Patterns must use the same inline flags as detection. Detection may trim a
    /// line or validate captures, but must not synthesize text absent from the line.
    ///
    /// The default (no patterns) always runs the detector, preserving compatibility
    /// with custom implementations. Unparseable patterns and patterns without a
    /// required literal also fall back to running on every line. Called once when
    /// constructing a scanner, never per line.
    fn prefilter_patterns(&self, _enable_eager_search: bool) -> Vec<&str> {
        Vec::new()
    }

    /// Optionally verify a secret externally (network). Defaults to Unverified.
    fn verify(&self, _secret: &str, _ctx: &DetectorContext) -> VerifiedResult {
        VerifiedResult::Unverified
    }
}

/// Thread-safe registry of detectors.
///
/// Backed by `Vec<Arc<dyn Detector>>` so it can be shared across threads
/// (parallel scans) freely. Order is registration order.
#[derive(Debug, Clone, Default)]
pub struct DetectorRegistry {
    detectors: Vec<Arc<dyn Detector>>,
}

impl DetectorRegistry {
    pub fn new() -> Self {
        Self {
            detectors: Vec::new(),
        }
    }

    /// Register a detector, returning `&mut Self` for chaining.
    pub fn register<D: Detector + 'static>(&mut self, detector: D) -> &mut Self {
        self.detectors.push(Arc::new(detector));
        self
    }

    /// Register an already-boxed detector.
    pub fn register_arc(&mut self, detector: Arc<dyn Detector>) -> &mut Self {
        self.detectors.push(detector);
        self
    }

    /// All registered detectors (in registration order).
    pub fn detectors(&self) -> &[Arc<dyn Detector>] {
        &self.detectors
    }

    /// Names of all registered detectors.
    pub fn names(&self) -> Vec<String> {
        self.detectors
            .iter()
            .map(|d| d.name().to_string())
            .collect()
    }

    /// Look up a detector by name.
    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());
    }
}