kz-server 0.3.0

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

use serde::Deserialize;

use crate::error::{Result, ServerError};

// ---------------------------------------------------------------------------
// Top-level bundle
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize)]
pub struct Bundle {
    pub version: String,
    #[serde(default)]
    pub issuers: Vec<Issuer>,
    #[serde(default)]
    pub policies: Vec<Policy>,
    #[serde(default)]
    pub resources: Vec<Resource>,
    #[serde(default)]
    pub backends: HashMap<String, BackendConfig>,
}

impl Bundle {
    /// Load a bundle from a YAML file on disk.
    pub fn load(path: &Path) -> Result<Self> {
        let content = std::fs::read_to_string(path)
            .map_err(|e| ServerError::Config(format!("cannot read bundle file: {e}")))?;
        let bundle: Bundle = serde_yaml::from_str(&content)
            .map_err(|e| ServerError::Config(format!("cannot parse bundle YAML: {e}")))?;
        Ok(bundle)
    }

    /// Return the most-specific matching resource for `ref_path`.
    ///
    /// Priority:
    /// 1. Exact match (`ref_pattern == ref_path`) wins immediately.
    /// 2. Glob matches — highest specificity (longest literal prefix) wins.
    /// 3. Tie-breaker: first defined in the bundle.
    pub fn match_resource(&self, ref_path: &str) -> Option<&Resource> {
        // 1. Exact match
        if let Some(r) = self.resources.iter().find(|r| r.ref_pattern == ref_path) {
            return Some(r);
        }

        // 2. Glob matches — pick highest specificity, first-defined on tie
        self.resources
            .iter()
            .filter(|r| r.is_glob() && glob_match::glob_match(&r.ref_pattern, ref_path))
            .max_by_key(|r| r.specificity())
    }
}

// ---------------------------------------------------------------------------
// Issuer
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize)]
pub struct Issuer {
    pub name: String,
    #[serde(rename = "type", default)]
    pub issuer_type: IssuerType,
    pub issuer_url: String,
    pub jwks_url: Option<String>,
    pub audience: Option<String>,
    pub static_keys: Option<Vec<StaticKey>>,
    /// Claim field overrides; merged on top of the built-in profile.
    pub map: Option<HashMap<String, String>>,
}

impl Issuer {
    /// Returns the effective claim map: built-in profile merged with any
    /// user-supplied overrides from `map`.
    pub fn effective_map(&self) -> HashMap<String, String> {
        let mut m = self.issuer_type.default_map();
        if let Some(overrides) = &self.map {
            m.extend(overrides.iter().map(|(k, v)| (k.clone(), v.clone())));
        }
        m
    }
}

// ---------------------------------------------------------------------------
// IssuerType
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize, Default)]
#[serde(rename_all = "kebab-case")]
pub enum IssuerType {
    GithubActions,
    Kubernetes,
    Gcp,
    Aws,
    #[default]
    Custom,
}

const GITHUB_ACTIONS_MAP: &[(&str, &str)] = &[
    ("org", "repository_owner"),
    ("service", "repository"),
    ("env", "environment"),
    ("action", "workflow"),
    ("branch", "ref"),
    ("actor", "actor"),
];

const KUBERNETES_MAP: &[(&str, &str)] = &[
    ("org", "namespace"),
    ("service", "serviceaccount"),
];

const GCP_MAP: &[(&str, &str)] = &[
    ("org", "project_id"),
    ("service", "email"),
];

const AWS_MAP: &[(&str, &str)] = &[
    ("org", "account_id"),
    ("service", "arn"),
];

impl IssuerType {
    /// Returns the built-in claim-mapping profile for this issuer type.
    /// Keys are canonical identity field names; values are JWT claim names.
    pub fn default_map(&self) -> HashMap<String, String> {
        let pairs: &[(&str, &str)] = match self {
            IssuerType::GithubActions => GITHUB_ACTIONS_MAP,
            IssuerType::Kubernetes => KUBERNETES_MAP,
            IssuerType::Gcp => GCP_MAP,
            IssuerType::Aws => AWS_MAP,
            IssuerType::Custom => &[],
        };

        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect()
    }
}

// ---------------------------------------------------------------------------
// StaticKey
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize)]
pub struct StaticKey {
    pub kid: String,
    pub alg: String,
    pub pem: String,
}

// ---------------------------------------------------------------------------
// Policy / Effect
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize)]
pub struct Policy {
    pub name: String,
    pub description: Option<String>,
    pub rule: String,
    pub effect: Effect,
}

#[derive(Debug, Clone, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum Effect {
    Allow,
    Deny,
}

// ---------------------------------------------------------------------------
// Resource / ResolverMode
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize)]
pub struct Resource {
    #[serde(rename = "ref")]
    pub ref_pattern: String,
    pub resolver: String,
    #[serde(default)]
    pub mode: ResolverMode,
    pub credential_location: Option<String>,
    pub ttl: Option<u64>,
    pub path: Option<String>,
    pub field: Option<String>,
    pub role_arn: Option<String>,
    pub duration_seconds: Option<u64>,
    pub secret_id: Option<String>,
}

impl Resource {
    /// Length of the literal prefix before the first glob character.
    pub fn specificity(&self) -> usize {
        self.ref_pattern
            .find(|c| c == '*' || c == '?' || c == '[')
            .unwrap_or(self.ref_pattern.len())
    }

    /// Returns `true` if `ref_pattern` contains any glob metacharacter.
    pub fn is_glob(&self) -> bool {
        self.ref_pattern
            .contains(|c| c == '*' || c == '?' || c == '[')
    }
}

#[derive(Debug, Clone, Deserialize, PartialEq, Default)]
#[serde(rename_all = "snake_case")]
pub enum ResolverMode {
    #[default]
    Direct,
    ShortLived,
}

// ---------------------------------------------------------------------------
// BackendConfig / BackendType / BackendAuth
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize)]
pub struct BackendConfig {
    #[serde(rename = "type")]
    pub backend_type: BackendType,
    pub address: Option<String>,
    pub auth: Option<BackendAuth>,
    pub region: Option<String>,
    pub path: Option<String>,
    pub vault: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BackendType {
    EnvFile,
    HashicorpVault,
    AwsSecretsManager,
    AwsSts,
    #[serde(rename = "1password_cli")]
    OnepasswordCli,
}

impl BackendType {
    /// Maps to the secret-resolvers crate resolver name.
    pub fn as_resolver_name(&self) -> &'static str {
        match self {
            BackendType::EnvFile => "env_file",
            BackendType::HashicorpVault => "hashicorp",
            BackendType::AwsSecretsManager => "aws",
            BackendType::AwsSts => "aws_sts",
            BackendType::OnepasswordCli => "1password",
        }
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct BackendAuth {
    pub method: String,
    pub role: Option<String>,
}