fraiseql-db 2.2.0

Database abstraction layer for FraiseQL v2
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//! Escape utilities for JSON path SQL injection prevention.
//!
//! Different databases have different escaping requirements for JSON paths:
//! - PostgreSQL: Single quote in JSONB operators -> double it
//! - MySQL: Single quote in JSON_EXTRACT -> escape with backslash
//! - SQLite: Single quote in json_extract -> escape with backslash
//! - SQL Server: Single quote in JSON_VALUE -> double it

/// Escape a single path segment for use in PostgreSQL JSONB operators.
///
/// PostgreSQL JSONB operators (->,'->>',->) are literal string operators
/// where the right operand is interpreted as a JSON key string.
/// Single quotes within the string must be doubled for SQL escaping.
///
/// # Example
/// ```
/// use fraiseql_db::path_escape::escape_postgres_jsonb_segment;
/// assert_eq!(escape_postgres_jsonb_segment("user'name"), "user''name");
/// assert_eq!(escape_postgres_jsonb_segment("normal"), "normal");
/// ```
pub fn escape_postgres_jsonb_segment(segment: &str) -> String {
    segment.replace('\'', "''")
}

/// Escape a full JSON path for use in PostgreSQL JSONB operators.
///
/// # Example
/// ```
/// use fraiseql_db::path_escape::escape_postgres_jsonb_path;
/// let path = vec!["user".to_string(), "name".to_string()];
/// let result = escape_postgres_jsonb_path(&path);
/// // Ensures each segment is properly escaped
/// ```
pub fn escape_postgres_jsonb_path(path: &[String]) -> Vec<String> {
    path.iter().map(|segment| escape_postgres_jsonb_segment(segment)).collect()
}

/// Escape a JSON path for MySQL JSON_EXTRACT/JSON_UNQUOTE.
///
/// MySQL JSON paths use dot notation: '$.field.subfield'
/// Single quotes are doubled (`''`) rather than backslash-escaped so that the
/// path is safe even when the server runs with `NO_BACKSLASH_ESCAPES` mode.
///
/// # Example
/// ```
/// use fraiseql_db::path_escape::escape_mysql_json_path;
/// let path = vec!["user".to_string(), "name".to_string()];
/// let result = escape_mysql_json_path(&path);
/// assert_eq!(result, "$.user.name");
/// ```
pub fn escape_mysql_json_path(path: &[String]) -> String {
    let json_path = path.join(".");
    // Double single quotes for SQL string literal; safe under NO_BACKSLASH_ESCAPES.
    format!("$.{}", json_path.replace('\'', "''"))
}

/// Escape a JSON path for SQLite json_extract.
///
/// SQLite JSON paths use dot notation: '$.field.subfield'
/// Single quotes are doubled (`''`) rather than backslash-escaped so that the
/// path is safe regardless of SQLite compile-time escape settings.
pub fn escape_sqlite_json_path(path: &[String]) -> String {
    let json_path = path.join(".");
    // Double single quotes for SQL string literal; backslash escaping is not
    // a reliable cross-mode choice for SQLite.
    format!("$.{}", json_path.replace('\'', "''"))
}

/// Escape a JSON path for SQL Server JSON_VALUE.
///
/// SQL Server JSON paths use dot notation: '$.field.subfield'
/// Single quotes must be escaped for SQL string literals.
pub fn escape_sqlserver_json_path(path: &[String]) -> String {
    let json_path = path.join(".");
    format!("$.{}", json_path.replace('\'', "''"))
}

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

    #[test]
    fn test_postgres_single_quote() {
        assert_eq!(escape_postgres_jsonb_segment("user'admin"), "user''admin");
    }

    #[test]
    fn test_postgres_multiple_quotes() {
        assert_eq!(escape_postgres_jsonb_segment("it's"), "it''s");
    }

    #[test]
    fn test_postgres_no_quote() {
        assert_eq!(escape_postgres_jsonb_segment("username"), "username");
    }

    #[test]
    fn test_postgres_path_vector() {
        let path = vec!["user'name".to_string(), "id".to_string()];
        let result = escape_postgres_jsonb_path(&path);
        assert_eq!(result[0], "user''name");
        assert_eq!(result[1], "id");
    }

    #[test]
    fn test_mysql_single_quote() {
        let result = escape_mysql_json_path(&["user'admin".to_string()]);
        assert_eq!(result, "$.user''admin");
    }

    #[test]
    fn test_sqlite_single_quote() {
        let result = escape_sqlite_json_path(&["user'admin".to_string()]);
        assert_eq!(result, "$.user''admin");
    }

    #[test]
    fn test_sqlserver_single_quote() {
        let result = escape_sqlserver_json_path(&["user'admin".to_string()]);
        assert_eq!(result, "$.user''admin");
    }

    #[test]
    fn test_all_databases_empty_path() {
        let empty_path: Vec<String> = vec![];
        let pg_result = escape_postgres_jsonb_path(&empty_path);
        let mysql_result = escape_mysql_json_path(&empty_path);
        let sqlite_result = escape_sqlite_json_path(&empty_path);
        let sqlserver_result = escape_sqlserver_json_path(&empty_path);

        assert_eq!(pg_result.len(), 0);
        assert_eq!(mysql_result, "$.");
        assert_eq!(sqlite_result, "$.");
        assert_eq!(sqlserver_result, "$.");
    }

    // =========================================================================
    // Injection payload tests — 4 dialects × 10 payloads = 40 tests
    // =========================================================================

    // --- PostgreSQL segment escape ---

    #[test]
    fn test_postgres_injection_drop_table() {
        let payload = "'; DROP TABLE users; --";
        let escaped = escape_postgres_jsonb_segment(payload);
        // Single quotes must be doubled so they cannot break out of a SQL string literal
        // Payload starts with ' → becomes '' in the output
        assert!(escaped.starts_with("''"), "Opening single quote must be doubled for PostgreSQL");
        assert!(!escaped.starts_with("'\""), "Must not produce an unescaped sequence");
    }

    #[test]
    fn test_postgres_injection_or_1_eq_1() {
        let payload = "' OR '1'='1";
        let escaped = escape_postgres_jsonb_segment(payload);
        // All single quotes must be doubled — count of '' should match original ' count
        let original_quote_count = payload.chars().filter(|&c| c == '\'').count();
        let doubled_count = escaped.matches("''").count();
        assert_eq!(doubled_count, original_quote_count, "Every single quote must be doubled");
    }

    #[test]
    fn test_postgres_injection_double_quote_or() {
        let payload = r#"" OR "1"="1"#;
        let escaped = escape_postgres_jsonb_segment(payload);
        // No single quotes in payload — output must be identical (double quotes are not special in
        // PG segment)
        assert_eq!(escaped, payload);
    }

    #[test]
    fn test_postgres_injection_backslash() {
        let payload = r"\";
        let escaped = escape_postgres_jsonb_segment(payload);
        // PostgreSQL does not treat backslash specially in dollar-quoted / JSONB operators; output
        // is unchanged
        assert_eq!(escaped, payload);
    }

    #[test]
    fn test_postgres_injection_like_percent() {
        let payload = "%";
        let escaped = escape_postgres_jsonb_segment(payload);
        // No single quotes — output unchanged
        assert_eq!(escaped, payload);
    }

    #[test]
    fn test_postgres_injection_like_underscore() {
        let payload = "_";
        let escaped = escape_postgres_jsonb_segment(payload);
        assert_eq!(escaped, payload);
    }

    #[test]
    fn test_postgres_injection_xss_script_tag() {
        let payload = "<script>alert(1)</script>";
        let escaped = escape_postgres_jsonb_segment(payload);
        // No single quotes in XSS payload — output identical
        assert_eq!(escaped, payload);
    }

    #[test]
    fn test_postgres_injection_null_literal() {
        let payload = "NULL";
        let escaped = escape_postgres_jsonb_segment(payload);
        assert_eq!(escaped, "NULL");
    }

    #[test]
    fn test_postgres_injection_empty_string() {
        let payload = "";
        let escaped = escape_postgres_jsonb_segment(payload);
        assert_eq!(escaped, "");
    }

    #[test]
    fn test_postgres_injection_unicode_accents() {
        let payload = "François";
        let escaped = escape_postgres_jsonb_segment(payload);
        // No single quotes — output unchanged
        assert_eq!(escaped, "François");
    }

    // --- MySQL JSON path escape ---

    #[test]
    fn test_mysql_injection_drop_table() {
        let payload = "'; DROP TABLE users; --";
        let result = escape_mysql_json_path(&[payload.to_string()]);
        // MySQL single quotes are doubled (not backslash-escaped) so the path
        // is safe even under NO_BACKSLASH_ESCAPES.
        assert!(result.contains("''"), "Single quote must be doubled for MySQL");
        assert!(!result.contains("\\'"), "Must not use backslash escaping");
        // Path must start with $.
        assert!(result.starts_with("$."), "MySQL path must start with $.");
    }

    #[test]
    fn test_mysql_injection_or_1_eq_1() {
        let payload = "' OR '1'='1";
        let result = escape_mysql_json_path(&[payload.to_string()]);
        // All 4 single quotes in "' OR '1'='1" must be doubled.
        let original_quote_count = payload.chars().filter(|&c| c == '\'').count();
        let doubled_count = result.matches("''").count();
        assert_eq!(
            doubled_count, original_quote_count,
            "Every single quote must be doubled in MySQL"
        );
    }

    #[test]
    fn test_mysql_injection_double_quote_or() {
        let payload = r#"" OR "1"="1"#;
        let result = escape_mysql_json_path(&[payload.to_string()]);
        // No single quotes — path contains original (double quotes are not special in MySQL JSON
        // path string)
        assert!(result.starts_with("$."), "MySQL path must start with '$.'");
    }

    #[test]
    fn test_mysql_injection_backslash() {
        let payload = r"\";
        let result = escape_mysql_json_path(&[payload.to_string()]);
        assert!(result.starts_with("$."), "MySQL path must start with '$.'");
    }

    #[test]
    fn test_mysql_injection_like_percent() {
        let payload = "%";
        let result = escape_mysql_json_path(&[payload.to_string()]);
        assert_eq!(result, "$.%");
    }

    #[test]
    fn test_mysql_injection_like_underscore() {
        let payload = "_";
        let result = escape_mysql_json_path(&[payload.to_string()]);
        assert_eq!(result, "$._");
    }

    #[test]
    fn test_mysql_injection_xss_script_tag() {
        let payload = "<script>alert(1)</script>";
        let result = escape_mysql_json_path(&[payload.to_string()]);
        assert!(result.starts_with("$."), "MySQL path must start with '$.'");
        assert!(!result.contains("'; "), "Should not contain unescaped quotes");
    }

    #[test]
    fn test_mysql_injection_null_literal() {
        let payload = "NULL";
        let result = escape_mysql_json_path(&[payload.to_string()]);
        assert_eq!(result, "$.NULL");
    }

    #[test]
    fn test_mysql_injection_empty_segment() {
        // Single empty segment in path
        let result = escape_mysql_json_path(&[String::new()]);
        assert_eq!(result, "$.");
    }

    #[test]
    fn test_mysql_injection_unicode_accents() {
        let payload = "François";
        let result = escape_mysql_json_path(&[payload.to_string()]);
        assert_eq!(result, "$.François");
    }

    // --- SQLite JSON path escape ---

    #[test]
    fn test_sqlite_injection_drop_table() {
        let payload = "'; DROP TABLE users; --";
        let result = escape_sqlite_json_path(&[payload.to_string()]);
        // SQLite single quotes are doubled (not backslash-escaped) for
        // consistent behaviour across SQLite builds.
        assert!(result.contains("''"), "Single quote must be doubled for SQLite");
        assert!(!result.contains("\\'"), "Must not use backslash escaping");
        assert!(result.starts_with("$."), "SQLite path must start with $.");
    }

    #[test]
    fn test_sqlite_injection_or_1_eq_1() {
        let payload = "' OR '1'='1";
        let result = escape_sqlite_json_path(&[payload.to_string()]);
        let original_quote_count = payload.chars().filter(|&c| c == '\'').count();
        let doubled_count = result.matches("''").count();
        assert_eq!(
            doubled_count, original_quote_count,
            "Every single quote must be doubled in SQLite"
        );
    }

    #[test]
    fn test_sqlite_injection_double_quote_or() {
        let payload = r#"" OR "1"="1"#;
        let result = escape_sqlite_json_path(&[payload.to_string()]);
        assert!(result.starts_with("$."), "SQLite path must start with '$.'");
    }

    #[test]
    fn test_sqlite_injection_backslash() {
        let payload = r"\";
        let result = escape_sqlite_json_path(&[payload.to_string()]);
        assert!(result.starts_with("$."), "SQLite path must start with '$.'");
    }

    #[test]
    fn test_sqlite_injection_like_percent() {
        let payload = "%";
        let result = escape_sqlite_json_path(&[payload.to_string()]);
        assert_eq!(result, "$.%");
    }

    #[test]
    fn test_sqlite_injection_like_underscore() {
        let payload = "_";
        let result = escape_sqlite_json_path(&[payload.to_string()]);
        assert_eq!(result, "$._");
    }

    #[test]
    fn test_sqlite_injection_xss_script_tag() {
        let payload = "<script>alert(1)</script>";
        let result = escape_sqlite_json_path(&[payload.to_string()]);
        assert!(result.starts_with("$."), "SQLite path must start with '$.'");
    }

    #[test]
    fn test_sqlite_injection_null_literal() {
        let payload = "NULL";
        let result = escape_sqlite_json_path(&[payload.to_string()]);
        assert_eq!(result, "$.NULL");
    }

    #[test]
    fn test_sqlite_injection_empty_segment() {
        let result = escape_sqlite_json_path(&[String::new()]);
        assert_eq!(result, "$.");
    }

    #[test]
    fn test_sqlite_injection_unicode_accents() {
        let payload = "François";
        let result = escape_sqlite_json_path(&[payload.to_string()]);
        assert_eq!(result, "$.François");
    }

    // --- SQL Server JSON path escape ---

    #[test]
    fn test_sqlserver_injection_drop_table() {
        let payload = "'; DROP TABLE users; --";
        let result = escape_sqlserver_json_path(&[payload.to_string()]);
        // SQL Server uses doubling: ' → '' (same as PostgreSQL)
        assert!(result.contains("''"), "Single quote must be doubled in SQL Server");
        assert!(result.starts_with("$."), "SQL Server path must start with $.");
    }

    #[test]
    fn test_sqlserver_injection_or_1_eq_1() {
        let payload = "' OR '1'='1";
        let result = escape_sqlserver_json_path(&[payload.to_string()]);
        let original_quote_count = payload.chars().filter(|&c| c == '\'').count();
        let doubled_count = result.matches("''").count();
        assert_eq!(
            doubled_count, original_quote_count,
            "Every single quote must be doubled in SQL Server"
        );
    }

    #[test]
    fn test_sqlserver_injection_double_quote_or() {
        let payload = r#"" OR "1"="1"#;
        let result = escape_sqlserver_json_path(&[payload.to_string()]);
        assert!(result.starts_with("$."), "SQL Server path must start with '$.'");
    }

    #[test]
    fn test_sqlserver_injection_backslash() {
        let payload = r"\";
        let result = escape_sqlserver_json_path(&[payload.to_string()]);
        assert!(result.starts_with("$."), "SQL Server path must start with '$.'");
    }

    #[test]
    fn test_sqlserver_injection_like_percent() {
        let payload = "%";
        let result = escape_sqlserver_json_path(&[payload.to_string()]);
        assert_eq!(result, "$.%");
    }

    #[test]
    fn test_sqlserver_injection_like_underscore() {
        let payload = "_";
        let result = escape_sqlserver_json_path(&[payload.to_string()]);
        assert_eq!(result, "$._");
    }

    #[test]
    fn test_sqlserver_injection_xss_script_tag() {
        let payload = "<script>alert(1)</script>";
        let result = escape_sqlserver_json_path(&[payload.to_string()]);
        assert!(result.starts_with("$."), "SQL Server path must start with '$.'");
    }

    #[test]
    fn test_sqlserver_injection_null_literal() {
        let payload = "NULL";
        let result = escape_sqlserver_json_path(&[payload.to_string()]);
        assert_eq!(result, "$.NULL");
    }

    #[test]
    fn test_sqlserver_injection_empty_segment() {
        let result = escape_sqlserver_json_path(&[String::new()]);
        assert_eq!(result, "$.");
    }

    #[test]
    fn test_sqlserver_injection_unicode_accents() {
        let payload = "François";
        let result = escape_sqlserver_json_path(&[payload.to_string()]);
        assert_eq!(result, "$.François");
    }

    // --- Cross-dialect consistency checks ---

    #[test]
    fn test_postgres_segment_double_single_quote_roundtrip() {
        // A single quote in input → doubled in output
        let input = "it's";
        let escaped = escape_postgres_jsonb_segment(input);
        assert_eq!(escaped, "it''s");
    }

    #[test]
    fn test_mysql_vs_sqlite_same_escaping_for_single_quote() {
        let payload = "user'name";
        let mysql_result = escape_mysql_json_path(&[payload.to_string()]);
        let sqlite_result = escape_sqlite_json_path(&[payload.to_string()]);
        // Both use double-single-quote escaping (no backslash dependency)
        assert_eq!(
            mysql_result, sqlite_result,
            "MySQL and SQLite should escape single quotes identically"
        );
        assert!(mysql_result.contains("''"), "MySQL must use double-single-quote escaping");
        assert!(!mysql_result.contains("\\'"), "MySQL must not use backslash escaping");
    }

    #[test]
    fn test_sqlserver_vs_postgres_same_doubling_strategy() {
        let payload = "user'name";
        let pg_seg = escape_postgres_jsonb_segment(payload);
        let ss_result = escape_sqlserver_json_path(&[payload.to_string()]);
        // PostgreSQL doubles the quote in the segment; SQL Server doubles it in the path body
        assert!(pg_seg.contains("''"), "PostgreSQL should double the quote");
        assert!(ss_result.contains("''"), "SQL Server should double the quote");
    }

    #[test]
    fn test_postgres_path_multi_segment_escaping() {
        let path = vec!["user'name".to_string(), "field's".to_string()];
        let result = escape_postgres_jsonb_path(&path);
        assert_eq!(result[0], "user''name");
        assert_eq!(result[1], "field''s");
    }

    #[test]
    fn test_mysql_multi_segment_path_joins_with_dot() {
        let path = vec![
            "user".to_string(),
            "address".to_string(),
            "city".to_string(),
        ];
        let result = escape_mysql_json_path(&path);
        assert_eq!(result, "$.user.address.city");
    }

    // --- NO_BACKSLASH_ESCAPES safety ---

    #[test]
    fn mysql_escape_single_quote_no_backslash_mode() {
        // Verifies that the MySQL path escaper uses '' rather than \' so it is
        // safe when the server operates with NO_BACKSLASH_ESCAPES enabled.
        let result = escape_mysql_json_path(&["user'name".to_string()]);
        assert!(
            !result.contains('\\'),
            "Must not contain backslash (breaks under NO_BACKSLASH_ESCAPES)"
        );
        assert!(result.contains("''"), "Must double single quotes");
        assert_eq!(result, "$.user''name");
    }

    #[test]
    fn sqlite_escape_single_quote_no_backslash_mode() {
        // SQLite does not recognise \' as an escape sequence in standard mode;
        // doubling the quote is the only portable approach.
        let result = escape_sqlite_json_path(&["user'name".to_string()]);
        assert!(!result.contains('\\'), "Must not contain backslash");
        assert!(result.contains("''"), "Must double single quotes");
        assert_eq!(result, "$.user''name");
    }
}