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 std::time::{Duration, Instant};

use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation};
use reqwest::Client;
use serde::Deserialize;
use tokio::sync::RwLock;
use tracing::debug;

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

// ---------------------------------------------------------------------------
// Algorithm lookup
// ---------------------------------------------------------------------------

const ALGORITHM_TABLE: &[(&str, Algorithm)] = &[
    ("RS256", Algorithm::RS256),
    ("RS384", Algorithm::RS384),
    ("RS512", Algorithm::RS512),
    ("PS256", Algorithm::PS256),
    ("PS384", Algorithm::PS384),
    ("PS512", Algorithm::PS512),
    ("ES256", Algorithm::ES256),
    ("ES384", Algorithm::ES384),
    ("HS256", Algorithm::HS256),
    ("HS384", Algorithm::HS384),
    ("HS512", Algorithm::HS512),
];

fn parse_algorithm(s: &str) -> Option<Algorithm> {
    ALGORITHM_TABLE
        .iter()
        .find(|(name, _)| *name == s)
        .map(|(_, alg)| *alg)
}

// ---------------------------------------------------------------------------
// Identity — normalized JWT result
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
pub struct Identity {
    pub issuer: String,
    pub org: String,
    pub service: String,
    pub env: String,
    pub action: String,
    pub branch: String,
    pub actor: String,
    pub groups: Vec<String>,
    pub claims: HashMap<String, serde_json::Value>,
}

// ---------------------------------------------------------------------------
// Raw JWT claims
// ---------------------------------------------------------------------------

#[derive(Deserialize)]
struct RawClaims {
    iss: Option<String>,
    sub: Option<String>,
    aud: Option<Audience>,
    exp: Option<u64>,
    #[serde(flatten)]
    extra: HashMap<String, serde_json::Value>,
}

#[derive(Deserialize, Clone)]
#[serde(untagged)]
enum Audience {
    Single(String),
    Multiple(Vec<String>),
}

impl RawClaims {
    /// Flatten all fields into a single map.
    fn into_flat_map(self) -> HashMap<String, serde_json::Value> {
        let mut m = self.extra;
        if let Some(iss) = self.iss {
            m.insert("iss".into(), serde_json::Value::String(iss));
        }
        if let Some(sub) = self.sub {
            m.insert("sub".into(), serde_json::Value::String(sub));
        }
        if let Some(aud) = self.aud {
            match aud {
                Audience::Single(s) => {
                    m.insert("aud".into(), serde_json::Value::String(s));
                }
                Audience::Multiple(v) => {
                    m.insert(
                        "aud".into(),
                        serde_json::Value::Array(
                            v.into_iter().map(serde_json::Value::String).collect(),
                        ),
                    );
                }
            }
        }
        if let Some(exp) = self.exp {
            m.insert(
                "exp".into(),
                serde_json::Value::Number(serde_json::Number::from(exp)),
            );
        }
        m
    }
}

// ---------------------------------------------------------------------------
// JWKS cache
// ---------------------------------------------------------------------------

#[derive(Clone)]
struct CachedJwks {
    keys: Vec<JwksKey>,
    fetched_at: Instant,
}

#[derive(Deserialize, Clone)]
#[allow(dead_code)]
struct JwksKey {
    kid: Option<String>,
    kty: String,
    alg: Option<String>,
    n: Option<String>,
    e: Option<String>,
    x: Option<String>,
    y: Option<String>,
    crv: Option<String>,
}

#[derive(Deserialize)]
struct JwksResponse {
    keys: Vec<JwksKey>,
}

type JwksCache = Arc<RwLock<HashMap<String, CachedJwks>>>;

const JWKS_TTL: Duration = Duration::from_secs(3600);

async fn get_jwks_key(
    cache: &JwksCache,
    jwks_url: &str,
    kid: &str,
) -> Result<Option<(DecodingKey, Algorithm)>> {
    // Check cache first
    {
        let c = cache.read().await;
        if let Some(cached) = c.get(jwks_url) {
            if cached.fetched_at.elapsed() < JWKS_TTL {
                if let Some(result) = find_key_in_jwks(&cached.keys, kid) {
                    return Ok(Some(result));
                }
                return Ok(None);
            }
        }
    }

    // Fetch
    let client = Client::new();
    let resp: JwksResponse = client
        .get(jwks_url)
        .send()
        .await?
        .json()
        .await
        .map_err(|e| ServerError::Jwt(format!("failed to parse JWKS: {e}")))?;

    let result = find_key_in_jwks(&resp.keys, kid);

    // Store in cache
    {
        let mut c = cache.write().await;
        c.insert(
            jwks_url.to_string(),
            CachedJwks {
                keys: resp.keys,
                fetched_at: Instant::now(),
            },
        );
    }

    Ok(result)
}

fn find_key_in_jwks(keys: &[JwksKey], kid: &str) -> Option<(DecodingKey, Algorithm)> {
    let key = keys
        .iter()
        .find(|k| k.kid.as_deref() == Some(kid))?;

    let alg = key
        .alg
        .as_deref()
        .and_then(parse_algorithm)
        .unwrap_or(Algorithm::RS256);

    let decoding_key = match key.kty.as_str() {
        "RSA" => {
            let n = key.n.as_ref()?;
            let e = key.e.as_ref()?;
            DecodingKey::from_rsa_components(n, e).ok()?
        }
        "EC" => {
            let x = key.x.as_ref()?;
            let y = key.y.as_ref()?;
            DecodingKey::from_ec_components(x, y).ok()?
        }
        _ => return None,
    };

    Some((decoding_key, alg))
}

// ---------------------------------------------------------------------------
// JwtVerifier
// ---------------------------------------------------------------------------

pub struct JwtVerifier {
    issuers: Vec<Issuer>,
    jwks_cache: JwksCache,
}

impl JwtVerifier {
    pub fn new(issuers: Vec<Issuer>) -> Self {
        Self {
            issuers,
            jwks_cache: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    pub async fn verify(&self, token: &str) -> Result<Identity> {
        let header = decode_header(token)?;
        let kid = header.kid.unwrap_or_default();
        let header_alg = header.alg;

        for issuer in &self.issuers {
            match self
                .try_issuer(token, issuer, &kid, header_alg)
                .await
            {
                Ok(Some(identity)) => return Ok(identity),
                Ok(None) => continue,
                Err(e) => return Err(e),
            }
        }

        Err(ServerError::Jwt("no matching issuer found".into()))
    }

    async fn try_issuer(
        &self,
        token: &str,
        issuer: &Issuer,
        kid: &str,
        header_alg: Algorithm,
    ) -> Result<Option<Identity>> {
        // 1. Try static keys
        if let Some(static_keys) = &issuer.static_keys {
            for sk in static_keys {
                if sk.kid != kid {
                    continue;
                }
                let alg = match parse_algorithm(&sk.alg) {
                    Some(a) => a,
                    None => continue,
                };
                if alg != header_alg {
                    continue;
                }
                let dk = decoding_key_from_pem(&sk.pem, alg)?;
                match try_decode(token, &dk, alg, issuer) {
                    Ok(Some(claims)) => return Ok(Some(normalize(issuer, claims))),
                    Ok(None) => return Ok(None),
                    Err(e) => return Err(e),
                }
            }
        }

        // 2. Try JWKS
        if let Some(jwks_url) = &issuer.jwks_url {
            if let Some((dk, alg)) =
                get_jwks_key(&self.jwks_cache, jwks_url, kid).await?
            {
                match try_decode(token, &dk, alg, issuer) {
                    Ok(Some(claims)) => return Ok(Some(normalize(issuer, claims))),
                    Ok(None) => return Ok(None),
                    Err(e) => return Err(e),
                }
            }
        }

        Ok(None)
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn decoding_key_from_pem(pem: &str, alg: Algorithm) -> Result<DecodingKey> {
    let pem_bytes = pem.as_bytes();
    match alg {
        Algorithm::ES256 | Algorithm::ES384 => DecodingKey::from_ec_pem(pem_bytes)
            .map_err(|e| ServerError::Jwt(format!("invalid EC PEM: {e}"))),
        Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512 => {
            Ok(DecodingKey::from_secret(pem_bytes))
        }
        _ => DecodingKey::from_rsa_pem(pem_bytes)
            .map_err(|e| ServerError::Jwt(format!("invalid RSA PEM: {e}"))),
    }
}

/// Try to decode + validate a token against a specific issuer.
///
/// Returns:
/// - `Ok(Some(claims))` — decoded and valid
/// - `Ok(None)` — issuer/audience mismatch (skip to next issuer)
/// - `Err(...)` — expired or structurally invalid
fn try_decode(
    token: &str,
    key: &DecodingKey,
    alg: Algorithm,
    issuer: &Issuer,
) -> Result<Option<HashMap<String, serde_json::Value>>> {
    let mut validation = Validation::new(alg);
    validation.validate_exp = true;
    validation.set_issuer(&[&issuer.issuer_url]);

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

    match decode::<RawClaims>(token, key, &validation) {
        Ok(token_data) => Ok(Some(token_data.claims.into_flat_map())),
        Err(e) => {
            use jsonwebtoken::errors::ErrorKind;
            match e.kind() {
                ErrorKind::InvalidIssuer | ErrorKind::InvalidAudience => {
                    debug!(
                        issuer = issuer.name,
                        "issuer/audience mismatch, skipping"
                    );
                    Ok(None)
                }
                _ => Err(ServerError::Jwt(e.to_string())),
            }
        }
    }
}

fn normalize(issuer: &Issuer, claims: HashMap<String, serde_json::Value>) -> Identity {
    let map = issuer.effective_map();

    let get_str = |field: &str| -> String {
        map.get(field)
            .and_then(|claim_name| claims.get(claim_name))
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string()
    };

    let groups = map
        .get("groups")
        .and_then(|claim_name| claims.get(claim_name))
        .map(|v| match v {
            serde_json::Value::Array(arr) => arr
                .iter()
                .filter_map(|item| item.as_str().map(String::from))
                .collect(),
            serde_json::Value::String(s) => vec![s.clone()],
            _ => vec![],
        })
        .unwrap_or_default();

    Identity {
        issuer: issuer.name.clone(),
        org: get_str("org"),
        service: get_str("service"),
        env: get_str("env"),
        action: get_str("action"),
        branch: get_str("branch"),
        actor: get_str("actor"),
        groups,
        claims,
    }
}