kz-server 0.2.0

JWT verification, CEL policies, and HTTP/MCP server for keyzero
Documentation
use crate::config::Bundle;
use crate::error::{AgentError, Result};
use secret_resolvers::SecretResolver;
use axum::body::Body;
use secrecy::ExposeSecret;
use axum::extract::State;
use axum::http::{HeaderValue, Request, Response, StatusCode};
use axum::routing::any;
use axum::Router;
use jsonwebtoken::{decode, DecodingKey, Validation};
use std::collections::HashMap;
use std::sync::Arc;

struct ProxyState {
    bundle: Bundle,
    decoding_key: DecodingKey,
    resolvers: HashMap<String, Arc<dyn SecretResolver>>,
    http_client: reqwest::Client,
}

/// Build an axum Router that handles all requests as a credential-swapping proxy.
///
/// The proxy:
/// 1. Extracts the keyzero JWT from the Authorization header
/// 2. Verifies it (audience: "keyzero-proxy")
/// 3. Looks up the resource and resolver from the JWT claims
/// 4. Resolves the real secret from the backend
/// 5. Swaps the credential in the request (based on `credential_location`)
/// 6. Forwards the request to the original target URL
/// 7. Returns the response
pub async fn build_proxy_router(
    bundle: Bundle,
    public_key_pem: &[u8],
    resolvers: HashMap<String, Arc<dyn SecretResolver>>,
) -> Result<Router> {
    let decoding_key = DecodingKey::from_rsa_pem(public_key_pem)
        .map_err(|e| AgentError::Config(format!("invalid proxy key (must be RSA public key in PEM format): {e}")))?;
    let state = Arc::new(ProxyState {
        bundle,
        decoding_key,
        resolvers,
        http_client: reqwest::Client::builder().no_proxy().build().expect("reqwest client build is infallible"),
    });
    Ok(Router::new().fallback(any(proxy_handler)).with_state(state))
}

/// The main proxy handler. All requests (any method, any path) flow through here.
async fn proxy_handler(State(state): State<Arc<ProxyState>>, req: Request<Body>) -> Response<Body> {
    match handle_proxy_request(&state, req).await {
        Ok(response) => response,
        Err(e) => {
            let (status, client_message) = match &e {
                AgentError::JwtVerification(_) => {
                    (StatusCode::UNAUTHORIZED, "authentication failed")
                }
                AgentError::UnknownResource(_) => (StatusCode::NOT_FOUND, "resource not found"),
                AgentError::Config(_) => (StatusCode::BAD_REQUEST, "bad request"),
                _ => (StatusCode::INTERNAL_SERVER_ERROR, "internal error"),
            };
            tracing::error!(error = %e, "proxy request failed");
            let body = serde_json::json!({
                "error": "proxy_error",
                "message": client_message
            });
            Response::builder()
                .status(status)
                .header("content-type", "application/json")
                .body(Body::from(serde_json::to_string(&body).expect("response builder with valid status")))
                .expect("response builder with valid status")
        }
    }
}

async fn handle_proxy_request(state: &ProxyState, req: Request<Body>) -> Result<Response<Body>> {
    // Step 1: Extract Bearer token from Authorization header
    let auth_header = crate::security::extract_bearer_token(req.headers())
        .ok_or_else(|| {
            AgentError::JwtVerification("missing or malformed Authorization header".into())
        })?;

    // Step 2: Verify JWT with the proxy's public key
    let mut validation = Validation::new(crate::signing::PROXY_JWT_ALG);
    validation.set_audience(&[crate::signing::PROXY_JWT_AUDIENCE]);
    validation.set_required_spec_claims(&["exp", "iss"]);
    validation.set_issuer(&[crate::signing::PROXY_JWT_ISSUER]);

    let token_data = decode::<crate::signing::ProxyClaims>(&auth_header, &state.decoding_key, &validation)?;
    let claims = &token_data.claims;

    // Step 3: Extract resource and resolver from typed JWT claims
    let resource_id = claims.resource.as_str();
    let resolver_name = claims.resolver.as_str();

    // Step 4: Find resource and resolver config in bundle
    let resource = state
        .bundle
        .resources
        .iter()
        .find(|r| r.id == resource_id)
        .ok_or_else(|| AgentError::UnknownResource(resource_id.into()))?;

    let resolver_config = resource
        .resolvers
        .iter()
        .find(|r| r.name == resolver_name)
        .ok_or_else(|| {
            AgentError::Config(format!(
                "resolver '{resolver_name}' not found on resource '{resource_id}'"
            ))
        })?;

    // Step 5: Resolve real secret via backend
    let backend = state
        .resolvers
        .get(&resolver_config.backend)
        .ok_or_else(|| {
            AgentError::SecretResolution(format!(
                "backend '{}' not found for resolver '{}'",
                resolver_config.backend, resolver_config.name
            ))
        })?;

    let request = crate::pipeline::to_resolve_request(resolver_config);
    let resolved = backend.resolve(&request).await
        .map_err(|e| AgentError::SecretResolution(e.to_string()))?;

    // Step 6: Parse credential_location and swap credentials
    let credential_location = crate::security::effective_location(
        resolver_config.credential_location.as_deref(),
    );

    // Step 7: Build the forwarding request
    let method = req.method().clone();
    let uri = req.uri().clone();

    // Determine target URL: use the full URI if it's absolute, otherwise use Host header
    let target_url = if uri.scheme().is_some() {
        uri.to_string()
    } else {
        let host = req
            .headers()
            .get("host")
            .and_then(|v| v.to_str().ok())
            .unwrap_or("localhost");

        // SSRF protection: reject Host-header-derived requests to private/internal addresses
        if crate::security::is_blocked_host(host) {
            return Err(AgentError::Config(format!(
                "proxy request to private address '{host}' is not allowed"
            )));
        }

        let path = uri.path_and_query().map(|pq| pq.as_str()).unwrap_or("/");
        format!("https://{host}{path}")
    };

    // Copy headers (except authorization which we'll replace)
    let mut forward_headers = req.headers().clone();
    forward_headers.remove(axum::http::header::AUTHORIZATION);

    // Apply credential swapping based on credential_location format
    apply_credential(&mut forward_headers, credential_location, resolved.value.expose_secret())?;

    // 10 MB limit for the credential-swapping proxy (request/response only).
    // Intentionally smaller than kz-proxy's 100 MB limit, which buffers full
    // sandbox traffic including large payloads that pass through unchanged.
    const MAX_BODY_SIZE: usize = 10 * 1024 * 1024;
    let body_bytes = axum::body::to_bytes(req.into_body(), MAX_BODY_SIZE)
        .await
        .map_err(|e| AgentError::Config(format!("failed to read request body: {e}")))?;

    // Step 8: Forward request using reqwest
    let mut reqwest_req = state.http_client.request(
        reqwest::Method::from_bytes(method.as_str().as_bytes()).unwrap(),
        &target_url,
    );

    // Copy headers to reqwest request
    for (name, value) in &forward_headers {
        if name != "host" && name != "transfer-encoding" {
            if let Ok(v) = value.to_str() {
                reqwest_req = reqwest_req.header(name.as_str(), v);
            }
        }
    }

    if !body_bytes.is_empty() {
        reqwest_req = reqwest_req.body(body_bytes.to_vec());
    }

    let upstream_response = reqwest_req
        .send()
        .await
        .map_err(|e| AgentError::SecretResolution(format!("upstream request failed: {e}")))?;

    // Step 9: Build response from upstream
    let status = StatusCode::from_u16(upstream_response.status().as_u16())
        .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
    let mut response_builder = Response::builder().status(status);

    for (name, value) in upstream_response.headers() {
        if name != "transfer-encoding" {
            response_builder = response_builder.header(name, value);
        }
    }

    let response_body = upstream_response
        .bytes()
        .await
        .map_err(|e| AgentError::SecretResolution(format!("failed to read upstream body: {e}")))?;
    if response_body.len() > MAX_BODY_SIZE {
        return Err(AgentError::SecretResolution("upstream response too large".into()));
    }

    let response = response_builder
        .body(Body::from(response_body.to_vec()))
        .expect("response builder with valid status");

    Ok(response)
}

/// Apply the real credential to the request headers based on credential_location.
///
/// Format: "header:<header_name>:<prefix>"
/// Apply a credential to request headers using the parsed credential_location format.
fn apply_credential(
    headers: &mut axum::http::HeaderMap,
    credential_location: &str,
    secret_value: &str,
) -> Result<()> {
    let loc = crate::security::parse_credential_location(credential_location)
        .map_err(AgentError::Config)?;
    let value = crate::security::format_credential_value(&loc, secret_value);
    headers.insert(
        axum::http::header::HeaderName::from_bytes(loc.header_name.as_bytes())
            .map_err(|e| AgentError::Config(format!("invalid header name: {e}")))?,
        HeaderValue::from_str(&value)
            .map_err(|e| AgentError::Config(format!("invalid header value: {e}")))?,
    );
    Ok(())
}