Skip to main content

llm_config_devtools/security/
mod.rs

1//! Security scanning module.
2//!
3//! This module provides comprehensive security scanning capabilities including:
4//! - Clippy security lints
5//! - Unsafe code detection
6//! - Secret scanning
7//! - SQL injection vulnerability detection
8
9use crate::error::Result;
10use chrono::{DateTime, Utc};
11use serde::{Deserialize, Serialize};
12use std::path::PathBuf;
13
14pub mod clippy;
15pub mod secret;
16pub mod sql;
17pub mod unsafe_code;
18
19/// Security scan configuration.
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct ScanConfig {
22    /// Project root directory.
23    pub project_root: PathBuf,
24
25    /// Whether to include clippy scanning.
26    pub scan_clippy: bool,
27
28    /// Whether to scan for unsafe code.
29    pub scan_unsafe: bool,
30
31    /// Whether to scan for secrets.
32    pub scan_secrets: bool,
33
34    /// Whether to scan for SQL injection.
35    pub scan_sql: bool,
36
37    /// Maximum number of parallel workers.
38    pub max_workers: Option<usize>,
39}
40
41impl Default for ScanConfig {
42    fn default() -> Self {
43        Self {
44            project_root: PathBuf::from("."),
45            scan_clippy: true,
46            scan_unsafe: true,
47            scan_secrets: true,
48            scan_sql: true,
49            max_workers: None,
50        }
51    }
52}
53
54/// Security finding severity level.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
56#[serde(rename_all = "lowercase")]
57pub enum Severity {
58    /// Low severity - informational.
59    Low,
60    /// Medium severity - should be reviewed.
61    Medium,
62    /// High severity - should be fixed soon.
63    High,
64    /// Critical severity - must be fixed immediately.
65    Critical,
66}
67
68impl std::fmt::Display for Severity {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        match self {
71            Severity::Low => write!(f, "LOW"),
72            Severity::Medium => write!(f, "MEDIUM"),
73            Severity::High => write!(f, "HIGH"),
74            Severity::Critical => write!(f, "CRITICAL"),
75        }
76    }
77}
78
79/// A single security finding.
80#[derive(Debug, Clone, Serialize, Deserialize)]
81pub struct Finding {
82    /// Finding severity.
83    pub severity: Severity,
84
85    /// Finding category (e.g., "unsafe_code", "secret", "sql_injection").
86    pub category: String,
87
88    /// Brief description of the finding.
89    pub title: String,
90
91    /// Detailed message about the finding.
92    pub message: String,
93
94    /// File path where the finding was detected.
95    pub file: PathBuf,
96
97    /// Line number (if applicable).
98    pub line: Option<usize>,
99
100    /// Column number (if applicable).
101    pub column: Option<usize>,
102
103    /// Code snippet (if applicable).
104    pub snippet: Option<String>,
105
106    /// Recommendation for fixing.
107    pub recommendation: Option<String>,
108}
109
110/// Complete security scan report.
111#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct SecurityReport {
113    /// Timestamp when the scan was performed.
114    pub timestamp: DateTime<Utc>,
115
116    /// Project root directory.
117    pub project_root: PathBuf,
118
119    /// Git commit hash (if available).
120    pub git_commit: Option<String>,
121
122    /// Git branch (if available).
123    pub git_branch: Option<String>,
124
125    /// All findings from the scan.
126    pub findings: Vec<Finding>,
127
128    /// Summary statistics.
129    pub summary: ScanSummary,
130}
131
132/// Summary statistics for a security scan.
133#[derive(Debug, Clone, Serialize, Deserialize)]
134pub struct ScanSummary {
135    /// Total number of findings.
136    pub total: usize,
137
138    /// Number of critical findings.
139    pub critical: usize,
140
141    /// Number of high severity findings.
142    pub high: usize,
143
144    /// Number of medium severity findings.
145    pub medium: usize,
146
147    /// Number of low severity findings.
148    pub low: usize,
149
150    /// Number of files scanned.
151    pub files_scanned: usize,
152
153    /// Scan duration in seconds.
154    pub duration_seconds: f64,
155}
156
157impl SecurityReport {
158    /// Create a new security report.
159    pub fn new(project_root: PathBuf, findings: Vec<Finding>) -> Self {
160        let summary = Self::calculate_summary(&findings);
161
162        Self {
163            timestamp: Utc::now(),
164            project_root,
165            git_commit: Self::get_git_commit().ok(),
166            git_branch: Self::get_git_branch().ok(),
167            findings,
168            summary,
169        }
170    }
171
172    /// Calculate summary statistics from findings.
173    fn calculate_summary(findings: &[Finding]) -> ScanSummary {
174        let total = findings.len();
175        let critical = findings
176            .iter()
177            .filter(|f| f.severity == Severity::Critical)
178            .count();
179        let high = findings
180            .iter()
181            .filter(|f| f.severity == Severity::High)
182            .count();
183        let medium = findings
184            .iter()
185            .filter(|f| f.severity == Severity::Medium)
186            .count();
187        let low = findings
188            .iter()
189            .filter(|f| f.severity == Severity::Low)
190            .count();
191
192        ScanSummary {
193            total,
194            critical,
195            high,
196            medium,
197            low,
198            files_scanned: 0,
199            duration_seconds: 0.0,
200        }
201    }
202
203    /// Get current git commit hash.
204    fn get_git_commit() -> Result<String> {
205        let repo = git2::Repository::discover(".")?;
206        let head = repo.head()?;
207        let commit = head.peel_to_commit()?;
208        Ok(commit.id().to_string())
209    }
210
211    /// Get current git branch.
212    fn get_git_branch() -> Result<String> {
213        let repo = git2::Repository::discover(".")?;
214        let head = repo.head()?;
215        let branch = head.shorthand().unwrap_or("unknown").to_string();
216        Ok(branch)
217    }
218
219    /// Check if there are any critical or high severity findings.
220    pub fn has_high_severity(&self) -> bool {
221        self.summary.critical > 0 || self.summary.high > 0
222    }
223}
224
225/// Main security scanner.
226pub struct SecurityScanner {
227    config: ScanConfig,
228}
229
230impl SecurityScanner {
231    /// Create a new security scanner with the given configuration.
232    pub fn new(config: ScanConfig) -> Self {
233        Self { config }
234    }
235
236    /// Run the security scan.
237    pub fn scan(&self) -> Result<SecurityReport> {
238        use rayon::prelude::*;
239
240        let start_time = std::time::Instant::now();
241        let mut findings = Vec::new();
242
243        tracing::info!("Starting security scan at {:?}", self.config.project_root);
244
245        // Collect scanner functions to run
246        let mut scanners: Vec<Box<dyn Fn() -> Result<Vec<Finding>> + Send + Sync>> = Vec::new();
247
248        if self.config.scan_clippy {
249            let root = self.config.project_root.clone();
250            scanners.push(Box::new(move || {
251                clippy::ClippyScanner::new(&root).scan()
252            }));
253        }
254
255        if self.config.scan_unsafe {
256            let root = self.config.project_root.clone();
257            scanners.push(Box::new(move || {
258                unsafe_code::UnsafeCodeDetector::new(&root).scan()
259            }));
260        }
261
262        if self.config.scan_secrets {
263            let root = self.config.project_root.clone();
264            scanners.push(Box::new(move || {
265                secret::SecretScanner::new(&root).scan()
266            }));
267        }
268
269        if self.config.scan_sql {
270            let root = self.config.project_root.clone();
271            scanners.push(Box::new(move || {
272                sql::SqlInjectionScanner::new(&root).scan()
273            }));
274        }
275
276        // Run scans in parallel using rayon
277        let scan_results: Vec<Result<Vec<Finding>>> = scanners
278            .par_iter()
279            .map(|scanner| scanner())
280            .collect();
281
282        // Collect all findings
283        for result in scan_results {
284            match result {
285                Ok(mut found) => findings.append(&mut found),
286                Err(e) => tracing::warn!("Scanner error: {}", e),
287            }
288        }
289
290        let duration = start_time.elapsed();
291        let mut report = SecurityReport::new(self.config.project_root.clone(), findings);
292        report.summary.duration_seconds = duration.as_secs_f64();
293
294        tracing::info!(
295            "Security scan complete: {} findings in {:.2}s",
296            report.summary.total,
297            report.summary.duration_seconds
298        );
299
300        Ok(report)
301    }
302}
303
304#[cfg(test)]
305mod tests {
306    use super::*;
307
308    #[test]
309    fn test_severity_ordering() {
310        assert!(Severity::Critical > Severity::High);
311        assert!(Severity::High > Severity::Medium);
312        assert!(Severity::Medium > Severity::Low);
313    }
314
315    #[test]
316    fn test_default_config() {
317        let config = ScanConfig::default();
318        assert!(config.scan_clippy);
319        assert!(config.scan_unsafe);
320        assert!(config.scan_secrets);
321        assert!(config.scan_sql);
322    }
323
324    #[test]
325    fn test_security_report_summary() {
326        let findings = vec![
327            Finding {
328                severity: Severity::Critical,
329                category: "test".to_string(),
330                title: "Test Critical".to_string(),
331                message: "Test message".to_string(),
332                file: PathBuf::from("test.rs"),
333                line: Some(1),
334                column: None,
335                snippet: None,
336                recommendation: None,
337            },
338            Finding {
339                severity: Severity::High,
340                category: "test".to_string(),
341                title: "Test High".to_string(),
342                message: "Test message".to_string(),
343                file: PathBuf::from("test.rs"),
344                line: Some(2),
345                column: None,
346                snippet: None,
347                recommendation: None,
348            },
349        ];
350
351        let report = SecurityReport::new(PathBuf::from("."), findings);
352        assert_eq!(report.summary.total, 2);
353        assert_eq!(report.summary.critical, 1);
354        assert_eq!(report.summary.high, 1);
355        assert!(report.has_high_severity());
356    }
357}