llm_config_devtools/security/
mod.rs1use 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#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct ScanConfig {
22 pub project_root: PathBuf,
24
25 pub scan_clippy: bool,
27
28 pub scan_unsafe: bool,
30
31 pub scan_secrets: bool,
33
34 pub scan_sql: bool,
36
37 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
56#[serde(rename_all = "lowercase")]
57pub enum Severity {
58 Low,
60 Medium,
62 High,
64 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#[derive(Debug, Clone, Serialize, Deserialize)]
81pub struct Finding {
82 pub severity: Severity,
84
85 pub category: String,
87
88 pub title: String,
90
91 pub message: String,
93
94 pub file: PathBuf,
96
97 pub line: Option<usize>,
99
100 pub column: Option<usize>,
102
103 pub snippet: Option<String>,
105
106 pub recommendation: Option<String>,
108}
109
110#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct SecurityReport {
113 pub timestamp: DateTime<Utc>,
115
116 pub project_root: PathBuf,
118
119 pub git_commit: Option<String>,
121
122 pub git_branch: Option<String>,
124
125 pub findings: Vec<Finding>,
127
128 pub summary: ScanSummary,
130}
131
132#[derive(Debug, Clone, Serialize, Deserialize)]
134pub struct ScanSummary {
135 pub total: usize,
137
138 pub critical: usize,
140
141 pub high: usize,
143
144 pub medium: usize,
146
147 pub low: usize,
149
150 pub files_scanned: usize,
152
153 pub duration_seconds: f64,
155}
156
157impl SecurityReport {
158 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 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 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 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 pub fn has_high_severity(&self) -> bool {
221 self.summary.critical > 0 || self.summary.high > 0
222 }
223}
224
225pub struct SecurityScanner {
227 config: ScanConfig,
228}
229
230impl SecurityScanner {
231 pub fn new(config: ScanConfig) -> Self {
233 Self { config }
234 }
235
236 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 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 let scan_results: Vec<Result<Vec<Finding>>> = scanners
278 .par_iter()
279 .map(|scanner| scanner())
280 .collect();
281
282 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}