Skip to main content

kz_server/
policy.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3
4use cel_interpreter::{Context, Program, Value};
5use tracing::warn;
6
7use crate::config::{Effect, Policy};
8use crate::error::{Result, ServerError};
9use crate::identity::Identity;
10
11// ---------------------------------------------------------------------------
12// Decision
13// ---------------------------------------------------------------------------
14
15#[derive(Debug, Clone)]
16pub enum PolicyDecision {
17    Allow { policy: String },
18    Deny { policy: String, reason: String },
19}
20
21// ---------------------------------------------------------------------------
22// Input
23// ---------------------------------------------------------------------------
24
25pub struct PolicyInput<'a> {
26    pub identity: &'a Identity,
27    pub ref_path: &'a str,
28    pub context: &'a HashMap<String, serde_json::Value>,
29}
30
31// ---------------------------------------------------------------------------
32// Compiled policy
33// ---------------------------------------------------------------------------
34
35struct CompiledPolicy {
36    name: String,
37    program: Program,
38    effect: Effect,
39}
40
41// ---------------------------------------------------------------------------
42// Engine
43// ---------------------------------------------------------------------------
44
45pub struct PolicyEngine {
46    policies: Vec<CompiledPolicy>,
47}
48
49impl PolicyEngine {
50    /// Compile a list of policy definitions into a ready-to-evaluate engine.
51    ///
52    /// Glob patterns inside `ref.matches('...')` are automatically converted
53    /// to regex before compilation (e.g., `secret/**` becomes `^secret/.*$`).
54    pub fn new(policies: &[Policy]) -> Result<Self> {
55        let compiled = policies
56            .iter()
57            .map(|p| {
58                let processed_rule = preprocess_rule(&p.rule);
59                let program = Program::compile(&processed_rule).map_err(|e| {
60                    ServerError::Config(format!(
61                        "failed to compile CEL rule for policy '{}': {e}",
62                        p.name
63                    ))
64                })?;
65                Ok(CompiledPolicy {
66                    name: p.name.clone(),
67                    program,
68                    effect: p.effect.clone(),
69                })
70            })
71            .collect::<Result<Vec<_>>>()?;
72
73        Ok(Self { policies: compiled })
74    }
75
76    /// First-match-wins evaluation of the policy chain.
77    pub fn evaluate(&self, input: &PolicyInput<'_>) -> PolicyDecision {
78        for cp in &self.policies {
79            let mut ctx = Context::default();
80
81            // Normalized identity fields
82            ctx.add_variable_from_value("issuer", Value::String(Arc::new(input.identity.issuer.clone())));
83            ctx.add_variable_from_value("org", Value::String(Arc::new(input.identity.org.clone())));
84            ctx.add_variable_from_value("service", Value::String(Arc::new(input.identity.service.clone())));
85            ctx.add_variable_from_value("env", Value::String(Arc::new(input.identity.env.clone())));
86            ctx.add_variable_from_value("action", Value::String(Arc::new(input.identity.action.clone())));
87            ctx.add_variable_from_value("branch", Value::String(Arc::new(input.identity.branch.clone())));
88            ctx.add_variable_from_value("actor", Value::String(Arc::new(input.identity.actor.clone())));
89
90            // Groups as list of strings
91            let groups: Vec<Value> = input
92                .identity
93                .groups
94                .iter()
95                .map(|g| Value::String(Arc::new(g.clone())))
96                .collect();
97            ctx.add_variable_from_value("groups", Value::List(Arc::new(groups)));
98
99            // ref path
100            ctx.add_variable_from_value("ref", Value::String(Arc::new(input.ref_path.to_string())));
101
102            // claims map
103            ctx.add_variable_from_value("claims", json_map_to_cel(&input.identity.claims));
104
105            // context map
106            ctx.add_variable_from_value("context", json_map_to_cel(input.context));
107
108            match cp.program.execute(&ctx) {
109                Ok(Value::Bool(true)) => {
110                    return match cp.effect {
111                        Effect::Allow => PolicyDecision::Allow {
112                            policy: cp.name.clone(),
113                        },
114                        Effect::Deny => PolicyDecision::Deny {
115                            policy: cp.name.clone(),
116                            reason: "explicitly denied by policy".into(),
117                        },
118                    };
119                }
120                Ok(Value::Bool(false)) => continue,
121                Ok(other) => {
122                    warn!(
123                        policy = cp.name,
124                        result = ?other,
125                        "CEL rule returned non-boolean value, skipping"
126                    );
127                    continue;
128                }
129                Err(e) => {
130                    warn!(policy = cp.name, error = %e, "CEL rule execution error");
131                    return PolicyDecision::Deny {
132                        policy: cp.name.clone(),
133                        reason: format!("CEL execution error: {e}"),
134                    };
135                }
136            }
137        }
138
139        PolicyDecision::Deny {
140            policy: "implicit-deny".into(),
141            reason: "no matching policy found".into(),
142        }
143    }
144}
145
146// ---------------------------------------------------------------------------
147// JSON → CEL value conversion
148// ---------------------------------------------------------------------------
149
150fn json_to_cel_value(v: &serde_json::Value) -> Value {
151    match v {
152        serde_json::Value::String(s) => Value::String(Arc::new(s.clone())),
153        serde_json::Value::Bool(b) => Value::Bool(*b),
154        serde_json::Value::Number(n) => {
155            if let Some(i) = n.as_i64() {
156                Value::Int(i)
157            } else {
158                Value::Float(n.as_f64().unwrap_or(0.0))
159            }
160        }
161        serde_json::Value::Array(arr) => {
162            let items: Vec<Value> = arr.iter().map(json_to_cel_value).collect();
163            Value::List(Arc::new(items))
164        }
165        serde_json::Value::Object(obj) => {
166            let map: HashMap<cel_interpreter::objects::Key, Value> = obj
167                .iter()
168                .map(|(k, v)| {
169                    (
170                        cel_interpreter::objects::Key::String(Arc::new(k.clone())),
171                        json_to_cel_value(v),
172                    )
173                })
174                .collect();
175            Value::Map(map.into())
176        }
177        serde_json::Value::Null => Value::String(Arc::new(String::new())),
178    }
179}
180
181// ---------------------------------------------------------------------------
182// Glob-to-regex preprocessing for ref.matches()
183// ---------------------------------------------------------------------------
184
185/// Convert glob patterns in `ref.matches('...')` calls to regex.
186///
187/// Transforms: `ref.matches('secret/data/prod/**')` into
188/// `ref.matches('^secret/data/prod/.*$')`.
189///
190/// Supports both single-quoted and double-quoted patterns.
191fn preprocess_rule(rule: &str) -> String {
192    let mut result = rule.to_string();
193    let mut search_from = 0;
194
195    // Handle single-quoted patterns: ref.matches('...')
196    let marker = "ref.matches('";
197    loop {
198        let Some(start) = result[search_from..].find(marker) else {
199            break;
200        };
201        let abs_start = search_from + start;
202        let pattern_start = abs_start + marker.len();
203        let Some(end) = result[pattern_start..].find('\'') else {
204            break;
205        };
206        let pattern_end = pattern_start + end;
207        let glob = result[pattern_start..pattern_end].to_string();
208        let regex = glob_to_regex(&glob);
209        let replacement = format!("ref.matches('^{regex}$')");
210        let replacement_len = replacement.len();
211        result = format!(
212            "{}{}{}",
213            &result[..abs_start],
214            replacement,
215            &result[pattern_end + 2..]
216        );
217        search_from = abs_start + replacement_len;
218    }
219
220    // Handle double-quoted patterns: ref.matches("...")
221    let marker = "ref.matches(\"";
222    search_from = 0;
223    loop {
224        let Some(start) = result[search_from..].find(marker) else {
225            break;
226        };
227        let abs_start = search_from + start;
228        let pattern_start = abs_start + marker.len();
229        let Some(end) = result[pattern_start..].find('"') else {
230            break;
231        };
232        let pattern_end = pattern_start + end;
233        let glob = result[pattern_start..pattern_end].to_string();
234        let regex = glob_to_regex(&glob);
235        let replacement = format!("ref.matches(\"^{regex}$\")");
236        let replacement_len = replacement.len();
237        result = format!(
238            "{}{}{}",
239            &result[..abs_start],
240            replacement,
241            &result[pattern_end + 2..]
242        );
243        search_from = abs_start + replacement_len;
244    }
245
246    result
247}
248
249/// Convert a glob pattern to a regex string.
250///
251/// - `**` matches any characters (including `/`)
252/// - `*` matches any characters except `/`
253/// - Regex metacharacters in literal portions are escaped.
254fn glob_to_regex(glob: &str) -> String {
255    let mut result = String::new();
256    let mut chars = glob.chars().peekable();
257    while let Some(c) = chars.next() {
258        match c {
259            '*' => {
260                if chars.peek() == Some(&'*') {
261                    chars.next();
262                    result.push_str(".*");
263                } else {
264                    result.push_str("[^/]*");
265                }
266            }
267            '.' | '+' | '(' | ')' | '{' | '}' | '[' | ']' | '^' | '$' | '|' | '\\' => {
268                result.push('\\');
269                result.push(c);
270            }
271            _ => result.push(c),
272        }
273    }
274    result
275}
276
277fn json_map_to_cel(map: &HashMap<String, serde_json::Value>) -> Value {
278    let cel_map: HashMap<cel_interpreter::objects::Key, Value> = map
279        .iter()
280        .map(|(k, v)| {
281            (
282                cel_interpreter::objects::Key::String(Arc::new(k.clone())),
283                json_to_cel_value(v),
284            )
285        })
286        .collect();
287    Value::Map(cel_map.into())
288}