Skip to main content

llm_config_devtools/security/
unsafe_code.rs

1//! Unsafe code detection scanner.
2//!
3//! Scans Rust source files for unsafe code blocks and provides analysis.
4
5use crate::error::Result;
6use crate::security::{Finding, Severity};
7use ignore::WalkBuilder;
8use std::fs;
9use std::path::{Path, PathBuf};
10
11/// Scanner for detecting unsafe code blocks.
12pub struct UnsafeCodeDetector {
13    project_root: PathBuf,
14}
15
16impl UnsafeCodeDetector {
17    /// Create a new unsafe code detector.
18    pub fn new(project_root: &Path) -> Self {
19        Self {
20            project_root: project_root.to_path_buf(),
21        }
22    }
23
24    /// Scan for unsafe code blocks.
25    pub fn scan(&self) -> Result<Vec<Finding>> {
26        tracing::info!("Scanning for unsafe code blocks");
27
28        let mut findings = Vec::new();
29
30        // Walk through all Rust source files
31        for entry in WalkBuilder::new(&self.project_root)
32            .filter_entry(|e| !Self::is_excluded(e.path()))
33            .build()
34        {
35            let entry = entry?;
36            let path = entry.path();
37
38            if path.extension().and_then(|s| s.to_str()) == Some("rs") {
39                if let Ok(content) = fs::read_to_string(path) {
40                    findings.extend(self.scan_file(path, &content)?);
41                }
42            }
43        }
44
45        tracing::info!("Found {} unsafe code blocks", findings.len());
46        Ok(findings)
47    }
48
49    fn is_excluded(path: &Path) -> bool {
50        let path_str = path.to_string_lossy();
51        path_str.contains("target/") || path_str.contains("node_modules/")
52    }
53
54    fn scan_file(&self, path: &Path, content: &str) -> Result<Vec<Finding>> {
55        let mut findings = Vec::new();
56
57        for (line_num, line) in content.lines().enumerate() {
58            if line.trim_start().starts_with("unsafe") {
59                let relative_path = path
60                    .strip_prefix(&self.project_root)
61                    .unwrap_or(path)
62                    .to_path_buf();
63
64                findings.push(Finding {
65                    severity: Severity::Medium,
66                    category: "unsafe_code".to_string(),
67                    title: "Unsafe code block detected".to_string(),
68                    message: "Found unsafe code block. Ensure proper safety invariants are maintained.".to_string(),
69                    file: relative_path,
70                    line: Some(line_num + 1),
71                    column: None,
72                    snippet: Some(line.trim().to_string()),
73                    recommendation: Some(
74                        "Review unsafe code for correctness. Add safety documentation comments explaining why the unsafe code is sound.".to_string(),
75                    ),
76                });
77            }
78        }
79
80        Ok(findings)
81    }
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87    use tempfile::TempDir;
88
89    #[test]
90    fn test_unsafe_code_detector() {
91        let dir = TempDir::new().unwrap();
92        let file_path = dir.path().join("test.rs");
93        fs::write(
94            &file_path,
95            r#"
96fn safe_function() {
97    println!("Safe");
98}
99
100unsafe fn unsafe_function() {
101    // Unsafe operation
102}
103
104fn another_safe() {
105    unsafe {
106        // Unsafe block
107    }
108}
109"#,
110        )
111        .unwrap();
112
113        let detector = UnsafeCodeDetector::new(dir.path());
114        let findings = detector.scan().unwrap();
115
116        // Should find 2 unsafe blocks (function and block)
117        assert!(findings.len() >= 2);
118        assert!(findings.iter().all(|f| f.category == "unsafe_code"));
119    }
120
121    #[test]
122    fn test_no_unsafe_code() {
123        let dir = TempDir::new().unwrap();
124        let file_path = dir.path().join("test.rs");
125        fs::write(
126            &file_path,
127            r#"
128fn safe_function() {
129    println!("All safe!");
130}
131"#,
132        )
133        .unwrap();
134
135        let detector = UnsafeCodeDetector::new(dir.path());
136        let findings = detector.scan().unwrap();
137
138        assert_eq!(findings.len(), 0);
139    }
140}