use crate::config::Bundle;
use crate::error::{AgentError, Result};
use crate::resolver::SecretResolver;
use axum::body::Body;
use axum::extract::State;
use axum::http::{HeaderValue, Request, Response, StatusCode};
use axum::routing::any;
use axum::Router;
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use std::collections::HashMap;
use std::sync::Arc;
struct ProxyState {
bundle: Bundle,
decoding_key: DecodingKey,
resolvers: HashMap<String, Arc<dyn SecretResolver>>,
http_client: reqwest::Client,
}
pub async fn build_proxy_router(
bundle: Bundle,
public_key_pem: &[u8],
resolvers: HashMap<String, Arc<dyn SecretResolver>>,
) -> Result<Router> {
let decoding_key = DecodingKey::from_rsa_pem(public_key_pem)
.map_err(|e| AgentError::Config(format!("invalid proxy key: {e}")))?;
let state = Arc::new(ProxyState {
bundle,
decoding_key,
resolvers,
http_client: reqwest::Client::builder().no_proxy().build().unwrap(),
});
Ok(Router::new().fallback(any(proxy_handler)).with_state(state))
}
async fn proxy_handler(State(state): State<Arc<ProxyState>>, req: Request<Body>) -> Response<Body> {
match handle_proxy_request(&state, req).await {
Ok(response) => response,
Err(e) => {
let (status, client_message) = match &e {
AgentError::JwtVerification(_) | AgentError::Jwt(_) => {
(StatusCode::UNAUTHORIZED, "authentication failed")
}
AgentError::UnknownResource(_) => (StatusCode::NOT_FOUND, "resource not found"),
AgentError::Config(_) => (StatusCode::BAD_REQUEST, "bad request"),
_ => (StatusCode::INTERNAL_SERVER_ERROR, "internal error"),
};
tracing::error!(error = %e, "proxy request failed");
let body = serde_json::json!({
"error": "proxy_error",
"message": client_message
});
Response::builder()
.status(status)
.header("content-type", "application/json")
.body(Body::from(serde_json::to_string(&body).unwrap()))
.unwrap()
}
}
}
async fn handle_proxy_request(state: &ProxyState, req: Request<Body>) -> Result<Response<Body>> {
let auth_header = req
.headers()
.get("authorization")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.strip_prefix("Bearer "))
.ok_or_else(|| {
AgentError::JwtVerification("missing or malformed Authorization header".into())
})?;
let mut validation = Validation::new(Algorithm::RS256);
validation.set_audience(&["kzagent-proxy"]);
validation.set_required_spec_claims(&["exp", "iss"]);
validation.set_issuer(&["kzagent"]);
let token_data = decode::<serde_json::Value>(auth_header, &state.decoding_key, &validation)?;
let claims = &token_data.claims;
let resource_id = claims["resource"]
.as_str()
.ok_or_else(|| AgentError::Config("JWT missing 'resource' claim".into()))?;
let resolver_name = claims["resolver"]
.as_str()
.ok_or_else(|| AgentError::Config("JWT missing 'resolver' claim".into()))?;
let resource = state
.bundle
.resources
.iter()
.find(|r| r.id == resource_id)
.ok_or_else(|| AgentError::UnknownResource(resource_id.into()))?;
let resolver_config = resource
.resolvers
.iter()
.find(|r| r.name == resolver_name)
.ok_or_else(|| {
AgentError::Config(format!(
"resolver '{resolver_name}' not found on resource '{resource_id}'"
))
})?;
let backend = state
.resolvers
.get(&resolver_config.backend)
.ok_or_else(|| {
AgentError::SecretResolution(format!(
"backend '{}' not found for resolver '{}'",
resolver_config.backend, resolver_config.name
))
})?;
let resolved = backend.resolve(resolver_config).await?;
let credential_location = resolver_config
.credential_location
.as_deref()
.unwrap_or("header:Authorization:Bearer");
let method = req.method().clone();
let uri = req.uri().clone();
let target_url = if uri.scheme().is_some() {
uri.to_string()
} else {
let host = req
.headers()
.get("host")
.and_then(|v| v.to_str().ok())
.unwrap_or("localhost");
let path = uri.path_and_query().map(|pq| pq.as_str()).unwrap_or("/");
format!("https://{host}{path}")
};
let mut forward_headers = req.headers().clone();
forward_headers.remove("authorization");
apply_credential(&mut forward_headers, credential_location, &resolved.value)?;
const MAX_BODY_SIZE: usize = 10 * 1024 * 1024;
let body_bytes = axum::body::to_bytes(req.into_body(), MAX_BODY_SIZE)
.await
.map_err(|e| AgentError::Config(format!("failed to read request body: {e}")))?;
let mut reqwest_req = state.http_client.request(
reqwest::Method::from_bytes(method.as_str().as_bytes()).unwrap(),
&target_url,
);
for (name, value) in &forward_headers {
if name != "host" && name != "transfer-encoding" {
if let Ok(v) = value.to_str() {
reqwest_req = reqwest_req.header(name.as_str(), v);
}
}
}
if !body_bytes.is_empty() {
reqwest_req = reqwest_req.body(body_bytes.to_vec());
}
let upstream_response = reqwest_req
.send()
.await
.map_err(|e| AgentError::SecretResolution(format!("upstream request failed: {e}")))?;
let status = StatusCode::from_u16(upstream_response.status().as_u16())
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
let mut response_builder = Response::builder().status(status);
for (name, value) in upstream_response.headers() {
if name != "transfer-encoding" {
response_builder = response_builder.header(name, value);
}
}
let response_body = upstream_response
.bytes()
.await
.map_err(|e| AgentError::SecretResolution(format!("failed to read upstream body: {e}")))?;
let response = response_builder
.body(Body::from(response_body.to_vec()))
.unwrap();
Ok(response)
}
fn apply_credential(
headers: &mut axum::http::HeaderMap,
credential_location: &str,
secret_value: &str,
) -> Result<()> {
let parts: Vec<&str> = credential_location.splitn(3, ':').collect();
match parts.as_slice() {
["header", header_name, prefix] => {
let value = if prefix.is_empty() {
secret_value.to_string()
} else {
format!("{prefix} {secret_value}")
};
headers.insert(
axum::http::header::HeaderName::from_bytes(header_name.as_bytes())
.map_err(|e| AgentError::Config(format!("invalid header name: {e}")))?,
HeaderValue::from_str(&value)
.map_err(|e| AgentError::Config(format!("invalid header value: {e}")))?,
);
Ok(())
}
_ => Err(AgentError::Config(format!(
"unsupported credential_location format: '{credential_location}'. Expected 'header:<name>:<prefix>'"
))),
}
}