kz-server 0.1.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_json::json;

/// 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. "kzagent")
    /// - `aud`: "kzagent-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 = json!({
            "iss": self.issuer,
            "aud": "kzagent-proxy",
            "iat": now.timestamp(),
            "exp": exp.timestamp(),
            "resource": resource,
            "resolver": resolver_name,
        });
        let token = encode(&Header::new(Algorithm::RS256), &claims, &self.encoding_key)?;
        Ok(token)
    }
}