use crate::error::{AuditError, Result};
use crate::ignore::IgnoreFilter;
use crate::rules::{DynamicRule, Finding, RuleEngine};
use std::fs;
use std::path::Path;
use tracing::{debug, trace};
pub trait Scanner {
fn scan_file(&self, path: &Path) -> Result<Vec<Finding>>;
fn scan_directory(&self, dir: &Path) -> Result<Vec<Finding>>;
fn scan_path(&self, path: &Path) -> Result<Vec<Finding>> {
trace!(path = %path.display(), "Scanning path");
if !path.exists() {
debug!(path = %path.display(), "Path not found");
return Err(AuditError::FileNotFound(path.display().to_string()));
}
if path.is_file() {
trace!(path = %path.display(), "Scanning as file");
return self.scan_file(path);
}
if !path.is_dir() {
debug!(path = %path.display(), "Path is not a directory");
return Err(AuditError::NotADirectory(path.display().to_string()));
}
trace!(path = %path.display(), "Scanning as directory");
self.scan_directory(path)
}
}
pub trait ContentScanner: Scanner {
fn config(&self) -> &ScannerConfig;
fn scan_content(&self, content: &str, file_path: &str) -> Result<Vec<Finding>> {
Ok(self.config().check_content(content, file_path))
}
}
pub type ProgressCallback = std::sync::Arc<dyn Fn() + Send + Sync>;
pub struct ScannerConfig {
engine: RuleEngine,
ignore_filter: Option<IgnoreFilter>,
skip_comments: bool,
strict_secrets: bool,
recursive: bool,
progress_callback: Option<ProgressCallback>,
}
impl ScannerConfig {
pub fn new() -> Self {
Self {
engine: RuleEngine::new(),
ignore_filter: None,
skip_comments: false,
strict_secrets: false,
recursive: true,
progress_callback: None,
}
}
pub fn with_recursive(mut self, recursive: bool) -> Self {
self.recursive = recursive;
self
}
pub fn is_recursive(&self) -> bool {
self.recursive
}
pub fn max_depth(&self) -> Option<usize> {
if self.recursive { None } else { Some(3) }
}
pub fn with_skip_comments(mut self, skip: bool) -> Self {
self.skip_comments = skip;
self.engine = self.engine.with_skip_comments(skip);
self
}
pub fn with_strict_secrets(mut self, strict: bool) -> Self {
self.strict_secrets = strict;
self.engine = self.engine.with_strict_secrets(strict);
self
}
pub fn with_ignore_filter(mut self, filter: IgnoreFilter) -> Self {
self.ignore_filter = Some(filter);
self
}
pub fn with_dynamic_rules(mut self, rules: Vec<DynamicRule>) -> Self {
self.engine = self.engine.with_dynamic_rules(rules);
self
}
pub fn with_progress_callback(mut self, callback: ProgressCallback) -> Self {
self.progress_callback = Some(callback);
self
}
pub fn report_progress(&self) {
if let Some(ref callback) = self.progress_callback {
callback();
}
}
pub fn is_ignored(&self, path: &Path) -> bool {
self.ignore_filter
.as_ref()
.is_some_and(|f| f.is_ignored(path))
}
pub fn ignore_filter(&self) -> Option<&IgnoreFilter> {
self.ignore_filter.as_ref()
}
pub fn read_file(&self, path: &Path) -> Result<String> {
trace!(path = %path.display(), "Reading file");
fs::read_to_string(path).map_err(|e| {
debug!(path = %path.display(), error = %e, "Failed to read file");
AuditError::ReadError {
path: path.display().to_string(),
source: e,
}
})
}
pub fn check_content(&self, content: &str, file_path: &str) -> Vec<Finding> {
trace!(
file = file_path,
content_len = content.len(),
"Checking content"
);
let findings = self.engine.check_content(content, file_path);
if !findings.is_empty() {
debug!(file = file_path, count = findings.len(), "Found issues");
}
findings
}
pub fn check_frontmatter(&self, frontmatter: &str, file_path: &str) -> Vec<Finding> {
self.engine.check_frontmatter(frontmatter, file_path)
}
pub fn skip_comments(&self) -> bool {
self.skip_comments
}
pub fn strict_secrets(&self) -> bool {
self.strict_secrets
}
pub fn engine(&self) -> &RuleEngine {
&self.engine
}
}
impl Default for ScannerConfig {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use tempfile::TempDir;
#[test]
fn test_new_config() {
let config = ScannerConfig::new();
assert!(!config.skip_comments());
}
#[test]
fn test_progress_callback_is_called() {
use std::sync::Mutex;
let call_count = Arc::new(Mutex::new(0));
let call_count_clone = Arc::clone(&call_count);
let progress_fn = move || {
let mut count = call_count_clone.lock().unwrap();
*count += 1;
};
let config = ScannerConfig::new().with_progress_callback(Arc::new(progress_fn));
config.report_progress();
config.report_progress();
let final_count = *call_count.lock().unwrap();
assert_eq!(final_count, 2, "Progress callback should be called twice");
}
#[test]
fn test_with_skip_comments() {
let config = ScannerConfig::new().with_skip_comments(true);
assert!(config.skip_comments());
}
#[test]
fn test_default_config() {
let config = ScannerConfig::default();
assert!(!config.skip_comments());
}
#[test]
fn test_is_ignored_without_filter() {
let config = ScannerConfig::new();
assert!(!config.is_ignored(Path::new("test.rs")));
}
#[test]
fn test_read_file_success() {
let dir = TempDir::new().unwrap();
let file_path = dir.path().join("test.txt");
fs::write(&file_path, "test content").unwrap();
let config = ScannerConfig::new();
let content = config.read_file(&file_path).unwrap();
assert_eq!(content, "test content");
}
#[test]
fn test_read_file_not_found() {
let config = ScannerConfig::new();
let result = config.read_file(Path::new("/nonexistent/file.txt"));
assert!(result.is_err());
}
#[test]
fn test_check_content_detects_sudo() {
let config = ScannerConfig::new();
let findings = config.check_content("sudo rm -rf /", "test.sh");
assert!(findings.iter().any(|f| f.id == "PE-001"));
}
#[test]
fn test_check_content_skip_comments() {
let config = ScannerConfig::new().with_skip_comments(true);
let findings = config.check_content("# sudo rm -rf /", "test.sh");
assert!(findings.iter().all(|f| f.id != "PE-001"));
}
#[test]
fn test_check_frontmatter_wildcard() {
let config = ScannerConfig::new();
let findings = config.check_frontmatter("allowed-tools: *", "SKILL.md");
assert!(findings.iter().any(|f| f.id == "OP-001"));
}
#[test]
fn test_engine_accessor() {
let config = ScannerConfig::new();
let _engine = config.engine();
}
}