Skip to main content

wami_condition/
operators.rs

1//! Condition Operators
2//!
3//! Implements all condition operators for policy evaluation.
4
5use super::{ConditionError, ConditionValue};
6use std::str::FromStr;
7
8/// Condition operator types
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum ConditionOperator {
11    // String operators
12    StringEquals,
13    StringNotEquals,
14    StringLike,
15    StringNotLike,
16    StringEqualsIgnoreCase,
17    StringNotEqualsIgnoreCase,
18    StringEqualsIfExists,
19    StringNotEqualsIfExists,
20    StringLikeIfExists,
21    StringNotLikeIfExists,
22
23    // Numeric operators
24    NumericEquals,
25    NumericNotEquals,
26    NumericLessThan,
27    NumericLessThanEquals,
28    NumericGreaterThan,
29    NumericGreaterThanEquals,
30    NumericEqualsIfExists,
31    NumericNotEqualsIfExists,
32    NumericLessThanIfExists,
33    NumericLessThanEqualsIfExists,
34    NumericGreaterThanIfExists,
35    NumericGreaterThanEqualsIfExists,
36
37    // Date operators
38    DateEquals,
39    DateNotEquals,
40    DateLessThan,
41    DateLessThanEquals,
42    DateGreaterThan,
43    DateGreaterThanEquals,
44    DateEqualsIfExists,
45    DateNotEqualsIfExists,
46    DateLessThanIfExists,
47    DateLessThanEqualsIfExists,
48    DateGreaterThanIfExists,
49    DateGreaterThanEqualsIfExists,
50
51    // IP address operators
52    IpAddress,
53    NotIpAddress,
54    IpAddressIfExists,
55    NotIpAddressIfExists,
56
57    // ARN operators
58    ArnEquals,
59    ArnNotEquals,
60    ArnLike,
61    ArnNotLike,
62    ArnEqualsIfExists,
63    ArnNotEqualsIfExists,
64    ArnLikeIfExists,
65    ArnNotLikeIfExists,
66
67    // Boolean operators
68    Bool,
69    BoolIfExists,
70
71    // Binary operators
72    BinaryEquals,
73    BinaryEqualsIfExists,
74
75    // Null operators
76    Null,
77    NullIfExists,
78
79    // Set operators (ForAllValues)
80    ForAllValuesStringEquals,
81    ForAllValuesStringNotEquals,
82    ForAllValuesStringLike,
83    ForAllValuesStringNotLike,
84    ForAllValuesArnEquals,
85    ForAllValuesArnLike,
86    ForAllValuesNumericLessThan,
87    ForAllValuesNumericGreaterThan,
88    ForAllValuesIpAddress,
89    ForAllValuesDateLessThan,
90    ForAllValuesDateGreaterThan,
91
92    // Set operators (ForAnyValue)
93    ForAnyValueStringEquals,
94    ForAnyValueStringNotEquals,
95    ForAnyValueStringLike,
96    ForAnyValueStringNotLike,
97    ForAnyValueArnEquals,
98    ForAnyValueArnLike,
99    ForAnyValueNumericLessThan,
100    ForAnyValueNumericGreaterThan,
101    ForAnyValueIpAddress,
102    ForAnyValueDateLessThan,
103    ForAnyValueDateGreaterThan,
104}
105
106impl FromStr for ConditionOperator {
107    type Err = ConditionError;
108
109    fn from_str(s: &str) -> Result<Self, Self::Err> {
110        match s {
111            "StringEquals" => Ok(ConditionOperator::StringEquals),
112            "StringNotEquals" => Ok(ConditionOperator::StringNotEquals),
113            "StringLike" => Ok(ConditionOperator::StringLike),
114            "StringNotLike" => Ok(ConditionOperator::StringNotLike),
115            "StringEqualsIgnoreCase" => Ok(ConditionOperator::StringEqualsIgnoreCase),
116            "StringNotEqualsIgnoreCase" => Ok(ConditionOperator::StringNotEqualsIgnoreCase),
117            "StringEqualsIfExists" => Ok(ConditionOperator::StringEqualsIfExists),
118            "StringNotEqualsIfExists" => Ok(ConditionOperator::StringNotEqualsIfExists),
119            "StringLikeIfExists" => Ok(ConditionOperator::StringLikeIfExists),
120            "StringNotLikeIfExists" => Ok(ConditionOperator::StringNotLikeIfExists),
121
122            "NumericEquals" => Ok(ConditionOperator::NumericEquals),
123            "NumericNotEquals" => Ok(ConditionOperator::NumericNotEquals),
124            "NumericLessThan" => Ok(ConditionOperator::NumericLessThan),
125            "NumericLessThanEquals" => Ok(ConditionOperator::NumericLessThanEquals),
126            "NumericGreaterThan" => Ok(ConditionOperator::NumericGreaterThan),
127            "NumericGreaterThanEquals" => Ok(ConditionOperator::NumericGreaterThanEquals),
128            "NumericEqualsIfExists" => Ok(ConditionOperator::NumericEqualsIfExists),
129            "NumericNotEqualsIfExists" => Ok(ConditionOperator::NumericNotEqualsIfExists),
130            "NumericLessThanIfExists" => Ok(ConditionOperator::NumericLessThanIfExists),
131            "NumericLessThanEqualsIfExists" => Ok(ConditionOperator::NumericLessThanEqualsIfExists),
132            "NumericGreaterThanIfExists" => Ok(ConditionOperator::NumericGreaterThanIfExists),
133            "NumericGreaterThanEqualsIfExists" => {
134                Ok(ConditionOperator::NumericGreaterThanEqualsIfExists)
135            }
136
137            "DateEquals" => Ok(ConditionOperator::DateEquals),
138            "DateNotEquals" => Ok(ConditionOperator::DateNotEquals),
139            "DateLessThan" => Ok(ConditionOperator::DateLessThan),
140            "DateLessThanEquals" => Ok(ConditionOperator::DateLessThanEquals),
141            "DateGreaterThan" => Ok(ConditionOperator::DateGreaterThan),
142            "DateGreaterThanEquals" => Ok(ConditionOperator::DateGreaterThanEquals),
143            "DateEqualsIfExists" => Ok(ConditionOperator::DateEqualsIfExists),
144            "DateNotEqualsIfExists" => Ok(ConditionOperator::DateNotEqualsIfExists),
145            "DateLessThanIfExists" => Ok(ConditionOperator::DateLessThanIfExists),
146            "DateLessThanEqualsIfExists" => Ok(ConditionOperator::DateLessThanEqualsIfExists),
147            "DateGreaterThanIfExists" => Ok(ConditionOperator::DateGreaterThanIfExists),
148            "DateGreaterThanEqualsIfExists" => Ok(ConditionOperator::DateGreaterThanEqualsIfExists),
149
150            "IpAddress" => Ok(ConditionOperator::IpAddress),
151            "NotIpAddress" => Ok(ConditionOperator::NotIpAddress),
152            "IpAddressIfExists" => Ok(ConditionOperator::IpAddressIfExists),
153            "NotIpAddressIfExists" => Ok(ConditionOperator::NotIpAddressIfExists),
154
155            "ArnEquals" => Ok(ConditionOperator::ArnEquals),
156            "ArnNotEquals" => Ok(ConditionOperator::ArnNotEquals),
157            "ArnLike" => Ok(ConditionOperator::ArnLike),
158            "ArnNotLike" => Ok(ConditionOperator::ArnNotLike),
159            "ArnEqualsIfExists" => Ok(ConditionOperator::ArnEqualsIfExists),
160            "ArnNotEqualsIfExists" => Ok(ConditionOperator::ArnNotEqualsIfExists),
161            "ArnLikeIfExists" => Ok(ConditionOperator::ArnLikeIfExists),
162            "ArnNotLikeIfExists" => Ok(ConditionOperator::ArnNotLikeIfExists),
163
164            "Bool" => Ok(ConditionOperator::Bool),
165            "BoolIfExists" => Ok(ConditionOperator::BoolIfExists),
166
167            "BinaryEquals" => Ok(ConditionOperator::BinaryEquals),
168            "BinaryEqualsIfExists" => Ok(ConditionOperator::BinaryEqualsIfExists),
169
170            "Null" => Ok(ConditionOperator::Null),
171            "NullIfExists" => Ok(ConditionOperator::NullIfExists),
172
173            "ForAllValues:StringEquals" => Ok(ConditionOperator::ForAllValuesStringEquals),
174            "ForAllValues:StringNotEquals" => Ok(ConditionOperator::ForAllValuesStringNotEquals),
175            "ForAllValues:StringLike" => Ok(ConditionOperator::ForAllValuesStringLike),
176            "ForAllValues:StringNotLike" => Ok(ConditionOperator::ForAllValuesStringNotLike),
177            "ForAllValues:ArnEquals" => Ok(ConditionOperator::ForAllValuesArnEquals),
178            "ForAllValues:ArnLike" => Ok(ConditionOperator::ForAllValuesArnLike),
179            "ForAllValues:NumericLessThan" => Ok(ConditionOperator::ForAllValuesNumericLessThan),
180            "ForAllValues:NumericGreaterThan" => {
181                Ok(ConditionOperator::ForAllValuesNumericGreaterThan)
182            }
183            "ForAllValues:IpAddress" => Ok(ConditionOperator::ForAllValuesIpAddress),
184            "ForAllValues:DateLessThan" => Ok(ConditionOperator::ForAllValuesDateLessThan),
185            "ForAllValues:DateGreaterThan" => Ok(ConditionOperator::ForAllValuesDateGreaterThan),
186
187            "ForAnyValue:StringEquals" => Ok(ConditionOperator::ForAnyValueStringEquals),
188            "ForAnyValue:StringNotEquals" => Ok(ConditionOperator::ForAnyValueStringNotEquals),
189            "ForAnyValue:StringLike" => Ok(ConditionOperator::ForAnyValueStringLike),
190            "ForAnyValue:StringNotLike" => Ok(ConditionOperator::ForAnyValueStringNotLike),
191            "ForAnyValue:ArnEquals" => Ok(ConditionOperator::ForAnyValueArnEquals),
192            "ForAnyValue:ArnLike" => Ok(ConditionOperator::ForAnyValueArnLike),
193            "ForAnyValue:NumericLessThan" => Ok(ConditionOperator::ForAnyValueNumericLessThan),
194            "ForAnyValue:NumericGreaterThan" => {
195                Ok(ConditionOperator::ForAnyValueNumericGreaterThan)
196            }
197            "ForAnyValue:IpAddress" => Ok(ConditionOperator::ForAnyValueIpAddress),
198            "ForAnyValue:DateLessThan" => Ok(ConditionOperator::ForAnyValueDateLessThan),
199            "ForAnyValue:DateGreaterThan" => Ok(ConditionOperator::ForAnyValueDateGreaterThan),
200
201            _ => Err(ConditionError::UnknownOperator(s.to_string())),
202        }
203    }
204}
205
206/// Evaluate a condition operator
207pub fn evaluate_operator(
208    operator: ConditionOperator,
209    actual: Option<ConditionValue>,
210    expected: &ConditionValue,
211) -> Result<bool, ConditionError> {
212    match operator {
213        // String operators
214        ConditionOperator::StringEquals => evaluate_string_equals(actual, expected),
215        ConditionOperator::StringNotEquals => evaluate_string_equals(actual, expected).map(|r| !r),
216        ConditionOperator::StringLike => evaluate_string_like(actual, expected),
217        ConditionOperator::StringNotLike => evaluate_string_like(actual, expected).map(|r| !r),
218        ConditionOperator::StringEqualsIgnoreCase => {
219            evaluate_string_equals_ignore_case(actual, expected)
220        }
221        ConditionOperator::StringNotEqualsIgnoreCase => {
222            evaluate_string_equals_ignore_case(actual, expected).map(|r| !r)
223        }
224        ConditionOperator::StringEqualsIfExists => {
225            evaluate_if_exists(actual, |a| evaluate_string_equals(Some(a), expected))
226        }
227        ConditionOperator::StringNotEqualsIfExists => evaluate_if_exists(actual, |a| {
228            evaluate_string_equals(Some(a), expected).map(|r| !r)
229        }),
230        ConditionOperator::StringLikeIfExists => {
231            evaluate_if_exists(actual, |a| evaluate_string_like(Some(a), expected))
232        }
233        ConditionOperator::StringNotLikeIfExists => evaluate_if_exists(actual, |a| {
234            evaluate_string_like(Some(a), expected).map(|r| !r)
235        }),
236
237        // Numeric operators
238        ConditionOperator::NumericEquals => evaluate_numeric_equals(actual, expected),
239        ConditionOperator::NumericNotEquals => {
240            evaluate_numeric_equals(actual, expected).map(|r| !r)
241        }
242        ConditionOperator::NumericLessThan => evaluate_numeric_less_than(actual, expected),
243        ConditionOperator::NumericLessThanEquals => {
244            evaluate_numeric_less_than_equals(actual, expected)
245        }
246        ConditionOperator::NumericGreaterThan => evaluate_numeric_greater_than(actual, expected),
247        ConditionOperator::NumericGreaterThanEquals => {
248            evaluate_numeric_greater_than_equals(actual, expected)
249        }
250        ConditionOperator::NumericEqualsIfExists => {
251            evaluate_if_exists(actual, |a| evaluate_numeric_equals(Some(a), expected))
252        }
253        ConditionOperator::NumericNotEqualsIfExists => evaluate_if_exists(actual, |a| {
254            evaluate_numeric_equals(Some(a), expected).map(|r| !r)
255        }),
256        ConditionOperator::NumericLessThanIfExists => {
257            evaluate_if_exists(actual, |a| evaluate_numeric_less_than(Some(a), expected))
258        }
259        ConditionOperator::NumericLessThanEqualsIfExists => evaluate_if_exists(actual, |a| {
260            evaluate_numeric_less_than_equals(Some(a), expected)
261        }),
262        ConditionOperator::NumericGreaterThanIfExists => {
263            evaluate_if_exists(actual, |a| evaluate_numeric_greater_than(Some(a), expected))
264        }
265        ConditionOperator::NumericGreaterThanEqualsIfExists => evaluate_if_exists(actual, |a| {
266            evaluate_numeric_greater_than_equals(Some(a), expected)
267        }),
268
269        // Date operators
270        ConditionOperator::DateEquals => evaluate_date_equals(actual, expected),
271        ConditionOperator::DateNotEquals => evaluate_date_equals(actual, expected).map(|r| !r),
272        ConditionOperator::DateLessThan => evaluate_date_less_than(actual, expected),
273        ConditionOperator::DateLessThanEquals => evaluate_date_less_than_equals(actual, expected),
274        ConditionOperator::DateGreaterThan => evaluate_date_greater_than(actual, expected),
275        ConditionOperator::DateGreaterThanEquals => {
276            evaluate_date_greater_than_equals(actual, expected)
277        }
278        ConditionOperator::DateEqualsIfExists => {
279            evaluate_if_exists(actual, |a| evaluate_date_equals(Some(a), expected))
280        }
281        ConditionOperator::DateNotEqualsIfExists => evaluate_if_exists(actual, |a| {
282            evaluate_date_equals(Some(a), expected).map(|r| !r)
283        }),
284        ConditionOperator::DateLessThanIfExists => {
285            evaluate_if_exists(actual, |a| evaluate_date_less_than(Some(a), expected))
286        }
287        ConditionOperator::DateLessThanEqualsIfExists => evaluate_if_exists(actual, |a| {
288            evaluate_date_less_than_equals(Some(a), expected)
289        }),
290        ConditionOperator::DateGreaterThanIfExists => {
291            evaluate_if_exists(actual, |a| evaluate_date_greater_than(Some(a), expected))
292        }
293        ConditionOperator::DateGreaterThanEqualsIfExists => evaluate_if_exists(actual, |a| {
294            evaluate_date_greater_than_equals(Some(a), expected)
295        }),
296
297        // IP address operators
298        ConditionOperator::IpAddress => evaluate_ip_address(actual, expected),
299        ConditionOperator::NotIpAddress => evaluate_ip_address(actual, expected).map(|r| !r),
300        ConditionOperator::IpAddressIfExists => {
301            evaluate_if_exists(actual, |a| evaluate_ip_address(Some(a), expected))
302        }
303        ConditionOperator::NotIpAddressIfExists => evaluate_if_exists(actual, |a| {
304            evaluate_ip_address(Some(a), expected).map(|r| !r)
305        }),
306
307        // ARN operators
308        ConditionOperator::ArnEquals => evaluate_arn_equals(actual, expected),
309        ConditionOperator::ArnNotEquals => evaluate_arn_equals(actual, expected).map(|r| !r),
310        ConditionOperator::ArnLike => evaluate_arn_like(actual, expected),
311        ConditionOperator::ArnNotLike => evaluate_arn_like(actual, expected).map(|r| !r),
312        ConditionOperator::ArnEqualsIfExists => {
313            evaluate_if_exists(actual, |a| evaluate_arn_equals(Some(a), expected))
314        }
315        ConditionOperator::ArnNotEqualsIfExists => evaluate_if_exists(actual, |a| {
316            evaluate_arn_equals(Some(a), expected).map(|r| !r)
317        }),
318        ConditionOperator::ArnLikeIfExists => {
319            evaluate_if_exists(actual, |a| evaluate_arn_like(Some(a), expected))
320        }
321        ConditionOperator::ArnNotLikeIfExists => {
322            evaluate_if_exists(actual, |a| evaluate_arn_like(Some(a), expected).map(|r| !r))
323        }
324
325        // Boolean operators
326        ConditionOperator::Bool => evaluate_bool(actual, expected),
327        ConditionOperator::BoolIfExists => {
328            evaluate_if_exists(actual, |a| evaluate_bool(Some(a), expected))
329        }
330
331        // Binary operators
332        ConditionOperator::BinaryEquals => evaluate_binary_equals(actual, expected),
333        ConditionOperator::BinaryEqualsIfExists => {
334            evaluate_if_exists(actual, |a| evaluate_binary_equals(Some(a), expected))
335        }
336
337        // Null operators
338        ConditionOperator::Null => evaluate_null(actual, expected),
339        ConditionOperator::NullIfExists => {
340            evaluate_if_exists(actual, |a| evaluate_null(Some(a), expected))
341        }
342
343        // Set operators - ForAllValues
344        ConditionOperator::ForAllValuesStringEquals => {
345            set_string_equals(Quantifier::All, actual, expected)
346        }
347        ConditionOperator::ForAllValuesStringNotEquals => {
348            set_string_equals(Quantifier::All, actual, expected).map(|r| !r)
349        }
350        ConditionOperator::ForAllValuesStringLike => {
351            set_string_like(Quantifier::All, actual, expected)
352        }
353        ConditionOperator::ForAllValuesStringNotLike => {
354            set_string_like(Quantifier::All, actual, expected).map(|r| !r)
355        }
356        ConditionOperator::ForAllValuesArnEquals => {
357            set_string_equals(Quantifier::All, actual, expected)
358        }
359        ConditionOperator::ForAllValuesArnLike => {
360            set_string_like(Quantifier::All, actual, expected)
361        }
362        ConditionOperator::ForAllValuesNumericLessThan => without_key(operator),
363        ConditionOperator::ForAllValuesNumericGreaterThan => without_key(operator),
364        ConditionOperator::ForAllValuesIpAddress => without_key(operator),
365        ConditionOperator::ForAllValuesDateLessThan => without_key(operator),
366        ConditionOperator::ForAllValuesDateGreaterThan => without_key(operator),
367
368        // Set operators - ForAnyValue
369        ConditionOperator::ForAnyValueStringEquals => {
370            set_string_equals(Quantifier::Any, actual, expected)
371        }
372        ConditionOperator::ForAnyValueStringNotEquals => {
373            set_string_equals(Quantifier::Any, actual, expected).map(|r| !r)
374        }
375        ConditionOperator::ForAnyValueStringLike => {
376            set_string_like(Quantifier::Any, actual, expected)
377        }
378        ConditionOperator::ForAnyValueStringNotLike => {
379            set_string_like(Quantifier::Any, actual, expected).map(|r| !r)
380        }
381        ConditionOperator::ForAnyValueArnEquals => {
382            set_string_equals(Quantifier::Any, actual, expected)
383        }
384        ConditionOperator::ForAnyValueArnLike => set_string_like(Quantifier::Any, actual, expected),
385        ConditionOperator::ForAnyValueNumericLessThan => without_key(operator),
386        ConditionOperator::ForAnyValueNumericGreaterThan => without_key(operator),
387        ConditionOperator::ForAnyValueIpAddress => without_key(operator),
388        ConditionOperator::ForAnyValueDateLessThan => without_key(operator),
389        ConditionOperator::ForAnyValueDateGreaterThan => without_key(operator),
390    }
391}
392
393// Helper: Evaluate IfExists behavior
394fn evaluate_if_exists<F>(
395    actual: Option<ConditionValue>,
396    evaluator: F,
397) -> Result<bool, ConditionError>
398where
399    F: FnOnce(ConditionValue) -> Result<bool, ConditionError>,
400{
401    match actual {
402        Some(value) => evaluator(value),
403        None => Ok(true), // IfExists: missing value passes
404    }
405}
406
407// String operator implementations
408fn evaluate_string_equals(
409    actual: Option<ConditionValue>,
410    expected: &ConditionValue,
411) -> Result<bool, ConditionError> {
412    match actual {
413        Some(ConditionValue::String(actual_str)) => {
414            let expected_str = expected.as_string()?;
415            Ok(actual_str == expected_str)
416        }
417        None => Ok(false), // Missing value = no match
418        Some(other) => Err(other.mismatch("String")),
419    }
420}
421
422fn evaluate_string_equals_ignore_case(
423    actual: Option<ConditionValue>,
424    expected: &ConditionValue,
425) -> Result<bool, ConditionError> {
426    match actual {
427        Some(ConditionValue::String(actual_str)) => {
428            let expected_str = expected.as_string()?;
429            Ok(actual_str.eq_ignore_ascii_case(&expected_str))
430        }
431        None => Ok(false),
432        Some(other) => Err(other.mismatch("String")),
433    }
434}
435
436fn evaluate_string_like(
437    actual: Option<ConditionValue>,
438    expected: &ConditionValue,
439) -> Result<bool, ConditionError> {
440    match actual {
441        Some(ConditionValue::String(actual_str)) => {
442            let pattern = expected.as_string()?;
443            Ok(matches_wildcard_pattern(&actual_str, &pattern))
444        }
445        None => Ok(false),
446        Some(other) => Err(other.mismatch("String")),
447    }
448}
449
450// Wildcard pattern matching (* and ?)
451fn matches_wildcard_pattern(value: &str, pattern: &str) -> bool {
452    // Simple wildcard matching: * matches any sequence, ? matches single character
453    // This is a simplified implementation - AWS uses more complex matching
454    if pattern == "*" {
455        return true;
456    }
457
458    // Convert pattern to regex-like matching
459    let mut value_chars = value.chars();
460    let mut pattern_chars = pattern.chars();
461
462    while let Some(pc) = pattern_chars.next() {
463        match pc {
464            '*' => {
465                // Match zero or more characters
466                // Try matching rest of pattern against remaining value
467                let remaining_pattern: String = pattern_chars.collect();
468                if remaining_pattern.is_empty() {
469                    return true; // * at end matches everything
470                }
471                // Try matching remaining pattern at each position (including position 0)
472                let remaining_value: String = value_chars.as_str().chars().collect();
473                if matches_wildcard_pattern(&remaining_value, &remaining_pattern) {
474                    return true; // Try matching at current position (zero characters)
475                }
476                // Try matching at each subsequent position
477                while let Some(_) = value_chars.next() {
478                    let remaining_value: String = value_chars.as_str().chars().collect();
479                    if matches_wildcard_pattern(&remaining_value, &remaining_pattern) {
480                        return true;
481                    }
482                }
483                return false;
484            }
485            '?' => {
486                // Match single character
487                if value_chars.next().is_none() {
488                    return false;
489                }
490            }
491            _ => {
492                // Match exact character
493                if value_chars.next() != Some(pc) {
494                    return false;
495                }
496            }
497        }
498    }
499
500    // Pattern exhausted - value must also be exhausted
501    value_chars.next().is_none()
502}
503
504// Numeric operator implementations
505fn evaluate_numeric_equals(
506    actual: Option<ConditionValue>,
507    expected: &ConditionValue,
508) -> Result<bool, ConditionError> {
509    match actual {
510        Some(actual_val) => {
511            let actual_num = actual_val.as_number()?;
512            let expected_num = expected.as_number()?;
513            Ok((actual_num - expected_num).abs() < f64::EPSILON)
514        }
515        None => Ok(false),
516    }
517}
518
519fn evaluate_numeric_less_than(
520    actual: Option<ConditionValue>,
521    expected: &ConditionValue,
522) -> Result<bool, ConditionError> {
523    match actual {
524        Some(actual_val) => {
525            let actual_num = actual_val.as_number()?;
526            let expected_num = expected.as_number()?;
527            Ok(actual_num < expected_num)
528        }
529        None => Ok(false),
530    }
531}
532
533fn evaluate_numeric_less_than_equals(
534    actual: Option<ConditionValue>,
535    expected: &ConditionValue,
536) -> Result<bool, ConditionError> {
537    match actual {
538        Some(actual_val) => {
539            let actual_num = actual_val.as_number()?;
540            let expected_num = expected.as_number()?;
541            Ok(actual_num <= expected_num)
542        }
543        None => Ok(false),
544    }
545}
546
547fn evaluate_numeric_greater_than(
548    actual: Option<ConditionValue>,
549    expected: &ConditionValue,
550) -> Result<bool, ConditionError> {
551    match actual {
552        Some(actual_val) => {
553            let actual_num = actual_val.as_number()?;
554            let expected_num = expected.as_number()?;
555            Ok(actual_num > expected_num)
556        }
557        None => Ok(false),
558    }
559}
560
561fn evaluate_numeric_greater_than_equals(
562    actual: Option<ConditionValue>,
563    expected: &ConditionValue,
564) -> Result<bool, ConditionError> {
565    match actual {
566        Some(actual_val) => {
567            let actual_num = actual_val.as_number()?;
568            let expected_num = expected.as_number()?;
569            Ok(actual_num >= expected_num)
570        }
571        None => Ok(false),
572    }
573}
574
575// Date operator implementations
576fn evaluate_date_equals(
577    actual: Option<ConditionValue>,
578    expected: &ConditionValue,
579) -> Result<bool, ConditionError> {
580    match actual {
581        Some(ConditionValue::String(actual_str)) => {
582            let expected_str = expected.as_string()?;
583            let actual_time = parse_rfc3339(&actual_str)?;
584            let expected_time = parse_rfc3339(&expected_str)?;
585            Ok(actual_time == expected_time)
586        }
587        None => Ok(false),
588        Some(other) => Err(other.mismatch("String")),
589    }
590}
591
592fn evaluate_date_less_than(
593    actual: Option<ConditionValue>,
594    expected: &ConditionValue,
595) -> Result<bool, ConditionError> {
596    match actual {
597        Some(ConditionValue::String(actual_str)) => {
598            let expected_str = expected.as_string()?;
599            let actual_time = parse_rfc3339(&actual_str)?;
600            let expected_time = parse_rfc3339(&expected_str)?;
601            Ok(actual_time < expected_time)
602        }
603        None => Ok(false),
604        Some(other) => Err(other.mismatch("String")),
605    }
606}
607
608fn evaluate_date_less_than_equals(
609    actual: Option<ConditionValue>,
610    expected: &ConditionValue,
611) -> Result<bool, ConditionError> {
612    match actual {
613        Some(ConditionValue::String(actual_str)) => {
614            let expected_str = expected.as_string()?;
615            let actual_time = parse_rfc3339(&actual_str)?;
616            let expected_time = parse_rfc3339(&expected_str)?;
617            Ok(actual_time <= expected_time)
618        }
619        None => Ok(false),
620        Some(other) => Err(other.mismatch("String")),
621    }
622}
623
624fn evaluate_date_greater_than(
625    actual: Option<ConditionValue>,
626    expected: &ConditionValue,
627) -> Result<bool, ConditionError> {
628    match actual {
629        Some(ConditionValue::String(actual_str)) => {
630            let expected_str = expected.as_string()?;
631            let actual_time = parse_rfc3339(&actual_str)?;
632            let expected_time = parse_rfc3339(&expected_str)?;
633            Ok(actual_time > expected_time)
634        }
635        None => Ok(false),
636        Some(other) => Err(other.mismatch("String")),
637    }
638}
639
640fn evaluate_date_greater_than_equals(
641    actual: Option<ConditionValue>,
642    expected: &ConditionValue,
643) -> Result<bool, ConditionError> {
644    match actual {
645        Some(ConditionValue::String(actual_str)) => {
646            let expected_str = expected.as_string()?;
647            let actual_time = parse_rfc3339(&actual_str)?;
648            let expected_time = parse_rfc3339(&expected_str)?;
649            Ok(actual_time >= expected_time)
650        }
651        None => Ok(false),
652        Some(other) => Err(other.mismatch("String")),
653    }
654}
655
656pub(crate) fn parse_rfc3339(s: &str) -> Result<chrono::DateTime<chrono::Utc>, ConditionError> {
657    chrono::DateTime::parse_from_rfc3339(s)
658        .map(|dt| dt.with_timezone(&chrono::Utc))
659        .map_err(|e| ConditionError::InvalidDate {
660            // chrono's message describes the fault, never the input.
661            error: e.to_string(),
662        })
663}
664
665// IP address operator implementations
666fn evaluate_ip_address(
667    actual: Option<ConditionValue>,
668    expected: &ConditionValue,
669) -> Result<bool, ConditionError> {
670    match actual {
671        Some(ConditionValue::String(actual_ip)) => {
672            check_address(&actual_ip, None)?;
673            // One network, or a list of them: at least one must match.
674            let networks: Vec<&str> = match expected {
675                ConditionValue::String(network) => vec![network.as_str()],
676                ConditionValue::Array(networks) => networks.iter().map(String::as_str).collect(),
677                other => return Err(other.mismatch("an IP address or a list of them")),
678            };
679            for (index, network) in networks.iter().enumerate() {
680                check_ip_or_cidr(
681                    network,
682                    matches!(expected, ConditionValue::Array(_)).then_some(index),
683                )?;
684            }
685            Ok(networks
686                .iter()
687                .any(|network| ip_matches_cidr(&actual_ip, network)))
688        }
689        None => Ok(false),
690        Some(other) => Err(other.mismatch("an IP address")),
691    }
692}
693
694/// Whether `s` is an IP address alone.
695pub(crate) fn is_address(s: &str) -> bool {
696    parse_ipv4(s).is_some() || s.parse::<std::net::Ipv6Addr>().is_ok()
697}
698
699fn not_an_address(expected: &str, position: Option<usize>) -> ConditionError {
700    ConditionError::TypeMismatch {
701        expected: match position {
702            Some(index) => format!("{expected} at element {index}"),
703            None => expected.to_string(),
704        },
705        actual: "String".to_string(),
706    }
707}
708
709/// A request's address: an IP address alone. One that is not used to make
710/// `IpAddress` false and `NotIpAddress` TRUE (wami 001).
711fn check_address(s: &str, position: Option<usize>) -> Result<(), ConditionError> {
712    if is_address(s) {
713        Ok(())
714    } else {
715        Err(not_an_address("an IP address", position))
716    }
717}
718
719/// A policy's network: an address alone, or one with a prefix `ip_matches_cidr`
720/// does not ignore (a v4 prefix above 32 never matches anything).
721///
722/// Parse checks a policy's addresses with this very function, so parse and
723/// evaluation cannot disagree on what an address is (wami 001).
724pub(crate) fn check_ip_or_cidr(s: &str, position: Option<usize>) -> Result<(), ConditionError> {
725    let is_v4 = |a: &str| parse_ipv4(a).is_some();
726    let is_v6 = |a: &str| a.parse::<std::net::Ipv6Addr>().is_ok();
727    let readable = match s.split_once('/') {
728        None => is_address(s),
729        Some((network, prefix)) => match prefix.parse::<u8>() {
730            Ok(p) if is_v4(network) => p <= 32,
731            Ok(p) if is_v6(network) => p <= 128,
732            _ => false,
733        },
734    };
735    if readable {
736        Ok(())
737    } else {
738        Err(not_an_address("an IP address or CIDR", position))
739    }
740}
741
742fn ip_matches_cidr(ip: &str, cidr: &str) -> bool {
743    // Simple CIDR matching - for production, use a proper IP/CIDR library
744    if ip == cidr {
745        return true; // Exact match
746    }
747
748    // Parse CIDR notation (e.g., "203.0.113.0/24")
749    if let Some((network, prefix_len_str)) = cidr.split_once('/') {
750        if let Ok(prefix_len) = prefix_len_str.parse::<u8>() {
751            // For IPv4
752            if let (Some(ip_addr), Some(net_addr)) = (parse_ipv4(ip), parse_ipv4(network)) {
753                return ip_in_cidr_v4(ip_addr, net_addr, prefix_len);
754            }
755            // For IPv6 (simplified - basic prefix matching)
756            if ip.contains(':') && cidr.contains(':') {
757                // Basic IPv6 CIDR matching - check if IP starts with network prefix
758                // This is simplified - proper IPv6 CIDR would need full parsing
759                if let Some((network_part, _)) = cidr.split_once('/') {
760                    // For /32 prefix, check first 32 bits (8 hex groups of 4 chars each)
761                    // Simplified: check if IP starts with network part
762                    if prefix_len <= 128 {
763                        // For now, do prefix string matching (simplified)
764                        // Proper implementation would parse IPv6 addresses and masks
765                        return ip.starts_with(network_part) || ip == network;
766                    }
767                }
768                return ip == network; // Fallback to exact match
769            }
770        }
771    }
772
773    false
774}
775
776pub(crate) fn parse_ipv4(ip: &str) -> Option<[u8; 4]> {
777    let parts: Vec<&str> = ip.split('.').collect();
778    if parts.len() != 4 {
779        return None;
780    }
781    let mut bytes = [0u8; 4];
782    for (i, part) in parts.iter().enumerate() {
783        bytes[i] = part.parse().ok()?;
784    }
785    Some(bytes)
786}
787
788fn ip_in_cidr_v4(ip: [u8; 4], network: [u8; 4], prefix_len: u8) -> bool {
789    if prefix_len > 32 {
790        return false;
791    }
792    let mask_bits = prefix_len;
793    let full_bytes = (mask_bits / 8) as usize;
794    let remaining_bits = mask_bits % 8;
795
796    // Check full bytes
797    for i in 0..full_bytes {
798        if ip[i] != network[i] {
799            return false;
800        }
801    }
802
803    // Check remaining bits
804    if remaining_bits > 0 && full_bytes < 4 {
805        let mask = !((1u8 << (8 - remaining_bits)) - 1);
806        if (ip[full_bytes] & mask) != (network[full_bytes] & mask) {
807            return false;
808        }
809    }
810
811    true
812}
813
814// ARN operator implementations
815fn evaluate_arn_equals(
816    actual: Option<ConditionValue>,
817    expected: &ConditionValue,
818) -> Result<bool, ConditionError> {
819    match actual {
820        Some(ConditionValue::String(actual_arn)) => {
821            let expected_arn = expected.as_string()?;
822            Ok(actual_arn == expected_arn)
823        }
824        None => Ok(false),
825        Some(other) => Err(other.mismatch("String")),
826    }
827}
828
829fn evaluate_arn_like(
830    actual: Option<ConditionValue>,
831    expected: &ConditionValue,
832) -> Result<bool, ConditionError> {
833    match actual {
834        Some(ConditionValue::String(actual_arn)) => {
835            let pattern = expected.as_string()?;
836            Ok(matches_wildcard_pattern(&actual_arn, &pattern))
837        }
838        None => Ok(false),
839        Some(other) => Err(other.mismatch("String")),
840    }
841}
842
843// Boolean operator implementations
844fn evaluate_bool(
845    actual: Option<ConditionValue>,
846    expected: &ConditionValue,
847) -> Result<bool, ConditionError> {
848    match actual {
849        Some(actual_val) => {
850            let actual_bool = actual_val.as_boolean()?;
851            let expected_bool = expected.as_boolean()?;
852            Ok(actual_bool == expected_bool)
853        }
854        None => Ok(false),
855    }
856}
857
858// Binary operator implementations
859fn evaluate_binary_equals(
860    actual: Option<ConditionValue>,
861    expected: &ConditionValue,
862) -> Result<bool, ConditionError> {
863    match actual {
864        Some(ConditionValue::String(actual_base64)) => {
865            let expected_base64 = expected.as_string()?;
866            // Decode and compare (simplified - would use base64 crate in production)
867            Ok(actual_base64 == expected_base64)
868        }
869        None => Ok(false),
870        Some(other) => Err(other.mismatch("String")),
871    }
872}
873
874// Null operator implementations
875fn evaluate_null(
876    actual: Option<ConditionValue>,
877    expected: &ConditionValue,
878) -> Result<bool, ConditionError> {
879    let expected_bool = expected.as_boolean()?;
880    let is_null = actual.is_none();
881    Ok(is_null == expected_bool)
882}
883
884// Set operator implementations — ForAllValues / ForAnyValue
885//
886// One body per comparison, the quantifier passed in. Only the string and ARN
887// forms have a body: the numeric, date and address forms compare a list no
888// key holds, so parse refuses them and they have no evaluator (wami 001).
889
890/// How a set operator combines its per-element results.
891#[derive(Clone, Copy)]
892enum Quantifier {
893    /// `ForAllValues`: every request value must match.
894    All,
895    /// `ForAnyValue`: one request value must match.
896    Any,
897}
898
899impl Quantifier {
900    fn over<T>(self, items: &[T], test: impl Fn(&T) -> bool) -> bool {
901        match self {
902            Quantifier::All => items.iter().all(test),
903            Quantifier::Any => items.iter().any(test),
904        }
905    }
906
907    /// What an absent key, or a request with no values, answers: vacuously
908    /// true for every value, false for any value.
909    fn on_nothing(self) -> bool {
910        matches!(self, Quantifier::All)
911    }
912}
913
914/// The request's values: a list, or one string read as a list of one.
915fn request_values(actual: ConditionValue) -> Result<Vec<String>, ConditionError> {
916    match actual {
917        ConditionValue::Array(values) => Ok(values),
918        ConditionValue::String(value) => Ok(vec![value]),
919        other => Err(other.mismatch("a String or an Array of Strings")),
920    }
921}
922
923fn set_string_equals(
924    quantifier: Quantifier,
925    actual: Option<ConditionValue>,
926    expected: &ConditionValue,
927) -> Result<bool, ConditionError> {
928    let Some(actual) = actual else {
929        return Ok(quantifier.on_nothing());
930    };
931    let values = request_values(actual)?;
932    if values.is_empty() {
933        return Ok(quantifier.on_nothing());
934    }
935    let expected = expected.as_array()?;
936    Ok(quantifier.over(&values, |value| expected.contains(value)))
937}
938
939fn set_string_like(
940    quantifier: Quantifier,
941    actual: Option<ConditionValue>,
942    expected: &ConditionValue,
943) -> Result<bool, ConditionError> {
944    let Some(actual) = actual else {
945        return Ok(quantifier.on_nothing());
946    };
947    let values = request_values(actual)?;
948    if values.is_empty() {
949        return Ok(quantifier.on_nothing());
950    }
951    let patterns = expected.as_array()?;
952    Ok(quantifier.over(&values, |value| {
953        patterns
954            .iter()
955            .any(|pattern| matches_wildcard_pattern(value, pattern))
956    }))
957}
958
959/// A hand-built block reaching an operator no key can feed: refused as parse
960/// refuses it — the operator has no evaluator (wami 001).
961fn without_key(operator: ConditionOperator) -> Result<bool, ConditionError> {
962    Err(ConditionError::OperatorWithoutKey {
963        operator: crate::validate::without_key(operator)
964            .unwrap_or("a set operator")
965            .to_string(),
966    })
967}