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
#![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable

//! Integration tests for validation audit logging.
//!
//! Tests validation-specific audit logging with tenant isolation, PII redaction,
//! and compliance features.

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use fraiseql_core::security::validation_audit::{
        RedactionPolicy, ValidationAuditEntry, ValidationAuditLogger, ValidationAuditLoggerConfig,
    };

    fn create_test_entry(field: &str, valid: bool, rule: &str) -> ValidationAuditEntry {
        ValidationAuditEntry {
            timestamp: chrono::Utc::now(),
            user_id: Some("user:123".to_string()),
            tenant_id: Some("tenant:1".to_string()),
            ip_address: "192.168.1.100".to_string(),
            query_string: "{ user { id name } }".to_string(),
            mutation_name: None,
            field: field.to_string(),
            validation_rule: rule.to_string(),
            valid,
            failure_reason: if valid {
                None
            } else {
                Some("Value exceeds maximum length".to_string())
            },
            duration_us: 125,
            execution_context: "pattern_validator".to_string(),
        }
    }

    /// Test basic audit entry creation and properties.
    #[test]
    fn test_validation_audit_entry_creation() {
        let entry = create_test_entry("email", false, "pattern");

        assert_eq!(entry.field, "email");
        assert_eq!(entry.validation_rule, "pattern");
        assert!(!entry.valid);
        assert!(entry.failure_reason.is_some());
        assert_eq!(entry.duration_us, 125);
    }

    /// Test successful validation entries.
    #[test]
    fn test_validation_audit_entry_success() {
        let entry = create_test_entry("age", true, "range");

        assert_eq!(entry.field, "age");
        assert!(entry.valid);
        assert!(entry.failure_reason.is_none());
    }

    /// Test audit logger initialization with default config.
    #[test]
    fn test_validation_audit_logger_default_config() {
        let config = ValidationAuditLoggerConfig::default();

        assert!(config.enabled);
        assert!(config.capture_successful_validations);
        assert!(config.capture_query_strings);
    }

    /// Test audit logger with custom redaction policy.
    #[test]
    fn test_validation_audit_logger_with_redaction() {
        let config = ValidationAuditLoggerConfig {
            redaction_policy: RedactionPolicy::Aggressive,
            ..Default::default()
        };

        let logger = ValidationAuditLogger::new(config);
        let entry = create_test_entry("password", false, "length");

        logger.log_entry(entry);

        // Logger should be initialized without panic
        assert!(logger.is_enabled());
    }

    /// Test audit logger enables and disables.
    #[test]
    fn test_validation_audit_logger_enable_disable() {
        let config = ValidationAuditLoggerConfig {
            enabled: false,
            ..Default::default()
        };

        let logger = ValidationAuditLogger::new(config);
        assert!(!logger.is_enabled());

        let config2 = ValidationAuditLoggerConfig {
            enabled: true,
            ..Default::default()
        };

        let logger2 = ValidationAuditLogger::new(config2);
        assert!(logger2.is_enabled());
    }

    /// Test logging entry with user context.
    #[test]
    fn test_validation_audit_entry_user_context() {
        let entry = create_test_entry("username", false, "pattern");

        assert_eq!(entry.user_id, Some("user:123".to_string()));
        assert!(entry.user_id.is_some());
    }

    /// Test logging entry with tenant context.
    #[test]
    fn test_validation_audit_entry_tenant_isolation() {
        let entry = create_test_entry("field", true, "required");

        assert_eq!(entry.tenant_id, Some("tenant:1".to_string()));
        assert_ne!(entry.tenant_id, Some("tenant:2".to_string()));
    }

    /// Test audit entry with IP address.
    #[test]
    fn test_validation_audit_entry_ip_address() {
        let entry = create_test_entry("email", false, "pattern");

        assert_eq!(entry.ip_address, "192.168.1.100");
        assert!(!entry.ip_address.is_empty());
    }

    /// Test audit entry with query string.
    #[test]
    fn test_validation_audit_entry_query_string() {
        let entry = create_test_entry("id", true, "required");

        assert_eq!(entry.query_string, "{ user { id name } }");
        assert!(!entry.query_string.is_empty());
    }

    /// Test audit entry with mutation name.
    #[test]
    fn test_validation_audit_entry_mutation_name() {
        let mut entry = create_test_entry("email", false, "pattern");
        entry.mutation_name = Some("createUser".to_string());

        assert_eq!(entry.mutation_name, Some("createUser".to_string()));
    }

    /// Test validation rule name tracking.
    #[test]
    fn test_validation_audit_entry_rule_types() {
        let rules = vec!["required", "pattern", "range", "length", "enum", "checksum"];

        for rule in rules {
            let entry = create_test_entry("field", false, rule);
            assert_eq!(entry.validation_rule, rule);
        }
    }

    /// Test execution context tracking (validator type).
    #[test]
    fn test_validation_audit_entry_execution_context() {
        let contexts = vec!["pattern_validator", "async_validator", "checksum_validator"];

        for context in contexts {
            let mut entry = create_test_entry("field", false, "pattern");
            entry.execution_context = context.to_string();
            assert_eq!(entry.execution_context, context);
        }
    }

    /// Test validation duration tracking in microseconds.
    #[test]
    fn test_validation_audit_entry_duration() {
        let mut entry = create_test_entry("field", true, "pattern");
        entry.duration_us = 1500;

        assert_eq!(entry.duration_us, 1500);
        assert!(entry.duration_us > 0);
    }

    /// Test audit logger processes entries without panic.
    #[test]
    fn test_validation_audit_logger_process_entry() {
        let config = ValidationAuditLoggerConfig::default();
        let logger = ValidationAuditLogger::new(config);
        let entry = create_test_entry("email", false, "pattern");

        logger.log_entry(entry);
        // Test passes if no panic
    }

    /// Test logging multiple entries in sequence.
    #[test]
    fn test_validation_audit_logger_multiple_entries() {
        let config = ValidationAuditLoggerConfig::default();
        let logger = ValidationAuditLogger::new(config);

        for i in 0..10 {
            let field = format!("field{}", i);
            let entry = create_test_entry(&field, i % 2 == 0, "pattern");
            logger.log_entry(entry);
        }
        // Test passes if all entries logged without panic
    }

    /// Test tenant isolation in audit entries.
    #[test]
    fn test_validation_audit_tenant_different_entries() {
        let config = ValidationAuditLoggerConfig::default();
        let logger = ValidationAuditLogger::new(config);

        let mut entry1 = create_test_entry("field", true, "required");
        entry1.tenant_id = Some("tenant:1".to_string());

        let mut entry2 = create_test_entry("field", true, "required");
        entry2.tenant_id = Some("tenant:2".to_string());

        let tenant1 = entry1.tenant_id.clone();
        let tenant2 = entry2.tenant_id.clone();

        logger.log_entry(entry1);
        logger.log_entry(entry2);

        // Tenants should be isolated
        assert_ne!(tenant1.as_ref().unwrap(), tenant2.as_ref().unwrap());
    }

    /// Test redaction policy configuration.
    #[test]
    fn test_validation_audit_redaction_policies() {
        let policies = vec![
            RedactionPolicy::None,
            RedactionPolicy::Conservative,
            RedactionPolicy::Aggressive,
        ];

        for policy in policies {
            let config = ValidationAuditLoggerConfig {
                redaction_policy: policy,
                ..Default::default()
            };

            let logger = ValidationAuditLogger::new(config);
            assert!(logger.is_enabled());
        }
    }

    /// Test capture successful validations flag.
    #[test]
    fn test_validation_audit_capture_successful_flag() {
        let config = ValidationAuditLoggerConfig {
            capture_successful_validations: true,
            ..Default::default()
        };

        let logger = ValidationAuditLogger::new(config);
        let entry = create_test_entry("field", true, "pattern");

        logger.log_entry(entry);
        // Should handle successful entries
    }

    /// Test capture query strings flag.
    #[test]
    fn test_validation_audit_capture_query_strings_flag() {
        let config = ValidationAuditLoggerConfig {
            capture_query_strings: true,
            ..Default::default()
        };

        let logger = ValidationAuditLogger::new(config);
        let entry = create_test_entry("field", false, "pattern");

        logger.log_entry(entry);
        // Should capture query strings when enabled
    }

    /// Test concurrent logging access.
    #[test]
    fn test_validation_audit_logger_concurrent() {
        let config = ValidationAuditLoggerConfig::default();
        let logger = Arc::new(ValidationAuditLogger::new(config));

        let mut handles = vec![];

        // Spawn 10 threads, each logging 10 entries
        for thread_id in 0..10 {
            let logger_clone = Arc::clone(&logger);

            let handle = std::thread::spawn(move || {
                for i in 0..10 {
                    let field = format!("thread_{}_field_{}", thread_id, i);
                    let entry = create_test_entry(&field, i % 2 == 0, "pattern");
                    logger_clone.log_entry(entry);
                }
            });

            handles.push(handle);
        }

        // Wait for all threads to complete
        for handle in handles {
            handle.join().unwrap();
        }

        // Test passes if all concurrent logging completed without panic
    }

    /// Test failure reason capture.
    #[test]
    fn test_validation_audit_entry_failure_reason() {
        let mut entry = create_test_entry("email", false, "pattern");
        entry.failure_reason = Some("Invalid email format: missing @".to_string());

        assert!(entry.failure_reason.is_some());
        assert_eq!(entry.failure_reason.unwrap(), "Invalid email format: missing @");
    }

    /// Test no failure reason on successful validation.
    #[test]
    fn test_validation_audit_entry_no_failure_on_success() {
        let entry = create_test_entry("email", true, "pattern");

        assert!(entry.failure_reason.is_none());
    }

    /// Test audit logger can clone and share state.
    #[test]
    fn test_validation_audit_logger_clone() {
        let logger1 = ValidationAuditLogger::new(ValidationAuditLoggerConfig::default());
        let logger2 = logger1.clone();

        let entry1 = create_test_entry("field1", true, "required");
        let entry2 = create_test_entry("field2", false, "pattern");

        logger1.log_entry(entry1);
        logger2.log_entry(entry2);

        // Both loggers should be operational
        assert!(logger1.is_enabled());
        assert!(logger2.is_enabled());
    }

    /// Test with all PII fields present.
    #[test]
    fn test_validation_audit_entry_all_pii_fields() {
        let mut entry = create_test_entry("sensitive_field", false, "pattern");
        entry.user_id = Some("alice@example.com".to_string());
        entry.tenant_id = Some("enterprise_customer".to_string());
        entry.ip_address = "203.0.113.42".to_string();

        assert!(entry.user_id.is_some());
        assert!(entry.tenant_id.is_some());
        assert!(!entry.ip_address.is_empty());
    }

    /// Test config with disabled audit logging.
    #[test]
    fn test_validation_audit_disabled_config() {
        let config = ValidationAuditLoggerConfig {
            enabled: false,
            ..Default::default()
        };

        let logger = ValidationAuditLogger::new(config);
        let entry = create_test_entry("field", false, "pattern");

        logger.log_entry(entry);
        // Should handle disabled state gracefully
        assert!(!logger.is_enabled());
    }

    /// Test timestamp precision.
    #[test]
    fn test_validation_audit_entry_timestamp() {
        let entry = create_test_entry("field", true, "required");
        let now = chrono::Utc::now();

        // Timestamp should be recent (within 1 second)
        let diff = now.signed_duration_since(entry.timestamp);
        assert!(diff.num_seconds() <= 1);
    }

    /// Test validation rules with different failure reasons.
    #[test]
    fn test_validation_audit_various_failure_reasons() {
        let test_cases = vec![
            ("field", "pattern", "Value does not match pattern"),
            ("age", "range", "Value exceeds maximum: 150"),
            ("password", "length", "Value shorter than minimum: 8"),
            ("status", "enum", "Value not in allowed set"),
            ("card", "checksum", "Invalid checksum"),
        ];

        for (field, rule, reason) in test_cases {
            let mut entry = create_test_entry(field, false, rule);
            entry.failure_reason = Some(reason.to_string());

            assert_eq!(entry.field, field);
            assert_eq!(entry.validation_rule, rule);
            assert_eq!(entry.failure_reason.unwrap(), reason);
        }
    }
}