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
use std::collections::HashMap;
use cel_interpreter::{Context, Program, Value};
use crate::config::{Effect, Policy};
use crate::error::{AgentError, Result};
use crate::tags::json_value_to_string;
const DEFAULT_DENY_POLICY: &str = "default-deny";
const DEFAULT_DENY_REASON: &str = "no matching policy found";
/// Input to the policy engine for a single evaluation.
pub struct PolicyInput {
pub caller_tags: Vec<String>,
pub resource_tags: Vec<String>,
pub claims: HashMap<String, serde_json::Value>,
}
/// The decision returned by the policy engine after evaluating all policies.
#[derive(Debug, PartialEq)]
pub enum PolicyDecision {
Allow { policy: String },
Deny { policy: String, reason: String },
}
/// A compiled policy ready for evaluation.
struct CompiledPolicy {
name: String,
match_resource_tags: Option<Vec<String>>,
program: Program,
effect: Effect,
}
/// The CEL policy engine evaluates policies top-down, first-match-wins.
pub struct PolicyEngine {
policies: Vec<CompiledPolicy>,
}
impl PolicyEngine {
/// Create a new PolicyEngine by compiling all CEL expressions in the provided policies.
pub fn new(policies: Vec<Policy>) -> Result<Self> {
let mut compiled = Vec::with_capacity(policies.len());
for policy in policies {
let program = Program::compile(&policy.rule).map_err(|e| {
AgentError::Config(format!(
"failed to compile CEL rule for policy '{}': {}",
policy.name, e
))
})?;
let match_resource_tags = policy
.match_rule
.map(|m| m.resource_tags)
.filter(|tags| !tags.is_empty());
compiled.push(CompiledPolicy {
name: policy.name,
match_resource_tags,
program,
effect: policy.effect,
});
}
Ok(PolicyEngine { policies: compiled })
}
/// Evaluate the policy engine against the given input.
///
/// Policies are evaluated top-down, first-match-wins:
/// 1. If a policy has match_rule.resource_tags, all must be present in input.resource_tags.
/// If not, the policy is skipped.
/// 2. A CEL context is created with caller_tags, resource_tags, and claims variables.
/// 3. The compiled CEL program is executed.
/// 4. If the result is true, the policy's effect (allow/deny) is returned.
/// 5. If no policy matched, an implicit deny is returned.
pub fn evaluate(&self, input: &PolicyInput) -> PolicyDecision {
for policy in &self.policies {
// Step 1: Check resource tag filter
if let Some(ref required_tags) = policy.match_resource_tags {
let all_present = required_tags
.iter()
.all(|tag| input.resource_tags.contains(tag));
if !all_present {
continue;
}
}
// Step 2: Create CEL context with variables
let mut context = Context::default();
let caller_tags_val: Vec<String> = input.caller_tags.clone();
let resource_tags_val: Vec<String> = input.resource_tags.clone();
context.add_variable_from_value("caller_tags", Value::from(caller_tags_val));
context.add_variable_from_value("resource_tags", Value::from(resource_tags_val));
// Add claims as a map so CEL rules can reference claims.sub, claims.iss, etc.
let claims_map: HashMap<String, String> = input
.claims
.iter()
.map(|(k, v)| (k.clone(), json_value_to_string(v)))
.collect();
context.add_variable_from_value("claims", Value::from(claims_map));
// Step 3: Execute the CEL program
match policy.program.execute(&context) {
Ok(Value::Bool(true)) => {
// Step 4: Return decision based on effect
return match policy.effect {
Effect::Allow => PolicyDecision::Allow {
policy: policy.name.clone(),
},
Effect::Deny => PolicyDecision::Deny {
policy: policy.name.clone(),
reason: format!("denied by policy '{}'", policy.name),
},
};
}
Ok(Value::Bool(false)) => {
// Rule did not match, continue to next policy
continue;
}
Ok(other) => {
tracing::warn!(
policy = %policy.name,
result = ?other,
"CEL rule returned non-boolean value, skipping policy"
);
continue;
}
Err(e) => {
tracing::error!(
policy = %policy.name,
error = %e,
"CEL rule execution failed — returning error instead of silently skipping"
);
return PolicyDecision::Deny {
policy: policy.name.clone(),
reason: format!("policy evaluation error: {e}"),
};
}
}
}
// Step 5: Implicit deny if no policy matched
PolicyDecision::Deny {
policy: DEFAULT_DENY_POLICY.to_string(),
reason: DEFAULT_DENY_REASON.to_string(),
}
}
}