ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! SQL Validation and Sanitization
//!
//! Provides comprehensive validation and sanitization for custom SQL migrations
//! to prevent SQL injection and ensure safe database operations.

use anyhow::{anyhow, Result};
use regex::Regex;
use std::collections::HashSet;

/// SQL validation result
#[derive(Debug, Clone)]
pub struct SqlValidationResult {
    pub is_valid: bool,
    pub errors: Vec<String>,
    pub warnings: Vec<String>,
    pub sanitized_sql: Option<String>,
}

/// SQL validator for custom migrations
pub struct SqlValidator {
    dangerous_patterns: Vec<Regex>,
    forbidden_patterns: Vec<Regex>,
    allowed_operations: HashSet<String>,
}

impl Default for SqlValidator {
    fn default() -> Self {
        Self::new()
    }
}

impl SqlValidator {
    /// Create a new SQL validator with default security rules
    pub fn new() -> Self {
        let mut validator = Self {
            dangerous_patterns: Vec::new(),
            forbidden_patterns: Vec::new(),
            allowed_operations: HashSet::new(),
        };

        validator.initialize_patterns();
        validator
    }

    /// Initialize dangerous and forbidden SQL patterns
    fn initialize_patterns(&mut self) {
        // Dangerous patterns that require careful review
        self.dangerous_patterns = vec![
            Regex::new(r"(?i)\b(DROP|TRUNCATE|DELETE|UPDATE)\b").unwrap(),
            Regex::new(r"(?i)\b(ALTER|CREATE|DROP)\s+(TABLE|INDEX|DATABASE|SCHEMA)\b").unwrap(),
            Regex::new(r"(?i)\b(GRANT|REVOKE)\b").unwrap(),
            Regex::new(r"(?i)\b(EXEC|EXECUTE)\b").unwrap(),
            Regex::new(r"(?i)\b(UNION|UNION ALL)\b").unwrap(),
            Regex::new(r"(?i)\b(INTO OUTFILE|INTO DUMPFILE)\b").unwrap(),
            Regex::new(r"(?i)\b(LOAD_FILE|LOAD DATA)\b").unwrap(),
        ];

        // Forbidden patterns that should never be allowed
        self.forbidden_patterns = vec![
            Regex::new(r"(?i)\b(DROP DATABASE|DROP SCHEMA)\b").unwrap(),
            Regex::new(r"(?i)\b(TRUNCATE\s+TABLE)\b").unwrap(),
            Regex::new(r"(?i)\b(DELETE\s+FROM\s+\w+\s*;?\s*$)\b").unwrap(),
            Regex::new(r"(?i)\b(INSERT\s+INTO\s+\w+\s+VALUES\s*\([^)]*\)\s*;?\s*$)\b").unwrap(),
            Regex::new(r"(?i)\b(UPDATE\s+\w+\s+SET\s+[^;]*;?\s*$)\b").unwrap(),
            Regex::new(r"(?i)\b(GRANT\s+ALL|REVOKE\s+ALL)\b").unwrap(),
            Regex::new(r"(?i)\b(EXEC\s+sp_|EXECUTE\s+sp_)\b").unwrap(),
            Regex::new(r"(?i)\b(UNION\s+SELECT\s+.*\s+FROM\s+information_schema)\b").unwrap(),
        ];

        // Allowed operations for custom migrations
        self.allowed_operations = [
            "CREATE TABLE",
            "CREATE INDEX",
            "CREATE VIEW",
            "CREATE FUNCTION",
            "CREATE PROCEDURE",
            "CREATE TRIGGER",
            "CREATE SEQUENCE",
            "ALTER TABLE",
            "ALTER INDEX",
            "ALTER VIEW",
            "DROP TABLE",
            "DROP INDEX",
            "DROP VIEW",
            "DROP FUNCTION",
            "DROP PROCEDURE",
            "DROP TRIGGER",
            "DROP SEQUENCE",
            "INSERT INTO",
            "UPDATE",
            "DELETE FROM",
            "SELECT",
            "EXPLAIN",
            "ANALYZE",
            "VACUUM",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
    }

    /// Validate SQL for security and safety
    pub fn validate(&self, sql: &str) -> SqlValidationResult {
        let mut errors = Vec::new();
        let mut warnings = Vec::new();

        // Check for forbidden patterns
        for pattern in &self.forbidden_patterns {
            if pattern.is_match(sql) {
                errors.push(format!(
                    "Forbidden SQL pattern detected: {}",
                    pattern.as_str()
                ));
            }
        }

        // Check for dangerous patterns
        for pattern in &self.dangerous_patterns {
            if pattern.is_match(sql) {
                warnings.push(format!("Dangerous DDL patterns detected in statement"));
            }
        }

        // Check for SQL injection patterns
        if self.detect_sql_injection(sql) {
            errors.push("Potential SQL injection pattern detected".to_string());
        }

        // Check for balanced parentheses and quotes
        if !self.is_balanced(sql) {
            errors.push("Unbalanced parentheses or quotes detected".to_string());
        }

        // Check for semicolon injection
        if self.detect_semicolon_injection(sql) {
            errors.push("Potential semicolon injection detected".to_string());
        }

        // Validate SQL structure
        if let Err(e) = self.validate_sql_structure(sql) {
            errors.push(format!("Invalid SQL structure: {}", e));
        }

        let is_valid = errors.is_empty();
        let sanitized_sql = if is_valid {
            Some(self.sanitize_sql(sql))
        } else {
            None
        };

        SqlValidationResult {
            is_valid,
            errors,
            warnings,
            sanitized_sql,
        }
    }

    /// Detect potential SQL injection patterns
    fn detect_sql_injection(&self, sql: &str) -> bool {
        let injection_patterns = [
            r"(?i)\b(OR|AND)\s+1\s*=\s*1\b",
            r"(?i)\b(OR|AND)\s+true\b",
            r"(?i)\b(OR|AND)\s+false\b",
            r"(?i)\bUNION\s+SELECT\b",
            r"(?i)\bUNION\s+ALL\s+SELECT\b",
            r"(?i)\b(SELECT|INSERT|UPDATE|DELETE)\s+.*\s+(OR|AND)\s+.*\b",
            r"(?i)\b(OR|AND)\s+.*\s*=\s*.*\b",
            r"(?i)\b(OR|AND)\s+.*\s*LIKE\s+.*\b",
            r"(?i)\b(OR|AND)\s+.*\s*IN\s*\(.*\)\b",
            r"(?i)\b(OR|AND)\s+.*\s*BETWEEN\s+.*\b",
            r"(?i)\b(OR|AND)\s+.*\s*EXISTS\s*\(.*\)\b",
            r"(?i)\b(OR|AND)\s+.*\s*NOT\s+EXISTS\s*\(.*\)\b",
        ];

        for pattern in &injection_patterns {
            if Regex::new(pattern).unwrap().is_match(sql) {
                return true;
            }
        }

        false
    }

    /// Check if parentheses and quotes are balanced
    fn is_balanced(&self, sql: &str) -> bool {
        let mut paren_count = 0;
        let mut single_quote = false;
        let mut double_quote = false;
        let mut backtick = false;

        for ch in sql.chars() {
            match ch {
                '(' if !single_quote && !double_quote && !backtick => paren_count += 1,
                ')' if !single_quote && !double_quote && !backtick => {
                    paren_count -= 1;
                    if paren_count < 0 {
                        return false;
                    }
                }
                '\'' if !double_quote && !backtick => single_quote = !single_quote,
                '"' if !single_quote && !backtick => double_quote = !double_quote,
                '`' if !single_quote && !double_quote => backtick = !backtick,
                _ => {}
            }
        }

        paren_count == 0 && !single_quote && !double_quote && !backtick
    }

    /// Detect potential semicolon injection
    fn detect_semicolon_injection(&self, sql: &str) -> bool {
        // Look for multiple statements separated by semicolons
        let statements: Vec<&str> = sql.split(';').collect();
        if statements.len() > 1 {
            // Check if any statement after the first one is potentially dangerous
            for stmt in statements.iter().skip(1) {
                let trimmed = stmt.trim();
                if !trimmed.is_empty() {
                    for pattern in &self.dangerous_patterns {
                        if pattern.is_match(trimmed) {
                            return true;
                        }
                    }
                }
            }
        }
        false
    }

    /// Validate basic SQL structure
    fn validate_sql_structure(&self, sql: &str) -> Result<()> {
        let trimmed = sql.trim();

        if trimmed.is_empty() {
            return Err(anyhow!("SQL statement cannot be empty"));
        }

        // Check for basic SQL keywords
        let sql_upper = trimmed.to_uppercase();
        let has_sql_keyword = [
            "SELECT", "INSERT", "UPDATE", "DELETE", "CREATE", "ALTER", "DROP", "EXPLAIN",
            "ANALYZE", "VACUUM", "GRANT", "REVOKE",
        ]
        .iter()
        .any(|keyword| sql_upper.starts_with(keyword));

        if !has_sql_keyword {
            return Err(anyhow!("SQL statement must start with a valid SQL keyword"));
        }

        // Check for minimum length
        if trimmed.len() < 10 {
            return Err(anyhow!("SQL statement too short to be valid"));
        }

        Ok(())
    }

    /// Sanitize SQL by removing potentially dangerous patterns
    fn sanitize_sql(&self, sql: &str) -> String {
        let mut sanitized = sql.to_string();

        // Remove comments that might contain dangerous code
        let comment_patterns = [
            r"--.*$",     // Single line comments
            r"/\*.*?\*/", // Multi-line comments
        ];

        for pattern in &comment_patterns {
            let regex = Regex::new(pattern).unwrap();
            sanitized = regex.replace_all(&sanitized, "").to_string();
        }

        // Normalize whitespace
        let whitespace_regex = Regex::new(r"\s+").unwrap();
        sanitized = whitespace_regex.replace_all(&sanitized, " ").to_string();

        sanitized.trim().to_string()
    }

    /// Create a validator with custom allowed operations
    pub fn with_allowed_operations(mut self, operations: Vec<String>) -> Self {
        self.allowed_operations = operations.into_iter().collect();
        self
    }

    /// Add custom dangerous pattern
    pub fn add_dangerous_pattern(mut self, pattern: Regex) -> Self {
        self.dangerous_patterns.push(pattern);
        self
    }

    /// Add custom forbidden pattern
    pub fn add_forbidden_pattern(mut self, pattern: Regex) -> Self {
        self.forbidden_patterns.push(pattern);
        self
    }
}

/// Enhanced SQL validation for custom migrations
pub struct CustomSqlValidator {
    base_validator: SqlValidator,
    migration_context: MigrationContext,
}

#[derive(Debug, Clone)]
pub struct MigrationContext {
    pub is_destructive: bool,
    pub requires_rollback: bool,
    pub allowed_tables: Option<Vec<String>>,
    pub forbidden_tables: Option<Vec<String>>,
}

impl CustomSqlValidator {
    /// Create a new custom SQL validator
    pub fn new() -> Self {
        Self {
            base_validator: SqlValidator::new(),
            migration_context: MigrationContext {
                is_destructive: false,
                requires_rollback: true,
                allowed_tables: None,
                forbidden_tables: None,
            },
        }
    }

    /// Set migration context
    pub fn with_context(mut self, context: MigrationContext) -> Self {
        self.migration_context = context;
        self
    }

    /// Validate custom SQL migration
    pub fn validate_migration(&self, sql: &str) -> SqlValidationResult {
        let mut result = self.base_validator.validate(sql);

        // Additional migration-specific validation
        if self.migration_context.is_destructive && !self.detect_destructive_operations(sql) {
            result.warnings.push(
                "Migration marked as destructive but no destructive operations detected"
                    .to_string(),
            );
        }

        if self.migration_context.requires_rollback && !self.detect_rollback_safety(sql) {
            result
                .warnings
                .push("Migration requires rollback but may not be safely reversible".to_string());
        }

        // Check table restrictions
        if let Some(ref allowed_tables) = self.migration_context.allowed_tables {
            if let Err(e) = self.validate_table_access(sql, allowed_tables, true) {
                result.errors.push(e.to_string());
            }
        }

        if let Some(ref forbidden_tables) = self.migration_context.forbidden_tables {
            if let Err(e) = self.validate_table_access(sql, forbidden_tables, false) {
                result.errors.push(e.to_string());
            }
        }

        result
    }

    /// Detect destructive operations in SQL
    fn detect_destructive_operations(&self, sql: &str) -> bool {
        let destructive_patterns = [
            r"(?i)\b(DROP|TRUNCATE|DELETE)\b",
            r"(?i)\b(ALTER\s+TABLE.*DROP)\b",
            r"(?i)\b(ALTER\s+TABLE.*MODIFY)\b",
        ];

        destructive_patterns
            .iter()
            .any(|pattern| Regex::new(pattern).unwrap().is_match(sql))
    }

    /// Detect if SQL is rollback-safe
    fn detect_rollback_safety(&self, sql: &str) -> bool {
        let unsafe_patterns = [
            r"(?i)\b(TRUNCATE|DROP\s+TABLE)\b",
            r"(?i)\b(DELETE\s+FROM.*WHERE\s+1\s*=\s*1)\b",
            r"(?i)\b(DELETE\s+FROM.*WHERE\s+true)\b",
        ];

        !unsafe_patterns
            .iter()
            .any(|pattern| Regex::new(pattern).unwrap().is_match(sql))
    }

    /// Validate table access permissions
    fn validate_table_access(&self, sql: &str, tables: &[String], is_allowed: bool) -> Result<()> {
        let table_pattern = Regex::new(r"(?i)\b(FROM|INTO|UPDATE|DELETE\s+FROM)\s+(\w+)")?;

        for cap in table_pattern.captures_iter(sql) {
            if let Some(table_match) = cap.get(2) {
                let table_name = table_match.as_str().to_lowercase();
                let is_in_list = tables.iter().any(|t| t.to_lowercase() == table_name);

                if is_allowed && !is_in_list {
                    return Err(anyhow!("Table '{}' is not in the allowed list", table_name));
                } else if !is_allowed && is_in_list {
                    return Err(anyhow!("Table '{}' is in the forbidden list", table_name));
                }
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sql_validation_safe_operations() {
        let validator = SqlValidator::new();

        let safe_sql = "CREATE TABLE test (id INT PRIMARY KEY, name VARCHAR(255))";
        let result = validator.validate(safe_sql);

        assert!(result.is_valid);
        assert!(result.errors.is_empty());
    }

    #[test]
    fn test_sql_validation_dangerous_operations() {
        let validator = SqlValidator::new();

        let dangerous_sql = "DROP TABLE users";
        let result = validator.validate(dangerous_sql);

        assert!(!result.warnings.is_empty());
        assert!(result
            .warnings
            .iter()
            .any(|w| w.contains("Dangerous DDL patterns")));
    }

    #[test]
    fn test_sql_validation_forbidden_operations() {
        let validator = SqlValidator::new();

        let forbidden_sql = "DROP DATABASE test_db";
        let result = validator.validate(forbidden_sql);

        assert!(!result.is_valid);
        assert!(result
            .errors
            .iter()
            .any(|e| e.contains("Forbidden SQL pattern")));
    }

    #[test]
    fn test_sql_injection_detection() {
        let validator = SqlValidator::new();

        let injection_sql = "SELECT * FROM users WHERE id = 1 OR 1=1";
        let result = validator.validate(injection_sql);

        assert!(!result.is_valid);
        assert!(result.errors.iter().any(|e| e.contains("SQL injection")));
    }

    #[test]
    fn test_balanced_parentheses() {
        let validator = SqlValidator::new();

        let unbalanced_sql = "CREATE TABLE test (id INT, name VARCHAR(255)";
        let result = validator.validate(unbalanced_sql);

        assert!(!result.is_valid);
        assert!(result.errors.iter().any(|e| e.contains("Unbalanced")));
    }

    #[test]
    fn test_custom_sql_validator_with_context() {
        let context = MigrationContext {
            is_destructive: true,
            requires_rollback: true,
            allowed_tables: Some(vec!["users".to_string(), "posts".to_string()]),
            forbidden_tables: None,
        };

        let validator = CustomSqlValidator::new().with_context(context);

        let sql = "DROP TABLE users";
        let result = validator.validate_migration(sql);

        assert!(result.is_valid);
        assert!(result.warnings.is_empty());
    }
}