ferrous_forge/
security.rs

1//! Security audit integration module
2//!
3//! This module provides integration with cargo-audit to scan for security
4//! vulnerabilities in dependencies.
5
6use crate::{Error, Result};
7use serde::{Deserialize, Serialize};
8use std::path::Path;
9use std::process::Command;
10
11/// Security audit report
12#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct AuditReport {
14    /// List of vulnerabilities found
15    pub vulnerabilities: Vec<Vulnerability>,
16    /// Total number of dependencies
17    pub dependencies_count: usize,
18    /// Whether the audit passed (no vulnerabilities)
19    pub passed: bool,
20}
21
22/// A single security vulnerability
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct Vulnerability {
25    /// Package name
26    pub package: String,
27    /// Version with vulnerability
28    pub version: String,
29    /// Severity level
30    pub severity: String,
31    /// Title of the vulnerability
32    pub title: String,
33    /// Description of the issue
34    pub description: String,
35    /// CVE identifier if available
36    pub cve: Option<String>,
37    /// CVSS score if available
38    pub cvss: Option<f32>,
39}
40
41impl AuditReport {
42    /// Generate a human-readable report
43    pub fn report(&self) -> String {
44        let mut report = String::new();
45
46        if self.passed {
47            report.push_str("✅ Security audit passed - No vulnerabilities found!\n");
48            report.push_str(&format!(
49                "   Scanned {} dependencies\n",
50                self.dependencies_count
51            ));
52        } else {
53            report.push_str(&format!(
54                "🚨 Security audit failed - Found {} vulnerabilities\n\n",
55                self.vulnerabilities.len()
56            ));
57
58            for vuln in &self.vulnerabilities {
59                let severity_emoji = match vuln.severity.to_lowercase().as_str() {
60                    "critical" => "🔴",
61                    "high" => "🟠",
62                    "medium" => "🟡",
63                    "low" => "🟢",
64                    _ => "⚪",
65                };
66
67                report.push_str(&format!(
68                    "{} {} [{}] in {} v{}\n",
69                    severity_emoji,
70                    vuln.severity.to_uppercase(),
71                    vuln.cve.as_ref().unwrap_or(&"N/A".to_string()),
72                    vuln.package,
73                    vuln.version
74                ));
75                report.push_str(&format!("   {}\n", vuln.title));
76                report.push_str(&format!("   {}\n", vuln.description));
77
78                if let Some(cvss) = vuln.cvss {
79                    report.push_str(&format!("   CVSS Score: {:.1}\n", cvss));
80                }
81
82                report.push('\n');
83            }
84        }
85
86        report
87    }
88}
89
90/// Run security audit on a project
91pub async fn run_security_audit(project_path: &Path) -> Result<AuditReport> {
92    // Ensure cargo-audit is installed
93    ensure_cargo_audit_installed().await?;
94
95    // Run cargo audit with JSON output
96    let output = Command::new("cargo")
97        .args(&["audit", "--json"])
98        .current_dir(project_path)
99        .output()
100        .map_err(|e| Error::process(format!("Failed to run cargo audit: {}", e)))?;
101
102    // Parse the output
103    parse_audit_output(&output.stdout)
104}
105
106/// Ensure cargo-audit is installed
107async fn ensure_cargo_audit_installed() -> Result<()> {
108    let check = Command::new("cargo").args(&["audit", "--version"]).output();
109
110    if check
111        .as_ref()
112        .map_or(true, |output| !output.status.success())
113    {
114        println!("📦 Installing cargo-audit for security scanning...");
115
116        let install = Command::new("cargo")
117            .args(&["install", "cargo-audit", "--locked"])
118            .output()
119            .map_err(|e| Error::process(format!("Failed to install cargo-audit: {}", e)))?;
120
121        if !install.status.success() {
122            return Err(Error::process("Failed to install cargo-audit"));
123        }
124
125        println!("✅ cargo-audit installed successfully");
126    }
127
128    Ok(())
129}
130
131/// Parse cargo audit JSON output
132fn parse_audit_output(output: &[u8]) -> Result<AuditReport> {
133    let output_str = String::from_utf8_lossy(output);
134
135    // Try to parse as JSON
136    if let Ok(json) = serde_json::from_str::<serde_json::Value>(&output_str) {
137        let mut vulnerabilities = Vec::new();
138
139        // Extract vulnerabilities from the JSON structure
140        if let Some(vulns) = json["vulnerabilities"]["list"].as_array() {
141            for vuln in vulns {
142                if let Some(advisory) = vuln["advisory"].as_object() {
143                    vulnerabilities.push(Vulnerability {
144                        package: vuln["package"]["name"]
145                            .as_str()
146                            .unwrap_or("unknown")
147                            .to_string(),
148                        version: vuln["package"]["version"]
149                            .as_str()
150                            .unwrap_or("unknown")
151                            .to_string(),
152                        severity: advisory["severity"]
153                            .as_str()
154                            .unwrap_or("unknown")
155                            .to_string(),
156                        title: advisory["title"]
157                            .as_str()
158                            .unwrap_or("Security vulnerability")
159                            .to_string(),
160                        description: advisory["description"]
161                            .as_str()
162                            .unwrap_or("No description available")
163                            .to_string(),
164                        cve: advisory["id"].as_str().map(String::from),
165                        cvss: advisory["cvss"].as_f64().map(|v| v as f32),
166                    });
167                }
168            }
169        }
170
171        let dependencies_count = json["dependencies"]["count"].as_u64().unwrap_or(0) as usize;
172
173        Ok(AuditReport {
174            passed: vulnerabilities.is_empty(),
175            vulnerabilities,
176            dependencies_count,
177        })
178    } else {
179        // Fallback: If JSON parsing fails, check for success/failure in text
180        if output_str.contains("0 vulnerabilities") || output_str.contains("Success") {
181            Ok(AuditReport {
182                vulnerabilities: vec![],
183                dependencies_count: 0,
184                passed: true,
185            })
186        } else {
187            // Try to extract vulnerability count from text
188            let vuln_count = if output_str.contains("vulnerability") {
189                1
190            } else {
191                0
192            };
193
194            Ok(AuditReport {
195                vulnerabilities: vec![],
196                dependencies_count: 0,
197                passed: vuln_count == 0,
198            })
199        }
200    }
201}
202
203/// Quick security check (non-blocking)
204pub async fn quick_security_check(project_path: &Path) -> Result<bool> {
205    // Check if Cargo.lock exists
206    let cargo_lock = project_path.join("Cargo.lock");
207    if !cargo_lock.exists() {
208        return Ok(true); // No dependencies to check
209    }
210
211    // Run quick audit check
212    match run_security_audit(project_path).await {
213        Ok(report) => Ok(report.passed),
214        Err(_) => Ok(true), // Don't block on audit failures
215    }
216}
217
218#[cfg(test)]
219#[allow(clippy::expect_used, clippy::unwrap_used)]
220mod tests {
221    use super::*;
222
223    #[test]
224    fn test_vulnerability_severity_classification() {
225        let vuln = Vulnerability {
226            package: "test".to_string(),
227            version: "1.0.0".to_string(),
228            severity: "critical".to_string(),
229            title: "Test vulnerability".to_string(),
230            description: "Test description".to_string(),
231            cve: Some("CVE-2024-0001".to_string()),
232            cvss: Some(9.5),
233        };
234
235        assert_eq!(vuln.severity, "critical");
236        assert!(vuln.cvss.unwrap_or(0.0) > 9.0);
237    }
238
239    #[test]
240    fn test_audit_report_passed() {
241        let report = AuditReport {
242            vulnerabilities: vec![],
243            dependencies_count: 10,
244            passed: true,
245        };
246
247        assert!(report.passed);
248        assert!(report.vulnerabilities.is_empty());
249    }
250}