kz-server 0.1.0

JWT verification, CEL policies, and HTTP/MCP server for keyzero
Documentation
use std::collections::HashMap;
use std::sync::RwLock;
use std::time::{Duration, Instant};

use jsonwebtoken::jwk::{AlgorithmParameters, Jwk, JwkSet};
use jsonwebtoken::{Algorithm, DecodingKey};

use crate::error::{AgentError, Result};

struct CachedJwks {
    keys: Vec<Jwk>,
    fetched_at: Instant,
}

/// A cache for JWKS (JSON Web Key Sets) fetched from remote URLs.
///
/// Keys are cached for a configurable TTL (default: 1 hour).
pub struct JwksCache {
    cache: RwLock<HashMap<String, CachedJwks>>,
    http_client: reqwest::Client,
    ttl: Duration,
}

impl Default for JwksCache {
    fn default() -> Self {
        Self::new()
    }
}

impl JwksCache {
    pub fn new() -> Self {
        Self {
            cache: RwLock::new(HashMap::new()),
            http_client: reqwest::Client::new(),
            ttl: Duration::from_secs(3600),
        }
    }

    /// Get a decoding key by kid from the JWKS at the given URL.
    /// Returns (DecodingKey, Algorithm) if found.
    pub async fn get_key(&self, jwks_url: &str, kid: &str) -> Result<(DecodingKey, Algorithm)> {
        // Check cache first
        if let Some(key) = self.find_in_cache(jwks_url, kid) {
            return key;
        }

        // Fetch fresh JWKS
        self.fetch_and_cache(jwks_url).await?;

        // Try again from cache
        self.find_in_cache(jwks_url, kid).unwrap_or_else(|| {
            Err(AgentError::JwtVerification(format!(
                "kid '{kid}' not found in JWKS at {jwks_url}"
            )))
        })
    }

    fn find_in_cache(&self, jwks_url: &str, kid: &str) -> Option<Result<(DecodingKey, Algorithm)>> {
        let cache = self.cache.read().ok()?;
        let entry = cache.get(jwks_url)?;
        if entry.fetched_at.elapsed() > self.ttl {
            return None;
        }
        let jwk = entry
            .keys
            .iter()
            .find(|k| k.common.key_id.as_deref() == Some(kid))?;
        Some(decoding_key_from_jwk(jwk))
    }

    async fn fetch_and_cache(&self, jwks_url: &str) -> Result<()> {
        let response = self.http_client.get(jwks_url).send().await.map_err(|e| {
            AgentError::JwtVerification(format!("failed to fetch JWKS from {jwks_url}: {e}"))
        })?;

        let jwks: JwkSet = response.json().await.map_err(|e| {
            AgentError::JwtVerification(format!("failed to parse JWKS from {jwks_url}: {e}"))
        })?;

        if let Ok(mut cache) = self.cache.write() {
            cache.insert(
                jwks_url.to_string(),
                CachedJwks {
                    keys: jwks.keys,
                    fetched_at: Instant::now(),
                },
            );
        }

        Ok(())
    }
}

/// Convert a JWK into a DecodingKey and Algorithm.
fn decoding_key_from_jwk(jwk: &Jwk) -> Result<(DecodingKey, Algorithm)> {
    match &jwk.algorithm {
        AlgorithmParameters::RSA(rsa) => {
            let key = DecodingKey::from_rsa_components(&rsa.n, &rsa.e)
                .map_err(|e| AgentError::JwtVerification(format!("invalid RSA JWK: {e}")))?;
            let alg = jwk
                .common
                .key_algorithm
                .and_then(|a| match a {
                    jsonwebtoken::jwk::KeyAlgorithm::RS256 => Some(Algorithm::RS256),
                    jsonwebtoken::jwk::KeyAlgorithm::RS384 => Some(Algorithm::RS384),
                    jsonwebtoken::jwk::KeyAlgorithm::RS512 => Some(Algorithm::RS512),
                    jsonwebtoken::jwk::KeyAlgorithm::PS256 => Some(Algorithm::PS256),
                    jsonwebtoken::jwk::KeyAlgorithm::PS384 => Some(Algorithm::PS384),
                    jsonwebtoken::jwk::KeyAlgorithm::PS512 => Some(Algorithm::PS512),
                    _ => None,
                })
                .unwrap_or(Algorithm::RS256);
            Ok((key, alg))
        }
        AlgorithmParameters::EllipticCurve(ec) => {
            let key = DecodingKey::from_ec_components(&ec.x, &ec.y)
                .map_err(|e| AgentError::JwtVerification(format!("invalid EC JWK: {e}")))?;
            let alg = jwk
                .common
                .key_algorithm
                .and_then(|a| match a {
                    jsonwebtoken::jwk::KeyAlgorithm::ES256 => Some(Algorithm::ES256),
                    jsonwebtoken::jwk::KeyAlgorithm::ES384 => Some(Algorithm::ES384),
                    _ => None,
                })
                .unwrap_or(Algorithm::ES256);
            Ok((key, alg))
        }
        _ => Err(AgentError::JwtVerification(
            "unsupported JWK algorithm type".into(),
        )),
    }
}