Skip to main content

llm_config_devtools/security/
sql.rs

1//! SQL injection vulnerability scanner.
2//!
3//! Scans for potential SQL injection vulnerabilities in Rust code.
4
5use crate::error::Result;
6use crate::security::{Finding, Severity};
7use ignore::WalkBuilder;
8use lazy_static::lazy_static;
9use regex::Regex;
10use std::fs;
11use std::path::{Path, PathBuf};
12
13lazy_static! {
14    /// Regex patterns for detecting SQL injection vulnerabilities.
15    static ref SQL_PATTERNS: Vec<SqlPattern> = vec![
16        SqlPattern {
17            name: "format! with SELECT",
18            regex: Regex::new(r#"format!\s*\(\s*["'].*SELECT.*\{.*\}.*["']"#).unwrap(),
19            severity: Severity::Critical,
20        },
21        SqlPattern {
22            name: "format! with INSERT",
23            regex: Regex::new(r#"format!\s*\(\s*["'].*INSERT.*\{.*\}.*["']"#).unwrap(),
24            severity: Severity::Critical,
25        },
26        SqlPattern {
27            name: "format! with UPDATE",
28            regex: Regex::new(r#"format!\s*\(\s*["'].*UPDATE.*\{.*\}.*["']"#).unwrap(),
29            severity: Severity::Critical,
30        },
31        SqlPattern {
32            name: "format! with DELETE",
33            regex: Regex::new(r#"format!\s*\(\s*["'].*DELETE.*\{.*\}.*["']"#).unwrap(),
34            severity: Severity::Critical,
35        },
36        SqlPattern {
37            name: "String concatenation with SELECT",
38            regex: Regex::new(r#"SELECT.*\+.*"#).unwrap(),
39            severity: Severity::High,
40        },
41        SqlPattern {
42            name: "String concatenation with INSERT",
43            regex: Regex::new(r#"INSERT.*\+.*"#).unwrap(),
44            severity: Severity::High,
45        },
46        SqlPattern {
47            name: "String interpolation with sql",
48            regex: Regex::new(r#"&format!\s*\(\s*["'].*sql.*\{.*\}"#).unwrap(),
49            severity: Severity::High,
50        },
51    ];
52}
53
54/// A pattern for detecting SQL injection vulnerabilities.
55struct SqlPattern {
56    name: &'static str,
57    regex: Regex,
58    severity: Severity,
59}
60
61/// Scanner for detecting SQL injection vulnerabilities.
62pub struct SqlInjectionScanner {
63    project_root: PathBuf,
64}
65
66impl SqlInjectionScanner {
67    /// Create a new SQL injection scanner.
68    pub fn new(project_root: &Path) -> Self {
69        Self {
70            project_root: project_root.to_path_buf(),
71        }
72    }
73
74    /// Scan for SQL injection vulnerabilities.
75    pub fn scan(&self) -> Result<Vec<Finding>> {
76        tracing::info!("Scanning for SQL injection vulnerabilities");
77
78        let mut findings = Vec::new();
79
80        // Walk through all Rust source files
81        for entry in WalkBuilder::new(&self.project_root)
82            .filter_entry(|e| !Self::is_excluded(e.path()))
83            .build()
84        {
85            let entry = entry?;
86            let path = entry.path();
87
88            if path.extension().and_then(|s| s.to_str()) == Some("rs") {
89                if let Ok(content) = fs::read_to_string(path) {
90                    findings.extend(self.scan_file(path, &content)?);
91                }
92            }
93        }
94
95        tracing::info!("Found {} potential SQL injection risks", findings.len());
96        Ok(findings)
97    }
98
99    fn is_excluded(path: &Path) -> bool {
100        let path_str = path.to_string_lossy();
101        path_str.contains("target/") || path_str.contains("node_modules/")
102    }
103
104    fn scan_file(&self, path: &Path, content: &str) -> Result<Vec<Finding>> {
105        let mut findings = Vec::new();
106
107        for (line_num, line) in content.lines().enumerate() {
108            // Skip comments
109            let trimmed = line.trim();
110            if trimmed.starts_with("//") || trimmed.starts_with("/*") {
111                continue;
112            }
113
114            for pattern in SQL_PATTERNS.iter() {
115                if pattern.regex.is_match(line) {
116                    let relative_path = path
117                        .strip_prefix(&self.project_root)
118                        .unwrap_or(path)
119                        .to_path_buf();
120
121                    findings.push(Finding {
122                        severity: pattern.severity,
123                        category: "sql_injection".to_string(),
124                        title: format!("Potential SQL injection: {}", pattern.name),
125                        message: format!(
126                            "Found {} which may be vulnerable to SQL injection. Use parameterized queries instead.",
127                            pattern.name
128                        ),
129                        file: relative_path,
130                        line: Some(line_num + 1),
131                        column: None,
132                        snippet: Some(line.trim().to_string()),
133                        recommendation: Some(
134                            "Use parameterized queries or a query builder that prevents SQL injection (e.g., sqlx with compile-time checked queries, or diesel ORM).".to_string(),
135                        ),
136                    });
137                }
138            }
139        }
140
141        Ok(findings)
142    }
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148    use tempfile::TempDir;
149
150    #[test]
151    fn test_sql_injection_scanner_detects_format() {
152        let dir = TempDir::new().unwrap();
153        let file_path = dir.path().join("db.rs");
154        fs::write(
155            &file_path,
156            r#"
157fn bad_query(user_input: &str) -> String {
158    format!("SELECT * FROM users WHERE name = '{}'", user_input)
159}
160"#,
161        )
162        .unwrap();
163
164        let scanner = SqlInjectionScanner::new(dir.path());
165        let findings = scanner.scan().unwrap();
166
167        assert!(findings.len() > 0);
168        assert!(findings.iter().any(|f| f.category == "sql_injection"));
169        assert!(findings.iter().any(|f| f.severity == Severity::Critical));
170    }
171
172    #[test]
173    fn test_sql_injection_scanner_safe_query() {
174        let dir = TempDir::new().unwrap();
175        let file_path = dir.path().join("db.rs");
176        fs::write(
177            &file_path,
178            r#"
179fn safe_query(pool: &Pool) -> Result<Vec<User>> {
180    sqlx::query_as::<_, User>("SELECT * FROM users WHERE id = $1")
181        .bind(user_id)
182        .fetch_all(pool)
183        .await
184}
185"#,
186        )
187        .unwrap();
188
189        let scanner = SqlInjectionScanner::new(dir.path());
190        let findings = scanner.scan().unwrap();
191
192        // Should not flag parameterized queries
193        assert_eq!(findings.len(), 0);
194    }
195}