wami_condition/evaluator.rs
1//! Condition Evaluator
2//!
3//! Evaluates condition blocks against a context.
4
5use super::{
6 get_context_value, ConditionBlock, ConditionContext, ConditionOperator, ConditionValue,
7};
8use serde_json::Value;
9use std::collections::HashMap;
10use std::str::FromStr;
11
12/// Error types for condition evaluation
13///
14/// An error names what the policy's author wrote and must fix — the operator,
15/// the key, the position of an element — and the KIND of a value, never the
16/// value itself, neither the policy's nor the request's: a caller logging the
17/// error must not echo text it has not checked (wami 001).
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum ConditionError {
20 UnknownOperator(String),
21 TypeMismatch {
22 expected: String,
23 actual: String,
24 },
25 /// A string that is neither `true` nor `false` where a boolean is read.
26 InvalidBooleanValue,
27 /// A string that is not an RFC 3339 date where a date is read.
28 InvalidDate {
29 /// What the date parser objected to — never the input.
30 error: String,
31 },
32 MissingContextKey(String),
33 InvalidConditionStructure(String),
34 /// A value its operator cannot read, refused when the condition is parsed.
35 ///
36 /// It names where the value sits — operator, key, and the element when the
37 /// value is a list — and what the operator reads, but never the value
38 /// itself.
39 InvalidConditionValue {
40 /// The operator as written in the condition.
41 operator: String,
42 /// The condition key the value is compared with.
43 key: String,
44 /// The offending element's index, when the value is a list.
45 position: Option<usize>,
46 /// What the operator reads.
47 expected: String,
48 },
49 /// An operator no key can feed: the `ForAllValues`/`ForAnyValue` forms of
50 /// `Numeric*`, `Date*` and `IpAddress` compare a LIST of numbers, dates or
51 /// addresses, and no declared key holds one (`keys::KeyType` has no such
52 /// type; custom keys are compared as strings). Refused at parse rather
53 /// than kept as a path no parsed policy reaches (wami 001).
54 OperatorWithoutKey {
55 /// The operator as written in the condition.
56 operator: String,
57 },
58 /// An operator that cannot compare the type of the key it is given — a
59 /// string operator on the Boolean `aws:SecureTransport`, a numeric one on
60 /// a key nobody declared (compared as a string). Refused at parse: it used
61 /// to evaluate to `false`, so a Deny carrying it vanished.
62 OperatorKeyMismatch {
63 /// The operator as written in the condition.
64 operator: String,
65 /// The condition key.
66 key: String,
67 /// The key's declared type, or that it is undeclared.
68 key_type: String,
69 },
70}
71
72impl std::fmt::Display for ConditionError {
73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 match self {
75 ConditionError::UnknownOperator(op) => write!(f, "Unknown operator: {}", op),
76 ConditionError::TypeMismatch { expected, actual } => {
77 write!(f, "Type mismatch: expected {}, got {}", expected, actual)
78 }
79 ConditionError::InvalidBooleanValue => {
80 write!(f, "Invalid boolean value: must be 'true' or 'false'")
81 }
82 ConditionError::InvalidDate { error } => {
83 write!(f, "Invalid date value: {error}")
84 }
85 ConditionError::MissingContextKey(key) => {
86 write!(f, "Missing context key: {}", key)
87 }
88 ConditionError::InvalidConditionStructure(msg) => {
89 write!(f, "Invalid condition structure: {}", msg)
90 }
91 ConditionError::InvalidConditionValue {
92 operator,
93 key,
94 position,
95 expected,
96 } => {
97 write!(f, "Invalid value for {operator} on key {key}")?;
98 if let Some(index) = position {
99 write!(f, " at element {index}")?;
100 }
101 write!(f, ": expected {expected}")
102 }
103 ConditionError::OperatorWithoutKey { operator } => write!(
104 f,
105 "{operator} cannot be used: no key of that kind holds a list"
106 ),
107 ConditionError::OperatorKeyMismatch {
108 operator,
109 key,
110 key_type,
111 } => write!(
112 f,
113 "{operator} cannot compare key {key}, which is {key_type}"
114 ),
115 }
116 }
117}
118
119impl std::error::Error for ConditionError {}
120
121impl From<ConditionError> for crate::error::AmiError {
122 fn from(err: ConditionError) -> Self {
123 crate::error::AmiError::InvalidParameter {
124 message: err.to_string(),
125 }
126 }
127}
128
129/// Evaluate a condition block
130///
131/// A condition block evaluates to `true` if ALL operator blocks evaluate to `true` (AND logic).
132///
133/// Parts are read in sorted order (operators, then keys); a false part does
134/// not stop the reading; the first part that cannot be compared stops the
135/// evaluation with its error. So a part that cannot be compared is an error
136/// even when another part is false, and the answer is deterministic (wami 001,
137/// read everything before deciding). It used to stop at the first FALSE part,
138/// in `HashMap` order: one request was refused on one parse and decided on the
139/// next.
140///
141/// # Errors
142///
143/// The first error in that order, from an unknown operator or a comparison
144/// that cannot be made.
145pub fn evaluate_condition_block(
146 block: &ConditionBlock,
147 context: &ConditionContext,
148) -> Result<bool, ConditionError> {
149 let mut operators: Vec<_> = block.iter().collect();
150 operators.sort_by_key(|(name, _)| *name);
151 let mut holds = true;
152 for (operator_name, key_value_map) in operators {
153 let operator = ConditionOperator::from_str(operator_name)?;
154 holds &= evaluate_operator_block(operator, key_value_map, context)?;
155 }
156 Ok(holds)
157}
158
159/// Evaluate an operator block
160///
161/// An operator block evaluates to `true` if ALL key-value pairs evaluate to
162/// `true` (AND logic) — keys read in sorted order, a false one not stopping
163/// the reading, the first that cannot be compared stopping it with its error.
164fn evaluate_operator_block(
165 operator: ConditionOperator,
166 key_value_map: &HashMap<String, ConditionValue>,
167 context: &ConditionContext,
168) -> Result<bool, ConditionError> {
169 let mut keys: Vec<_> = key_value_map.iter().collect();
170 keys.sort_by_key(|(key, _)| *key);
171 let mut holds = true;
172 for (key, expected_value) in keys {
173 let actual_value = get_context_value(key, context)
174 .map_err(|e| ConditionError::MissingContextKey(format!("{}: {}", key, e)))?;
175 // An error is not a `false`: answering it as one made the statement
176 // vanish, and a vanished Deny is a fail-open. `parse_condition_block`
177 // refuses every policy-side value an operator cannot read and every
178 // operator its key's declared type rules out, so what still errs here
179 // is the CONTEXT side — a custom key holding a value of another type,
180 // an `aws:SourceIp` that is no address — or a block built by hand
181 // without going through parse.
182 holds &= super::operators::evaluate_operator(operator, actual_value, expected_value)?;
183 }
184 Ok(holds)
185}
186
187/// Parse a condition block from JSON Value
188///
189/// Refuses, rather than defers to evaluation, everything evaluation could not
190/// read: a block that is not an object, an operator nobody defined, an
191/// operator that cannot compare its key's declared type, and a value its
192/// operator cannot compare (the table in `validate.rs`). Each used to evaluate
193/// to `false`, which made the statement carrying it vanish.
194///
195/// # Errors
196///
197/// [`ConditionError::InvalidConditionStructure`] for the shape,
198/// [`ConditionError::UnknownOperator`] for a misspelt operator,
199/// [`ConditionError::OperatorKeyMismatch`] for an operator its key rules out, and
200/// [`ConditionError::InvalidConditionValue`] for a value its operator cannot
201/// read — including a list where the operator reads one value (wami 002).
202pub fn parse_condition_block(value: &Value) -> Result<ConditionBlock, ConditionError> {
203 let obj = value.as_object().ok_or_else(|| {
204 ConditionError::InvalidConditionStructure("Condition must be an object".to_string())
205 })?;
206
207 let mut block = ConditionBlock::new();
208
209 for (operator_name, key_value_obj) in obj {
210 let operator = ConditionOperator::from_str(operator_name)?;
211 let key_value_map = key_value_obj.as_object().ok_or_else(|| {
212 ConditionError::InvalidConditionStructure(format!(
213 "Operator '{}' value must be an object",
214 operator_name
215 ))
216 })?;
217
218 let mut key_values = HashMap::new();
219 for (key, value) in key_value_map {
220 crate::validate::check_value(operator_name, operator, key, value)?;
221 let condition_value = ConditionValue::from(value.clone());
222 key_values.insert(key.clone(), condition_value);
223 }
224
225 block.insert(operator_name.clone(), key_values);
226 }
227
228 Ok(block)
229}