kz-server 0.3.0

JWT verification, CEL policies, and HTTP/MCP server for keyzero
Documentation
use std::collections::HashMap;
use std::sync::Arc;

use cel_interpreter::{Context, Program, Value};
use tracing::warn;

use crate::config::{Effect, Policy};
use crate::error::{Result, ServerError};
use crate::identity::Identity;

// ---------------------------------------------------------------------------
// Decision
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
pub enum PolicyDecision {
    Allow { policy: String },
    Deny { policy: String, reason: String },
}

// ---------------------------------------------------------------------------
// Input
// ---------------------------------------------------------------------------

pub struct PolicyInput<'a> {
    pub identity: &'a Identity,
    pub ref_path: &'a str,
    pub context: &'a HashMap<String, serde_json::Value>,
}

// ---------------------------------------------------------------------------
// Compiled policy
// ---------------------------------------------------------------------------

struct CompiledPolicy {
    name: String,
    program: Program,
    effect: Effect,
}

// ---------------------------------------------------------------------------
// Engine
// ---------------------------------------------------------------------------

pub struct PolicyEngine {
    policies: Vec<CompiledPolicy>,
}

impl PolicyEngine {
    /// Compile a list of policy definitions into a ready-to-evaluate engine.
    ///
    /// Glob patterns inside `ref.matches('...')` are automatically converted
    /// to regex before compilation (e.g., `secret/**` becomes `^secret/.*$`).
    pub fn new(policies: &[Policy]) -> Result<Self> {
        let compiled = policies
            .iter()
            .map(|p| {
                let processed_rule = preprocess_rule(&p.rule);
                let program = Program::compile(&processed_rule).map_err(|e| {
                    ServerError::Config(format!(
                        "failed to compile CEL rule for policy '{}': {e}",
                        p.name
                    ))
                })?;
                Ok(CompiledPolicy {
                    name: p.name.clone(),
                    program,
                    effect: p.effect.clone(),
                })
            })
            .collect::<Result<Vec<_>>>()?;

        Ok(Self { policies: compiled })
    }

    /// First-match-wins evaluation of the policy chain.
    pub fn evaluate(&self, input: &PolicyInput<'_>) -> PolicyDecision {
        for cp in &self.policies {
            let mut ctx = Context::default();

            // Normalized identity fields
            ctx.add_variable_from_value("issuer", Value::String(Arc::new(input.identity.issuer.clone())));
            ctx.add_variable_from_value("org", Value::String(Arc::new(input.identity.org.clone())));
            ctx.add_variable_from_value("service", Value::String(Arc::new(input.identity.service.clone())));
            ctx.add_variable_from_value("env", Value::String(Arc::new(input.identity.env.clone())));
            ctx.add_variable_from_value("action", Value::String(Arc::new(input.identity.action.clone())));
            ctx.add_variable_from_value("branch", Value::String(Arc::new(input.identity.branch.clone())));
            ctx.add_variable_from_value("actor", Value::String(Arc::new(input.identity.actor.clone())));

            // Groups as list of strings
            let groups: Vec<Value> = input
                .identity
                .groups
                .iter()
                .map(|g| Value::String(Arc::new(g.clone())))
                .collect();
            ctx.add_variable_from_value("groups", Value::List(Arc::new(groups)));

            // ref path
            ctx.add_variable_from_value("ref", Value::String(Arc::new(input.ref_path.to_string())));

            // claims map
            ctx.add_variable_from_value("claims", json_map_to_cel(&input.identity.claims));

            // context map
            ctx.add_variable_from_value("context", json_map_to_cel(input.context));

            match cp.program.execute(&ctx) {
                Ok(Value::Bool(true)) => {
                    return match cp.effect {
                        Effect::Allow => PolicyDecision::Allow {
                            policy: cp.name.clone(),
                        },
                        Effect::Deny => PolicyDecision::Deny {
                            policy: cp.name.clone(),
                            reason: "explicitly denied by policy".into(),
                        },
                    };
                }
                Ok(Value::Bool(false)) => continue,
                Ok(other) => {
                    warn!(
                        policy = cp.name,
                        result = ?other,
                        "CEL rule returned non-boolean value, skipping"
                    );
                    continue;
                }
                Err(e) => {
                    warn!(policy = cp.name, error = %e, "CEL rule execution error");
                    return PolicyDecision::Deny {
                        policy: cp.name.clone(),
                        reason: format!("CEL execution error: {e}"),
                    };
                }
            }
        }

        PolicyDecision::Deny {
            policy: "implicit-deny".into(),
            reason: "no matching policy found".into(),
        }
    }
}

// ---------------------------------------------------------------------------
// JSON → CEL value conversion
// ---------------------------------------------------------------------------

fn json_to_cel_value(v: &serde_json::Value) -> Value {
    match v {
        serde_json::Value::String(s) => Value::String(Arc::new(s.clone())),
        serde_json::Value::Bool(b) => Value::Bool(*b),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                Value::Int(i)
            } else {
                Value::Float(n.as_f64().unwrap_or(0.0))
            }
        }
        serde_json::Value::Array(arr) => {
            let items: Vec<Value> = arr.iter().map(json_to_cel_value).collect();
            Value::List(Arc::new(items))
        }
        serde_json::Value::Object(obj) => {
            let map: HashMap<cel_interpreter::objects::Key, Value> = obj
                .iter()
                .map(|(k, v)| {
                    (
                        cel_interpreter::objects::Key::String(Arc::new(k.clone())),
                        json_to_cel_value(v),
                    )
                })
                .collect();
            Value::Map(map.into())
        }
        serde_json::Value::Null => Value::String(Arc::new(String::new())),
    }
}

// ---------------------------------------------------------------------------
// Glob-to-regex preprocessing for ref.matches()
// ---------------------------------------------------------------------------

/// Convert glob patterns in `ref.matches('...')` calls to regex.
///
/// Transforms: `ref.matches('secret/data/prod/**')` into
/// `ref.matches('^secret/data/prod/.*$')`.
///
/// Supports both single-quoted and double-quoted patterns.
fn preprocess_rule(rule: &str) -> String {
    let mut result = rule.to_string();
    let mut search_from = 0;

    // Handle single-quoted patterns: ref.matches('...')
    let marker = "ref.matches('";
    loop {
        let Some(start) = result[search_from..].find(marker) else {
            break;
        };
        let abs_start = search_from + start;
        let pattern_start = abs_start + marker.len();
        let Some(end) = result[pattern_start..].find('\'') else {
            break;
        };
        let pattern_end = pattern_start + end;
        let glob = result[pattern_start..pattern_end].to_string();
        let regex = glob_to_regex(&glob);
        let replacement = format!("ref.matches('^{regex}$')");
        let replacement_len = replacement.len();
        result = format!(
            "{}{}{}",
            &result[..abs_start],
            replacement,
            &result[pattern_end + 2..]
        );
        search_from = abs_start + replacement_len;
    }

    // Handle double-quoted patterns: ref.matches("...")
    let marker = "ref.matches(\"";
    search_from = 0;
    loop {
        let Some(start) = result[search_from..].find(marker) else {
            break;
        };
        let abs_start = search_from + start;
        let pattern_start = abs_start + marker.len();
        let Some(end) = result[pattern_start..].find('"') else {
            break;
        };
        let pattern_end = pattern_start + end;
        let glob = result[pattern_start..pattern_end].to_string();
        let regex = glob_to_regex(&glob);
        let replacement = format!("ref.matches(\"^{regex}$\")");
        let replacement_len = replacement.len();
        result = format!(
            "{}{}{}",
            &result[..abs_start],
            replacement,
            &result[pattern_end + 2..]
        );
        search_from = abs_start + replacement_len;
    }

    result
}

/// Convert a glob pattern to a regex string.
///
/// - `**` matches any characters (including `/`)
/// - `*` matches any characters except `/`
/// - Regex metacharacters in literal portions are escaped.
fn glob_to_regex(glob: &str) -> String {
    let mut result = String::new();
    let mut chars = glob.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '*' => {
                if chars.peek() == Some(&'*') {
                    chars.next();
                    result.push_str(".*");
                } else {
                    result.push_str("[^/]*");
                }
            }
            '.' | '+' | '(' | ')' | '{' | '}' | '[' | ']' | '^' | '$' | '|' | '\\' => {
                result.push('\\');
                result.push(c);
            }
            _ => result.push(c),
        }
    }
    result
}

fn json_map_to_cel(map: &HashMap<String, serde_json::Value>) -> Value {
    let cel_map: HashMap<cel_interpreter::objects::Key, Value> = map
        .iter()
        .map(|(k, v)| {
            (
                cel_interpreter::objects::Key::String(Arc::new(k.clone())),
                json_to_cel_value(v),
            )
        })
        .collect();
    Value::Map(cel_map.into())
}