use crate::config::Bundle;
use crate::error::{AgentError, Result};
use secret_resolvers::SecretResolver;
use axum::body::Body;
use secrecy::ExposeSecret;
use axum::extract::State;
use axum::http::{HeaderValue, Request, Response, StatusCode};
use axum::routing::any;
use axum::Router;
use jsonwebtoken::{decode, 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 (must be RSA public key in PEM format): {e}")))?;
let state = Arc::new(ProxyState {
bundle,
decoding_key,
resolvers,
http_client: reqwest::Client::builder().no_proxy().build().expect("reqwest client build is infallible"),
});
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(_) => {
(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).expect("response builder with valid status")))
.expect("response builder with valid status")
}
}
}
async fn handle_proxy_request(state: &ProxyState, req: Request<Body>) -> Result<Response<Body>> {
let auth_header = crate::security::extract_bearer_token(req.headers())
.ok_or_else(|| {
AgentError::JwtVerification("missing or malformed Authorization header".into())
})?;
let mut validation = Validation::new(crate::signing::PROXY_JWT_ALG);
validation.set_audience(&[crate::signing::PROXY_JWT_AUDIENCE]);
validation.set_required_spec_claims(&["exp", "iss"]);
validation.set_issuer(&[crate::signing::PROXY_JWT_ISSUER]);
let token_data = decode::<crate::signing::ProxyClaims>(&auth_header, &state.decoding_key, &validation)?;
let claims = &token_data.claims;
let resource_id = claims.resource.as_str();
let resolver_name = claims.resolver.as_str();
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 request = crate::pipeline::to_resolve_request(resolver_config);
let resolved = backend.resolve(&request).await
.map_err(|e| AgentError::SecretResolution(e.to_string()))?;
let credential_location = crate::security::effective_location(
resolver_config.credential_location.as_deref(),
);
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");
if crate::security::is_blocked_host(host) {
return Err(AgentError::Config(format!(
"proxy request to private address '{host}' is not allowed"
)));
}
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(axum::http::header::AUTHORIZATION);
apply_credential(&mut forward_headers, credential_location, resolved.value.expose_secret())?;
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}")))?;
if response_body.len() > MAX_BODY_SIZE {
return Err(AgentError::SecretResolution("upstream response too large".into()));
}
let response = response_builder
.body(Body::from(response_body.to_vec()))
.expect("response builder with valid status");
Ok(response)
}
fn apply_credential(
headers: &mut axum::http::HeaderMap,
credential_location: &str,
secret_value: &str,
) -> Result<()> {
let loc = crate::security::parse_credential_location(credential_location)
.map_err(AgentError::Config)?;
let value = crate::security::format_credential_value(&loc, secret_value);
headers.insert(
axum::http::header::HeaderName::from_bytes(loc.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(())
}