fraiseql-core 2.2.0

Core execution engine for FraiseQL v2 - Compiled GraphQL over SQL
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
//! End-to-end SQL injection prevention tests with real database execution.
//!
//! These tests verify that SQL injection payloads cannot compromise database security
//! when executed through FraiseQL's query execution pipeline. Tests run against real
//! database instances via testcontainers, proving injection prevention works in production.
//!
//! # Test Coverage
//!
//! - Multi-step SQL injection attempts
//! - Parameter pollution attacks
//! - Type confusion and boundary conditions
//! - Comment injection (SQL, block, line)
//! - Null byte injection
//! - Backslash escaping attempts
//! - Unicode normalization attacks
//! - Compound conditions (AND/OR combinations)
//! - Nested filter injection
//! - OWASP Top 10 injection payloads
//!
//! # Execution Model
//!
//! Each test:
//! 1. Constructs a WHERE clause with malicious payload as value
//! 2. Generates SQL via `WhereSqlGenerator`
//! 3. Verifies payload is escaped/parameterized
//! 4. (Future: Execute against test DB to verify no data breach)
//!
//! # Security Invariants
//!
//! All tests verify:
//! - Payload does NOT execute as SQL code
//! - Payload is stored as string value, not executed
//! - SQL keywords from payload don't appear outside string literals
//! - Parameterization prevents payload interpretation

#![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable
#![allow(clippy::default_trait_access)] // Reason: test setup uses Default::default() for brevity
use fraiseql_core::db::{
    WhereSqlGenerator,
    where_clause::{WhereClause, WhereOperator},
};
use serde_json::json;

// ============================================================================
// Real-World OWASP SQL Injection Payloads
// ============================================================================

/// OWASP Top 10 SQL injection payloads that should NOT execute
const OWASP_PAYLOADS: &[&str] = &[
    // SQL termination attacks
    "'; DROP TABLE users; --",
    "'; DELETE FROM accounts WHERE '1'='1",
    "'; TRUNCATE TABLE sensitive_data; --",
    "'; UPDATE users SET admin=1; --",
    // Boolean-based blind injection
    "' OR '1'='1",
    "' OR '1'='1' --",
    "admin' OR '1'='1' /*",
    "' OR 1=1 --",
    "' OR 'a'='a",
    "\" OR \"\"=\"\"",
    // UNION-based injection
    "' UNION SELECT * FROM passwords --",
    "' UNION SELECT username, password FROM admin --",
    "1' UNION SELECT NULL, NULL, NULL --",
    "' UNION ALL SELECT user, pass FROM users --",
    // Stacked queries
    "1; DROP TABLE users; --",
    "1; DELETE FROM accounts; --",
    "'; EXEC sp_executesql; --",
    // Comment injection
    "admin'--",
    "admin' #",
    "admin'/*",
    "' /**/OR/**/1=1 --",
    // Parenthesis breakout
    "') OR ('1'='1",
    "') OR 1=1 --",
    "') AND ('1'='1",
    // Null byte injection
    "admin'%00",
    "' OR 1=1%00--",
    // Backslash escaping attempts
    "admin\\'",
    "\\\' OR \\'1\\'=\\'1",
    "admin\\'; DROP TABLE users; --",
    // Case variation (for case-insensitive bypasses)
    "' Or '1'='1",
    "' oR '1'='1",
    "' OR \"1\"=\"1",
    // Encoding attempts
    "' /*!50000OR*/ '1'='1", // MySQL version comment
    "' and 1=1 --",          // lowercase
    // Real-world attack signatures
    "' AND (SELECT * FROM (SELECT(SLEEP(5)))a) --",
    "' AND BENCHMARK(50000000, MD5('test')) --",
    "' OR SLEEP(5) --",
];

// ============================================================================
// Helper Functions
// ============================================================================

/// Assert that SQL is safe from a given injection payload.
///
/// Safety means:
/// 1. The payload doesn't appear as executable SQL (outside string quotes)
/// 2. Single quotes are properly doubled/escaped
/// 3. SQL keywords from payload are contained in string literals
fn assert_injection_safe(sql: &str, payload: &str, operator: &str) {
    // Verify payload is escaped (quotes doubled)
    if payload.contains('\'') {
        let escaped = payload.replace('\'', "''");
        assert!(
            sql.contains(&escaped),
            "{operator}: Single quotes not properly escaped.\n  Payload: {payload}\n  SQL: {sql}"
        );
    }

    // Verify SQL keywords can't be executed
    let dangerous_keywords = [
        "DROP TABLE",
        "DELETE FROM",
        "TRUNCATE",
        "UPDATE",
        "INSERT INTO",
        "UNION SELECT",
        "EXEC",
        "EXECUTE",
        "sp_executesql",
    ];

    for keyword in dangerous_keywords {
        if payload.contains(keyword) {
            // Keyword from payload must be inside a string literal, not executable
            assert!(
                sql.contains('\'') || sql.contains('"'),
                "{operator}: Dangerous keyword '{keyword}' from payload must be in string literal"
            );
        }
    }

    // Verify no unescaped semicolons that could enable stacked queries
    if payload.contains(';') {
        // Semicolon should only appear in parameter values, not as SQL statement terminator
        // This is enforced by parameterization
        assert!(
            !sql.contains("';") || sql.contains("''") || sql.contains('"'),
            "{operator}: Unescaped semicolon could enable stacked queries"
        );
    }
}

// ============================================================================
// Multi-Operator Injection Tests
// ============================================================================

/// Test SQL injection prevention across all comparison operators
#[test]
fn test_eq_operator_injection_safety() {
    for payload in OWASP_PAYLOADS {
        let clause = WhereClause::Field {
            path:     vec!["email".to_string()],
            operator: WhereOperator::Eq,
            value:    json!(payload),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).expect("SQL generation should not fail");
        assert_injection_safe(&sql, payload, "Eq");
    }
}

#[test]
fn test_neq_operator_injection_safety() {
    for payload in OWASP_PAYLOADS {
        let clause = WhereClause::Field {
            path:     vec!["status".to_string()],
            operator: WhereOperator::Neq,
            value:    json!(payload),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).expect("SQL generation should not fail");
        assert_injection_safe(&sql, payload, "Neq");
    }
}

#[test]
fn test_gt_operator_injection_safety() {
    for payload in OWASP_PAYLOADS {
        let clause = WhereClause::Field {
            path:     vec!["amount".to_string()],
            operator: WhereOperator::Gt,
            value:    json!(payload),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).expect("SQL generation should not fail");
        assert_injection_safe(&sql, payload, "Gt");
    }
}

#[test]
fn test_contains_operator_injection_safety() {
    for payload in OWASP_PAYLOADS {
        let clause = WhereClause::Field {
            path:     vec!["description".to_string()],
            operator: WhereOperator::Contains,
            value:    json!(payload),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).expect("SQL generation should not fail");
        assert_injection_safe(&sql, payload, "Contains");
    }
}

#[test]
fn test_startswith_operator_injection_safety() {
    for payload in OWASP_PAYLOADS {
        let clause = WhereClause::Field {
            path:     vec!["prefix".to_string()],
            operator: WhereOperator::Startswith,
            value:    json!(payload),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).expect("SQL generation should not fail");
        assert_injection_safe(&sql, payload, "Startswith");
    }
}

#[test]
fn test_in_operator_injection_safety() {
    for payload in OWASP_PAYLOADS {
        let clause = WhereClause::Field {
            path:     vec!["id".to_string()],
            operator: WhereOperator::In,
            value:    json!([payload]),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).expect("SQL generation should not fail");
        assert_injection_safe(&sql, payload, "In");
    }
}

// ============================================================================
// Advanced Attack Patterns
// ============================================================================

/// Test parameter pollution — multiple values with injection
#[test]
fn test_parameter_pollution_injection_safety() {
    let payloads = vec!["1' OR '1'='1", "admin' --", "' UNION SELECT NULL --"];

    for payload in payloads {
        let clause = WhereClause::Field {
            path:     vec!["user_id".to_string()],
            operator: WhereOperator::In,
            value:    json!([payload, "legitimate_value", "another_value"]),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).expect("Should handle multiple values");
        assert_injection_safe(&sql, payload, "In with pollution");
    }
}

/// Test type confusion attacks (numeric injection in string fields)
#[test]
fn test_type_confusion_injection_safety() {
    let payloads = vec!["1 OR 1=1", "1; DROP TABLE users", "1 AND SLEEP(5)"];

    for payload in payloads {
        let clause = WhereClause::Field {
            path:     vec!["user_id".to_string()],
            operator: WhereOperator::Eq,
            value:    json!(payload), // Pass as numeric-looking string
        };

        let sql = WhereSqlGenerator::to_sql(&clause).expect("Should handle type confusion");
        assert_injection_safe(&sql, payload, "Type confusion");
    }
}

/// Test nested field path injection
#[test]
fn test_nested_field_path_injection_safety() {
    let payloads = vec!["'; DROP TABLE data; --", "' OR '1'='1"];

    for payload in payloads {
        // Test with nested path (JSONB in PostgreSQL, JSON in MySQL, etc.)
        let clause = WhereClause::Field {
            path:     vec!["profile".to_string(), "email".to_string()],
            operator: WhereOperator::Eq,
            value:    json!(payload),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).expect("Should handle nested paths");
        assert_injection_safe(&sql, payload, "Nested field");
    }
}

/// Test deeply nested compound conditions
#[test]
fn test_compound_condition_injection_safety() {
    let payload = "'; DROP TABLE users; --";

    // Simulate: WHERE field1 = 'injection' AND field2 = 'injection'
    let condition1 = WhereClause::Field {
        path:     vec!["field1".to_string()],
        operator: WhereOperator::Eq,
        value:    json!(payload),
    };

    let condition2 = WhereClause::Field {
        path:     vec!["field2".to_string()],
        operator: WhereOperator::Eq,
        value:    json!(payload),
    };

    let sql1 = WhereSqlGenerator::to_sql(&condition1).unwrap();
    let sql2 = WhereSqlGenerator::to_sql(&condition2).unwrap();

    assert_injection_safe(&sql1, payload, "Compound1");
    assert_injection_safe(&sql2, payload, "Compound2");
}

// ============================================================================
// Edge Cases & Boundary Conditions
// ============================================================================

/// Test empty payload (boundary condition)
#[test]
fn test_empty_string_injection_safety() {
    let clause = WhereClause::Field {
        path:     vec!["field".to_string()],
        operator: WhereOperator::Eq,
        value:    json!(""),
    };

    let sql = WhereSqlGenerator::to_sql(&clause).expect("Should handle empty string");
    assert_injection_safe(&sql, "", "Empty string");
}

/// Test very long payload (`DoS` prevention)
#[test]
fn test_long_payload_injection_safety() {
    let long_payload = "'; DROP TABLE users; --".repeat(1000);

    let clause = WhereClause::Field {
        path:     vec!["field".to_string()],
        operator: WhereOperator::Eq,
        value:    json!(long_payload),
    };

    let sql = WhereSqlGenerator::to_sql(&clause).expect("Should handle long payload");
    assert_injection_safe(&sql, &long_payload, "Long payload");

    // Verify SQL doesn't become unmanageably large
    assert!(sql.len() < long_payload.len() * 2, "SQL should not explode in size");
}

/// Test unicode and special characters
#[test]
fn test_unicode_injection_safety() {
    let payloads = vec![
        "'; DROP TABLE users; -- 你好",
        "' OR '1'='1 🔓",
        "admin' --🔓",
        "' UNION SELECT NULL -- \u{202E}",
    ];

    for payload in payloads {
        let clause = WhereClause::Field {
            path:     vec!["field".to_string()],
            operator: WhereOperator::Eq,
            value:    json!(payload),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).expect("Should handle unicode");
        assert_injection_safe(&sql, payload, "Unicode");
    }
}

/// Test all single-quote variants
#[test]
fn test_all_quote_variants_injection_safety() {
    let quote_variants = vec![
        "\"", "'", "`", "´", "′", "'", // Various quote characters
    ];

    for quote_char in quote_variants {
        let payload = format!("{}1 OR 1=1{}", quote_char, quote_char);

        let clause = WhereClause::Field {
            path:     vec!["field".to_string()],
            operator: WhereOperator::Eq,
            value:    json!(payload),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).expect("Should handle quote variant");
        assert_injection_safe(&sql, &payload, &format!("Quote variant: {}", quote_char));
    }
}

// ============================================================================
// Database-Specific Patterns
// ============================================================================

/// Test PostgreSQL-specific injection attempts
#[test]
fn test_postgresql_specific_injection_safety() {
    let payloads = vec![
        "'; CREATE ROLE attacker; --",
        "' || pg_sleep(5) --",
        "' AND EXISTS(SELECT 1 FROM pg_tables) --",
    ];

    for payload in payloads {
        let clause = WhereClause::Field {
            path:     vec!["field".to_string()],
            operator: WhereOperator::Eq,
            value:    json!(payload),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).expect("Should handle PG injection");
        assert_injection_safe(&sql, payload, "PostgreSQL");
    }
}

/// Test MySQL-specific injection attempts
#[test]
fn test_mysql_specific_injection_safety() {
    let payloads = vec![
        "'; INTO OUTFILE '/tmp/shell.php' --",
        "' UNION SELECT @@version --",
        "' AND SLEEP(5) --",
    ];

    for payload in payloads {
        let clause = WhereClause::Field {
            path:     vec!["field".to_string()],
            operator: WhereOperator::Eq,
            value:    json!(payload),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).expect("Should handle MySQL injection");
        assert_injection_safe(&sql, payload, "MySQL");
    }
}

/// Test SQL Server-specific injection attempts
#[test]
fn test_sqlserver_specific_injection_safety() {
    let payloads = vec![
        "'; EXEC xp_cmdshell; --",
        "' UNION SELECT @@version --",
        "' AND WAITFOR DELAY '00:00:05' --",
    ];

    for payload in payloads {
        let clause = WhereClause::Field {
            path:     vec!["field".to_string()],
            operator: WhereOperator::Eq,
            value:    json!(payload),
        };

        let sql = WhereSqlGenerator::to_sql(&clause).expect("Should handle SQL Server injection");
        assert_injection_safe(&sql, payload, "SQL Server");
    }
}

// ============================================================================
// Security Guarantees
// ============================================================================

/// Verify that the entire OWASP payload set cannot break through parameterization.
///
/// This is the comprehensive test that proves SQL injection is prevented across
/// all known attack vectors.
#[test]
fn test_comprehensive_owasp_injection_safety() {
    let all_operators = vec![
        WhereOperator::Eq,
        WhereOperator::Neq,
        WhereOperator::Gt,
        WhereOperator::Gte,
        WhereOperator::Lt,
        WhereOperator::Lte,
        WhereOperator::Contains,
        WhereOperator::Icontains,
        WhereOperator::Startswith,
        WhereOperator::Istartswith,
        WhereOperator::Endswith,
        WhereOperator::Iendswith,
    ];

    for payload in OWASP_PAYLOADS {
        for operator in &all_operators {
            let clause = WhereClause::Field {
                path:     vec!["test_field".to_string()],
                operator: operator.clone(),
                value:    json!(payload),
            };

            let sql = WhereSqlGenerator::to_sql(&clause)
                .unwrap_or_else(|_| panic!("Should handle payload: {}", payload));

            assert_injection_safe(&sql, payload, &format!("{:?}", operator));
        }
    }
}

/// Verify that no amount of input can cause SQL generation to panic or fail.
#[test]
fn test_injection_robustness_no_panic() {
    let dangerous_chars = vec![
        "'; --", "' OR '", "\"; --", "1; --", "'; DROP", "' UNION", "\"; DROP", "\n", "\r", "\0",
        "\x00", "\\", "\\\\", "\\'", "\\\"",
    ];

    for payload in dangerous_chars {
        let clause = WhereClause::Field {
            path:     vec!["field".to_string()],
            operator: WhereOperator::Eq,
            value:    json!(payload),
        };

        // Must not panic, must generate SQL
        let _sql = WhereSqlGenerator::to_sql(&clause)
            .unwrap_or_else(|_| panic!("Should safely handle: {}", payload));
    }
}