kz-server 0.2.0

JWT verification, CEL policies, and HTTP/MCP server for keyzero
Documentation
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(),
        }
    }
}