kz-server 0.2.0

JWT verification, CEL policies, and HTTP/MCP server for keyzero
Documentation
use crate::error::{AgentError, Result};
use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
use serde::{Deserialize, Serialize};

/// The JWT algorithm used for proxy tokens. Shared between signing and verification.
pub const PROXY_JWT_ALG: Algorithm = Algorithm::RS256;

/// The audience claim expected in proxy JWTs.
pub const PROXY_JWT_AUDIENCE: &str = "keyzero-proxy";

/// The issuer claim expected in proxy JWTs.
pub const PROXY_JWT_ISSUER: &str = "keyzero";

/// Typed claims embedded in proxy JWTs. Used for both signing and verification.
#[derive(Debug, Serialize, Deserialize)]
pub struct ProxyClaims {
    pub iss: String,
    pub aud: String,
    pub iat: i64,
    pub exp: i64,
    pub resource: String,
    pub resolver: String,
}

/// Signs short-lived JWTs that prove a caller is authorized for a resource.
/// Used in the ShortLived resolver mode to produce tokens that the HTTP proxy
/// can later verify and swap for real credentials.
pub struct KeyzeroSigner {
    encoding_key: EncodingKey,
    issuer: String,
}

impl KeyzeroSigner {
    /// Create a new signer from an RSA private key PEM and an issuer string.
    pub fn new(private_key_pem: &[u8], issuer: &str) -> Result<Self> {
        let encoding_key = EncodingKey::from_rsa_pem(private_key_pem)
            .map_err(|e| AgentError::Config(format!("invalid signing key: {e}")))?;
        Ok(Self {
            encoding_key,
            issuer: issuer.into(),
        })
    }

    /// Sign a short-lived JWT for the given resource and resolver.
    ///
    /// The JWT contains:
    /// - `iss`: the configured issuer (e.g. "keyzero")
    /// - `aud`: "keyzero-proxy" (the proxy verifies this)
    /// - `iat`: current timestamp
    /// - `exp`: current timestamp + ttl_seconds
    /// - `resource`: the resource id
    /// - `resolver`: the resolver name
    pub fn sign_short_lived(
        &self,
        resource: &str,
        resolver_name: &str,
        ttl_seconds: u64,
    ) -> Result<String> {
        let now = chrono::Utc::now();
        let exp = now + chrono::Duration::seconds(ttl_seconds as i64);
        let claims = ProxyClaims {
            iss: self.issuer.clone(),
            aud: PROXY_JWT_AUDIENCE.into(),
            iat: now.timestamp(),
            exp: exp.timestamp(),
            resource: resource.into(),
            resolver: resolver_name.into(),
        };
        let token = encode(&Header::new(PROXY_JWT_ALG), &claims, &self.encoding_key)?;
        Ok(token)
    }
}