Skip to main content

ignis_db/builders/
sql_validation.rs

1//! SQL Validation and Sanitization
2//!
3//! Provides comprehensive validation and sanitization for custom SQL migrations
4//! to prevent SQL injection and ensure safe database operations.
5
6use anyhow::{anyhow, Result};
7use regex::Regex;
8use std::collections::HashSet;
9
10/// SQL validation result
11#[derive(Debug, Clone)]
12pub struct SqlValidationResult {
13    pub is_valid: bool,
14    pub errors: Vec<String>,
15    pub warnings: Vec<String>,
16    pub sanitized_sql: Option<String>,
17}
18
19/// SQL validator for custom migrations
20pub struct SqlValidator {
21    dangerous_patterns: Vec<Regex>,
22    forbidden_patterns: Vec<Regex>,
23    allowed_operations: HashSet<String>,
24}
25
26impl Default for SqlValidator {
27    fn default() -> Self {
28        Self::new()
29    }
30}
31
32impl SqlValidator {
33    /// Create a new SQL validator with default security rules
34    pub fn new() -> Self {
35        let mut validator = Self {
36            dangerous_patterns: Vec::new(),
37            forbidden_patterns: Vec::new(),
38            allowed_operations: HashSet::new(),
39        };
40
41        validator.initialize_patterns();
42        validator
43    }
44
45    /// Initialize dangerous and forbidden SQL patterns
46    fn initialize_patterns(&mut self) {
47        // Dangerous patterns that require careful review
48        self.dangerous_patterns = vec![
49            Regex::new(r"(?i)\b(DROP|TRUNCATE|DELETE|UPDATE)\b").unwrap(),
50            Regex::new(r"(?i)\b(ALTER|CREATE|DROP)\s+(TABLE|INDEX|DATABASE|SCHEMA)\b").unwrap(),
51            Regex::new(r"(?i)\b(GRANT|REVOKE)\b").unwrap(),
52            Regex::new(r"(?i)\b(EXEC|EXECUTE)\b").unwrap(),
53            Regex::new(r"(?i)\b(UNION|UNION ALL)\b").unwrap(),
54            Regex::new(r"(?i)\b(INTO OUTFILE|INTO DUMPFILE)\b").unwrap(),
55            Regex::new(r"(?i)\b(LOAD_FILE|LOAD DATA)\b").unwrap(),
56        ];
57
58        // Forbidden patterns that should never be allowed
59        self.forbidden_patterns = vec![
60            Regex::new(r"(?i)\b(DROP DATABASE|DROP SCHEMA)\b").unwrap(),
61            Regex::new(r"(?i)\b(TRUNCATE\s+TABLE)\b").unwrap(),
62            Regex::new(r"(?i)\b(DELETE\s+FROM\s+\w+\s*;?\s*$)\b").unwrap(),
63            Regex::new(r"(?i)\b(INSERT\s+INTO\s+\w+\s+VALUES\s*\([^)]*\)\s*;?\s*$)\b").unwrap(),
64            Regex::new(r"(?i)\b(UPDATE\s+\w+\s+SET\s+[^;]*;?\s*$)\b").unwrap(),
65            Regex::new(r"(?i)\b(GRANT\s+ALL|REVOKE\s+ALL)\b").unwrap(),
66            Regex::new(r"(?i)\b(EXEC\s+sp_|EXECUTE\s+sp_)\b").unwrap(),
67            Regex::new(r"(?i)\b(UNION\s+SELECT\s+.*\s+FROM\s+information_schema)\b").unwrap(),
68        ];
69
70        // Allowed operations for custom migrations
71        self.allowed_operations = [
72            "CREATE TABLE",
73            "CREATE INDEX",
74            "CREATE VIEW",
75            "CREATE FUNCTION",
76            "CREATE PROCEDURE",
77            "CREATE TRIGGER",
78            "CREATE SEQUENCE",
79            "ALTER TABLE",
80            "ALTER INDEX",
81            "ALTER VIEW",
82            "DROP TABLE",
83            "DROP INDEX",
84            "DROP VIEW",
85            "DROP FUNCTION",
86            "DROP PROCEDURE",
87            "DROP TRIGGER",
88            "DROP SEQUENCE",
89            "INSERT INTO",
90            "UPDATE",
91            "DELETE FROM",
92            "SELECT",
93            "EXPLAIN",
94            "ANALYZE",
95            "VACUUM",
96        ]
97        .iter()
98        .map(|s| s.to_string())
99        .collect();
100    }
101
102    /// Validate SQL for security and safety
103    pub fn validate(&self, sql: &str) -> SqlValidationResult {
104        let mut errors = Vec::new();
105        let mut warnings = Vec::new();
106
107        // Check for forbidden patterns
108        for pattern in &self.forbidden_patterns {
109            if pattern.is_match(sql) {
110                errors.push(format!(
111                    "Forbidden SQL pattern detected: {}",
112                    pattern.as_str()
113                ));
114            }
115        }
116
117        // Check for dangerous patterns
118        for pattern in &self.dangerous_patterns {
119            if pattern.is_match(sql) {
120                warnings.push(format!("Dangerous DDL patterns detected in statement"));
121            }
122        }
123
124        // Check for SQL injection patterns
125        if self.detect_sql_injection(sql) {
126            errors.push("Potential SQL injection pattern detected".to_string());
127        }
128
129        // Check for balanced parentheses and quotes
130        if !self.is_balanced(sql) {
131            errors.push("Unbalanced parentheses or quotes detected".to_string());
132        }
133
134        // Check for semicolon injection
135        if self.detect_semicolon_injection(sql) {
136            errors.push("Potential semicolon injection detected".to_string());
137        }
138
139        // Validate SQL structure
140        if let Err(e) = self.validate_sql_structure(sql) {
141            errors.push(format!("Invalid SQL structure: {}", e));
142        }
143
144        let is_valid = errors.is_empty();
145        let sanitized_sql = if is_valid {
146            Some(self.sanitize_sql(sql))
147        } else {
148            None
149        };
150
151        SqlValidationResult {
152            is_valid,
153            errors,
154            warnings,
155            sanitized_sql,
156        }
157    }
158
159    /// Detect potential SQL injection patterns
160    fn detect_sql_injection(&self, sql: &str) -> bool {
161        let injection_patterns = [
162            r"(?i)\b(OR|AND)\s+1\s*=\s*1\b",
163            r"(?i)\b(OR|AND)\s+true\b",
164            r"(?i)\b(OR|AND)\s+false\b",
165            r"(?i)\bUNION\s+SELECT\b",
166            r"(?i)\bUNION\s+ALL\s+SELECT\b",
167            r"(?i)\b(SELECT|INSERT|UPDATE|DELETE)\s+.*\s+(OR|AND)\s+.*\b",
168            r"(?i)\b(OR|AND)\s+.*\s*=\s*.*\b",
169            r"(?i)\b(OR|AND)\s+.*\s*LIKE\s+.*\b",
170            r"(?i)\b(OR|AND)\s+.*\s*IN\s*\(.*\)\b",
171            r"(?i)\b(OR|AND)\s+.*\s*BETWEEN\s+.*\b",
172            r"(?i)\b(OR|AND)\s+.*\s*EXISTS\s*\(.*\)\b",
173            r"(?i)\b(OR|AND)\s+.*\s*NOT\s+EXISTS\s*\(.*\)\b",
174        ];
175
176        for pattern in &injection_patterns {
177            if Regex::new(pattern).unwrap().is_match(sql) {
178                return true;
179            }
180        }
181
182        false
183    }
184
185    /// Check if parentheses and quotes are balanced
186    fn is_balanced(&self, sql: &str) -> bool {
187        let mut paren_count = 0;
188        let mut single_quote = false;
189        let mut double_quote = false;
190        let mut backtick = false;
191
192        for ch in sql.chars() {
193            match ch {
194                '(' if !single_quote && !double_quote && !backtick => paren_count += 1,
195                ')' if !single_quote && !double_quote && !backtick => {
196                    paren_count -= 1;
197                    if paren_count < 0 {
198                        return false;
199                    }
200                }
201                '\'' if !double_quote && !backtick => single_quote = !single_quote,
202                '"' if !single_quote && !backtick => double_quote = !double_quote,
203                '`' if !single_quote && !double_quote => backtick = !backtick,
204                _ => {}
205            }
206        }
207
208        paren_count == 0 && !single_quote && !double_quote && !backtick
209    }
210
211    /// Detect potential semicolon injection
212    fn detect_semicolon_injection(&self, sql: &str) -> bool {
213        // Look for multiple statements separated by semicolons
214        let statements: Vec<&str> = sql.split(';').collect();
215        if statements.len() > 1 {
216            // Check if any statement after the first one is potentially dangerous
217            for stmt in statements.iter().skip(1) {
218                let trimmed = stmt.trim();
219                if !trimmed.is_empty() {
220                    for pattern in &self.dangerous_patterns {
221                        if pattern.is_match(trimmed) {
222                            return true;
223                        }
224                    }
225                }
226            }
227        }
228        false
229    }
230
231    /// Validate basic SQL structure
232    fn validate_sql_structure(&self, sql: &str) -> Result<()> {
233        let trimmed = sql.trim();
234
235        if trimmed.is_empty() {
236            return Err(anyhow!("SQL statement cannot be empty"));
237        }
238
239        // Check for basic SQL keywords
240        let sql_upper = trimmed.to_uppercase();
241        let has_sql_keyword = [
242            "SELECT", "INSERT", "UPDATE", "DELETE", "CREATE", "ALTER", "DROP", "EXPLAIN",
243            "ANALYZE", "VACUUM", "GRANT", "REVOKE",
244        ]
245        .iter()
246        .any(|keyword| sql_upper.starts_with(keyword));
247
248        if !has_sql_keyword {
249            return Err(anyhow!("SQL statement must start with a valid SQL keyword"));
250        }
251
252        // Check for minimum length
253        if trimmed.len() < 10 {
254            return Err(anyhow!("SQL statement too short to be valid"));
255        }
256
257        Ok(())
258    }
259
260    /// Sanitize SQL by removing potentially dangerous patterns
261    fn sanitize_sql(&self, sql: &str) -> String {
262        let mut sanitized = sql.to_string();
263
264        // Remove comments that might contain dangerous code
265        let comment_patterns = [
266            r"--.*$",     // Single line comments
267            r"/\*.*?\*/", // Multi-line comments
268        ];
269
270        for pattern in &comment_patterns {
271            let regex = Regex::new(pattern).unwrap();
272            sanitized = regex.replace_all(&sanitized, "").to_string();
273        }
274
275        // Normalize whitespace
276        let whitespace_regex = Regex::new(r"\s+").unwrap();
277        sanitized = whitespace_regex.replace_all(&sanitized, " ").to_string();
278
279        sanitized.trim().to_string()
280    }
281
282    /// Create a validator with custom allowed operations
283    pub fn with_allowed_operations(mut self, operations: Vec<String>) -> Self {
284        self.allowed_operations = operations.into_iter().collect();
285        self
286    }
287
288    /// Add custom dangerous pattern
289    pub fn add_dangerous_pattern(mut self, pattern: Regex) -> Self {
290        self.dangerous_patterns.push(pattern);
291        self
292    }
293
294    /// Add custom forbidden pattern
295    pub fn add_forbidden_pattern(mut self, pattern: Regex) -> Self {
296        self.forbidden_patterns.push(pattern);
297        self
298    }
299}
300
301/// Enhanced SQL validation for custom migrations
302pub struct CustomSqlValidator {
303    base_validator: SqlValidator,
304    migration_context: MigrationContext,
305}
306
307#[derive(Debug, Clone)]
308pub struct MigrationContext {
309    pub is_destructive: bool,
310    pub requires_rollback: bool,
311    pub allowed_tables: Option<Vec<String>>,
312    pub forbidden_tables: Option<Vec<String>>,
313}
314
315impl CustomSqlValidator {
316    /// Create a new custom SQL validator
317    pub fn new() -> Self {
318        Self {
319            base_validator: SqlValidator::new(),
320            migration_context: MigrationContext {
321                is_destructive: false,
322                requires_rollback: true,
323                allowed_tables: None,
324                forbidden_tables: None,
325            },
326        }
327    }
328
329    /// Set migration context
330    pub fn with_context(mut self, context: MigrationContext) -> Self {
331        self.migration_context = context;
332        self
333    }
334
335    /// Validate custom SQL migration
336    pub fn validate_migration(&self, sql: &str) -> SqlValidationResult {
337        let mut result = self.base_validator.validate(sql);
338
339        // Additional migration-specific validation
340        if self.migration_context.is_destructive && !self.detect_destructive_operations(sql) {
341            result.warnings.push(
342                "Migration marked as destructive but no destructive operations detected"
343                    .to_string(),
344            );
345        }
346
347        if self.migration_context.requires_rollback && !self.detect_rollback_safety(sql) {
348            result
349                .warnings
350                .push("Migration requires rollback but may not be safely reversible".to_string());
351        }
352
353        // Check table restrictions
354        if let Some(ref allowed_tables) = self.migration_context.allowed_tables {
355            if let Err(e) = self.validate_table_access(sql, allowed_tables, true) {
356                result.errors.push(e.to_string());
357            }
358        }
359
360        if let Some(ref forbidden_tables) = self.migration_context.forbidden_tables {
361            if let Err(e) = self.validate_table_access(sql, forbidden_tables, false) {
362                result.errors.push(e.to_string());
363            }
364        }
365
366        result
367    }
368
369    /// Detect destructive operations in SQL
370    fn detect_destructive_operations(&self, sql: &str) -> bool {
371        let destructive_patterns = [
372            r"(?i)\b(DROP|TRUNCATE|DELETE)\b",
373            r"(?i)\b(ALTER\s+TABLE.*DROP)\b",
374            r"(?i)\b(ALTER\s+TABLE.*MODIFY)\b",
375        ];
376
377        destructive_patterns
378            .iter()
379            .any(|pattern| Regex::new(pattern).unwrap().is_match(sql))
380    }
381
382    /// Detect if SQL is rollback-safe
383    fn detect_rollback_safety(&self, sql: &str) -> bool {
384        let unsafe_patterns = [
385            r"(?i)\b(TRUNCATE|DROP\s+TABLE)\b",
386            r"(?i)\b(DELETE\s+FROM.*WHERE\s+1\s*=\s*1)\b",
387            r"(?i)\b(DELETE\s+FROM.*WHERE\s+true)\b",
388        ];
389
390        !unsafe_patterns
391            .iter()
392            .any(|pattern| Regex::new(pattern).unwrap().is_match(sql))
393    }
394
395    /// Validate table access permissions
396    fn validate_table_access(&self, sql: &str, tables: &[String], is_allowed: bool) -> Result<()> {
397        let table_pattern = Regex::new(r"(?i)\b(FROM|INTO|UPDATE|DELETE\s+FROM)\s+(\w+)")?;
398
399        for cap in table_pattern.captures_iter(sql) {
400            if let Some(table_match) = cap.get(2) {
401                let table_name = table_match.as_str().to_lowercase();
402                let is_in_list = tables.iter().any(|t| t.to_lowercase() == table_name);
403
404                if is_allowed && !is_in_list {
405                    return Err(anyhow!("Table '{}' is not in the allowed list", table_name));
406                } else if !is_allowed && is_in_list {
407                    return Err(anyhow!("Table '{}' is in the forbidden list", table_name));
408                }
409            }
410        }
411
412        Ok(())
413    }
414}
415
416#[cfg(test)]
417mod tests {
418    use super::*;
419
420    #[test]
421    fn test_sql_validation_safe_operations() {
422        let validator = SqlValidator::new();
423
424        let safe_sql = "CREATE TABLE test (id INT PRIMARY KEY, name VARCHAR(255))";
425        let result = validator.validate(safe_sql);
426
427        assert!(result.is_valid);
428        assert!(result.errors.is_empty());
429    }
430
431    #[test]
432    fn test_sql_validation_dangerous_operations() {
433        let validator = SqlValidator::new();
434
435        let dangerous_sql = "DROP TABLE users";
436        let result = validator.validate(dangerous_sql);
437
438        assert!(!result.warnings.is_empty());
439        assert!(result
440            .warnings
441            .iter()
442            .any(|w| w.contains("Dangerous DDL patterns")));
443    }
444
445    #[test]
446    fn test_sql_validation_forbidden_operations() {
447        let validator = SqlValidator::new();
448
449        let forbidden_sql = "DROP DATABASE test_db";
450        let result = validator.validate(forbidden_sql);
451
452        assert!(!result.is_valid);
453        assert!(result
454            .errors
455            .iter()
456            .any(|e| e.contains("Forbidden SQL pattern")));
457    }
458
459    #[test]
460    fn test_sql_injection_detection() {
461        let validator = SqlValidator::new();
462
463        let injection_sql = "SELECT * FROM users WHERE id = 1 OR 1=1";
464        let result = validator.validate(injection_sql);
465
466        assert!(!result.is_valid);
467        assert!(result.errors.iter().any(|e| e.contains("SQL injection")));
468    }
469
470    #[test]
471    fn test_balanced_parentheses() {
472        let validator = SqlValidator::new();
473
474        let unbalanced_sql = "CREATE TABLE test (id INT, name VARCHAR(255)";
475        let result = validator.validate(unbalanced_sql);
476
477        assert!(!result.is_valid);
478        assert!(result.errors.iter().any(|e| e.contains("Unbalanced")));
479    }
480
481    #[test]
482    fn test_custom_sql_validator_with_context() {
483        let context = MigrationContext {
484            is_destructive: true,
485            requires_rollback: true,
486            allowed_tables: Some(vec!["users".to_string(), "posts".to_string()]),
487            forbidden_tables: None,
488        };
489
490        let validator = CustomSqlValidator::new().with_context(context);
491
492        let sql = "DROP TABLE users";
493        let result = validator.validate_migration(sql);
494
495        assert!(result.is_valid);
496        assert!(result.warnings.is_empty());
497    }
498}