kz-server 0.1.0

JWT verification, CEL policies, and HTTP/MCP server for keyzero
Documentation
use crate::config::Bundle;
use crate::error::{AgentError, Result};
use crate::resolver::SecretResolver;
use axum::body::Body;
use axum::extract::State;
use axum::http::{HeaderValue, Request, Response, StatusCode};
use axum::routing::any;
use axum::Router;
use jsonwebtoken::{decode, Algorithm, 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: "kzagent-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: {e}")))?;
    let state = Arc::new(ProxyState {
        bundle,
        decoding_key,
        resolvers,
        http_client: reqwest::Client::builder().no_proxy().build().unwrap(),
    });
    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(_) | AgentError::Jwt(_) => {
                    (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).unwrap()))
                .unwrap()
        }
    }
}

async fn handle_proxy_request(state: &ProxyState, req: Request<Body>) -> Result<Response<Body>> {
    // Step 1: Extract Bearer token from Authorization header
    let auth_header = req
        .headers()
        .get("authorization")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.strip_prefix("Bearer "))
        .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(Algorithm::RS256);
    validation.set_audience(&["kzagent-proxy"]);
    validation.set_required_spec_claims(&["exp", "iss"]);
    validation.set_issuer(&["kzagent"]);

    let token_data = decode::<serde_json::Value>(auth_header, &state.decoding_key, &validation)?;
    let claims = &token_data.claims;

    // Step 3: Extract resource and resolver from JWT claims
    let resource_id = claims["resource"]
        .as_str()
        .ok_or_else(|| AgentError::Config("JWT missing 'resource' claim".into()))?;
    let resolver_name = claims["resolver"]
        .as_str()
        .ok_or_else(|| AgentError::Config("JWT missing 'resolver' claim".into()))?;

    // 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 resolved = backend.resolve(resolver_config).await?;

    // Step 6: Parse credential_location and swap credentials
    let credential_location = resolver_config
        .credential_location
        .as_deref()
        .unwrap_or("header:Authorization:Bearer");

    // 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");
        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("authorization");

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

    // Read the body (10 MB limit)
    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}")))?;

    let response = response_builder
        .body(Body::from(response_body.to_vec()))
        .unwrap();

    Ok(response)
}

/// Apply the real credential to the request headers based on credential_location.
///
/// Format: "header:<header_name>:<prefix>"
/// Example: "header:Authorization:Bearer" -> sets Authorization: Bearer <secret>
/// Example: "header:X-API-Key:" -> sets X-API-Key: <secret>
fn apply_credential(
    headers: &mut axum::http::HeaderMap,
    credential_location: &str,
    secret_value: &str,
) -> Result<()> {
    let parts: Vec<&str> = credential_location.splitn(3, ':').collect();
    match parts.as_slice() {
        ["header", header_name, prefix] => {
            let value = if prefix.is_empty() {
                secret_value.to_string()
            } else {
                format!("{prefix} {secret_value}")
            };
            headers.insert(
                axum::http::header::HeaderName::from_bytes(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(())
        }
        _ => Err(AgentError::Config(format!(
            "unsupported credential_location format: '{credential_location}'. Expected 'header:<name>:<prefix>'"
        ))),
    }
}