iam-rs 0.6.0

Complete Rust library for parsing, validating, and evaluating IAM policies. Provider-agnostic authorization engine with full AWS IAM compatibility.
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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
use super::{context::Context, matcher::ArnMatcher, request::IAMRequest};
use crate::{
    Arn, Validate,
    core::{IAMAction, IAMEffect, IAMResource, Principal, PrincipalId},
    evaluation::{
        operator_eval::{evaluate_condition, wildcard_match},
        variable::interpolate_variables,
    },
    policy::{ConditionBlock, IAMPolicy, IAMStatement},
};
use serde::{Deserialize, Serialize};

/// Result of policy evaluation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum Decision {
    /// Access is explicitly allowed
    Allow,
    /// Access is explicitly denied
    Deny,
    /// No applicable policy found (implicit deny)
    NotApplicable,
}

impl std::fmt::Display for Decision {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        serde_json::to_string(self)
            .map_err(|_| std::fmt::Error)?
            .trim_matches('"')
            .fmt(f)
    }
}

/// Error types for policy evaluation
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum EvaluationError {
    /// Invalid request context
    InvalidRequest(String),
    /// Policy parsing or validation error
    InvalidPolicy(String),
    /// ARN format error during evaluation
    InvalidArn(String),
    /// Invalid variable reference
    InvalidVariable(String),
    /// Condition evaluation error
    ConditionError(String),
    /// Internal evaluation error
    InternalError(String),
}

impl std::fmt::Display for EvaluationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EvaluationError::InvalidRequest(msg) => write!(f, "Invalid request: {msg}"),
            EvaluationError::InvalidPolicy(msg) => write!(f, "Invalid policy: {msg}"),
            EvaluationError::InvalidArn(msg) => write!(f, "Invalid ARN: {msg}"),
            EvaluationError::InvalidVariable(msg) => write!(f, "Invalid variable: {msg}"),
            EvaluationError::ConditionError(msg) => write!(f, "Condition error: {msg}"),
            EvaluationError::InternalError(msg) => write!(f, "Internal error: {msg}"),
        }
    }
}

impl std::error::Error for EvaluationError {}

/// Evaluation result with decision and metadata
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct EvaluationResult {
    /// The final decision
    pub decision: Decision,
    /// Per-statement evaluation details, whether or not each statement matched.
    /// Populated only when [`EvaluationOptions::collect_match_details`] is
    /// enabled; otherwise empty.
    pub statement_details: Vec<StatementMatch>,
    /// Evaluation context used
    pub context: IAMRequest,
}

/// Information about a statement's evaluation result (whether or not it matched)
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct StatementMatch {
    /// Statement ID if available
    pub sid: Option<String>,
    /// Effect of the statement
    pub effect: IAMEffect,
    /// Whether all conditions were satisfied
    pub conditions_satisfied: bool,
    /// Reason for the match/non-match
    pub reason: String,
}

/// Policy evaluation engine
#[derive(Debug, Clone)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct PolicyEvaluator {
    /// Policies to evaluate
    policies: Vec<IAMPolicy>,
    /// Evaluation options
    options: EvaluationOptions,
}

/// Options for policy evaluation
#[derive(Debug, Clone)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct EvaluationOptions {
    /// Whether to continue evaluation after finding an explicit deny
    pub stop_on_explicit_deny: bool,
    /// Whether to collect detailed match information
    pub collect_match_details: bool,
    /// Maximum number of statements to evaluate (for safety)
    pub max_statements: usize,
    /// Whether to ignore resource constraints
    pub ignore_resource_constraints: bool,
}

impl Default for EvaluationOptions {
    fn default() -> Self {
        Self {
            stop_on_explicit_deny: true,
            collect_match_details: false,
            max_statements: 1000,
            ignore_resource_constraints: false,
        }
    }
}

impl PolicyEvaluator {
    /// Create a new policy evaluator
    #[must_use]
    pub fn new() -> Self {
        Self {
            policies: Vec::new(),
            options: EvaluationOptions::default(),
        }
    }

    /// Create evaluator with policies
    #[must_use]
    pub fn with_policies(policies: Vec<IAMPolicy>) -> Self {
        Self {
            policies,
            options: EvaluationOptions::default(),
        }
    }

    /// Add a policy to the evaluator
    pub fn add_policy(&mut self, policy: IAMPolicy) {
        self.policies.push(policy);
    }

    /// Set evaluation options
    #[must_use]
    pub fn with_options(mut self, options: EvaluationOptions) -> Self {
        self.options = options;
        self
    }

    /// Evaluate an authorization request against all policies
    ///
    /// # Errors
    ///
    /// Returns `EvaluationError` if:
    /// - The request context is invalid
    /// - ARN format errors occur during evaluation
    /// - Variable interpolation fails
    /// - Condition evaluation fails
    /// - Maximum statement evaluation limit is exceeded
    pub fn evaluate(&self, request: &IAMRequest) -> Result<EvaluationResult, EvaluationError> {
        if !request.principal.is_single() {
            return Err(EvaluationError::InvalidRequest(
                "Request principal must be a single entity".to_string(),
            ));
        }
        if !request.principal.is_valid() {
            return Err(EvaluationError::InvalidRequest(
                "Invalid principal".to_string(),
            ));
        }
        if request.action.is_empty() {
            return Err(EvaluationError::InvalidRequest(
                "Action cannot be empty".to_string(),
            ));
        }
        if !request.resource.is_valid() && !self.options.ignore_resource_constraints {
            return Err(EvaluationError::InvalidRequest(
                "Invalid resource ARN".to_string(),
            ));
        }

        let mut statement_details = Vec::new();
        let mut has_explicit_allow = false;
        let mut has_explicit_deny = false;
        let mut statement_count = 0;

        // Evaluate each policy
        for policy in &self.policies {
            for statement in &policy.statement {
                statement_count += 1;
                if statement_count > self.options.max_statements {
                    return Err(EvaluationError::InternalError(
                        "Maximum statement evaluation limit exceeded".to_string(),
                    ));
                }

                let statement_result = Self::evaluate_statement(statement, request, &self.options)?;

                if self.options.collect_match_details {
                    statement_details.push(statement_result.clone());
                }

                // Check if this statement applies to the request
                if statement_result.conditions_satisfied {
                    match statement.effect {
                        IAMEffect::Allow => {
                            has_explicit_allow = true;
                        }
                        IAMEffect::Deny => {
                            has_explicit_deny = true;
                            if self.options.stop_on_explicit_deny {
                                return Ok(EvaluationResult {
                                    decision: Decision::Deny,
                                    statement_details,
                                    context: request.clone(),
                                });
                            }
                        }
                    }
                }
            }
        }

        // Apply IAM evaluation logic: Explicit deny overrides everything,
        // then explicit allow, then implicit deny
        let decision = if has_explicit_deny {
            Decision::Deny
        } else if has_explicit_allow {
            Decision::Allow
        } else {
            Decision::NotApplicable
        };

        Ok(EvaluationResult {
            decision,
            statement_details,
            context: request.clone(),
        })
    }

    /// Evaluate a single statement against a request
    fn evaluate_statement(
        statement: &IAMStatement,
        request: &IAMRequest,
        options: &EvaluationOptions,
    ) -> Result<StatementMatch, EvaluationError> {
        // Check if principal matches (for resource-based policies)
        if let Some(ref principal) = statement.principal
            && !Self::principal_matches(principal, &request.principal)?
        {
            return Ok(StatementMatch {
                sid: statement.sid.clone(),
                effect: statement.effect,
                conditions_satisfied: false,
                reason: "Principal does not match".to_string(),
            });
        }

        if let Some(ref not_principal) = statement.not_principal
            && Self::principal_matches(not_principal, &request.principal)?
        {
            return Ok(StatementMatch {
                sid: statement.sid.clone(),
                effect: statement.effect,
                conditions_satisfied: false,
                reason: "Principal matches NotPrincipal exclusion".to_string(),
            });
        }

        // Check if action matches
        let action_matches = if let Some(ref action) = statement.action {
            Self::action_matches(action, &request.action)
        } else if let Some(ref not_action) = statement.not_action {
            !Self::action_matches(not_action, &request.action)
        } else {
            return Ok(StatementMatch {
                sid: statement.sid.clone(),
                effect: statement.effect,
                conditions_satisfied: false,
                reason: "No action or not_action specified".to_string(),
            });
        };

        if !action_matches {
            return Ok(StatementMatch {
                sid: statement.sid.clone(),
                effect: statement.effect,
                conditions_satisfied: false,
                reason: "Action does not match".to_string(),
            });
        }

        // Check if resource matches
        let resource_matches = if options.ignore_resource_constraints {
            true
        } else if let Some(ref resource) = statement.resource {
            Self::resource_matches(resource, &request.resource, &request.context)?
        } else if let Some(ref not_resource) = statement.not_resource {
            !Self::resource_matches(not_resource, &request.resource, &request.context)?
        } else {
            return Ok(StatementMatch {
                sid: statement.sid.clone(),
                effect: statement.effect,
                conditions_satisfied: false,
                reason: "No resource or not_resource specified".to_string(),
            });
        };

        if !resource_matches {
            return Ok(StatementMatch {
                sid: statement.sid.clone(),
                effect: statement.effect,
                conditions_satisfied: false,
                reason: "Resource does not match".to_string(),
            });
        }

        // Check conditions
        if let Some(ref condition_block) = statement.condition
            && !Self::evaluate_conditions(condition_block, &request.context)?
        {
            return Ok(StatementMatch {
                sid: statement.sid.clone(),
                effect: statement.effect,
                conditions_satisfied: false,
                reason: "Conditions not satisfied".to_string(),
            });
        }

        // All checks passed
        Ok(StatementMatch {
            sid: statement.sid.clone(),
            effect: statement.effect,
            conditions_satisfied: true,
            reason: "Statement fully matched".to_string(),
        })
    }

    /// Check if a principal matches the request principal
    fn principal_matches(
        principal: &Principal,
        request_principal: &Principal,
    ) -> Result<bool, EvaluationError> {
        if !request_principal.is_single() {
            return Err(EvaluationError::InvalidRequest(
                "Request principal must be a single entity".to_string(),
            ));
        }

        match (principal, request_principal) {
            // If either is Wildcard, it matches
            (Principal::Wildcard, _) | (_, Principal::Wildcard) => Ok(true),

            //
            // Check: AWS
            //
            (
                Principal::Aws(principal_id),
                Principal::Aws(PrincipalId::String(request_principal_id)),
            ) => Self::principal_id_matches(principal_id, request_principal_id, |id| {
                // AWS principal can be an account ID, an ARN, or "*"
                // See: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html
                // "*" matches any principal
                if id == "*" || id == request_principal_id {
                    return Ok(true);
                }
                // Account ID (e.g., "123456789012")
                if id.len() == 12 && id.chars().all(|c| c.is_ascii_digit()) {
                    // Accept either the raw account ID or the root ARN
                    let root_arn = format!("arn:aws:iam::{id}:root");
                    if request_principal_id == id || request_principal_id.as_str() == root_arn {
                        return Ok(true);
                    }
                }
                // If it's an ARN, match directly or with wildcard
                if id.starts_with("arn:") {
                    return Self::principal_string_matches(id, request_principal_id);
                }
                Ok(false)
            }),

            //
            // Check: Federated
            //
            (
                Principal::Federated(principal_id),
                Principal::Federated(PrincipalId::String(request_principal_id)),
            ) => Self::principal_id_matches(principal_id, request_principal_id, |id| {
                // Federated principal can be a provider name or ARN
                // e.g., "cognito-identity.amazonaws.com", "arn:aws:iam::account-id:oidc-provider/..."
                if id == request_principal_id {
                    return Ok(true);
                }
                // For OIDC/SAML, match by prefix
                if request_principal_id.starts_with(id) {
                    return Ok(true);
                }
                Ok(false)
            }),

            //
            // Check: Service
            //
            (
                Principal::Service(principal_id),
                Principal::Service(PrincipalId::String(request_principal_id)),
            ) => Self::principal_id_matches(principal_id, request_principal_id, |id| {
                // Service principal, e.g., "ec2.amazonaws.com"
                // Can also be regionalized, e.g., "s3.ap-east-1.amazonaws.com"
                if id == request_principal_id {
                    return Ok(true);
                }
                Ok(false)
            }),

            //
            // Check: CanonicalUser
            //
            (
                Principal::CanonicalUser(principal_id),
                Principal::CanonicalUser(PrincipalId::String(request_principal_id)),
            ) => Self::principal_id_matches(principal_id, request_principal_id, |id| {
                // Canonical user ID, e.g., "79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be"
                if id == request_principal_id {
                    return Ok(true);
                }
                Ok(false)
            }),
            _ => {
                // If principal types don't match, they can't match
                Ok(false)
            }
        }
    }

    /// Helper function to handle `PrincipalId` enum matching
    fn principal_id_matches<F>(
        principal_id: &PrincipalId,
        _request_principal: &str,
        matcher: F,
    ) -> Result<bool, EvaluationError>
    where
        F: Fn(&str) -> Result<bool, EvaluationError>,
    {
        match principal_id {
            PrincipalId::String(id) => matcher(id),
            PrincipalId::Array(ids) => {
                // If any ID in the array matches, return true
                for id in ids {
                    if matcher(id)? {
                        return Ok(true);
                    }
                }
                Ok(false)
            }
        }
    }

    /// Check if a principal string matches the request principal
    fn principal_string_matches(
        principal_str: &str,
        request_principal: &str,
    ) -> Result<bool, EvaluationError> {
        if principal_str == "*" || principal_str == request_principal {
            Ok(true)
        } else if principal_str.starts_with("arn:") {
            // ARN-based principal matching
            let matcher = ArnMatcher::from_pattern(principal_str)
                .map_err(|e| EvaluationError::InvalidArn(e.to_string()))?;
            // A request principal that isn't a valid ARN can't match an ARN pattern
            let Ok(request_arn) = Arn::parse(request_principal) else {
                return Ok(false);
            };
            matcher
                .matches(&request_arn)
                .map_err(|e| EvaluationError::InvalidArn(e.to_string()))
        } else {
            Ok(false)
        }
    }

    /// Check if an action matches the request action
    ///
    /// AWS treats action names as case-insensitive (e.g. `iam:ListAccessKeys`
    /// is the same as `IAM:listaccesskeys`), so both the request action and the
    /// policy pattern are compared lowercased.
    fn action_matches(action: &IAMAction, request_action: &str) -> bool {
        let request_action = request_action.to_ascii_lowercase();
        let pattern_matches =
            |a: &str| a == "*" || wildcard_match(&request_action, &a.to_ascii_lowercase());
        match action {
            IAMAction::Single(a) => pattern_matches(a),
            IAMAction::Multiple(actions) => actions.iter().any(|a| pattern_matches(a)),
        }
    }

    /// Check if a resource matches the request resource
    fn resource_matches(
        resource: &IAMResource,
        request_resource: &Arn,
        context: &Context,
    ) -> Result<bool, EvaluationError> {
        match resource {
            IAMResource::Single(r) => {
                if r == "*" {
                    Ok(true)
                } else {
                    // First, interpolate variables
                    let interpolated = interpolate_variables(r, context)?;

                    // Then use ARN matcher for pattern matching
                    let matcher = ArnMatcher::from_pattern(&interpolated)
                        .map_err(|e| EvaluationError::InvalidArn(e.to_string()))?;
                    matcher
                        .matches(request_resource)
                        .map_err(|e| EvaluationError::InvalidArn(e.to_string()))
                }
            }
            IAMResource::Multiple(resources) => {
                for r in resources {
                    if Self::resource_matches(
                        &IAMResource::Single(r.clone()),
                        request_resource,
                        context,
                    )? {
                        return Ok(true);
                    }
                }
                Ok(false)
            }
        }
    }

    /// Evaluate condition block
    fn evaluate_conditions(
        condition_block: &ConditionBlock,
        context: &Context,
    ) -> Result<bool, EvaluationError> {
        // All conditions in a block must be satisfied (AND logic)
        for (operator, condition_map) in &condition_block.conditions {
            for (key, value) in condition_map {
                if !evaluate_condition(context, operator, key, &value.to_json_value())? {
                    return Ok(false);
                }
            }
        }
        Ok(true)
    }
}

impl Default for PolicyEvaluator {
    fn default() -> Self {
        Self::new()
    }
}

/// Convenience function for simple policy evaluation
///
/// # Errors
///
/// Returns `EvaluationError` if the policy evaluation fails due to:
/// - Invalid request context
/// - ARN format errors
/// - Variable interpolation failures
/// - Condition evaluation errors
pub fn evaluate_policy(
    policy: &IAMPolicy,
    request: &IAMRequest,
) -> Result<Decision, EvaluationError> {
    let evaluator = PolicyEvaluator::with_policies(vec![policy.clone()]);
    let result = evaluator.evaluate(request)?;
    Ok(result.decision)
}

/// Convenience function for evaluating multiple policies
///
/// # Errors
///
/// Returns `EvaluationError` if the policy evaluation fails due to:
/// - Invalid request context
/// - ARN format errors
/// - Variable interpolation failures
/// - Condition evaluation errors
pub fn evaluate_policies(
    policies: &[IAMPolicy],
    request: &IAMRequest,
) -> Result<Decision, EvaluationError> {
    let evaluator = PolicyEvaluator::with_policies(policies.to_vec());
    let result = evaluator.evaluate(request)?;
    Ok(result.decision)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        Arn, ConditionValue, ContextValue, IAMAction, IAMEffect, IAMOperator, IAMResource,
        IAMStatement,
    };

    #[test]
    fn test_simple_allow_policy() {
        let policy = IAMPolicy::new().add_statement(
            IAMStatement::new(IAMEffect::Allow)
                .with_action(IAMAction::Single("s3:GetObject".to_string()))
                .with_resource(IAMResource::Single("arn:aws:s3:::my-bucket/*".to_string())),
        );

        let request = IAMRequest::new(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "s3:GetObject",
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
        );

        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::Allow);
    }

    #[test]
    fn test_simple_deny_policy() {
        let policy = IAMPolicy::new().add_statement(
            IAMStatement::new(IAMEffect::Deny)
                .with_action(IAMAction::Single("s3:DeleteObject".to_string()))
                .with_resource(IAMResource::Single("arn:aws:s3:::my-bucket/*".to_string())),
        );

        let request = IAMRequest::new(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "s3:DeleteObject",
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
        );

        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::Deny);
    }

    #[test]
    fn test_not_applicable_policy() {
        let policy = IAMPolicy::new().add_statement(
            IAMStatement::new(IAMEffect::Allow)
                .with_action(IAMAction::Single("s3:GetObject".to_string()))
                .with_resource(IAMResource::Single(
                    "arn:aws:s3:::other-bucket/*".to_string(),
                )),
        );

        let request = IAMRequest::new(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "s3:GetObject",
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
        );

        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::NotApplicable);
    }

    #[test]
    fn test_wildcard_action_matching() {
        let policy = IAMPolicy::new().add_statement(
            IAMStatement::new(IAMEffect::Allow)
                .with_action(IAMAction::Single("s3:*".to_string()))
                .with_resource(IAMResource::Single("arn:aws:s3:::my-bucket/*".to_string())),
        );

        let request = IAMRequest::new(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "s3:GetObject",
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
        );

        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::Allow);
    }

    #[test]
    fn test_action_case_insensitive() {
        // AWS: action names are case-insensitive (iam:ListAccessKeys == IAM:listaccesskeys).
        let policy = IAMPolicy::new().add_statement(
            IAMStatement::new(IAMEffect::Allow)
                .with_action(IAMAction::Single("s3:GetObject".to_string()))
                .with_resource(IAMResource::Single("arn:aws:s3:::my-bucket/*".to_string())),
        );

        let request = IAMRequest::new(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "S3:getobject", // different case
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
        );

        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::Allow);
    }

    #[test]
    fn test_action_multiple_case_insensitive() {
        let policy = IAMPolicy::new().add_statement(
            IAMStatement::new(IAMEffect::Allow)
                .with_action(IAMAction::Multiple(vec![
                    "s3:GetObject".to_string(),
                    "s3:PutObject".to_string(),
                ]))
                .with_resource(IAMResource::Single("*".to_string())),
        );

        let request = IAMRequest::new(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "S3:PUTOBJECT",
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
        );

        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::Allow);
    }

    #[test]
    fn test_action_wildcard_case_insensitive() {
        let policy = IAMPolicy::new().add_statement(
            IAMStatement::new(IAMEffect::Allow)
                .with_action(IAMAction::Single("iam:*AccessKey*".to_string()))
                .with_resource(IAMResource::Single("*".to_string())),
        );

        let request = IAMRequest::new(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "IAM:listaccesskeys",
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
        );

        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::Allow);
    }

    #[test]
    fn test_condition_evaluation() {
        use crate::IAMOperator;

        let mut context = Context::new();
        context.insert(
            "aws:userid".to_string(),
            ContextValue::String("test-user".to_string()),
        );

        let policy = IAMPolicy::new().add_statement(
            IAMStatement::new(IAMEffect::Allow)
                .with_action(IAMAction::Single("s3:GetObject".to_string()))
                .with_resource(IAMResource::Single("arn:aws:s3:::my-bucket/*".to_string()))
                .with_condition(
                    IAMOperator::StringEquals,
                    "aws:userid".to_string(),
                    ConditionValue::String("test-user".to_string()),
                ),
        );

        let request = IAMRequest::new_with_context(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "s3:GetObject",
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
            context,
        );

        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::Allow);
    }

    #[test]
    fn test_condition_evaluation_failure() {
        use crate::IAMOperator;

        let mut context = Context::new();
        context.insert(
            "aws:userid".to_string(),
            ContextValue::String("other-user".to_string()),
        );

        let policy = IAMPolicy::new().add_statement(
            IAMStatement::new(IAMEffect::Allow)
                .with_action(IAMAction::Single("s3:GetObject".to_string()))
                .with_resource(IAMResource::Single("arn:aws:s3:::my-bucket/*".to_string()))
                .with_condition(
                    IAMOperator::StringEquals,
                    "aws:userid".to_string(),
                    ConditionValue::String("test-user".to_string()),
                ),
        );

        let request = IAMRequest::new_with_context(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "s3:GetObject",
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
            context,
        );

        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::NotApplicable);
    }

    #[test]
    fn test_deny_with_negated_condition_on_missing_key() {
        // AWS: a negated condition (StringNotEquals) with an absent context key
        // is true, so this Deny statement applies and denies access.
        let policy = IAMPolicy::new().add_statement(
            IAMStatement::new(IAMEffect::Deny)
                .with_action(IAMAction::Single("s3:GetObject".to_string()))
                .with_resource(IAMResource::Single("*".to_string()))
                .with_condition(
                    IAMOperator::StringNotEquals,
                    "aws:SecureTransport".to_string(),
                    ConditionValue::String("true".to_string()),
                ),
        );

        // No context provided: aws:SecureTransport is absent.
        let request = IAMRequest::new(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "s3:GetObject",
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
        );

        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::Deny);
    }

    #[test]
    fn test_for_all_values_allow() {
        // AWS: ForAllValues is true when every request value matches at least
        // one policy value. Here each of the two TagKeys has a matching entry.
        let mut ctx = Context::new();
        ctx.insert(
            "aws:TagKeys".to_string(),
            ContextValue::StringList(vec!["environment".to_string(), "cost-center".to_string()]),
        );

        let policy = IAMPolicy::new().add_statement(
            IAMStatement::new(IAMEffect::Allow)
                .with_action(IAMAction::Single("s3:GetObject".to_string()))
                .with_resource(IAMResource::Single("*".to_string()))
                .with_condition(
                    IAMOperator::ForAllValuesStringEquals,
                    "aws:TagKeys".to_string(),
                    ConditionValue::StringList(vec!["environment".into(), "cost-center".into()]),
                ),
        );

        let mut request = IAMRequest::new(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "s3:GetObject",
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
        );
        request.context = ctx;

        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::Allow);
    }

    #[test]
    fn test_for_all_values_negated_deny_region() {
        // Classic AWS pattern: deny if the requested region is not in the
        // allowed set. A request to an allowed region must NOT be denied.
        let policy = IAMPolicy::new().add_statement(
            IAMStatement::new(IAMEffect::Deny)
                .with_action(IAMAction::Single("*".to_string()))
                .with_resource(IAMResource::Single("*".to_string()))
                .with_condition(
                    IAMOperator::ForAllValuesStringNotEquals,
                    "aws:RequestedRegion".to_string(),
                    ConditionValue::StringList(vec!["eu-central-1".into(), "eu-west-1".into()]),
                ),
        );

        // Inside the allowed set -> not denied.
        let mut ctx = Context::new();
        ctx.insert(
            "aws:RequestedRegion".to_string(),
            ContextValue::String("eu-central-1".to_string()),
        );
        let mut request = IAMRequest::new(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "s3:GetObject",
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
        );
        request.context = ctx;
        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::NotApplicable);

        // Outside the allowed set -> denied.
        let mut ctx = Context::new();
        ctx.insert(
            "aws:RequestedRegion".to_string(),
            ContextValue::String("us-east-1".to_string()),
        );
        let mut request = IAMRequest::new(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "s3:GetObject",
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
        );
        request.context = ctx;
        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::Deny);
    }

    #[test]
    fn test_null_condition_string_form() {
        // AWS IAM policies commonly use the string form "true"/"false".
        let policy = IAMPolicy::new().add_statement(
            IAMStatement::new(IAMEffect::Allow)
                .with_action(IAMAction::Single("s3:GetObject".to_string()))
                .with_resource(IAMResource::Single("*".to_string()))
                .with_condition(
                    IAMOperator::Null,
                    "aws:TokenIssueTime".to_string(),
                    ConditionValue::String("false".to_string()), // key must exist
                ),
        );

        // Key present -> condition true -> allowed.
        let mut ctx = Context::new();
        ctx.insert(
            "aws:TokenIssueTime".to_string(),
            ContextValue::String("2024-01-01T00:00:00Z".to_string()),
        );
        let mut request = IAMRequest::new(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "s3:GetObject",
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
        );
        request.context = ctx;
        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::Allow);

        // Key absent -> condition false -> not applicable.
        let request = IAMRequest::new(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "s3:GetObject",
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
        );
        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::NotApplicable);
    }

    #[test]
    fn test_float_numeric_condition() {
        let policy_json = r#"{
            "Version": "2012-10-17",
            "Statement": [{
                "Effect": "Allow",
                "Action": "s3:GetObject",
                "Resource": "*",
                "Condition": {"NumericLessThan": {"aws:multifactorAuthAge": 1234.5}}
            }]
        }"#;
        let policy = IAMPolicy::from_json(policy_json).unwrap();

        // Context value 500.0 < 1234.5 -> allowed.
        let mut ctx = Context::new();
        ctx.insert(
            "aws:multifactorAuthAge".to_string(),
            ContextValue::Number(500.0),
        );
        let mut request = IAMRequest::new(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "s3:GetObject",
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
        );
        request.context = ctx;
        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::Allow);

        // Context value 2000.0 >= 1234.5 -> not applicable.
        let mut ctx = Context::new();
        ctx.insert(
            "aws:multifactorAuthAge".to_string(),
            ContextValue::Number(2000.0),
        );
        let mut request = IAMRequest::new(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "s3:GetObject",
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
        );
        request.context = ctx;
        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::NotApplicable);
    }

    #[test]
    fn test_plain_operator_multivalued_context() {
        // A plain operator against a multivalued context key matches if any
        // value matches (implicit ForAnyValue semantics).
        let policy = IAMPolicy::new().add_statement(
            IAMStatement::new(IAMEffect::Allow)
                .with_action(IAMAction::Single("ec2:DeleteTags".to_string()))
                .with_resource(IAMResource::Single("*".to_string()))
                .with_condition(
                    IAMOperator::StringEquals,
                    "aws:TagKeys".to_string(),
                    ConditionValue::String("environment".to_string()),
                ),
        );

        // "environment" is among the request's tag keys -> allowed.
        let mut ctx = Context::new();
        ctx.insert(
            "aws:TagKeys".to_string(),
            ContextValue::StringList(vec!["environment".to_string(), "dept".to_string()]),
        );
        let mut request = IAMRequest::new(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "ec2:DeleteTags",
            Arn::parse("arn:aws:ec2:us-east-1:123456789012:instance/i-123").unwrap(),
        );
        request.context = ctx;
        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::Allow);

        // No tag key matches -> not applicable.
        let mut ctx = Context::new();
        ctx.insert(
            "aws:TagKeys".to_string(),
            ContextValue::StringList(vec!["dept".to_string()]),
        );
        let mut request = IAMRequest::new(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "ec2:DeleteTags",
            Arn::parse("arn:aws:ec2:us-east-1:123456789012:instance/i-123").unwrap(),
        );
        request.context = ctx;
        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::NotApplicable);
    }

    #[test]
    fn test_context_key_case_insensitive() {
        // AWS: context key names are case-insensitive.
        let policy = IAMPolicy::new().add_statement(
            IAMStatement::new(IAMEffect::Allow)
                .with_action(IAMAction::Single("s3:GetObject".to_string()))
                .with_resource(IAMResource::Single("*".to_string()))
                .with_condition(
                    IAMOperator::StringEquals,
                    "aws:username".to_string(),
                    ConditionValue::String("alice".to_string()),
                ),
        );

        // Context uses a different case for the key name.
        let mut ctx = Context::new();
        ctx.insert(
            "AWS:UserName".to_string(),
            ContextValue::String("alice".to_string()),
        );
        let mut request = IAMRequest::new(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "s3:GetObject",
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
        );
        request.context = ctx;
        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::Allow);
    }

    #[test]
    fn test_explicit_deny_overrides_allow() {
        let policies = vec![
            IAMPolicy::new().add_statement(
                IAMStatement::new(IAMEffect::Allow)
                    .with_action(IAMAction::Single("s3:*".to_string()))
                    .with_resource(IAMResource::Single("*".to_string())),
            ),
            IAMPolicy::new().add_statement(
                IAMStatement::new(IAMEffect::Deny)
                    .with_action(IAMAction::Single("s3:DeleteObject".to_string()))
                    .with_resource(IAMResource::Single(
                        "arn:aws:s3:::protected-bucket/*".to_string(),
                    )),
            ),
        ];

        let request = IAMRequest::new(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "s3:DeleteObject",
            Arn::parse("arn:aws:s3:::protected-bucket/file.txt").unwrap(),
        );

        let result = evaluate_policies(&policies, &request).unwrap();
        assert_eq!(result, Decision::Deny);
    }

    #[test]
    fn test_non_arn_principal_does_not_panic() {
        // A request principal that is valid but not an ARN (e.g. a 12-digit
        // account ID) must not panic when matched against a wildcard ARN
        // principal. Previously this hit an unwrap on a failed ARN parse.
        let policy = IAMPolicy::new().add_statement(
            IAMStatement::new(IAMEffect::Allow)
                .with_principal(Principal::Aws(PrincipalId::String(
                    "arn:aws:iam::123456789012:role/*".to_string(),
                )))
                .with_action(IAMAction::Single("s3:GetObject".to_string()))
                .with_resource(IAMResource::Single("*".to_string())),
        );

        let request = IAMRequest::new(
            Principal::Aws(PrincipalId::String("123456789012".to_string())),
            "s3:GetObject",
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
        );

        // Principal doesn't match the ARN pattern -> statement not applicable.
        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::NotApplicable);
    }

    #[test]
    fn test_numeric_condition() {
        let mut context = Context::new();
        context.insert("aws:RequestedRegion".to_string(), ContextValue::Number(5.0));

        let policy = IAMPolicy::new().add_statement(
            IAMStatement::new(IAMEffect::Allow)
                .with_action(IAMAction::Single("s3:GetObject".to_string()))
                .with_resource(IAMResource::Single("*".to_string()))
                .with_condition(
                    IAMOperator::NumericLessThan,
                    "aws:RequestedRegion".to_string(),
                    ConditionValue::Number(10.into()),
                ),
        );

        let request = IAMRequest::new_with_context(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "s3:GetObject",
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
            context,
        );

        let result = evaluate_policy(&policy, &request).unwrap();
        assert_eq!(result, Decision::Allow);
    }

    #[test]
    fn test_evaluator_with_options() {
        let policy = IAMPolicy::new().add_statement(
            IAMStatement::new(IAMEffect::Allow)
                .with_sid("AllowS3Read")
                .with_action(IAMAction::Single("s3:GetObject".to_string()))
                .with_resource(IAMResource::Single("arn:aws:s3:::my-bucket/*".to_string())),
        );

        let request = IAMRequest::new(
            Principal::Aws(PrincipalId::String(
                "arn:aws:iam::123456789012:user/test".into(),
            )),
            "s3:GetObject",
            Arn::parse("arn:aws:s3:::my-bucket/file.txt").unwrap(),
        );

        let evaluator =
            PolicyEvaluator::with_policies(vec![policy]).with_options(EvaluationOptions {
                collect_match_details: true,
                ..Default::default()
            });

        let result = evaluator.evaluate(&request).unwrap();
        assert_eq!(result.decision, Decision::Allow);
        assert!(!result.statement_details.is_empty());
        assert_eq!(
            result.statement_details[0].sid,
            Some("AllowS3Read".to_string())
        );
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct TestCase {
        result: Decision,
        request: IAMRequest,
        policy: IAMPolicy,
    }

    #[test]
    fn test_requests_testset() {
        // List filenames in the tests/requests directory
        let request_dir = "tests/requests";
        let mut request_files = std::fs::read_dir(request_dir)
            .unwrap_or_else(|e| panic!("Failed to read requests directory '{request_dir}': {e}"))
            .filter_map(|entry| {
                let entry = entry.ok()?;
                let path = entry.path();
                if path.extension()? == "json" {
                    Some(path)
                } else {
                    None
                }
            })
            .collect::<Vec<_>>();

        // Verify we actually found request files to test
        assert!(
            !request_files.is_empty(),
            "No request JSON files found in {request_dir}/"
        );

        // Sort files by name for consistent test order
        // All files are called 1.json, 2.json, ..., 10.json, etc.
        request_files.sort_by_key(|p| {
            p.file_name()
                .and_then(|n| n.to_str())
                .map(|s| s.split('.').next().unwrap().parse::<u32>().unwrap())
                .map(|n| format!("{n:010}"))
        });

        println!(
            "Testing {} request files from {}/",
            request_files.len(),
            request_dir
        );

        for (index, request_file) in request_files.iter().enumerate() {
            let filename = request_file
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("unknown");

            println!("Testing request #{}: {} ... ", index + 1, filename);

            // Read the JSON file
            let json_content = std::fs::read_to_string(request_file).unwrap_or_else(|e| {
                panic!("Failed to read file '{}': {}", request_file.display(), e)
            });

            // Parse the test case from JSON
            let test: TestCase = serde_json::from_str(&json_content).unwrap_or_else(|e| {
                panic!(
                    "Failed to parse JSON from file '{}': {:?}",
                    request_file.display(),
                    e
                )
            });

            // Evaluate the policy against the request
            let result = evaluate_policy(&test.policy, &test.request).unwrap();
            assert_eq!(result, test.result);
        }
    }
}