use crate::error::Result;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
pub mod clippy;
pub mod secret;
pub mod sql;
pub mod unsafe_code;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScanConfig {
pub project_root: PathBuf,
pub scan_clippy: bool,
pub scan_unsafe: bool,
pub scan_secrets: bool,
pub scan_sql: bool,
pub max_workers: Option<usize>,
}
impl Default for ScanConfig {
fn default() -> Self {
Self {
project_root: PathBuf::from("."),
scan_clippy: true,
scan_unsafe: true,
scan_secrets: true,
scan_sql: true,
max_workers: None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
Low,
Medium,
High,
Critical,
}
impl std::fmt::Display for Severity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Severity::Low => write!(f, "LOW"),
Severity::Medium => write!(f, "MEDIUM"),
Severity::High => write!(f, "HIGH"),
Severity::Critical => write!(f, "CRITICAL"),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Finding {
pub severity: Severity,
pub category: String,
pub title: String,
pub message: String,
pub file: PathBuf,
pub line: Option<usize>,
pub column: Option<usize>,
pub snippet: Option<String>,
pub recommendation: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityReport {
pub timestamp: DateTime<Utc>,
pub project_root: PathBuf,
pub git_commit: Option<String>,
pub git_branch: Option<String>,
pub findings: Vec<Finding>,
pub summary: ScanSummary,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScanSummary {
pub total: usize,
pub critical: usize,
pub high: usize,
pub medium: usize,
pub low: usize,
pub files_scanned: usize,
pub duration_seconds: f64,
}
impl SecurityReport {
pub fn new(project_root: PathBuf, findings: Vec<Finding>) -> Self {
let summary = Self::calculate_summary(&findings);
Self {
timestamp: Utc::now(),
project_root,
git_commit: Self::get_git_commit().ok(),
git_branch: Self::get_git_branch().ok(),
findings,
summary,
}
}
fn calculate_summary(findings: &[Finding]) -> ScanSummary {
let total = findings.len();
let critical = findings
.iter()
.filter(|f| f.severity == Severity::Critical)
.count();
let high = findings
.iter()
.filter(|f| f.severity == Severity::High)
.count();
let medium = findings
.iter()
.filter(|f| f.severity == Severity::Medium)
.count();
let low = findings
.iter()
.filter(|f| f.severity == Severity::Low)
.count();
ScanSummary {
total,
critical,
high,
medium,
low,
files_scanned: 0,
duration_seconds: 0.0,
}
}
fn get_git_commit() -> Result<String> {
let repo = git2::Repository::discover(".")?;
let head = repo.head()?;
let commit = head.peel_to_commit()?;
Ok(commit.id().to_string())
}
fn get_git_branch() -> Result<String> {
let repo = git2::Repository::discover(".")?;
let head = repo.head()?;
let branch = head.shorthand().unwrap_or("unknown").to_string();
Ok(branch)
}
pub fn has_high_severity(&self) -> bool {
self.summary.critical > 0 || self.summary.high > 0
}
}
pub struct SecurityScanner {
config: ScanConfig,
}
impl SecurityScanner {
pub fn new(config: ScanConfig) -> Self {
Self { config }
}
pub fn scan(&self) -> Result<SecurityReport> {
use rayon::prelude::*;
let start_time = std::time::Instant::now();
let mut findings = Vec::new();
tracing::info!("Starting security scan at {:?}", self.config.project_root);
let mut scanners: Vec<Box<dyn Fn() -> Result<Vec<Finding>> + Send + Sync>> = Vec::new();
if self.config.scan_clippy {
let root = self.config.project_root.clone();
scanners.push(Box::new(move || {
clippy::ClippyScanner::new(&root).scan()
}));
}
if self.config.scan_unsafe {
let root = self.config.project_root.clone();
scanners.push(Box::new(move || {
unsafe_code::UnsafeCodeDetector::new(&root).scan()
}));
}
if self.config.scan_secrets {
let root = self.config.project_root.clone();
scanners.push(Box::new(move || {
secret::SecretScanner::new(&root).scan()
}));
}
if self.config.scan_sql {
let root = self.config.project_root.clone();
scanners.push(Box::new(move || {
sql::SqlInjectionScanner::new(&root).scan()
}));
}
let scan_results: Vec<Result<Vec<Finding>>> = scanners
.par_iter()
.map(|scanner| scanner())
.collect();
for result in scan_results {
match result {
Ok(mut found) => findings.append(&mut found),
Err(e) => tracing::warn!("Scanner error: {}", e),
}
}
let duration = start_time.elapsed();
let mut report = SecurityReport::new(self.config.project_root.clone(), findings);
report.summary.duration_seconds = duration.as_secs_f64();
tracing::info!(
"Security scan complete: {} findings in {:.2}s",
report.summary.total,
report.summary.duration_seconds
);
Ok(report)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_severity_ordering() {
assert!(Severity::Critical > Severity::High);
assert!(Severity::High > Severity::Medium);
assert!(Severity::Medium > Severity::Low);
}
#[test]
fn test_default_config() {
let config = ScanConfig::default();
assert!(config.scan_clippy);
assert!(config.scan_unsafe);
assert!(config.scan_secrets);
assert!(config.scan_sql);
}
#[test]
fn test_security_report_summary() {
let findings = vec![
Finding {
severity: Severity::Critical,
category: "test".to_string(),
title: "Test Critical".to_string(),
message: "Test message".to_string(),
file: PathBuf::from("test.rs"),
line: Some(1),
column: None,
snippet: None,
recommendation: None,
},
Finding {
severity: Severity::High,
category: "test".to_string(),
title: "Test High".to_string(),
message: "Test message".to_string(),
file: PathBuf::from("test.rs"),
line: Some(2),
column: None,
snippet: None,
recommendation: None,
},
];
let report = SecurityReport::new(PathBuf::from("."), findings);
assert_eq!(report.summary.total, 2);
assert_eq!(report.summary.critical, 1);
assert_eq!(report.summary.high, 1);
assert!(report.has_high_severity());
}
}