kz-server 0.2.0

JWT verification, CEL policies, and HTTP/MCP server for keyzero
Documentation
use anyhow::Result;
use clap::Subcommand;
use std::path::Path;

#[derive(Debug, Subcommand)]
pub enum ServerCommand {
    /// Start the keyzero server (HTTP, MCP, or proxy mode)
    Start {
        /// Path to the bundle YAML file
        #[arg(short, long)]
        bundle: std::path::PathBuf,

        /// Listen address
        #[arg(short, long, default_value = "0.0.0.0:8080")]
        listen: String,

        /// Run as an MCP server over stdio instead of HTTP
        #[arg(long, conflicts_with = "proxy")]
        mcp: bool,

        /// Run as a credential-swapping proxy instead of the standard server
        #[arg(long, conflicts_with = "mcp")]
        proxy: bool,
    },
    /// Validate a keyzero server bundle file
    Check {
        /// Path to the bundle YAML file
        #[arg(short, long)]
        bundle: std::path::PathBuf,
    },
}

pub async fn run(cmd: ServerCommand) -> Result<()> {
    match cmd {
        ServerCommand::Start {
            bundle,
            listen,
            mcp,
            proxy,
        } => start(&bundle, &listen, mcp, proxy).await,
        ServerCommand::Check { bundle } => check(&bundle).await,
    }
}

async fn start(bundle_path: &Path, listen: &str, mcp: bool, proxy: bool) -> Result<()> {
    tracing::info!("Loading bundle from {}", bundle_path.display());
    let bundle = crate::config::Bundle::load(bundle_path)?;

    if mcp {
        tracing::info!("Starting MCP server over stdio");
        let pipeline = crate::pipeline::Pipeline::new(bundle).await?;
        crate::mcp::serve_mcp(pipeline).await?;
    } else if proxy {
        let key_path = std::env::var("KEYZERO_PUBLIC_KEY_PATH").map_err(|_| {
            anyhow::anyhow!(
                "--proxy mode requires KEYZERO_PUBLIC_KEY_PATH env var pointing to an RSA public key PEM file\n  \
                 example: KEYZERO_PUBLIC_KEY_PATH=/path/to/key.pem kz server start --bundle policies.yaml --proxy"
            )
        })?;
        let public_key_pem = std::fs::read(&key_path).map_err(|e| {
            anyhow::anyhow!(
                "failed to read proxy public key at '{}': {}",
                key_path,
                e
            )
        })?;

        // Build resolvers via pipeline initialization, then extract them
        let pipeline = crate::pipeline::Pipeline::new(bundle.clone()).await?;
        let resolvers = pipeline.into_resolvers();

        let app = crate::proxy::build_proxy_router(bundle, &public_key_pem, resolvers).await?;
        let listener = tokio::net::TcpListener::bind(listen).await?;
        tracing::info!("Proxy listening on {listen}");
        axum::serve(listener, app).await?;
    } else {
        let app = crate::server::build_router(bundle).await?;
        let listener = tokio::net::TcpListener::bind(listen).await?;
        tracing::info!("Serving on {listen}");
        axum::serve(listener, app).await?;
    }

    Ok(())
}

async fn check(bundle_path: &Path) -> Result<()> {
    tracing::info!("Validating bundle from {}", bundle_path.display());
    let bundle = crate::config::Bundle::load(bundle_path)?;

    // Validate policies compile (CEL syntax check)
    let _ = crate::cel::PolicyEngine::new(bundle.policies.clone())?;

    // Validate all resource resolvers reference existing backends
    for resource in &bundle.resources {
        for resolver in &resource.resolvers {
            if !bundle.backends.contains_key(&resolver.backend) {
                anyhow::bail!(
                    "Resource '{}' resolver '{}' references unknown backend '{}'",
                    resource.id,
                    resolver.name,
                    resolver.backend
                );
            }
        }
    }

    // Validate tag mappings reference known issuers
    let issuer_names: Vec<&str> = bundle.issuers.iter().map(|i| i.name.as_str()).collect();
    for mapping in &bundle.tag_mappings {
        if !issuer_names.contains(&mapping.match_rule.issuer.as_str()) {
            anyhow::bail!(
                "Tag mapping references unknown issuer '{}'",
                mapping.match_rule.issuer
            );
        }
    }

    println!(
        "Bundle is valid: {} issuers, {} mappings, {} policies, {} resources, {} backends",
        bundle.issuers.len(),
        bundle.tag_mappings.len(),
        bundle.policies.len(),
        bundle.resources.len(),
        bundle.backends.len()
    );

    Ok(())
}