kz-server 0.2.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::{decode, decode_header, Algorithm, DecodingKey, Validation};
use serde::{Deserialize, Serialize};

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

/// Verified claims extracted from a successfully validated JWT.
#[derive(Debug, Clone)]
pub struct VerifiedClaims {
    /// The configured issuer name (from `Issuer.name`).
    pub issuer_name: String,
    /// All raw claims as a map.
    pub claims: HashMap<String, serde_json::Value>,
}

/// Internal claims struct for deserialization. We use a flattened map
/// to capture all claims (standard and custom).
#[derive(Debug, Serialize, Deserialize)]
struct RawClaims {
    #[serde(default)]
    iss: Option<String>,
    #[serde(default)]
    sub: Option<String>,
    #[serde(default)]
    aud: Option<Audience>,
    #[serde(default)]
    exp: Option<u64>,
    #[serde(flatten)]
    extra: HashMap<String, serde_json::Value>,
}

/// The `aud` claim can be a single string or an array of strings.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
enum Audience {
    Single(String),
    Multiple(Vec<String>),
}

impl Audience {
    fn into_vec(self) -> Vec<String> {
        match self {
            Audience::Single(s) => vec![s],
            Audience::Multiple(v) => v,
        }
    }
}

// ---------------------------------------------------------------------------
// JWKS cache (private)
// ---------------------------------------------------------------------------

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).
struct JwksCache {
    cache: RwLock<HashMap<String, CachedJwks>>,
    http_client: reqwest::Client,
    ttl: Duration,
}

impl JwksCache {
    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.
    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(),
        )),
    }
}

// ---------------------------------------------------------------------------
// JWT verifier (public)
// ---------------------------------------------------------------------------

/// JWT verifier that validates tokens against a set of configured issuers.
pub struct JwtVerifier {
    issuers: Vec<Issuer>,
    jwks_cache: JwksCache,
}

impl JwtVerifier {
    /// Create a new verifier with the given issuer configurations.
    pub fn new(issuers: Vec<Issuer>) -> Self {
        Self {
            issuers,
            jwks_cache: JwksCache::new(),
        }
    }

    /// Verify a JWT token against the configured issuers.
    ///
    /// Algorithm:
    /// 1. Decode the JWT header to get the `kid` and algorithm.
    /// 2. Iterate over configured issuers.
    /// 3. For each issuer, try static keys first (matching by kid if present).
    /// 4. If no static key matched, try JWKS if the issuer has a jwks_url.
    /// 5. Use `jsonwebtoken::decode()` with proper Validation (issuer, audience).
    /// 6. Extract claims into a `VerifiedClaims` struct.
    pub async fn verify(&self, token: &str) -> Result<VerifiedClaims> {
        let header = decode_header(token).map_err(|e| {
            AgentError::JwtVerification(format!("failed to decode JWT header: {e}"))
        })?;

        let token_kid = header.kid.as_deref();
        let token_alg = header.alg;

        for issuer in &self.issuers {
            // Try static keys first
            if let Some(ref static_keys) = issuer.static_keys {
                for key in static_keys {
                    let key_alg = parse_algorithm(&key.alg)?;

                    // If the token has a kid, only try keys that match
                    if let Some(tk) = token_kid {
                        if tk != key.kid {
                            continue;
                        }
                    }

                    // Algorithm must match
                    if key_alg != token_alg {
                        if token_kid.is_some() && token_kid == Some(&key.kid) {
                            return Err(AgentError::JwtVerification(format!(
                                "kid '{}' matched but algorithm mismatch: token={:?}, key={}",
                                key.kid, token_alg, key.alg
                            )));
                        }
                        continue;
                    }

                    // Build the decoding key based on algorithm family
                    let decoding_key = build_decoding_key(key_alg, &key.pem, &key.kid)?;

                    match self.try_decode(token, &decoding_key, key_alg, issuer) {
                        Ok(claims) => return Ok(claims),
                        Err(e) => {
                            if token_kid.is_some() && token_kid == Some(&key.kid) {
                                return Err(AgentError::JwtVerification(format!(
                                    "kid '{}' matched but verification failed: {e}",
                                    key.kid
                                )));
                            }
                            continue;
                        }
                    }
                }
            }

            // Try JWKS if available and token has a kid
            if let (Some(ref jwks_url), Some(kid)) = (&issuer.jwks_url, token_kid) {
                match self.jwks_cache.get_key(jwks_url, kid).await {
                    Ok((decoding_key, jwk_alg)) => {
                        if jwk_alg != token_alg {
                            continue;
                        }
                        match self.try_decode(token, &decoding_key, jwk_alg, issuer) {
                            Ok(claims) => return Ok(claims),
                            Err(e) => {
                                return Err(AgentError::JwtVerification(format!(
                                    "JWKS kid '{kid}' matched but verification failed: {e}"
                                )));
                            }
                        }
                    }
                    Err(_) => continue,
                }
            }
        }

        Err(AgentError::JwtVerification("no issuer matched".to_string()))
    }

    fn try_decode(
        &self,
        token: &str,
        decoding_key: &DecodingKey,
        alg: Algorithm,
        issuer: &Issuer,
    ) -> std::result::Result<VerifiedClaims, String> {
        let mut validation = Validation::new(alg);
        validation.set_issuer(&[&issuer.issuer_url]);

        if let Some(ref aud) = issuer.audience {
            validation.set_audience(&[aud]);
        } else {
            validation.validate_aud = false;
        }

        validation.set_required_spec_claims(&["exp", "iss"]);

        match decode::<RawClaims>(token, decoding_key, &validation) {
            Ok(token_data) => {
                let raw = token_data.claims;
                let iss = raw.iss.unwrap_or_default();
                let sub = raw.sub.unwrap_or_default();
                let aud = raw.aud.map(|a| a.into_vec()).unwrap_or_default();

                let mut all_claims = raw.extra;
                all_claims.insert("iss".to_string(), serde_json::Value::String(iss.clone()));
                all_claims.insert("sub".to_string(), serde_json::Value::String(sub.clone()));
                if !aud.is_empty() {
                    all_claims.insert(
                        "aud".to_string(),
                        serde_json::Value::Array(
                            aud.iter()
                                .map(|a| serde_json::Value::String(a.clone()))
                                .collect(),
                        ),
                    );
                }
                if let Some(exp) = raw.exp {
                    all_claims.insert("exp".to_string(), serde_json::Value::Number(exp.into()));
                }

                Ok(VerifiedClaims {
                    issuer_name: issuer.name.clone(),
                    claims: all_claims,
                })
            }
            Err(e) => Err(format!("{e}")),
        }
    }
}

// ---------------------------------------------------------------------------
// Private helpers
// ---------------------------------------------------------------------------

/// Build a DecodingKey from PEM bytes based on the algorithm family.
fn build_decoding_key(alg: Algorithm, pem: &str, kid: &str) -> Result<DecodingKey> {
    let pem_bytes = pem.as_bytes();
    let err_map = |e: jsonwebtoken::errors::Error| {
        AgentError::JwtVerification(format!("invalid PEM for kid '{kid}': {e}"))
    };
    match alg {
        Algorithm::RS256
        | Algorithm::RS384
        | Algorithm::RS512
        | Algorithm::PS256
        | Algorithm::PS384
        | Algorithm::PS512 => DecodingKey::from_rsa_pem(pem_bytes).map_err(err_map),
        Algorithm::ES256 | Algorithm::ES384 => DecodingKey::from_ec_pem(pem_bytes).map_err(err_map),
        Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512 => {
            Ok(DecodingKey::from_secret(pem_bytes))
        }
        _ => Err(AgentError::JwtVerification(format!(
            "unsupported algorithm for key decoding: {alg:?}"
        ))),
    }
}

/// Parse an algorithm string (e.g. "RS256") into a `jsonwebtoken::Algorithm`.
fn parse_algorithm(alg: &str) -> Result<Algorithm> {
    use Algorithm::*;
    const TABLE: &[(&str, Algorithm)] = &[
        ("RS256", RS256), ("RS384", RS384), ("RS512", RS512),
        ("ES256", ES256), ("ES384", ES384),
        ("PS256", PS256), ("PS384", PS384), ("PS512", PS512),
        ("HS256", HS256), ("HS384", HS384), ("HS512", HS512),
    ];
    TABLE.iter().find(|(name, _)| *name == alg).map(|(_, a)| *a)
        .ok_or_else(|| AgentError::JwtVerification(format!("unsupported algorithm: {alg}")))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_algorithm() {
        assert_eq!(parse_algorithm("RS256").unwrap(), Algorithm::RS256);
        assert_eq!(parse_algorithm("ES256").unwrap(), Algorithm::ES256);
        assert!(parse_algorithm("UNKNOWN").is_err());
    }
}