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 secret_resolvers::{ExposeSecret, Request, SecretResolver};
use serde::{Deserialize, Serialize};
use crate::config::{BackendConfig, Bundle, ResolverMode, Resource};
use crate::error::{Result, ServerError};
use crate::identity::{Identity, JwtVerifier};
use crate::policy::{PolicyDecision, PolicyEngine, PolicyInput};
use crate::security::validate_ref;
use crate::signing::Signer;

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

const VAULT_TOKEN_ENV: &str = "VAULT_TOKEN";
const SIGNING_KEY_ENV: &str = "KEYZERO_SIGNING_KEY_PATH";
const PROXY_URL_ENV: &str = "KEYZERO_PROXY_URL";
const DEFAULT_TTL: u64 = 300;

// ---------------------------------------------------------------------------
// Request / Response types
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
pub struct ResolveRequest {
    #[serde(rename = "ref")]
    pub ref_path: Option<String>,
    pub refs: Option<Vec<String>>,
    #[serde(default)]
    pub context: Option<HashMap<String, serde_json::Value>>,
}

/// Response for /v1/resolve. Always wraps results in a `results` map,
/// even for single-ref requests, for client consistency.
#[derive(Debug, Serialize)]
pub struct ResolveResponse {
    pub results: HashMap<String, RefResult>,
}

#[derive(Debug, Serialize)]
pub struct RefResult {
    pub allowed: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policy: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mode: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub token: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub proxy: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ttl: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

impl Default for RefResult {
    fn default() -> Self {
        Self {
            allowed: false,
            policy: None,
            mode: None,
            value: None,
            token: None,
            proxy: None,
            ttl: None,
            reason: None,
            error: None,
        }
    }
}

impl RefResult {
    fn denied(policy: &str, reason: &str) -> Self {
        Self {
            allowed: false,
            policy: Some(policy.to_string()),
            reason: Some(reason.to_string()),
            ..Default::default()
        }
    }
}

// ---------------------------------------------------------------------------
// Pipeline
// ---------------------------------------------------------------------------

pub struct Pipeline {
    pub(crate) bundle: Bundle,
    verifier: JwtVerifier,
    engine: PolicyEngine,
    resolvers: HashMap<String, Arc<dyn SecretResolver>>,
    signer: Option<Signer>,
    proxy_url: Option<String>,
}

impl Pipeline {
    /// Create a new pipeline from a bundle configuration.
    pub async fn new(bundle: Bundle) -> Result<Self> {
        // 1. JWT verifier
        let verifier = JwtVerifier::new(bundle.issuers.clone());

        // 2. Policy engine (compile CEL)
        let engine = PolicyEngine::new(&bundle.policies)?;

        // 3. Resolvers from backends
        let mut resolvers: HashMap<String, Arc<dyn SecretResolver>> = HashMap::new();
        for (name, backend) in &bundle.backends {
            let config_map = backend_to_config(backend);
            let resolver = secret_resolvers::registry::create_resolver(
                backend.backend_type.as_resolver_name(),
                config_map,
            )
            .await
            .map_err(|e| {
                ServerError::Config(format!("failed to create resolver '{name}': {e}"))
            })?;
            resolvers.insert(name.clone(), resolver);
        }

        // 4. Optional signer
        let signer = match std::env::var(SIGNING_KEY_ENV) {
            Ok(path) => {
                let pem = std::fs::read(&path).map_err(|e| {
                    ServerError::Config(format!("cannot read signing key at '{path}': {e}"))
                })?;
                Some(Signer::new(&pem, "keyzero")?)
            }
            Err(_) => None,
        };

        // 5. Optional proxy URL
        let proxy_url = std::env::var(PROXY_URL_ENV).ok();

        Ok(Self {
            bundle,
            verifier,
            engine,
            resolvers,
            signer,
            proxy_url,
        })
    }

    /// Batch resolve: verify JWT once, resolve each ref independently.
    pub async fn resolve(
        &self,
        token: &str,
        request: &ResolveRequest,
    ) -> Result<ResolveResponse> {
        // Extract refs
        let refs = match (&request.refs, &request.ref_path) {
            (Some(refs), _) => refs.clone(),
            (None, Some(r)) => vec![r.clone()],
            (None, None) => {
                return Err(ServerError::Resolution(
                    "request must contain 'ref' or 'refs'".into(),
                ))
            }
        };

        // Validate all refs upfront
        for r in &refs {
            validate_ref(r)?;
        }

        // Verify JWT once
        let identity = self.verifier.verify(token).await?;

        let context = request.context.clone().unwrap_or_default();

        // Resolve each ref
        let mut results = HashMap::new();
        for ref_path in &refs {
            let result = self
                .resolve_single_ref(&identity, ref_path, &context)
                .await;
            results.insert(ref_path.clone(), result);
        }

        Ok(ResolveResponse { results })
    }

    /// Resolve a single ref (used by MCP fetch tool).
    /// Returns the secret value and a reference to the matched resource.
    pub async fn resolve_single(
        &self,
        token: &str,
        ref_path: &str,
        context: &HashMap<String, serde_json::Value>,
    ) -> Result<(String, &Resource)> {
        validate_ref(ref_path)?;
        let identity = self.verifier.verify(token).await?;

        let resource = self
            .bundle
            .match_resource(ref_path)
            .ok_or_else(|| ServerError::UnknownRef(ref_path.into()))?;

        let input = PolicyInput {
            identity: &identity,
            ref_path,
            context,
        };
        match self.engine.evaluate(&input) {
            PolicyDecision::Allow { .. } => {}
            PolicyDecision::Deny { policy, reason } => {
                return Err(ServerError::Resolution(format!(
                    "denied by policy '{policy}': {reason}"
                )));
            }
        }

        let value = self.resolve_from_backend(ref_path, resource).await?;
        Ok((value, resource))
    }

    /// Consume the pipeline and return the resolvers map (for proxy mode).
    pub fn into_resolvers(self) -> HashMap<String, Arc<dyn SecretResolver>> {
        self.resolvers
    }

    /// Borrow the bundle.
    pub fn bundle(&self) -> &Bundle {
        &self.bundle
    }

    // -----------------------------------------------------------------------
    // Internal helpers
    // -----------------------------------------------------------------------

    async fn resolve_single_ref(
        &self,
        identity: &Identity,
        ref_path: &str,
        context: &HashMap<String, serde_json::Value>,
    ) -> RefResult {
        // 1. Match resource
        let resource = match self.bundle.match_resource(ref_path) {
            Some(r) => r,
            None => {
                return RefResult {
                    error: Some("no resource matches ref".into()),
                    ..Default::default()
                }
            }
        };

        // 2. Evaluate policy
        let input = PolicyInput {
            identity,
            ref_path,
            context,
        };
        let decision = self.engine.evaluate(&input);

        let policy = match decision {
            PolicyDecision::Deny { policy, reason } => {
                return RefResult::denied(&policy, &reason);
            }
            PolicyDecision::Allow { policy } => policy,
        };

        let mut result = RefResult {
            allowed: true,
            policy: Some(policy),
            ..Default::default()
        };

        match resource.mode {
            ResolverMode::Direct => {
                result.mode = Some("direct".into());
                match self.resolve_from_backend(ref_path, resource).await {
                    Ok(value) => result.value = Some(value),
                    Err(e) => result.error = Some(e.to_string()),
                }
            }
            ResolverMode::ShortLived => {
                result.mode = Some("short_lived".into());
                let ttl = resource.ttl.unwrap_or(DEFAULT_TTL);
                match &self.signer {
                    Some(signer) => match signer.sign(ref_path, &resource.resolver, ttl) {
                        Ok(token) => {
                            result.token = Some(token);
                            result.proxy = self.proxy_url.clone();
                            result.ttl = Some(ttl);
                        }
                        Err(e) => result.error = Some(format!("signing failed: {e}")),
                    },
                    None => {
                        result.error = Some("short-lived mode requires a signing key".into());
                    }
                }
            }
        }

        result
    }

    async fn resolve_from_backend(
        &self,
        ref_path: &str,
        resource: &Resource,
    ) -> Result<String> {
        let resolver = self.resolvers.get(&resource.resolver).ok_or_else(|| {
            ServerError::Config(format!(
                "no backend resolver named '{}'",
                resource.resolver
            ))
        })?;

        let params = build_resolve_params(ref_path, resource);
        let request = Request::resolve(params);
        let resolved = resolver.resolve(&request).await.map_err(|e| {
            ServerError::Resolution(format!("backend '{}' failed: {e}", resource.resolver))
        })?;

        Ok(resolved.value.expose_secret().to_string())
    }
}

// ---------------------------------------------------------------------------
// Shared resolve-param builder
// ---------------------------------------------------------------------------

/// Build the parameter map for a secret-resolver `Request::resolve()` call.
pub fn build_resolve_params(ref_path: &str, resource: &Resource) -> HashMap<String, toml::Value> {
    let mut params = HashMap::new();
    params.insert("ref".into(), toml::Value::String(ref_path.into()));

    let optional_fields: &[(&str, Option<&String>)] = &[
        ("field", resource.field.as_ref()),
        ("path", resource.path.as_ref()),
        ("role_arn", resource.role_arn.as_ref()),
        ("secret_id", resource.secret_id.as_ref()),
    ];
    for (key, value) in optional_fields {
        if let Some(v) = value {
            params.insert((*key).into(), toml::Value::String((*v).clone()));
        }
    }
    if let Some(duration) = &resource.duration_seconds {
        params.insert(
            "duration_seconds".into(),
            toml::Value::String(duration.to_string()),
        );
    }

    params
}

// ---------------------------------------------------------------------------
// Backend config helper
// ---------------------------------------------------------------------------

/// Convert a `BackendConfig` into a config map suitable for
/// `secret_resolvers::registry::create_resolver`.
pub fn backend_to_config(backend: &BackendConfig) -> HashMap<String, toml::Value> {
    let mut m = HashMap::new();

    if let Some(address) = &backend.address {
        m.insert("address".into(), toml::Value::String(address.clone()));
    }
    if let Some(region) = &backend.region {
        m.insert("region".into(), toml::Value::String(region.clone()));
    }
    if let Some(path) = &backend.path {
        m.insert("path".into(), toml::Value::String(path.clone()));
    }
    if let Some(vault) = &backend.vault {
        m.insert("vault".into(), toml::Value::String(vault.clone()));
    }
    if let Some(auth) = &backend.auth {
        m.insert("auth_method".into(), toml::Value::String(auth.method.clone()));
        if let Some(role) = &auth.role {
            m.insert("auth_role".into(), toml::Value::String(role.clone()));
        }
    }

    // Inject VAULT_TOKEN from environment if present
    if let Ok(token) = std::env::var(VAULT_TOKEN_ENV) {
        m.insert("token".into(), toml::Value::String(token));
    }

    m
}