Skip to main content

llm_config_devtools/security/
clippy.rs

1//! Clippy security lints scanner.
2//!
3//! Runs cargo clippy with security-focused lints and parses the output.
4
5use crate::error::{DevtoolsError, Result};
6use crate::security::{Finding, Severity};
7use std::path::{Path, PathBuf};
8use std::process::Command;
9
10/// Scanner for running clippy with security lints.
11pub struct ClippyScanner {
12    project_root: PathBuf,
13}
14
15impl ClippyScanner {
16    /// Create a new clippy scanner.
17    pub fn new(project_root: &Path) -> Self {
18        Self {
19            project_root: project_root.to_path_buf(),
20        }
21    }
22
23    /// Run clippy security scan.
24    pub fn scan(&self) -> Result<Vec<Finding>> {
25        tracing::info!("Running clippy security lints");
26
27        // Check if clippy is available
28        if !self.is_clippy_available() {
29            tracing::warn!("Clippy not available, skipping scan");
30            return Ok(Vec::new());
31        }
32
33        let output = Command::new("cargo")
34            .arg("clippy")
35            .arg("--all-targets")
36            .arg("--all-features")
37            .arg("--message-format=json")
38            .arg("--")
39            .arg("-W")
40            .arg("clippy::all")
41            .arg("-W")
42            .arg("clippy::pedantic")
43            .arg("-W")
44            .arg("clippy::nursery")
45            .arg("-W")
46            .arg("clippy::cargo")
47            .arg("-W")
48            .arg("unsafe-code")
49            .arg("-W")
50            .arg("missing-docs")
51            .arg("-A")
52            .arg("clippy::module-name-repetitions")
53            .arg("-A")
54            .arg("clippy::missing-errors-doc")
55            .arg("-A")
56            .arg("clippy::missing-panics-doc")
57            .current_dir(&self.project_root)
58            .output()
59            .map_err(|e| DevtoolsError::CargoExecution(e.to_string()))?;
60
61        if !output.status.success() {
62            let stderr = String::from_utf8_lossy(&output.stderr);
63            tracing::warn!("Clippy exited with non-zero status: {}", stderr);
64        }
65
66        let stdout = String::from_utf8_lossy(&output.stdout);
67        self.parse_clippy_output(&stdout)
68    }
69
70    fn is_clippy_available(&self) -> bool {
71        Command::new("cargo")
72            .arg("clippy")
73            .arg("--version")
74            .output()
75            .is_ok()
76    }
77
78    fn parse_clippy_output(&self, output: &str) -> Result<Vec<Finding>> {
79        let mut findings = Vec::new();
80
81        for line in output.lines() {
82            if let Ok(message) = serde_json::from_str::<serde_json::Value>(line) {
83                if let Some(msg) = message.get("message") {
84                    if let Some(level) = msg.get("level").and_then(|l| l.as_str()) {
85                        if level == "warning" || level == "error" {
86                            if let Some(finding) = self.parse_clippy_message(msg) {
87                                findings.push(finding);
88                            }
89                        }
90                    }
91                }
92            }
93        }
94
95        tracing::info!("Found {} clippy warnings/errors", findings.len());
96        Ok(findings)
97    }
98
99    fn parse_clippy_message(&self, msg: &serde_json::Value) -> Option<Finding> {
100        let message = msg.get("message")?.as_str()?.to_string();
101        let code = msg
102            .get("code")
103            .and_then(|c| c.get("code"))
104            .and_then(|c| c.as_str())
105            .unwrap_or("unknown");
106
107        let spans = msg.get("spans")?.as_array()?;
108        let span = spans.first()?;
109
110        let file = span
111            .get("file_name")
112            .and_then(|f| f.as_str())
113            .map(PathBuf::from)?;
114        let line = span.get("line_start").and_then(|l| l.as_u64()).map(|l| l as usize);
115        let column = span.get("column_start").and_then(|c| c.as_u64()).map(|c| c as usize);
116
117        let snippet = span
118            .get("text")
119            .and_then(|t| t.as_array())
120            .and_then(|arr| arr.first())
121            .and_then(|t| t.get("text"))
122            .and_then(|t| t.as_str())
123            .map(|s| s.to_string());
124
125        let severity = if code.contains("unsafe") || code.contains("security") {
126            Severity::High
127        } else if code.contains("clippy::pedantic") || code.contains("clippy::nursery") {
128            Severity::Medium
129        } else {
130            Severity::Low
131        };
132
133        Some(Finding {
134            severity,
135            category: "clippy".to_string(),
136            title: format!("Clippy: {}", code),
137            message,
138            file,
139            line,
140            column,
141            snippet,
142            recommendation: Some("Run 'cargo clippy --fix' to automatically fix some issues".to_string()),
143        })
144    }
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150
151    #[test]
152    fn test_clippy_scanner_creation() {
153        let scanner = ClippyScanner::new(Path::new("."));
154        assert_eq!(scanner.project_root, PathBuf::from("."));
155    }
156
157    #[test]
158    fn test_clippy_available() {
159        let scanner = ClippyScanner::new(Path::new("."));
160        // This might be false in CI without Rust toolchain
161        let _ = scanner.is_clippy_available();
162    }
163}