kz-server 0.1.0

JWT verification, CEL policies, and HTTP/MCP server for keyzero
Documentation
use super::{ResolvedSecret, SecretResolver};
use crate::config::{BackendConfig, ResolverConfig};
use crate::error::{AgentError, Result};
use async_trait::async_trait;

pub struct VaultResolver {
    client: reqwest::Client,
    address: String,
    token: Option<String>,
}

impl VaultResolver {
    pub fn new(config: &BackendConfig, token: Option<String>) -> Result<Self> {
        let address = config
            .address
            .as_ref()
            .ok_or_else(|| AgentError::Config("hashicorp_vault requires 'address'".into()))?
            .trim_end_matches('/')
            .to_string();
        Ok(Self {
            client: reqwest::Client::new(),
            address,
            token,
        })
    }
}

#[async_trait]
impl SecretResolver for VaultResolver {
    async fn resolve(&self, config: &ResolverConfig) -> Result<ResolvedSecret> {
        let path = config
            .path
            .as_ref()
            .ok_or_else(|| AgentError::SecretResolution("vault requires 'path'".into()))?;
        let field = config
            .field
            .as_ref()
            .ok_or_else(|| AgentError::SecretResolution("vault requires 'field'".into()))?;

        let url = format!("{}/v1/{}", self.address, path);
        let mut req = self.client.get(&url);
        if let Some(token) = &self.token {
            req = req.header("X-Vault-Token", token);
        }

        let response = req
            .send()
            .await
            .map_err(|e| AgentError::SecretResolution(format!("vault request failed: {e}")))?;
        if !response.status().is_success() {
            return Err(AgentError::SecretResolution(format!(
                "vault returned status {}",
                response.status()
            )));
        }

        let body: serde_json::Value = response
            .json()
            .await
            .map_err(|e| AgentError::SecretResolution(format!("vault parse error: {e}")))?;

        // KV v2: { "data": { "data": { ...fields... } } }
        let value = body
            .pointer("/data/data")
            .and_then(|d| d.get(field))
            .and_then(|v| v.as_str())
            .ok_or_else(|| AgentError::SecretResolution(format!("field '{field}' not found")))?
            .to_string();

        Ok(ResolvedSecret {
            value,
            ttl: config.ttl,
        })
    }
}