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
//! Validation framework for extended operator parameters.
//!
//! This module provides reusable validators that can be configured via TOML
//! at compile time. Validators are applied before SQL generation to ensure
//! parameters are valid before executing queries.
//!
//! # Design
//!
//! Validators are expressed as rules in fraiseql.toml:
//!
//! ```toml
//! [fraiseql.validation]
//! email_domain_eq = { pattern = "^[a-z0-9]..." }
//! vin_wmi_eq = { length = 3, pattern = "^[A-Z0-9]{3}$" }
//! iban_country_eq = { checksum = "mod97" }
//! ```
//!
//! Rules are compiled into schema.compiled.json and applied at runtime.

use fraiseql_error::{FraiseQLError, Result};
use regex::{Regex, RegexBuilder};
use serde_json::Value;

/// Maximum byte length for a validation regex pattern.
///
/// Long patterns with nested quantifiers can cause catastrophic backtracking
/// (ReDoS). Rejecting patterns above this threshold is a defence-in-depth
/// measure on top of the DFA size cap applied in [`compile_pattern`].
const MAX_PATTERN_BYTES: usize = 1024;

/// Compile a regex pattern with ReDoS defence-in-depth guards.
///
/// # Guards
/// 1. Rejects patterns longer than [`MAX_PATTERN_BYTES`] before compilation.
/// 2. Caps the DFA state-machine size at 1 MiB via [`RegexBuilder::size_limit`]. Patterns that
///    require a larger DFA are rejected rather than executed.
///
/// # Errors
///
/// Returns [`FraiseQLError::Validation`] if the pattern is too long, contains
/// invalid syntax, or exceeds the DFA size limit.
fn compile_pattern(pattern: &str) -> Result<Regex> {
    if pattern.len() > MAX_PATTERN_BYTES {
        return Err(FraiseQLError::validation(format!(
            "Validation pattern too long ({} bytes, max {MAX_PATTERN_BYTES})",
            pattern.len()
        )));
    }
    RegexBuilder::new(pattern)
        .size_limit(1 << 20) // 1 MiB DFA cap
        .build()
        .map_err(|e| {
            FraiseQLError::validation(format!("Invalid validation pattern '{pattern}': {e}"))
        })
}

/// Validation rule for an operator parameter.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ValidationRule {
    /// Pattern matching (pre-compiled regex)
    Pattern(Regex),
    /// Exact length
    Length(usize),
    /// Min and max length
    LengthRange {
        /// Minimum allowed length (inclusive).
        min: usize,
        /// Maximum allowed length (inclusive).
        max: usize,
    },
    /// Checksum algorithm
    Checksum(ChecksumType),
    /// Range of numeric values
    NumericRange {
        /// Minimum allowed numeric value (inclusive).
        min: f64,
        /// Maximum allowed numeric value (inclusive).
        max: f64,
    },
    /// Value must be one of these options
    Enum(Vec<String>),
    /// Composite rule (all must pass)
    All(Vec<ValidationRule>),
}

/// Supported checksum algorithms.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ChecksumType {
    /// IBAN MOD-97 checksum
    Mod97,
    /// Luhn algorithm (credit cards, VINs)
    Luhn,
}

impl ValidationRule {
    /// Validate a string value against this rule.
    ///
    /// # Errors
    ///
    /// Returns [`FraiseQLError::Validation`] if the value fails the validation rule,
    /// or if the pattern is an invalid regex.
    pub fn validate(&self, value: &str) -> Result<()> {
        match self {
            ValidationRule::Pattern(re) => {
                if !re.is_match(value) {
                    return Err(FraiseQLError::validation(format!(
                        "Value '{}' does not match pattern '{}'",
                        value,
                        re.as_str()
                    )));
                }
                Ok(())
            },

            ValidationRule::Length(expected) => {
                if value.len() != *expected {
                    return Err(FraiseQLError::validation(format!(
                        "Value '{}' has length {}, expected {}",
                        value,
                        value.len(),
                        expected
                    )));
                }
                Ok(())
            },

            ValidationRule::LengthRange { min, max } => {
                let len = value.len();
                if len < *min || len > *max {
                    return Err(FraiseQLError::validation(format!(
                        "Value '{}' has length {}, expected between {} and {}",
                        value, len, min, max
                    )));
                }
                Ok(())
            },

            ValidationRule::Checksum(checksum_type) => {
                match checksum_type {
                    ChecksumType::Mod97 => validate_mod97(value)?,
                    ChecksumType::Luhn => validate_luhn(value)?,
                }
                Ok(())
            },

            ValidationRule::NumericRange { min, max } => {
                let num: f64 = value.parse().map_err(|_| {
                    FraiseQLError::validation(format!("Value '{}' is not a valid number", value))
                })?;

                if num < *min || num > *max {
                    return Err(FraiseQLError::validation(format!(
                        "Value {} is outside range [{}, {}]",
                        num, min, max
                    )));
                }
                Ok(())
            },

            ValidationRule::Enum(options) => {
                if !options.contains(&value.to_string()) {
                    return Err(FraiseQLError::validation(format!(
                        "Value '{}' must be one of: {}",
                        value,
                        options.join(", ")
                    )));
                }
                Ok(())
            },

            ValidationRule::All(rules) => {
                for rule in rules {
                    rule.validate(value)?;
                }
                Ok(())
            },
        }
    }

    /// Parse validation rules from JSON (compiled from TOML).
    ///
    /// # Errors
    ///
    /// Returns [`FraiseQLError::Validation`] if the JSON structure does not match any
    /// known validation rule format.
    ///
    /// # Panics
    ///
    /// Cannot panic: the internal `.expect("len checked == 1")` is only reached
    /// after verifying `rules.len() == 1`.
    pub fn from_json(value: &Value) -> Result<Self> {
        match value {
            Value::String(s) => {
                // Simple case: just a pattern — compile at parse time
                let re = compile_pattern(s)?;
                Ok(ValidationRule::Pattern(re))
            },

            Value::Object(map) => {
                let mut rules = Vec::new();

                // Pattern rule — compile at parse time
                if let Some(Value::String(pattern)) = map.get("pattern") {
                    rules.push(ValidationRule::Pattern(compile_pattern(pattern)?));
                }

                // Length rule
                if let Some(Value::Number(n)) = map.get("length") {
                    if let Some(length) = n.as_u64() {
                        #[allow(clippy::cast_possible_truncation)]
                        // Reason: value is bounded; truncation cannot occur in practice
                        let length_usize = usize::try_from(length).unwrap_or(usize::MAX);
                        rules.push(ValidationRule::Length(length_usize));
                    }
                }

                // Length range rule
                if let (Some(Value::Number(min)), Some(Value::Number(max))) =
                    (map.get("min_length"), map.get("max_length"))
                {
                    if let (Some(min_val), Some(max_val)) = (min.as_u64(), max.as_u64()) {
                        #[allow(clippy::cast_possible_truncation)]
                        // Reason: value is bounded; truncation cannot occur in practice
                        let (min, max) = (
                            usize::try_from(min_val).unwrap_or(usize::MAX),
                            usize::try_from(max_val).unwrap_or(usize::MAX),
                        );
                        rules.push(ValidationRule::LengthRange { min, max });
                    }
                }

                // Checksum rule
                if let Some(Value::String(checksum)) = map.get("checksum") {
                    let checksum_type = match checksum.as_str() {
                        "mod97" => ChecksumType::Mod97,
                        "luhn" => ChecksumType::Luhn,
                        _ => {
                            return Err(FraiseQLError::validation(format!(
                                "Unknown checksum type: {}",
                                checksum
                            )));
                        },
                    };
                    rules.push(ValidationRule::Checksum(checksum_type));
                }

                // Enum rule
                if let Some(Value::Array(options)) = map.get("enum") {
                    let enum_values: Vec<String> =
                        options.iter().filter_map(|v| v.as_str().map(|s| s.to_string())).collect();

                    if !enum_values.is_empty() {
                        rules.push(ValidationRule::Enum(enum_values));
                    }
                }

                // Numeric range rule
                if let (Some(Value::Number(min)), Some(Value::Number(max))) =
                    (map.get("min"), map.get("max"))
                {
                    if let (Some(min_val), Some(max_val)) = (min.as_f64(), max.as_f64()) {
                        rules.push(ValidationRule::NumericRange {
                            min: min_val,
                            max: max_val,
                        });
                    }
                }

                if rules.is_empty() {
                    return Err(FraiseQLError::validation(
                        "No valid validation rules found".to_string(),
                    ));
                }

                if rules.len() == 1 {
                    Ok(rules.into_iter().next().expect("len checked == 1"))
                } else {
                    Ok(ValidationRule::All(rules))
                }
            },

            _ => Err(FraiseQLError::validation(
                "Validation rule must be string or object".to_string(),
            )),
        }
    }
}

/// MOD-97 checksum validation for IBAN and similar formats.
fn validate_mod97(value: &str) -> Result<()> {
    // Move country code (first 4 chars) to end
    if value.len() < 4 {
        return Err(FraiseQLError::validation("IBAN must be at least 4 characters".to_string()));
    }

    let rearranged = format!("{}{}", &value[4..], &value[..4]);

    // Convert letters to numbers (A=10, B=11, ..., Z=35)
    let numeric_string: String = rearranged
        .chars()
        .map(|c| {
            if c.is_ascii_digit() {
                c.to_string()
            } else {
                ((c.to_ascii_uppercase() as u32 - 'A' as u32) + 10).to_string()
            }
        })
        .collect();

    // Compute MOD 97
    let mut remainder: u64 = 0;
    for digit_char in numeric_string.chars() {
        if let Some(digit) = digit_char.to_digit(10) {
            remainder = (remainder * 10 + u64::from(digit)) % 97;
        }
    }

    if remainder == 1 {
        Ok(())
    } else {
        Err(FraiseQLError::validation("Invalid IBAN checksum".to_string()))
    }
}

/// Luhn algorithm checksum validation (used for VINs, credit cards, etc.).
fn validate_luhn(value: &str) -> Result<()> {
    let digits: Vec<u32> = value.chars().filter_map(|c| c.to_digit(10)).collect();

    if digits.is_empty() {
        return Err(FraiseQLError::validation("Value must contain at least one digit".to_string()));
    }

    let mut sum = 0u32;
    let mut is_even = false;

    for digit in digits.iter().rev() {
        let mut n = *digit;
        if is_even {
            n *= 2;
            if n > 9 {
                n -= 9;
            }
        }
        sum += n;
        is_even = !is_even;
    }

    if sum.is_multiple_of(10) {
        Ok(())
    } else {
        Err(FraiseQLError::validation("Invalid Luhn checksum".to_string()))
    }
}

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

    #[test]
    fn test_pattern_validation() {
        let rule = ValidationRule::Pattern(Regex::new("^[a-z]+$").expect("valid regex"));
        rule.validate("hello")
            .unwrap_or_else(|e| panic!("expected Ok for 'hello': {e}"));
        assert!(rule.validate("Hello").is_err(), "expected Err for 'Hello' (uppercase)");
    }

    #[test]
    fn test_length_validation() {
        let rule = ValidationRule::Length(3);
        rule.validate("abc")
            .unwrap_or_else(|e| panic!("expected Ok for len=3 string: {e}"));
        assert!(rule.validate("ab").is_err(), "expected Err for len=2 string");
        assert!(rule.validate("abcd").is_err(), "expected Err for len=4 string");
    }

    #[test]
    fn test_mod97_valid() {
        // Valid IBAN: GB82 WEST 1234 5698 7654 32
        let result = validate_mod97("GB82WEST12345698765432");
        result.unwrap_or_else(|e| panic!("expected Ok for valid IBAN: {e}"));
    }

    #[test]
    fn test_luhn_valid() {
        // Valid credit card number
        let result = validate_luhn("4532015112830366");
        result.unwrap_or_else(|e| panic!("expected Ok for valid Luhn number: {e}"));
    }

    #[test]
    fn test_enum_validation() {
        let rule = ValidationRule::Enum(vec!["US".to_string(), "CA".to_string()]);
        rule.validate("US").unwrap_or_else(|e| panic!("expected Ok for 'US': {e}"));
        assert!(rule.validate("UK").is_err(), "expected Err for 'UK' (not in enum)");
    }

    #[test]
    fn test_numeric_range_validation() {
        let rule = ValidationRule::NumericRange {
            min: 0.0,
            max: 90.0,
        };
        rule.validate("45.5").unwrap_or_else(|e| panic!("expected Ok for 45.5: {e}"));
        assert!(rule.validate("91").is_err(), "expected Err for 91 (out of range)");
    }
}