wami-condition 0.18.0

IAM policy condition key evaluation, as used by wami
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
//! Condition Operators
//!
//! Implements all condition operators for policy evaluation.

use super::{ConditionError, ConditionValue};
use std::str::FromStr;

/// Condition operator types
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConditionOperator {
    // String operators
    StringEquals,
    StringNotEquals,
    StringLike,
    StringNotLike,
    StringEqualsIgnoreCase,
    StringNotEqualsIgnoreCase,
    StringEqualsIfExists,
    StringNotEqualsIfExists,
    StringLikeIfExists,
    StringNotLikeIfExists,

    // Numeric operators
    NumericEquals,
    NumericNotEquals,
    NumericLessThan,
    NumericLessThanEquals,
    NumericGreaterThan,
    NumericGreaterThanEquals,
    NumericEqualsIfExists,
    NumericNotEqualsIfExists,
    NumericLessThanIfExists,
    NumericLessThanEqualsIfExists,
    NumericGreaterThanIfExists,
    NumericGreaterThanEqualsIfExists,

    // Date operators
    DateEquals,
    DateNotEquals,
    DateLessThan,
    DateLessThanEquals,
    DateGreaterThan,
    DateGreaterThanEquals,
    DateEqualsIfExists,
    DateNotEqualsIfExists,
    DateLessThanIfExists,
    DateLessThanEqualsIfExists,
    DateGreaterThanIfExists,
    DateGreaterThanEqualsIfExists,

    // IP address operators
    IpAddress,
    NotIpAddress,
    IpAddressIfExists,
    NotIpAddressIfExists,

    // ARN operators
    ArnEquals,
    ArnNotEquals,
    ArnLike,
    ArnNotLike,
    ArnEqualsIfExists,
    ArnNotEqualsIfExists,
    ArnLikeIfExists,
    ArnNotLikeIfExists,

    // Boolean operators
    Bool,
    BoolIfExists,

    // Binary operators
    BinaryEquals,
    BinaryEqualsIfExists,

    // Null operators
    Null,
    NullIfExists,

    // Set operators (ForAllValues)
    ForAllValuesStringEquals,
    ForAllValuesStringNotEquals,
    ForAllValuesStringLike,
    ForAllValuesStringNotLike,
    ForAllValuesArnEquals,
    ForAllValuesArnLike,
    ForAllValuesNumericLessThan,
    ForAllValuesNumericGreaterThan,
    ForAllValuesIpAddress,
    ForAllValuesDateLessThan,
    ForAllValuesDateGreaterThan,

    // Set operators (ForAnyValue)
    ForAnyValueStringEquals,
    ForAnyValueStringNotEquals,
    ForAnyValueStringLike,
    ForAnyValueStringNotLike,
    ForAnyValueArnEquals,
    ForAnyValueArnLike,
    ForAnyValueNumericLessThan,
    ForAnyValueNumericGreaterThan,
    ForAnyValueIpAddress,
    ForAnyValueDateLessThan,
    ForAnyValueDateGreaterThan,
}

impl FromStr for ConditionOperator {
    type Err = ConditionError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "StringEquals" => Ok(ConditionOperator::StringEquals),
            "StringNotEquals" => Ok(ConditionOperator::StringNotEquals),
            "StringLike" => Ok(ConditionOperator::StringLike),
            "StringNotLike" => Ok(ConditionOperator::StringNotLike),
            "StringEqualsIgnoreCase" => Ok(ConditionOperator::StringEqualsIgnoreCase),
            "StringNotEqualsIgnoreCase" => Ok(ConditionOperator::StringNotEqualsIgnoreCase),
            "StringEqualsIfExists" => Ok(ConditionOperator::StringEqualsIfExists),
            "StringNotEqualsIfExists" => Ok(ConditionOperator::StringNotEqualsIfExists),
            "StringLikeIfExists" => Ok(ConditionOperator::StringLikeIfExists),
            "StringNotLikeIfExists" => Ok(ConditionOperator::StringNotLikeIfExists),

            "NumericEquals" => Ok(ConditionOperator::NumericEquals),
            "NumericNotEquals" => Ok(ConditionOperator::NumericNotEquals),
            "NumericLessThan" => Ok(ConditionOperator::NumericLessThan),
            "NumericLessThanEquals" => Ok(ConditionOperator::NumericLessThanEquals),
            "NumericGreaterThan" => Ok(ConditionOperator::NumericGreaterThan),
            "NumericGreaterThanEquals" => Ok(ConditionOperator::NumericGreaterThanEquals),
            "NumericEqualsIfExists" => Ok(ConditionOperator::NumericEqualsIfExists),
            "NumericNotEqualsIfExists" => Ok(ConditionOperator::NumericNotEqualsIfExists),
            "NumericLessThanIfExists" => Ok(ConditionOperator::NumericLessThanIfExists),
            "NumericLessThanEqualsIfExists" => Ok(ConditionOperator::NumericLessThanEqualsIfExists),
            "NumericGreaterThanIfExists" => Ok(ConditionOperator::NumericGreaterThanIfExists),
            "NumericGreaterThanEqualsIfExists" => {
                Ok(ConditionOperator::NumericGreaterThanEqualsIfExists)
            }

            "DateEquals" => Ok(ConditionOperator::DateEquals),
            "DateNotEquals" => Ok(ConditionOperator::DateNotEquals),
            "DateLessThan" => Ok(ConditionOperator::DateLessThan),
            "DateLessThanEquals" => Ok(ConditionOperator::DateLessThanEquals),
            "DateGreaterThan" => Ok(ConditionOperator::DateGreaterThan),
            "DateGreaterThanEquals" => Ok(ConditionOperator::DateGreaterThanEquals),
            "DateEqualsIfExists" => Ok(ConditionOperator::DateEqualsIfExists),
            "DateNotEqualsIfExists" => Ok(ConditionOperator::DateNotEqualsIfExists),
            "DateLessThanIfExists" => Ok(ConditionOperator::DateLessThanIfExists),
            "DateLessThanEqualsIfExists" => Ok(ConditionOperator::DateLessThanEqualsIfExists),
            "DateGreaterThanIfExists" => Ok(ConditionOperator::DateGreaterThanIfExists),
            "DateGreaterThanEqualsIfExists" => Ok(ConditionOperator::DateGreaterThanEqualsIfExists),

            "IpAddress" => Ok(ConditionOperator::IpAddress),
            "NotIpAddress" => Ok(ConditionOperator::NotIpAddress),
            "IpAddressIfExists" => Ok(ConditionOperator::IpAddressIfExists),
            "NotIpAddressIfExists" => Ok(ConditionOperator::NotIpAddressIfExists),

            "ArnEquals" => Ok(ConditionOperator::ArnEquals),
            "ArnNotEquals" => Ok(ConditionOperator::ArnNotEquals),
            "ArnLike" => Ok(ConditionOperator::ArnLike),
            "ArnNotLike" => Ok(ConditionOperator::ArnNotLike),
            "ArnEqualsIfExists" => Ok(ConditionOperator::ArnEqualsIfExists),
            "ArnNotEqualsIfExists" => Ok(ConditionOperator::ArnNotEqualsIfExists),
            "ArnLikeIfExists" => Ok(ConditionOperator::ArnLikeIfExists),
            "ArnNotLikeIfExists" => Ok(ConditionOperator::ArnNotLikeIfExists),

            "Bool" => Ok(ConditionOperator::Bool),
            "BoolIfExists" => Ok(ConditionOperator::BoolIfExists),

            "BinaryEquals" => Ok(ConditionOperator::BinaryEquals),
            "BinaryEqualsIfExists" => Ok(ConditionOperator::BinaryEqualsIfExists),

            "Null" => Ok(ConditionOperator::Null),
            "NullIfExists" => Ok(ConditionOperator::NullIfExists),

            "ForAllValues:StringEquals" => Ok(ConditionOperator::ForAllValuesStringEquals),
            "ForAllValues:StringNotEquals" => Ok(ConditionOperator::ForAllValuesStringNotEquals),
            "ForAllValues:StringLike" => Ok(ConditionOperator::ForAllValuesStringLike),
            "ForAllValues:StringNotLike" => Ok(ConditionOperator::ForAllValuesStringNotLike),
            "ForAllValues:ArnEquals" => Ok(ConditionOperator::ForAllValuesArnEquals),
            "ForAllValues:ArnLike" => Ok(ConditionOperator::ForAllValuesArnLike),
            "ForAllValues:NumericLessThan" => Ok(ConditionOperator::ForAllValuesNumericLessThan),
            "ForAllValues:NumericGreaterThan" => {
                Ok(ConditionOperator::ForAllValuesNumericGreaterThan)
            }
            "ForAllValues:IpAddress" => Ok(ConditionOperator::ForAllValuesIpAddress),
            "ForAllValues:DateLessThan" => Ok(ConditionOperator::ForAllValuesDateLessThan),
            "ForAllValues:DateGreaterThan" => Ok(ConditionOperator::ForAllValuesDateGreaterThan),

            "ForAnyValue:StringEquals" => Ok(ConditionOperator::ForAnyValueStringEquals),
            "ForAnyValue:StringNotEquals" => Ok(ConditionOperator::ForAnyValueStringNotEquals),
            "ForAnyValue:StringLike" => Ok(ConditionOperator::ForAnyValueStringLike),
            "ForAnyValue:StringNotLike" => Ok(ConditionOperator::ForAnyValueStringNotLike),
            "ForAnyValue:ArnEquals" => Ok(ConditionOperator::ForAnyValueArnEquals),
            "ForAnyValue:ArnLike" => Ok(ConditionOperator::ForAnyValueArnLike),
            "ForAnyValue:NumericLessThan" => Ok(ConditionOperator::ForAnyValueNumericLessThan),
            "ForAnyValue:NumericGreaterThan" => {
                Ok(ConditionOperator::ForAnyValueNumericGreaterThan)
            }
            "ForAnyValue:IpAddress" => Ok(ConditionOperator::ForAnyValueIpAddress),
            "ForAnyValue:DateLessThan" => Ok(ConditionOperator::ForAnyValueDateLessThan),
            "ForAnyValue:DateGreaterThan" => Ok(ConditionOperator::ForAnyValueDateGreaterThan),

            _ => Err(ConditionError::UnknownOperator(s.to_string())),
        }
    }
}

/// Evaluate a condition operator
pub fn evaluate_operator(
    operator: ConditionOperator,
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    match operator {
        // String operators
        ConditionOperator::StringEquals => evaluate_string_equals(actual, expected),
        ConditionOperator::StringNotEquals => evaluate_string_equals(actual, expected).map(|r| !r),
        ConditionOperator::StringLike => evaluate_string_like(actual, expected),
        ConditionOperator::StringNotLike => evaluate_string_like(actual, expected).map(|r| !r),
        ConditionOperator::StringEqualsIgnoreCase => {
            evaluate_string_equals_ignore_case(actual, expected)
        }
        ConditionOperator::StringNotEqualsIgnoreCase => {
            evaluate_string_equals_ignore_case(actual, expected).map(|r| !r)
        }
        ConditionOperator::StringEqualsIfExists => {
            evaluate_if_exists(actual, |a| evaluate_string_equals(Some(a), expected))
        }
        ConditionOperator::StringNotEqualsIfExists => evaluate_if_exists(actual, |a| {
            evaluate_string_equals(Some(a), expected).map(|r| !r)
        }),
        ConditionOperator::StringLikeIfExists => {
            evaluate_if_exists(actual, |a| evaluate_string_like(Some(a), expected))
        }
        ConditionOperator::StringNotLikeIfExists => evaluate_if_exists(actual, |a| {
            evaluate_string_like(Some(a), expected).map(|r| !r)
        }),

        // Numeric operators
        ConditionOperator::NumericEquals => evaluate_numeric_equals(actual, expected),
        ConditionOperator::NumericNotEquals => {
            evaluate_numeric_equals(actual, expected).map(|r| !r)
        }
        ConditionOperator::NumericLessThan => evaluate_numeric_less_than(actual, expected),
        ConditionOperator::NumericLessThanEquals => {
            evaluate_numeric_less_than_equals(actual, expected)
        }
        ConditionOperator::NumericGreaterThan => evaluate_numeric_greater_than(actual, expected),
        ConditionOperator::NumericGreaterThanEquals => {
            evaluate_numeric_greater_than_equals(actual, expected)
        }
        ConditionOperator::NumericEqualsIfExists => {
            evaluate_if_exists(actual, |a| evaluate_numeric_equals(Some(a), expected))
        }
        ConditionOperator::NumericNotEqualsIfExists => evaluate_if_exists(actual, |a| {
            evaluate_numeric_equals(Some(a), expected).map(|r| !r)
        }),
        ConditionOperator::NumericLessThanIfExists => {
            evaluate_if_exists(actual, |a| evaluate_numeric_less_than(Some(a), expected))
        }
        ConditionOperator::NumericLessThanEqualsIfExists => evaluate_if_exists(actual, |a| {
            evaluate_numeric_less_than_equals(Some(a), expected)
        }),
        ConditionOperator::NumericGreaterThanIfExists => {
            evaluate_if_exists(actual, |a| evaluate_numeric_greater_than(Some(a), expected))
        }
        ConditionOperator::NumericGreaterThanEqualsIfExists => evaluate_if_exists(actual, |a| {
            evaluate_numeric_greater_than_equals(Some(a), expected)
        }),

        // Date operators
        ConditionOperator::DateEquals => evaluate_date_equals(actual, expected),
        ConditionOperator::DateNotEquals => evaluate_date_equals(actual, expected).map(|r| !r),
        ConditionOperator::DateLessThan => evaluate_date_less_than(actual, expected),
        ConditionOperator::DateLessThanEquals => evaluate_date_less_than_equals(actual, expected),
        ConditionOperator::DateGreaterThan => evaluate_date_greater_than(actual, expected),
        ConditionOperator::DateGreaterThanEquals => {
            evaluate_date_greater_than_equals(actual, expected)
        }
        ConditionOperator::DateEqualsIfExists => {
            evaluate_if_exists(actual, |a| evaluate_date_equals(Some(a), expected))
        }
        ConditionOperator::DateNotEqualsIfExists => evaluate_if_exists(actual, |a| {
            evaluate_date_equals(Some(a), expected).map(|r| !r)
        }),
        ConditionOperator::DateLessThanIfExists => {
            evaluate_if_exists(actual, |a| evaluate_date_less_than(Some(a), expected))
        }
        ConditionOperator::DateLessThanEqualsIfExists => evaluate_if_exists(actual, |a| {
            evaluate_date_less_than_equals(Some(a), expected)
        }),
        ConditionOperator::DateGreaterThanIfExists => {
            evaluate_if_exists(actual, |a| evaluate_date_greater_than(Some(a), expected))
        }
        ConditionOperator::DateGreaterThanEqualsIfExists => evaluate_if_exists(actual, |a| {
            evaluate_date_greater_than_equals(Some(a), expected)
        }),

        // IP address operators
        ConditionOperator::IpAddress => evaluate_ip_address(actual, expected),
        ConditionOperator::NotIpAddress => evaluate_ip_address(actual, expected).map(|r| !r),
        ConditionOperator::IpAddressIfExists => {
            evaluate_if_exists(actual, |a| evaluate_ip_address(Some(a), expected))
        }
        ConditionOperator::NotIpAddressIfExists => evaluate_if_exists(actual, |a| {
            evaluate_ip_address(Some(a), expected).map(|r| !r)
        }),

        // ARN operators
        ConditionOperator::ArnEquals => evaluate_arn_equals(actual, expected),
        ConditionOperator::ArnNotEquals => evaluate_arn_equals(actual, expected).map(|r| !r),
        ConditionOperator::ArnLike => evaluate_arn_like(actual, expected),
        ConditionOperator::ArnNotLike => evaluate_arn_like(actual, expected).map(|r| !r),
        ConditionOperator::ArnEqualsIfExists => {
            evaluate_if_exists(actual, |a| evaluate_arn_equals(Some(a), expected))
        }
        ConditionOperator::ArnNotEqualsIfExists => evaluate_if_exists(actual, |a| {
            evaluate_arn_equals(Some(a), expected).map(|r| !r)
        }),
        ConditionOperator::ArnLikeIfExists => {
            evaluate_if_exists(actual, |a| evaluate_arn_like(Some(a), expected))
        }
        ConditionOperator::ArnNotLikeIfExists => {
            evaluate_if_exists(actual, |a| evaluate_arn_like(Some(a), expected).map(|r| !r))
        }

        // Boolean operators
        ConditionOperator::Bool => evaluate_bool(actual, expected),
        ConditionOperator::BoolIfExists => {
            evaluate_if_exists(actual, |a| evaluate_bool(Some(a), expected))
        }

        // Binary operators
        ConditionOperator::BinaryEquals => evaluate_binary_equals(actual, expected),
        ConditionOperator::BinaryEqualsIfExists => {
            evaluate_if_exists(actual, |a| evaluate_binary_equals(Some(a), expected))
        }

        // Null operators
        ConditionOperator::Null => evaluate_null(actual, expected),
        ConditionOperator::NullIfExists => {
            evaluate_if_exists(actual, |a| evaluate_null(Some(a), expected))
        }

        // Set operators - ForAllValues
        ConditionOperator::ForAllValuesStringEquals => {
            set_string_equals(Quantifier::All, actual, expected)
        }
        ConditionOperator::ForAllValuesStringNotEquals => {
            set_string_equals(Quantifier::All, actual, expected).map(|r| !r)
        }
        ConditionOperator::ForAllValuesStringLike => {
            set_string_like(Quantifier::All, actual, expected)
        }
        ConditionOperator::ForAllValuesStringNotLike => {
            set_string_like(Quantifier::All, actual, expected).map(|r| !r)
        }
        ConditionOperator::ForAllValuesArnEquals => {
            set_string_equals(Quantifier::All, actual, expected)
        }
        ConditionOperator::ForAllValuesArnLike => {
            set_string_like(Quantifier::All, actual, expected)
        }
        ConditionOperator::ForAllValuesNumericLessThan => without_key(operator),
        ConditionOperator::ForAllValuesNumericGreaterThan => without_key(operator),
        ConditionOperator::ForAllValuesIpAddress => without_key(operator),
        ConditionOperator::ForAllValuesDateLessThan => without_key(operator),
        ConditionOperator::ForAllValuesDateGreaterThan => without_key(operator),

        // Set operators - ForAnyValue
        ConditionOperator::ForAnyValueStringEquals => {
            set_string_equals(Quantifier::Any, actual, expected)
        }
        ConditionOperator::ForAnyValueStringNotEquals => {
            set_string_equals(Quantifier::Any, actual, expected).map(|r| !r)
        }
        ConditionOperator::ForAnyValueStringLike => {
            set_string_like(Quantifier::Any, actual, expected)
        }
        ConditionOperator::ForAnyValueStringNotLike => {
            set_string_like(Quantifier::Any, actual, expected).map(|r| !r)
        }
        ConditionOperator::ForAnyValueArnEquals => {
            set_string_equals(Quantifier::Any, actual, expected)
        }
        ConditionOperator::ForAnyValueArnLike => set_string_like(Quantifier::Any, actual, expected),
        ConditionOperator::ForAnyValueNumericLessThan => without_key(operator),
        ConditionOperator::ForAnyValueNumericGreaterThan => without_key(operator),
        ConditionOperator::ForAnyValueIpAddress => without_key(operator),
        ConditionOperator::ForAnyValueDateLessThan => without_key(operator),
        ConditionOperator::ForAnyValueDateGreaterThan => without_key(operator),
    }
}

// Helper: Evaluate IfExists behavior
fn evaluate_if_exists<F>(
    actual: Option<ConditionValue>,
    evaluator: F,
) -> Result<bool, ConditionError>
where
    F: FnOnce(ConditionValue) -> Result<bool, ConditionError>,
{
    match actual {
        Some(value) => evaluator(value),
        None => Ok(true), // IfExists: missing value passes
    }
}

// String operator implementations
fn evaluate_string_equals(
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    match actual {
        Some(ConditionValue::String(actual_str)) => {
            let expected_str = expected.as_string()?;
            Ok(actual_str == expected_str)
        }
        None => Ok(false), // Missing value = no match
        Some(other) => Err(other.mismatch("String")),
    }
}

fn evaluate_string_equals_ignore_case(
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    match actual {
        Some(ConditionValue::String(actual_str)) => {
            let expected_str = expected.as_string()?;
            Ok(actual_str.eq_ignore_ascii_case(&expected_str))
        }
        None => Ok(false),
        Some(other) => Err(other.mismatch("String")),
    }
}

fn evaluate_string_like(
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    match actual {
        Some(ConditionValue::String(actual_str)) => {
            let pattern = expected.as_string()?;
            Ok(matches_wildcard_pattern(&actual_str, &pattern))
        }
        None => Ok(false),
        Some(other) => Err(other.mismatch("String")),
    }
}

// Wildcard pattern matching (* and ?)
fn matches_wildcard_pattern(value: &str, pattern: &str) -> bool {
    // Simple wildcard matching: * matches any sequence, ? matches single character
    // This is a simplified implementation - AWS uses more complex matching
    if pattern == "*" {
        return true;
    }

    // Convert pattern to regex-like matching
    let mut value_chars = value.chars();
    let mut pattern_chars = pattern.chars();

    while let Some(pc) = pattern_chars.next() {
        match pc {
            '*' => {
                // Match zero or more characters
                // Try matching rest of pattern against remaining value
                let remaining_pattern: String = pattern_chars.collect();
                if remaining_pattern.is_empty() {
                    return true; // * at end matches everything
                }
                // Try matching remaining pattern at each position (including position 0)
                let remaining_value: String = value_chars.as_str().chars().collect();
                if matches_wildcard_pattern(&remaining_value, &remaining_pattern) {
                    return true; // Try matching at current position (zero characters)
                }
                // Try matching at each subsequent position
                while let Some(_) = value_chars.next() {
                    let remaining_value: String = value_chars.as_str().chars().collect();
                    if matches_wildcard_pattern(&remaining_value, &remaining_pattern) {
                        return true;
                    }
                }
                return false;
            }
            '?' => {
                // Match single character
                if value_chars.next().is_none() {
                    return false;
                }
            }
            _ => {
                // Match exact character
                if value_chars.next() != Some(pc) {
                    return false;
                }
            }
        }
    }

    // Pattern exhausted - value must also be exhausted
    value_chars.next().is_none()
}

// Numeric operator implementations
fn evaluate_numeric_equals(
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    match actual {
        Some(actual_val) => {
            let actual_num = actual_val.as_number()?;
            let expected_num = expected.as_number()?;
            Ok((actual_num - expected_num).abs() < f64::EPSILON)
        }
        None => Ok(false),
    }
}

fn evaluate_numeric_less_than(
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    match actual {
        Some(actual_val) => {
            let actual_num = actual_val.as_number()?;
            let expected_num = expected.as_number()?;
            Ok(actual_num < expected_num)
        }
        None => Ok(false),
    }
}

fn evaluate_numeric_less_than_equals(
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    match actual {
        Some(actual_val) => {
            let actual_num = actual_val.as_number()?;
            let expected_num = expected.as_number()?;
            Ok(actual_num <= expected_num)
        }
        None => Ok(false),
    }
}

fn evaluate_numeric_greater_than(
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    match actual {
        Some(actual_val) => {
            let actual_num = actual_val.as_number()?;
            let expected_num = expected.as_number()?;
            Ok(actual_num > expected_num)
        }
        None => Ok(false),
    }
}

fn evaluate_numeric_greater_than_equals(
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    match actual {
        Some(actual_val) => {
            let actual_num = actual_val.as_number()?;
            let expected_num = expected.as_number()?;
            Ok(actual_num >= expected_num)
        }
        None => Ok(false),
    }
}

// Date operator implementations
fn evaluate_date_equals(
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    match actual {
        Some(ConditionValue::String(actual_str)) => {
            let expected_str = expected.as_string()?;
            let actual_time = parse_rfc3339(&actual_str)?;
            let expected_time = parse_rfc3339(&expected_str)?;
            Ok(actual_time == expected_time)
        }
        None => Ok(false),
        Some(other) => Err(other.mismatch("String")),
    }
}

fn evaluate_date_less_than(
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    match actual {
        Some(ConditionValue::String(actual_str)) => {
            let expected_str = expected.as_string()?;
            let actual_time = parse_rfc3339(&actual_str)?;
            let expected_time = parse_rfc3339(&expected_str)?;
            Ok(actual_time < expected_time)
        }
        None => Ok(false),
        Some(other) => Err(other.mismatch("String")),
    }
}

fn evaluate_date_less_than_equals(
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    match actual {
        Some(ConditionValue::String(actual_str)) => {
            let expected_str = expected.as_string()?;
            let actual_time = parse_rfc3339(&actual_str)?;
            let expected_time = parse_rfc3339(&expected_str)?;
            Ok(actual_time <= expected_time)
        }
        None => Ok(false),
        Some(other) => Err(other.mismatch("String")),
    }
}

fn evaluate_date_greater_than(
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    match actual {
        Some(ConditionValue::String(actual_str)) => {
            let expected_str = expected.as_string()?;
            let actual_time = parse_rfc3339(&actual_str)?;
            let expected_time = parse_rfc3339(&expected_str)?;
            Ok(actual_time > expected_time)
        }
        None => Ok(false),
        Some(other) => Err(other.mismatch("String")),
    }
}

fn evaluate_date_greater_than_equals(
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    match actual {
        Some(ConditionValue::String(actual_str)) => {
            let expected_str = expected.as_string()?;
            let actual_time = parse_rfc3339(&actual_str)?;
            let expected_time = parse_rfc3339(&expected_str)?;
            Ok(actual_time >= expected_time)
        }
        None => Ok(false),
        Some(other) => Err(other.mismatch("String")),
    }
}

pub(crate) fn parse_rfc3339(s: &str) -> Result<chrono::DateTime<chrono::Utc>, ConditionError> {
    chrono::DateTime::parse_from_rfc3339(s)
        .map(|dt| dt.with_timezone(&chrono::Utc))
        .map_err(|e| ConditionError::InvalidDate {
            // chrono's message describes the fault, never the input.
            error: e.to_string(),
        })
}

// IP address operator implementations
fn evaluate_ip_address(
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    match actual {
        Some(ConditionValue::String(actual_ip)) => {
            check_address(&actual_ip, None)?;
            // One network, or a list of them: at least one must match.
            let networks: Vec<&str> = match expected {
                ConditionValue::String(network) => vec![network.as_str()],
                ConditionValue::Array(networks) => networks.iter().map(String::as_str).collect(),
                other => return Err(other.mismatch("an IP address or a list of them")),
            };
            for (index, network) in networks.iter().enumerate() {
                check_ip_or_cidr(
                    network,
                    matches!(expected, ConditionValue::Array(_)).then_some(index),
                )?;
            }
            Ok(networks
                .iter()
                .any(|network| ip_matches_cidr(&actual_ip, network)))
        }
        None => Ok(false),
        Some(other) => Err(other.mismatch("an IP address")),
    }
}

/// Whether `s` is an IP address alone.
pub(crate) fn is_address(s: &str) -> bool {
    parse_ipv4(s).is_some() || s.parse::<std::net::Ipv6Addr>().is_ok()
}

fn not_an_address(expected: &str, position: Option<usize>) -> ConditionError {
    ConditionError::TypeMismatch {
        expected: match position {
            Some(index) => format!("{expected} at element {index}"),
            None => expected.to_string(),
        },
        actual: "String".to_string(),
    }
}

/// A request's address: an IP address alone. One that is not used to make
/// `IpAddress` false and `NotIpAddress` TRUE (wami 001).
fn check_address(s: &str, position: Option<usize>) -> Result<(), ConditionError> {
    if is_address(s) {
        Ok(())
    } else {
        Err(not_an_address("an IP address", position))
    }
}

/// A policy's network: an address alone, or one with a prefix `ip_matches_cidr`
/// does not ignore (a v4 prefix above 32 never matches anything).
///
/// Parse checks a policy's addresses with this very function, so parse and
/// evaluation cannot disagree on what an address is (wami 001).
pub(crate) fn check_ip_or_cidr(s: &str, position: Option<usize>) -> Result<(), ConditionError> {
    let is_v4 = |a: &str| parse_ipv4(a).is_some();
    let is_v6 = |a: &str| a.parse::<std::net::Ipv6Addr>().is_ok();
    let readable = match s.split_once('/') {
        None => is_address(s),
        Some((network, prefix)) => match prefix.parse::<u8>() {
            Ok(p) if is_v4(network) => p <= 32,
            Ok(p) if is_v6(network) => p <= 128,
            _ => false,
        },
    };
    if readable {
        Ok(())
    } else {
        Err(not_an_address("an IP address or CIDR", position))
    }
}

fn ip_matches_cidr(ip: &str, cidr: &str) -> bool {
    // Simple CIDR matching - for production, use a proper IP/CIDR library
    if ip == cidr {
        return true; // Exact match
    }

    // Parse CIDR notation (e.g., "203.0.113.0/24")
    if let Some((network, prefix_len_str)) = cidr.split_once('/') {
        if let Ok(prefix_len) = prefix_len_str.parse::<u8>() {
            // For IPv4
            if let (Some(ip_addr), Some(net_addr)) = (parse_ipv4(ip), parse_ipv4(network)) {
                return ip_in_cidr_v4(ip_addr, net_addr, prefix_len);
            }
            // For IPv6 (simplified - basic prefix matching)
            if ip.contains(':') && cidr.contains(':') {
                // Basic IPv6 CIDR matching - check if IP starts with network prefix
                // This is simplified - proper IPv6 CIDR would need full parsing
                if let Some((network_part, _)) = cidr.split_once('/') {
                    // For /32 prefix, check first 32 bits (8 hex groups of 4 chars each)
                    // Simplified: check if IP starts with network part
                    if prefix_len <= 128 {
                        // For now, do prefix string matching (simplified)
                        // Proper implementation would parse IPv6 addresses and masks
                        return ip.starts_with(network_part) || ip == network;
                    }
                }
                return ip == network; // Fallback to exact match
            }
        }
    }

    false
}

pub(crate) fn parse_ipv4(ip: &str) -> Option<[u8; 4]> {
    let parts: Vec<&str> = ip.split('.').collect();
    if parts.len() != 4 {
        return None;
    }
    let mut bytes = [0u8; 4];
    for (i, part) in parts.iter().enumerate() {
        bytes[i] = part.parse().ok()?;
    }
    Some(bytes)
}

fn ip_in_cidr_v4(ip: [u8; 4], network: [u8; 4], prefix_len: u8) -> bool {
    if prefix_len > 32 {
        return false;
    }
    let mask_bits = prefix_len;
    let full_bytes = (mask_bits / 8) as usize;
    let remaining_bits = mask_bits % 8;

    // Check full bytes
    for i in 0..full_bytes {
        if ip[i] != network[i] {
            return false;
        }
    }

    // Check remaining bits
    if remaining_bits > 0 && full_bytes < 4 {
        let mask = !((1u8 << (8 - remaining_bits)) - 1);
        if (ip[full_bytes] & mask) != (network[full_bytes] & mask) {
            return false;
        }
    }

    true
}

// ARN operator implementations
fn evaluate_arn_equals(
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    match actual {
        Some(ConditionValue::String(actual_arn)) => {
            let expected_arn = expected.as_string()?;
            Ok(actual_arn == expected_arn)
        }
        None => Ok(false),
        Some(other) => Err(other.mismatch("String")),
    }
}

fn evaluate_arn_like(
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    match actual {
        Some(ConditionValue::String(actual_arn)) => {
            let pattern = expected.as_string()?;
            Ok(matches_wildcard_pattern(&actual_arn, &pattern))
        }
        None => Ok(false),
        Some(other) => Err(other.mismatch("String")),
    }
}

// Boolean operator implementations
fn evaluate_bool(
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    match actual {
        Some(actual_val) => {
            let actual_bool = actual_val.as_boolean()?;
            let expected_bool = expected.as_boolean()?;
            Ok(actual_bool == expected_bool)
        }
        None => Ok(false),
    }
}

// Binary operator implementations
fn evaluate_binary_equals(
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    match actual {
        Some(ConditionValue::String(actual_base64)) => {
            let expected_base64 = expected.as_string()?;
            // Decode and compare (simplified - would use base64 crate in production)
            Ok(actual_base64 == expected_base64)
        }
        None => Ok(false),
        Some(other) => Err(other.mismatch("String")),
    }
}

// Null operator implementations
fn evaluate_null(
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    let expected_bool = expected.as_boolean()?;
    let is_null = actual.is_none();
    Ok(is_null == expected_bool)
}

// Set operator implementations — ForAllValues / ForAnyValue
//
// One body per comparison, the quantifier passed in. Only the string and ARN
// forms have a body: the numeric, date and address forms compare a list no
// key holds, so parse refuses them and they have no evaluator (wami 001).

/// How a set operator combines its per-element results.
#[derive(Clone, Copy)]
enum Quantifier {
    /// `ForAllValues`: every request value must match.
    All,
    /// `ForAnyValue`: one request value must match.
    Any,
}

impl Quantifier {
    fn over<T>(self, items: &[T], test: impl Fn(&T) -> bool) -> bool {
        match self {
            Quantifier::All => items.iter().all(test),
            Quantifier::Any => items.iter().any(test),
        }
    }

    /// What an absent key, or a request with no values, answers: vacuously
    /// true for every value, false for any value.
    fn on_nothing(self) -> bool {
        matches!(self, Quantifier::All)
    }
}

/// The request's values: a list, or one string read as a list of one.
fn request_values(actual: ConditionValue) -> Result<Vec<String>, ConditionError> {
    match actual {
        ConditionValue::Array(values) => Ok(values),
        ConditionValue::String(value) => Ok(vec![value]),
        other => Err(other.mismatch("a String or an Array of Strings")),
    }
}

fn set_string_equals(
    quantifier: Quantifier,
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    let Some(actual) = actual else {
        return Ok(quantifier.on_nothing());
    };
    let values = request_values(actual)?;
    if values.is_empty() {
        return Ok(quantifier.on_nothing());
    }
    let expected = expected.as_array()?;
    Ok(quantifier.over(&values, |value| expected.contains(value)))
}

fn set_string_like(
    quantifier: Quantifier,
    actual: Option<ConditionValue>,
    expected: &ConditionValue,
) -> Result<bool, ConditionError> {
    let Some(actual) = actual else {
        return Ok(quantifier.on_nothing());
    };
    let values = request_values(actual)?;
    if values.is_empty() {
        return Ok(quantifier.on_nothing());
    }
    let patterns = expected.as_array()?;
    Ok(quantifier.over(&values, |value| {
        patterns
            .iter()
            .any(|pattern| matches_wildcard_pattern(value, pattern))
    }))
}

/// A hand-built block reaching an operator no key can feed: refused as parse
/// refuses it — the operator has no evaluator (wami 001).
fn without_key(operator: ConditionOperator) -> Result<bool, ConditionError> {
    Err(ConditionError::OperatorWithoutKey {
        operator: crate::validate::without_key(operator)
            .unwrap_or("a set operator")
            .to_string(),
    })
}