Skip to main content

wami_condition/
lib.rs

1//! wami-condition crate
2//!
3//! This crate provides policy condition key evaluation used by WAMI.
4
5// Re-export core error module so paths like `crate::error::AmiError` resolve
6pub use wami_core::error;
7
8// Public modules
9pub mod context;
10pub mod evaluator;
11pub mod keys;
12pub mod operators;
13mod validate;
14
15#[cfg(test)]
16mod tests;
17
18pub use context::ConditionContext;
19pub use evaluator::{evaluate_condition_block, ConditionError};
20pub use keys::get_context_value;
21pub use operators::ConditionOperator;
22
23use serde_json::Value;
24use std::collections::HashMap;
25
26/// A condition block is a map of operator names to key-value pairs
27pub type ConditionBlock = HashMap<String, HashMap<String, ConditionValue>>;
28
29/// A condition value can be a string, number, boolean, or array of strings
30#[derive(Debug, Clone, PartialEq)]
31pub enum ConditionValue {
32    String(String),
33    Number(f64),
34    Boolean(bool),
35    Array(Vec<String>),
36}
37
38impl ConditionValue {
39    /// The variant's name — what an error says in place of the value, so a
40    /// request value or a policy value never reaches a log (wami 001).
41    pub fn kind(&self) -> &'static str {
42        match self {
43            ConditionValue::String(_) => "String",
44            ConditionValue::Number(_) => "Number",
45            ConditionValue::Boolean(_) => "Boolean",
46            ConditionValue::Array(_) => "Array",
47        }
48    }
49
50    fn mismatch(&self, expected: &str) -> ConditionError {
51        ConditionError::TypeMismatch {
52            expected: expected.to_string(),
53            actual: self.kind().to_string(),
54        }
55    }
56
57    /// The value as text: a string, or a number or boolean written out.
58    ///
59    /// # Errors
60    ///
61    /// [`ConditionError::TypeMismatch`] for a list.
62    pub fn as_string(&self) -> Result<String, ConditionError> {
63        match self {
64            ConditionValue::String(s) => Ok(s.clone()),
65            ConditionValue::Number(n) => Ok(n.to_string()),
66            ConditionValue::Boolean(b) => Ok(b.to_string()),
67            ConditionValue::Array(_) => Err(self.mismatch("String")),
68        }
69    }
70
71    /// The value as a finite number.
72    ///
73    /// Parse reads a policy's numbers through this very function, so what it
74    /// refuses is refused at parse too. `"NaN"` and `"inf"` are refused: they
75    /// read as `f64`, and a comparison with them is never met.
76    ///
77    /// # Errors
78    ///
79    /// [`ConditionError::TypeMismatch`] for anything else.
80    pub fn as_number(&self) -> Result<f64, ConditionError> {
81        match self {
82            ConditionValue::Number(n) if n.is_finite() => Ok(*n),
83            ConditionValue::String(s) => s
84                .parse::<f64>()
85                .ok()
86                .filter(|n| n.is_finite())
87                .ok_or_else(|| self.mismatch("a finite Number")),
88            _ => Err(self.mismatch("a finite Number")),
89        }
90    }
91
92    /// The value as a boolean: `true`/`false`, as such or as a string.
93    ///
94    /// # Errors
95    ///
96    /// [`ConditionError::InvalidBooleanValue`] for any other string,
97    /// [`ConditionError::TypeMismatch`] for a number or a list.
98    pub fn as_boolean(&self) -> Result<bool, ConditionError> {
99        match self {
100            ConditionValue::Boolean(b) => Ok(*b),
101            ConditionValue::String(s) => match s.as_str() {
102                "true" => Ok(true),
103                "false" => Ok(false),
104                _ => Err(ConditionError::InvalidBooleanValue),
105            },
106            _ => Err(self.mismatch("Boolean")),
107        }
108    }
109
110    /// The value as a list of strings.
111    ///
112    /// # Errors
113    ///
114    /// [`ConditionError::TypeMismatch`] for a scalar.
115    pub fn as_array(&self) -> Result<&Vec<String>, ConditionError> {
116        match self {
117            ConditionValue::Array(arr) => Ok(arr),
118            _ => Err(self.mismatch("Array")),
119        }
120    }
121}
122
123impl From<Value> for ConditionValue {
124    fn from(value: Value) -> Self {
125        match value {
126            Value::String(s) => ConditionValue::String(s),
127            Value::Number(n) => ConditionValue::Number(n.as_f64().unwrap_or(0.0)),
128            Value::Bool(b) => ConditionValue::Boolean(b),
129            Value::Array(arr) => {
130                let strings: Vec<String> = arr
131                    .into_iter()
132                    .filter_map(|v| v.as_str().map(String::from))
133                    .collect();
134                ConditionValue::Array(strings)
135            }
136            Value::Null => ConditionValue::String("".to_string()),
137            Value::Object(_) => ConditionValue::String("".to_string()), // Invalid, but handle gracefully
138        }
139    }
140}
141
142// Provide the expected namespace used by tests and downstream code:
143// `crate::wami::policies::condition::...`
144pub mod wami {
145    pub mod policies {
146        pub mod condition {
147            // Re-export modules and symbols so callers can use
148            // `crate::wami::policies::condition::{evaluator::..., ConditionContext, ...}`
149            pub use crate::{
150                context, evaluate_condition_block, evaluator, get_context_value, keys, operators,
151                ConditionBlock, ConditionContext, ConditionOperator, ConditionValue,
152            };
153        }
154    }
155}