core-policy 0.10.2

Pure RBAC/ABAC policy engine core (zero crypto/network dependencies)
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
//! Property-Based Tests for ContextExpr Parser
//!
//! These tests use proptest to generate random inputs and verify that
//! business logic invariants are ALWAYS maintained:
//!
//! 1. MAX_EXPR_LENGTH is enforced (DoS prevention)
//! 2. MAX_EXPR_DEPTH is enforced during evaluation (stack overflow prevention)
//! 3. Parsing never panics on any input
//! 4. Evaluation is deterministic (same input = same output)
//! 5. Boolean logic is correct (AND, OR, NOT semantics)

use core_policy::{CompareOp, ContextExpr, MAX_EXPR_DEPTH, MAX_EXPR_LENGTH};
use proptest::prelude::*;
use std::collections::BTreeMap;

// ============================================================================
// PROPERTY 1: MAX_EXPR_LENGTH is always enforced
// ============================================================================

proptest! {
    #![proptest_config(ProptestConfig::with_cases(1000))]

    /// Any string longer than MAX_EXPR_LENGTH must be rejected
    #[test]
    fn prop_max_length_enforced(extra_len in 1usize..1000) {
        let input = "a".repeat(MAX_EXPR_LENGTH + extra_len);
        let result = ContextExpr::parse(&input);

        prop_assert!(
            result.is_err(),
            "Input of length {} should be rejected (max: {})",
            input.len(),
            MAX_EXPR_LENGTH
        );
    }

    /// Strings at or below MAX_EXPR_LENGTH should not fail due to length
    #[test]
    fn prop_within_length_allowed(len in 1usize..=MAX_EXPR_LENGTH) {
        let input = "a".repeat(len);
        let result = ContextExpr::parse(&input);

        // May fail for syntax, but NOT for length
        // We can't easily check the error type, but we verify no panic
        let _ = result;
    }
}

// ============================================================================
// PROPERTY 2: Parsing NEVER panics
// ============================================================================

proptest! {
    #![proptest_config(ProptestConfig::with_cases(5000))]

    /// Parsing any arbitrary string must not panic
    #[test]
    fn prop_parse_never_panics(input in ".*") {
        // This should NEVER panic, only return Ok or Err
        let _ = ContextExpr::parse(&input);
    }

    /// Parsing strings with special characters must not panic
    #[test]
    fn prop_parse_special_chars_safe(
        prefix in "[()\"\\\\AND OR NOT HAS TRUE FALSE == != < <= > >=]*",
        middle in "\\PC*",  // Any printable char
        suffix in "[()\"\\\\]*"
    ) {
        let input = format!("{}{}{}", prefix, middle, suffix);
        if input.len() <= MAX_EXPR_LENGTH {
            let _ = ContextExpr::parse(&input);
        }
    }

    /// Parsing expressions with random nesting must not panic
    #[test]
    fn prop_parse_random_nesting_safe(
        open_count in 0usize..200,
        close_count in 0usize..200,
        inner in "(TRUE|FALSE|role == \"admin\")"
    ) {
        let input = format!(
            "{}{}{}",
            "(".repeat(open_count),
            inner,
            ")".repeat(close_count)
        );
        if input.len() <= MAX_EXPR_LENGTH {
            let _ = ContextExpr::parse(&input);
        }
    }
}

// ============================================================================
// PROPERTY 3: Evaluation is DETERMINISTIC
// ============================================================================

fn arbitrary_context() -> impl Strategy<Value = BTreeMap<String, String>> {
    prop::collection::btree_map(
        "[a-z]{1,10}",       // keys
        "[a-zA-Z0-9]{1,20}", // values
        0..10,               // size
    )
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(1000))]

    /// Same expression + same context = same result (determinism)
    #[test]
    fn prop_evaluation_deterministic(
        expr_str in "(TRUE|FALSE|role == \"admin\"|dept == \"IT\"|HAS role)",
        ctx in arbitrary_context()
    ) {
        if let Ok(expr) = ContextExpr::parse(&expr_str) {
            // Evaluate three times independently
            let r1 = expr.evaluate(&ctx, 0);
            let r2 = expr.evaluate(&ctx, 0);
            let r3 = expr.evaluate(&ctx, 0);

            // All three should have the same success/failure status
            prop_assert!(r1.is_ok() == r2.is_ok(), "Determinism: same ok status");
            prop_assert!(r2.is_ok() == r3.is_ok(), "Determinism: same ok status");

            // If successful, values must match
            if let (Ok(v1), Ok(v2), Ok(v3)) = (r1, r2, r3) {
                prop_assert_eq!(v1, v2, "Evaluation must be deterministic");
                prop_assert_eq!(v2, v3, "Evaluation must be deterministic");
            }
        }
    }

    /// Evaluation with depth 0 must be equivalent to fresh evaluation
    #[test]
    fn prop_depth_zero_consistent(
        expr_str in "(TRUE|FALSE|role == \"admin\")",
        ctx in arbitrary_context()
    ) {
        if let Ok(expr) = ContextExpr::parse(&expr_str) {
            let at_zero = expr.evaluate(&ctx, 0);
            let at_one = expr.evaluate(&ctx, 1);

            // Both should succeed for simple expressions
            if at_zero.is_ok() && at_one.is_ok() {
                prop_assert_eq!(
                    at_zero.unwrap(),
                    at_one.unwrap(),
                    "Result should be same regardless of starting depth for simple exprs"
                );
            }
        }
    }
}

// ============================================================================
// PROPERTY 4: MAX_EXPR_DEPTH is enforced during evaluation
// ============================================================================

/// Generate a deeply nested expression programmatically
fn make_nested_expr(depth: usize) -> ContextExpr {
    if depth == 0 {
        ContextExpr::True
    } else {
        ContextExpr::Not(Box::new(make_nested_expr(depth - 1)))
    }
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(100))]

    /// Expressions deeper than MAX_EXPR_DEPTH must fail at evaluation
    #[test]
    fn prop_max_depth_enforced(extra_depth in 1usize..50) {
        let expr = make_nested_expr(MAX_EXPR_DEPTH + extra_depth);
        let ctx = BTreeMap::new();
        let result = expr.evaluate(&ctx, 0);

        prop_assert!(
            result.is_err(),
            "Expression with depth {} should fail (max: {})",
            MAX_EXPR_DEPTH + extra_depth,
            MAX_EXPR_DEPTH
        );
    }

    /// Expressions at or below MAX_EXPR_DEPTH should succeed
    #[test]
    fn prop_within_depth_allowed(depth in 1usize..=MAX_EXPR_DEPTH) {
        let expr = make_nested_expr(depth);
        let ctx = BTreeMap::new();
        let result = expr.evaluate(&ctx, 0);

        // Should succeed (NOT NOT NOT ... TRUE = TRUE or FALSE)
        prop_assert!(
            result.is_ok(),
            "Expression with depth {} should succeed (max: {})",
            depth,
            MAX_EXPR_DEPTH
        );
    }
}

// ============================================================================
// PROPERTY 5: Boolean logic is CORRECT
// ============================================================================

proptest! {
    #![proptest_config(ProptestConfig::with_cases(1000))]

    /// TRUE always evaluates to true
    #[test]
    fn prop_true_is_true(ctx in arbitrary_context()) {
        let expr = ContextExpr::True;
        let result = expr.evaluate(&ctx, 0);
        prop_assert!(result.is_ok());
        prop_assert_eq!(result.unwrap(), true);
    }

    /// FALSE always evaluates to false
    #[test]
    fn prop_false_is_false(ctx in arbitrary_context()) {
        let expr = ContextExpr::False;
        let result = expr.evaluate(&ctx, 0);
        prop_assert!(result.is_ok());
        prop_assert_eq!(result.unwrap(), false);
    }

    /// NOT TRUE = FALSE
    #[test]
    fn prop_not_true_is_false(ctx in arbitrary_context()) {
        let expr = ContextExpr::Not(Box::new(ContextExpr::True));
        let result = expr.evaluate(&ctx, 0);
        prop_assert!(result.is_ok());
        prop_assert_eq!(result.unwrap(), false);
    }

    /// NOT FALSE = TRUE
    #[test]
    fn prop_not_false_is_true(ctx in arbitrary_context()) {
        let expr = ContextExpr::Not(Box::new(ContextExpr::False));
        let result = expr.evaluate(&ctx, 0);
        prop_assert!(result.is_ok());
        prop_assert_eq!(result.unwrap(), true);
    }

    /// Double negation: NOT NOT x = x
    #[test]
    fn prop_double_negation(b in any::<bool>(), ctx in arbitrary_context()) {
        let inner = if b { ContextExpr::True } else { ContextExpr::False };
        let expr = ContextExpr::Not(Box::new(ContextExpr::Not(Box::new(inner.clone()))));

        let original = inner.evaluate(&ctx, 0).unwrap();
        let double_neg = expr.evaluate(&ctx, 0).unwrap();

        prop_assert_eq!(original, double_neg, "NOT NOT x must equal x");
    }

    /// AND truth table: TRUE AND TRUE = TRUE
    #[test]
    fn prop_and_tt(ctx in arbitrary_context()) {
        let expr = ContextExpr::And(
            Box::new(ContextExpr::True),
            Box::new(ContextExpr::True)
        );
        prop_assert_eq!(expr.evaluate(&ctx, 0).unwrap(), true);
    }

    /// AND truth table: TRUE AND FALSE = FALSE
    #[test]
    fn prop_and_tf(ctx in arbitrary_context()) {
        let expr = ContextExpr::And(
            Box::new(ContextExpr::True),
            Box::new(ContextExpr::False)
        );
        prop_assert_eq!(expr.evaluate(&ctx, 0).unwrap(), false);
    }

    /// AND truth table: FALSE AND TRUE = FALSE
    #[test]
    fn prop_and_ft(ctx in arbitrary_context()) {
        let expr = ContextExpr::And(
            Box::new(ContextExpr::False),
            Box::new(ContextExpr::True)
        );
        prop_assert_eq!(expr.evaluate(&ctx, 0).unwrap(), false);
    }

    /// AND truth table: FALSE AND FALSE = FALSE
    #[test]
    fn prop_and_ff(ctx in arbitrary_context()) {
        let expr = ContextExpr::And(
            Box::new(ContextExpr::False),
            Box::new(ContextExpr::False)
        );
        prop_assert_eq!(expr.evaluate(&ctx, 0).unwrap(), false);
    }

    /// OR truth table: TRUE OR TRUE = TRUE
    #[test]
    fn prop_or_tt(ctx in arbitrary_context()) {
        let expr = ContextExpr::Or(
            Box::new(ContextExpr::True),
            Box::new(ContextExpr::True)
        );
        prop_assert_eq!(expr.evaluate(&ctx, 0).unwrap(), true);
    }

    /// OR truth table: TRUE OR FALSE = TRUE
    #[test]
    fn prop_or_tf(ctx in arbitrary_context()) {
        let expr = ContextExpr::Or(
            Box::new(ContextExpr::True),
            Box::new(ContextExpr::False)
        );
        prop_assert_eq!(expr.evaluate(&ctx, 0).unwrap(), true);
    }

    /// OR truth table: FALSE OR TRUE = TRUE
    #[test]
    fn prop_or_ft(ctx in arbitrary_context()) {
        let expr = ContextExpr::Or(
            Box::new(ContextExpr::False),
            Box::new(ContextExpr::True)
        );
        prop_assert_eq!(expr.evaluate(&ctx, 0).unwrap(), true);
    }

    /// OR truth table: FALSE OR FALSE = FALSE
    #[test]
    fn prop_or_ff(ctx in arbitrary_context()) {
        let expr = ContextExpr::Or(
            Box::new(ContextExpr::False),
            Box::new(ContextExpr::False)
        );
        prop_assert_eq!(expr.evaluate(&ctx, 0).unwrap(), false);
    }

    /// De Morgan's Law: NOT (A AND B) = (NOT A) OR (NOT B)
    #[test]
    fn prop_de_morgan_and(a in any::<bool>(), b in any::<bool>(), ctx in arbitrary_context()) {
        let a_expr = if a { ContextExpr::True } else { ContextExpr::False };
        let b_expr = if b { ContextExpr::True } else { ContextExpr::False };

        // NOT (A AND B)
        let left = ContextExpr::Not(Box::new(ContextExpr::And(
            Box::new(a_expr.clone()),
            Box::new(b_expr.clone())
        )));

        // (NOT A) OR (NOT B)
        let right = ContextExpr::Or(
            Box::new(ContextExpr::Not(Box::new(a_expr))),
            Box::new(ContextExpr::Not(Box::new(b_expr)))
        );

        prop_assert_eq!(
            left.evaluate(&ctx, 0).unwrap(),
            right.evaluate(&ctx, 0).unwrap(),
            "De Morgan's Law must hold"
        );
    }

    /// De Morgan's Law: NOT (A OR B) = (NOT A) AND (NOT B)
    #[test]
    fn prop_de_morgan_or(a in any::<bool>(), b in any::<bool>(), ctx in arbitrary_context()) {
        let a_expr = if a { ContextExpr::True } else { ContextExpr::False };
        let b_expr = if b { ContextExpr::True } else { ContextExpr::False };

        // NOT (A OR B)
        let left = ContextExpr::Not(Box::new(ContextExpr::Or(
            Box::new(a_expr.clone()),
            Box::new(b_expr.clone())
        )));

        // (NOT A) AND (NOT B)
        let right = ContextExpr::And(
            Box::new(ContextExpr::Not(Box::new(a_expr))),
            Box::new(ContextExpr::Not(Box::new(b_expr)))
        );

        prop_assert_eq!(
            left.evaluate(&ctx, 0).unwrap(),
            right.evaluate(&ctx, 0).unwrap(),
            "De Morgan's Law must hold"
        );
    }
}

// ============================================================================
// PROPERTY 6: Compare operations are correct
// ============================================================================

proptest! {
    #![proptest_config(ProptestConfig::with_cases(500))]

    /// Equal comparison: key exists and matches
    #[test]
    fn prop_compare_equal_match(value in "[a-z]{1,10}") {
        let mut ctx = BTreeMap::new();
        ctx.insert("key".to_string(), value.clone());

        let expr = ContextExpr::Compare {
            key: "key".to_string(),
            op: CompareOp::Equal,
            value: value.clone(),
        };

        prop_assert_eq!(expr.evaluate(&ctx, 0).unwrap(), true);
    }

    /// Equal comparison: key exists but doesn't match
    #[test]
    fn prop_compare_equal_mismatch(
        stored in "[a-z]{1,10}",
        compared in "[A-Z]{1,10}"  // Different case = different value
    ) {
        let mut ctx = BTreeMap::new();
        ctx.insert("key".to_string(), stored);

        let expr = ContextExpr::Compare {
            key: "key".to_string(),
            op: CompareOp::Equal,
            value: compared,
        };

        prop_assert_eq!(expr.evaluate(&ctx, 0).unwrap(), false);
    }

    /// NotEqual is the inverse of Equal
    #[test]
    fn prop_not_equal_inverse(
        stored in "[a-z]{1,5}",
        compared in "[a-z]{1,5}"
    ) {
        let mut ctx = BTreeMap::new();
        ctx.insert("key".to_string(), stored.clone());

        let eq_expr = ContextExpr::Compare {
            key: "key".to_string(),
            op: CompareOp::Equal,
            value: compared.clone(),
        };

        let neq_expr = ContextExpr::Compare {
            key: "key".to_string(),
            op: CompareOp::NotEqual,
            value: compared,
        };

        let eq_result = eq_expr.evaluate(&ctx, 0).unwrap();
        let neq_result = neq_expr.evaluate(&ctx, 0).unwrap();

        prop_assert_eq!(eq_result, !neq_result, "!= must be inverse of ==");
    }

    /// Missing key always returns false for comparisons
    #[test]
    fn prop_missing_key_false(value in "[a-z]{1,10}") {
        let ctx = BTreeMap::new(); // Empty context

        let expr = ContextExpr::Compare {
            key: "nonexistent".to_string(),
            op: CompareOp::Equal,
            value,
        };

        prop_assert_eq!(expr.evaluate(&ctx, 0).unwrap(), false);
    }

    /// HasAttribute returns true iff key exists
    #[test]
    fn prop_has_attribute_correct(
        key in "[a-z]{1,5}",
        value in "[a-z]{1,10}",
        check_existing in any::<bool>()
    ) {
        let mut ctx = BTreeMap::new();
        ctx.insert(key.clone(), value);

        let check_key = if check_existing { key } else { "other".to_string() };
        let expr = ContextExpr::HasAttribute(check_key.clone());

        let expected = ctx.contains_key(&check_key);
        prop_assert_eq!(expr.evaluate(&ctx, 0).unwrap(), expected);
    }
}

// ============================================================================
// PROPERTY 7: Lexicographic comparison operators
// ============================================================================

proptest! {
    #![proptest_config(ProptestConfig::with_cases(500))]

    /// Less than comparison (lexicographic)
    #[test]
    fn prop_less_than_correct(
        stored in "[a-m]{1,5}",  // First half of alphabet
        compared in "[n-z]{1,5}" // Second half of alphabet
    ) {
        let mut ctx = BTreeMap::new();
        ctx.insert("key".to_string(), stored.clone());

        // stored < compared should be true (first half < second half)
        let expr = ContextExpr::Compare {
            key: "key".to_string(),
            op: CompareOp::LessThan,
            value: compared.clone(),
        };

        // This should be true since a-m < n-z lexicographically
        let result = expr.evaluate(&ctx, 0).unwrap();
        let expected = stored < compared;
        prop_assert_eq!(result, expected);
    }

    /// Greater than comparison (lexicographic)
    #[test]
    fn prop_greater_than_correct(
        stored in "[n-z]{1,5}",  // Second half of alphabet
        compared in "[a-m]{1,5}" // First half of alphabet
    ) {
        let mut ctx = BTreeMap::new();
        ctx.insert("key".to_string(), stored.clone());

        let expr = ContextExpr::Compare {
            key: "key".to_string(),
            op: CompareOp::GreaterThan,
            value: compared.clone(),
        };

        let result = expr.evaluate(&ctx, 0).unwrap();
        let expected = stored > compared;
        prop_assert_eq!(result, expected);
    }

    /// LessThanOrEqual includes equality
    #[test]
    fn prop_lte_includes_equal(value in "[a-z]{1,5}") {
        let mut ctx = BTreeMap::new();
        ctx.insert("key".to_string(), value.clone());

        let expr = ContextExpr::Compare {
            key: "key".to_string(),
            op: CompareOp::LessThanOrEqual,
            value: value.clone(),
        };

        // value <= value should always be true
        prop_assert_eq!(expr.evaluate(&ctx, 0).unwrap(), true);
    }

    /// GreaterThanOrEqual includes equality
    #[test]
    fn prop_gte_includes_equal(value in "[a-z]{1,5}") {
        let mut ctx = BTreeMap::new();
        ctx.insert("key".to_string(), value.clone());

        let expr = ContextExpr::Compare {
            key: "key".to_string(),
            op: CompareOp::GreaterThanOrEqual,
            value: value.clone(),
        };

        // value >= value should always be true
        prop_assert_eq!(expr.evaluate(&ctx, 0).unwrap(), true);
    }
}