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 rmcp::handler::server::wrapper::Parameters;
use rmcp::model::{
    CallToolResult, Content, Implementation, ServerCapabilities, ServerInfo, ToolsCapability,
};
use rmcp::handler::server::tool::ToolRouter;
use rmcp::{ErrorData as McpError, ServerHandler, ServiceExt, tool, tool_handler, tool_router};
use schemars::JsonSchema;
use serde::Deserialize;

use crate::pipeline::{Pipeline, ResolveRequest};
use crate::security::{
    effective_location, format_credential_value, is_blocked_host, parse_credential_location,
};

// ---------------------------------------------------------------------------
// Tool parameter types
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize, JsonSchema)]
pub struct ResolveParams {
    /// JWT token for authentication
    pub jwt: String,
    /// Resource ref path to resolve
    pub resource: String,
    /// Optional additional context
    #[serde(default)]
    pub context: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct FetchParams {
    /// JWT token for authentication
    pub jwt: String,
    /// Resource ref path to resolve
    pub resource: String,
    /// Target URL to fetch
    pub url: String,
    /// HTTP method (defaults to GET)
    #[serde(default = "default_method")]
    pub method: String,
    /// Extra headers to send
    #[serde(default)]
    pub headers: HashMap<String, String>,
    /// Optional request body
    pub body: Option<String>,
    /// Optional additional context
    #[serde(default)]
    pub context: HashMap<String, serde_json::Value>,
}

fn default_method() -> String {
    "GET".to_string()
}

// ---------------------------------------------------------------------------
// MCP handler
// ---------------------------------------------------------------------------

#[derive(Clone)]
pub struct McpHandler {
    pipeline: Arc<Pipeline>,
    http_client: reqwest::Client,
    tool_router: ToolRouter<Self>,
}

#[tool_router]
impl McpHandler {
    pub fn new(pipeline: Arc<Pipeline>) -> Self {
        let http_client = reqwest::Client::new();
        Self {
            pipeline,
            http_client,
            tool_router: Self::tool_router(),
        }
    }

    /// Resolve a secret reference through the keyzero policy pipeline.
    /// Returns the resolution result as JSON including the credential value
    /// (if allowed), mode, and policy information.
    #[tool(name = "resolve", description = "Resolve a secret reference through the keyzero policy pipeline")]
    async fn resolve(
        &self,
        Parameters(params): Parameters<ResolveParams>,
    ) -> std::result::Result<CallToolResult, McpError> {
        let request = ResolveRequest {
            ref_path: Some(params.resource),
            refs: None,
            context: if params.context.is_empty() {
                None
            } else {
                Some(params.context)
            },
        };

        match self.pipeline.resolve(&params.jwt, &request).await {
            Ok(response) => {
                let json = serde_json::to_string_pretty(&response)
                    .unwrap_or_else(|e| format!("{{\"error\": \"serialization failed: {e}\"}}"));
                Ok(CallToolResult::success(vec![Content::text(json)]))
            }
            Err(e) => Ok(CallToolResult::error(vec![Content::text(e.to_string())])),
        }
    }

    /// Fetch a URL with credentials injected from the keyzero vault.
    /// Resolves the secret for the given resource, performs SSRF validation,
    /// injects the credential into the outgoing request, and returns the
    /// upstream response status and body.
    #[tool(name = "fetch", description = "Fetch a URL with credentials injected from the keyzero vault")]
    async fn fetch(
        &self,
        Parameters(params): Parameters<FetchParams>,
    ) -> std::result::Result<CallToolResult, McpError> {
        // 1. SSRF check
        let parsed_url = match reqwest::Url::parse(&params.url) {
            Ok(u) => u,
            Err(e) => {
                return Err(McpError::invalid_params(
                    format!("invalid URL: {e}"),
                    None,
                ));
            }
        };
        let host = parsed_url.host_str().unwrap_or("");
        if is_blocked_host(host) {
            return Ok(CallToolResult::error(vec![Content::text(format!(
                "blocked host: {host}"
            ))]));
        }

        // 2. Resolve credential
        let (secret_value, resource) = match self
            .pipeline
            .resolve_single(&params.jwt, &params.resource, &params.context)
            .await
        {
            Ok(v) => v,
            Err(e) => {
                return Ok(CallToolResult::error(vec![Content::text(e.to_string())]));
            }
        };

        // 3. Build outgoing request
        let method = match reqwest::Method::from_bytes(params.method.as_bytes()) {
            Ok(m) => m,
            Err(e) => {
                return Err(McpError::invalid_params(
                    format!("invalid HTTP method: {e}"),
                    None,
                ));
            }
        };

        let mut req_builder = self.http_client.request(method, parsed_url);

        // Copy user-supplied headers
        for (k, v) in &params.headers {
            req_builder = req_builder.header(k.as_str(), v.as_str());
        }

        // Inject credential
        let loc_str = effective_location(resource.credential_location.as_deref());
        let cred_loc = match parse_credential_location(loc_str) {
            Ok(loc) => loc,
            Err(e) => {
                return Err(McpError::invalid_params(
                    format!("invalid credential_location: {e}"),
                    None,
                ));
            }
        };
        let cred_value = format_credential_value(&cred_loc, &secret_value);
        req_builder = req_builder.header(cred_loc.header_name, &cred_value);

        // Attach body
        if let Some(body) = params.body {
            req_builder = req_builder.body(body);
        }

        // 4. Send
        let resp = match req_builder.send().await {
            Ok(r) => r,
            Err(e) => {
                return Err(McpError::internal_error(
                    format!("HTTP request failed: {e}"),
                    None,
                ));
            }
        };

        let status = resp.status().as_u16();
        let body = resp.text().await.unwrap_or_default();

        let result_json = serde_json::json!({
            "status": status,
            "body": body,
        });

        Ok(CallToolResult::success(vec![Content::text(
            result_json.to_string(),
        )]))
    }
}

#[tool_handler]
impl ServerHandler for McpHandler {
    fn get_info(&self) -> ServerInfo {
        ServerInfo {
            protocol_version: Default::default(),
            capabilities: ServerCapabilities {
                tools: Some(ToolsCapability { list_changed: None }),
                ..Default::default()
            },
            server_info: Implementation {
                name: "keyzero".to_string(),
                title: Some("KeyZero MCP Server".to_string()),
                version: env!("CARGO_PKG_VERSION").to_string(),
                icons: None,
                website_url: None,
            },
            instructions: Some(
                "KeyZero vault gateway — resolve secrets and fetch URLs with credential injection."
                    .to_string(),
            ),
        }
    }
}

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

/// Start the MCP server over stdio transport.
pub async fn serve_mcp(pipeline: Arc<Pipeline>) -> crate::error::Result<()> {
    let handler = McpHandler::new(pipeline);
    let transport = rmcp::transport::stdio();
    let service = handler.serve(transport).await.map_err(|e| {
        crate::error::ServerError::Config(format!("MCP server failed to start: {e}"))
    })?;

    service.waiting().await.map_err(|e| {
        crate::error::ServerError::Config(format!("MCP server error: {e}"))
    })?;

    Ok(())
}