From 8f1418b7d7df8013261006c85508c5f22011f1d6 Mon Sep 17 00:00:00 2001 From: Dmitry Prudnikov Date: Tue, 1 Dec 2026 09:51:07 +0200 Subject: [PATCH] feat(hooks): let the embedder answer a refused forwarded header - New hook ForwardedHeaderRefusal (ProxyServer::with_forwarded_header_refusal, TranscodeOptions::with_forwarded_header_refusal): for a transcoded request refused because a forwarded header carries a value gRPC metadata cannot carry, it gets the request view and the header's name and returns a RouteResponse, or None for the default INVALID_ARGUMENT body - The request is refused whatever the hook answers; the upstream is never called and the hook has no way to forward the value - Without the hook the behaviour and body are unchanged - The forwarded metadata is now built in `start`, where the request line is known, so the hook sees the method, path and query as received Why: a route whose protocol has its own error format (an RFC 9449 token endpoint answering `invalid_dpop_proof`) could not give that answer, since the request never reached its handler and no hook was consulted. Closes #177 --- README.md | 10 +- src/embed.rs | 17 +++- src/hooks.rs | 60 ++++++++++- src/lib.rs | 13 +++ src/transcode/mod.rs | 156 ++++++++++++++++++++-------- tests/forwarded_headers.rs | 203 +++++++++++++++++++++++++++++++++++-- 6 files changed, 403 insertions(+), 56 deletions(-) diff --git a/README.md b/README.md index 7bece47..58af69a 100644 --- a/README.md +++ b/README.md @@ -877,7 +877,10 @@ grpc-gateway do, so the same service works behind any of them. - a value gRPC metadata cannot carry (empty, a character outside visible ASCII and space, or bad base64 under a `-bin` key) is refused with `INVALID_ARGUMENT` (400) naming the header, since gRPC lets a receiver - silently drop such a value; + silently drop such a value. A route whose protocol has its own error format + (an RFC 9449 token endpoint answering `invalid_dpop_proof`) gets that answer + from `ProxyServer::with_forwarded_header_refusal`; the request still never + reaches the upstream; - a listed name that is not a gRPC metadata key (letters, digits, `_`, `-`, `.`) stops the proxy at startup. @@ -1349,6 +1352,11 @@ The hooks are: upstream's `google.rpc.Status` details (see [Error responses](#error-responses)). - **`with_denied_response_headers`**: keeps upstream response metadata keys off the HTTP responses (see [Upstream controls](#upstream-controls)). +- **`with_forwarded_header_refusal`**: answers a transcoded request refused + because a forwarded header carries a value gRPC metadata cannot carry, with + the status, headers and body of your choice (the request view and the + header's name in, a response or `None` for the default body out). The + request is refused whatever the hook answers. ## JWT verification diff --git a/src/embed.rs b/src/embed.rs index 2af5524..55af000 100644 --- a/src/embed.rs +++ b/src/embed.rs @@ -21,7 +21,9 @@ use axum::{Json, Router}; use crate::client_address::ClientAddress; use crate::guard::{http_to_grpc_code, mark_rejection}; -use crate::hooks::{AuthDecider, Decision, ExtraRoute, OidcBackend, RequestParts, RouteRequest}; +use crate::hooks::{ + AuthDecider, Decision, ExtraRoute, OidcBackend, RequestParts, RouteRequest, RouteResponse, +}; /// Cap on the body an extra-route handler will buffer (16 MiB). Extra routes are /// a stateless escape hatch, not a bulk-upload path; a bounded buffer keeps a @@ -268,10 +270,7 @@ where client, }) .await; - let mut response = Response::new(Body::from(resp.body)); - *response.status_mut() = resp.status; - *response.headers_mut() = resp.headers; - response + route_response(resp) } }); match by_path.remove(&route.path) { @@ -291,6 +290,14 @@ where router } +/// A hook's [`RouteResponse`], sent as the hook gave it. +pub(crate) fn route_response(resp: RouteResponse) -> Response { + let mut response = Response::new(Body::from(resp.body)); + *response.status_mut() = resp.status; + *response.headers_mut() = resp.headers; + response +} + /// Remove any incoming copies of the soon-to-be-injected header names, then /// insert the decider's values, so a client cannot forge them onto the upstream. /// A client-address header, or one in `reserved` the client-address diff --git a/src/hooks.rs b/src/hooks.rs index 55c7c2a..7de19a7 100644 --- a/src/hooks.rs +++ b/src/hooks.rs @@ -22,7 +22,7 @@ use std::sync::Arc; use async_trait::async_trait; use bytes::Bytes; -use http::{HeaderMap, Method, StatusCode}; +use http::{HeaderMap, HeaderName, Method, StatusCode}; use crate::client_address::ClientAddress; @@ -187,6 +187,61 @@ pub trait CorsOrigins: Send + Sync { fn admits(&self, origin: &str) -> bool; } +/// The answer to a transcoded request refused because a header in +/// `forwarded_headers` carries a value gRPC metadata cannot carry (empty, or +/// outside visible ASCII; not base64 under a `-bin` name), for a route whose +/// protocol has an error format of its own. +/// +/// The request is refused before the upstream is called, whatever the hook +/// answers: forwarding the value altered, or dropping it, would change what +/// the upstream sees. The hook only chooses the response. Returning `None` +/// keeps the proxy's own `INVALID_ARGUMENT` (400) body naming the header. +/// +/// Called inline on the refused request alone, so it answers from what the +/// embedder already holds, never by I/O. +/// +/// # Examples +/// +/// ``` +/// use http::{header::CONTENT_TYPE, HeaderName, HeaderValue, StatusCode}; +/// use structured_proxy::hooks::{ForwardedHeaderRefusal, RequestParts, RouteResponse}; +/// +/// /// A token endpoint answers a malformed DPoP proof as RFC 9449 §5 asks. +/// struct TokenEndpoint; +/// +/// impl ForwardedHeaderRefusal for TokenEndpoint { +/// fn respond(&self, request: &RequestParts<'_>, header: &HeaderName) -> Option { +/// if request.path != "/oauth2/token" || header != "dpop" { +/// return None; +/// } +/// let mut response = +/// RouteResponse::new(StatusCode::BAD_REQUEST, r#"{"error":"invalid_dpop_proof"}"#); +/// response +/// .headers +/// .insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); +/// Some(response) +/// } +/// } +/// +/// # use structured_proxy::ClientAddress; +/// let (headers, client) = (http::HeaderMap::new(), ClientAddress::from_peer(None)); +/// let token = RequestParts::new(&http::Method::POST, "/oauth2/token", None, &headers, &client); +/// let dpop = HeaderName::from_static("dpop"); +/// assert_eq!(TokenEndpoint.respond(&token, &dpop).unwrap().status, StatusCode::BAD_REQUEST); +/// let other = RequestParts::new(&http::Method::GET, "/v1/things", None, &headers, &client); +/// assert!(TokenEndpoint.respond(&other, &dpop).is_none()); +/// ``` +pub trait ForwardedHeaderRefusal: Send + Sync { + /// The response to `request`, refused for the value of `header`, or + /// `None` for the proxy's own answer. + /// + /// `request` is the request as received: its method, path and query + /// before a router the proxy is nested in strips its prefix, its headers, + /// and the client address the proxy resolved. The response goes out as + /// given: status, headers (`Content-Type` included) and body. + fn respond(&self, request: &RequestParts<'_>, header: &HeaderName) -> Option; +} + /// A static JSON document served at a fixed path (an OIDC metadata document or a /// JWKS document). #[derive(Debug, Clone)] @@ -277,7 +332,8 @@ impl RouteRequest { } } -/// Response produced by an [`ExtraRouteHandler`]. +/// Response produced by an [`ExtraRouteHandler`] or a +/// [`ForwardedHeaderRefusal`]. #[non_exhaustive] pub struct RouteResponse { /// HTTP status. diff --git a/src/lib.rs b/src/lib.rs index 49ce860..f542778 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -522,6 +522,19 @@ impl ProxyServer { self } + /// Let `refusal` answer a transcoded request refused because a header in + /// `forwarded_headers` carries a value gRPC metadata cannot carry, in the + /// format of the route's own protocol; see + /// [`hooks::ForwardedHeaderRefusal`]. The request still never reaches the + /// upstream. + pub fn with_forwarded_header_refusal( + mut self, + refusal: Arc, + ) -> Self { + self.transcode = self.transcode.with_forwarded_header_refusal(refusal); + self + } + /// Load descriptor pool from configured sources. /// /// Multiple descriptor files are merged into a single pool, diff --git a/src/transcode/mod.rs b/src/transcode/mod.rs index dc550d9..d5bea66 100644 --- a/src/transcode/mod.rs +++ b/src/transcode/mod.rs @@ -46,6 +46,7 @@ use tonic::metadata::MetadataMap; use crate::client_address::ClientAddress; use crate::config::AliasConfig; use crate::guard::BoxedService; +use crate::hooks::{ForwardedHeaderRefusal, RequestParts}; use crate::received::ReceivedRequest; use crate::service::ConnectionInfo; use crate::upstream::Upstream; @@ -159,6 +160,18 @@ struct RouteEntry { /// Response metadata keys the operator keeps off the HTTP response, on top /// of the ones that never go there. denied_headers: Arc<[HeaderName]>, + /// The embedder's answer to a request refused for a forwarded header. + refusal: Option, +} + +/// The embedder's [`ForwardedHeaderRefusal`], shared by every route. +#[derive(Clone)] +pub(crate) struct Refusal(Arc); + +impl std::fmt::Debug for Refusal { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("ForwardedHeaderRefusal") + } } impl RouteEntry { @@ -196,6 +209,7 @@ pub struct TranscodeOptions { pub(crate) ndjson_envelope: bool, pub(crate) denied_response_headers: Arc<[HeaderName]>, pub(crate) selection: RpcSelection, + pub(crate) refusal: Option, } impl TranscodeOptions { @@ -237,6 +251,18 @@ impl TranscodeOptions { self.denied_response_headers = names.into_iter().collect(); self } + + /// Let `refusal` decide the response to a request refused because a + /// forwarded header carries a value gRPC metadata cannot carry; the + /// request still never reaches the upstream. Without it the answer is + /// `INVALID_ARGUMENT` (400) naming the header. + pub fn with_forwarded_header_refusal( + mut self, + refusal: Arc, + ) -> Self { + self.refusal = Some(Refusal(refusal)); + self + } } /// Build transcoded REST→gRPC routes from a descriptor pool. @@ -642,6 +668,7 @@ fn path_tables( } binding.entry.ndjson_envelope = options.ndjson_envelope; binding.entry.denied_headers = options.denied_response_headers.clone(); + binding.entry.refusal = options.refusal.clone(); match by_shape.get(&binding.mount.shape) { Some(&index) => tables[index].add(binding.mount, binding.entry), None => { @@ -898,15 +925,13 @@ async fn begin( Ok(body) => body, Err(rejection) => return Begun::Answered(rejection.into_response()), }; - let entry = routes.tables[table].entry(index); - match start(state.clone(), client, &path_params, body, entry) { - Ok((call, sse, keep_alive_secs)) => Begun::Call { - call, - sse, - keep_alive_secs, - }, - Err(rejection) => Begun::Answered(rejection.into_response(entry)), - } + start( + state.clone(), + client, + &path_params, + body, + routes.tables[table].entry(index), + ) } /// Make the call [`begin`] got to, the parameters bound: the routes go on @@ -1307,25 +1332,39 @@ struct Origin { } /// The upstream call one request on a transcoded route makes, with whether a -/// streamed answer goes out as SSE and its keep-alive; or why the request -/// cannot be mapped onto the RPC. +/// streamed answer goes out as SSE and its keep-alive; or the answer to a +/// request that cannot be mapped onto the RPC. fn start( proxy_state: S, client: Client, path_params: &[(&str, Cow<'_, str>)], body: Bytes, entry: &RouteEntry, -) -> Result<(Call, bool, u64), Unmappable> { +) -> Begun { let keep_alive_secs = proxy_state.sse_keep_alive_secs(); let Client { headers, origin, line, } = client; + // A request the proxy resolved carries the client-address headers its + // forwarding policy wrote; one routed here without that resolution + // carries only what its client asserted, which is never forwarded. + let forwarded = match proxy_state.forwarded_header_names() { + Some(names) => metadata::Forwarded::Named(names), + None => metadata::Forwarded::Listed(proxy_state.forwarded_headers()), + }; + let request_metadata = + match metadata::forwarded_metadata(&headers, forwarded, origin.address.is_some()) { + Ok(request_metadata) => request_metadata, + Err(refused) => { + return Begun::Answered(refused_header(entry, &line, &headers, &origin, refused)) + } + }; // The query is read where it was received, before the request line is // handed on. let prepared = prepare( - proxy_state, + request_metadata, &headers, origin, path_params, @@ -1333,17 +1372,65 @@ fn start( body, entry, ) - .and_then(|mut call| { + .and_then(|(mut request, deadline)| { // Next to the extensions `prepare` sets, for an upstream in process. - call.request.extensions_mut().insert(line.received(entry)?); - Ok(call) + request.extensions_mut().insert(line.received(entry)?); + Ok((request, deadline)) }); - let call = prepared?; - Ok(( - call, - entry.streaming && wants_sse(&headers), + let (request, deadline) = match prepared { + Ok(prepared) => prepared, + Err(rejection) => return Begun::Answered(rejection.into_response(entry)), + }; + Begun::Call { + call: Call { + upstream: proxy_state.into_upstream(), + request, + deadline, + }, + sse: entry.streaming && wants_sse(&headers), keep_alive_secs, - )) + } +} + +/// The answer to a request whose forwarded header `refused` names carries a +/// value gRPC metadata cannot carry: the embedder's, when its hook gives one, +/// else `INVALID_ARGUMENT` naming the header. Either way the upstream is not +/// called. +fn refused_header( + entry: &RouteEntry, + line: &RequestLine, + headers: &HeaderMap, + origin: &Origin, + refused: metadata::InvalidForwardedHeader, +) -> Response { + if let Some(Refusal(hook)) = &entry.refusal { + // A request routed here without the proxy's resolution gets what + // resolution with no trusted proxy gives: the connection's peer. + let unresolved; + let client = match &origin.address { + Some(address) => address, + None => { + unresolved = ClientAddress::from_peer( + origin + .connection + .as_ref() + .and_then(ConnectionInfo::remote_addr), + ); + &unresolved + } + }; + let request = RequestParts::new( + &line.method, + line.uri.path(), + line.uri.query(), + headers, + client, + ); + if let Some(answer) = hook.respond(&request, &refused.header) { + return crate::embed::route_response(answer); + } + } + Unmappable(refused.to_string()).into_response(entry) } /// Why a request ends before the upstream is called: it cannot be mapped onto @@ -1402,29 +1489,22 @@ impl Call { } } -/// Map the request onto the RPC's input message. -fn prepare( - proxy_state: S, +/// Map the request onto the RPC's input message, which goes out with +/// `request_metadata`: the request to send, and how long the upstream may +/// take to answer it. +fn prepare( + request_metadata: MetadataMap, headers: &HeaderMap, origin: Origin, path_params: &[(&str, Cow<'_, str>)], raw_query: Option<&str>, body: Bytes, entry: &RouteEntry, -) -> Result, Unmappable> { +) -> Result<(tonic::Request, Duration), Unmappable> { let Origin { connection, address, } = origin; - // A request the proxy resolved carries the client-address headers its - // forwarding policy wrote; one routed here without that resolution - // carries only what its client asserted, which is never forwarded. - let forwarded = match proxy_state.forwarded_header_names() { - Some(names) => metadata::Forwarded::Named(names), - None => metadata::Forwarded::Listed(proxy_state.forwarded_headers()), - }; - let request_metadata = metadata::forwarded_metadata(headers, forwarded, address.is_some()) - .map_err(|e| Unmappable(e.to_string()))?; let message = decode_request(entry, headers, path_params, raw_query, body).map_err(Unmappable)?; let mut request = tonic::Request::new(message); @@ -1444,12 +1524,7 @@ fn prepare( // `grpc-timeout` to the whole call. let deadline = metadata::apply_request_deadline(&mut request, headers) .map_or(UPSTREAM_DEADLINE, |client| client.min(UPSTREAM_DEADLINE)); - - Ok(Call { - upstream: proxy_state.into_upstream(), - request, - deadline, - }) + Ok((request, deadline)) } /// A successful unary answer with its initial metadata and trailers kept @@ -1926,6 +2001,7 @@ fn extract_routes(pool: &DescriptorPool, selection: &RpcSelection) -> Vec DescriptorPool { common::compile("test/v1/headers.proto", HEADERS_PROTO) } -/// Answers with the `dpop` values it received, joined by `|`. +/// Answers with the `dpop` values it received, joined by `|`, counting its +/// calls. #[derive(Clone)] struct Seen { pool: DescriptorPool, + calls: Arc, +} + +impl Seen { + fn new() -> Self { + Self { + pool: pool(), + calls: Arc::default(), + } + } } impl tonic::server::NamedService for Seen { @@ -51,6 +66,7 @@ impl tonic::server::UnaryService for Seen { type Future = Ready, tonic::Status>>; fn call(&mut self, request: tonic::Request) -> Self::Future { + self.calls.fetch_add(1, Ordering::SeqCst); let seen: Vec = request .metadata() .get_all("dpop") @@ -91,15 +107,81 @@ impl tower::Service> for Seen { } async fn proxy(upstream: common::Upstream) -> common::App { - common::proxy( - upstream, - Seen { pool: pool() }, - pool(), - ErrorDetailsPolicy::default(), - ) + common::proxy(upstream, Seen::new(), pool(), ErrorDetailsPolicy::default()).await +} + +/// What a [`Refusal`] saw of one refused request. +#[derive(Debug, Clone, PartialEq, Eq)] +struct Refused { + method: http::Method, + path: String, + query: Option, + header: HeaderName, +} + +/// Answers a refused `dpop` as RFC 9449 §5 asks for an invalid proof, and +/// leaves any other refused header to the proxy; records what it was handed. +#[derive(Default)] +struct Refusal { + seen: Mutex>, +} + +impl ForwardedHeaderRefusal for Refusal { + fn respond(&self, request: &RequestParts<'_>, header: &HeaderName) -> Option { + self.seen.lock().unwrap().push(Refused { + method: request.method.clone(), + path: request.path.to_owned(), + query: request.query.map(str::to_owned), + header: header.clone(), + }); + if header != "dpop" { + return None; + } + let mut response = + RouteResponse::new(StatusCode::BAD_REQUEST, r#"{"error":"invalid_dpop_proof"}"#); + response.headers.insert( + http::header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + ); + Some(response) + } +} + +/// The proxy in front of `seen`, forwarding `dpop` and `x-proof`, with +/// `refusal` deciding the answer to a refused one. +async fn proxy_with_refusal( + upstream: common::Upstream, + seen: Seen, + refusal: Arc, +) -> common::App { + common::app(upstream, seen, |yaml| { + ProxyServer::from_yaml_str(yaml) + .unwrap() + .with_descriptors(pool()) + .with_forwarded_headers(["dpop", "x-proof"]) + .with_forwarded_header_refusal(refusal) + }) .await } +/// The request to `/v1/seen?client=a` with `name` set to each of `values`. +fn request_with(name: &str, values: &[HeaderValue]) -> http::Request { + let mut request = http::Request::get("/v1/seen?client=a"); + for value in values { + request = request.header(name, value.clone()); + } + request.body(Body::empty()).unwrap() +} + +/// The values gRPC metadata cannot carry under a text key: an empty one and +/// one outside visible ASCII. +fn uncarriable() -> [HeaderValue; 2] { + [ + HeaderValue::from_static(""), + HeaderValue::from_bytes(b"caf\xe9").unwrap(), + ] +} + upstream_tests! { async fn every_value_of_a_repeated_header_reaches_the_upstream_in_order() { // RFC 9449 §4.3 has the server reject a request with two DPoP headers; @@ -135,6 +217,111 @@ async fn a_value_grpc_metadata_cannot_carry_is_refused() { assert!(body["message"].as_str().unwrap().contains("dpop"), "{body}"); } +async fn without_a_refusal_hook_an_uncarriable_value_gets_the_generic_answer() { + // The default answer, for an empty value and a non-ASCII one alike: the + // transcoding error body naming the header, the upstream never called. + for value in uncarriable() { + let seen = Seen::new(); + let calls = seen.calls.clone(); + let app = common::proxy(UPSTREAM, seen, pool(), ErrorDetailsPolicy::default()).await; + let (status, body) = common::send(&app, request_with("dpop", std::slice::from_ref(&value))).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{value:?}: {body}"); + assert_eq!( + serde_json::from_str::(&body).unwrap(), + serde_json::json!({ + "error": "INVALID_ARGUMENT", + "message": "header `dpop` has a value gRPC metadata cannot carry", + "code": 3, + "details": [], + }), + "{value:?}" + ); + assert_eq!(calls.load(Ordering::SeqCst), 0, "{value:?}"); + } +} + +async fn a_refusal_hook_answers_an_uncarriable_value_in_its_own_format() { + // RFC 9449 §5 / RFC 6749 §5.2: an invalid DPoP proof is answered 400 with + // `invalid_dpop_proof`. The hook's answer goes out as it gave it, and the + // request still never reaches the upstream. + for value in uncarriable() { + let seen = Seen::new(); + let calls = seen.calls.clone(); + let refusal = Arc::new(Refusal::default()); + let app = proxy_with_refusal(UPSTREAM, seen, refusal.clone()).await; + let response = tower::ServiceExt::oneshot( + app, + request_with("dpop", &[HeaderValue::from_static("proof-a"), value.clone()]), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{value:?}"); + assert_eq!( + response.headers()[http::header::CONTENT_TYPE], + "application/json", + "{value:?}" + ); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + assert_eq!(&body[..], br#"{"error":"invalid_dpop_proof"}"#, "{value:?}"); + assert_eq!(calls.load(Ordering::SeqCst), 0, "{value:?}"); + // It saw the refused header's name and the request line, query apart. + assert_eq!( + *refusal.seen.lock().unwrap(), + [Refused { + method: http::Method::GET, + path: "/v1/seen".to_owned(), + query: Some("client=a".to_owned()), + header: HeaderName::from_static("dpop"), + }], + "{value:?}" + ); + } +} + +async fn a_refusal_hook_that_declines_leaves_the_generic_answer() { + // The hook answers `dpop` only: a refused `x-proof` is handed to it, it + // returns nothing, and the client gets the default body naming `x-proof`. + let seen = Seen::new(); + let calls = seen.calls.clone(); + let refusal = Arc::new(Refusal::default()); + let app = proxy_with_refusal(UPSTREAM, seen, refusal.clone()).await; + let (status, body) = common::send(&app, request_with("x-proof", &[HeaderValue::from_static("")])).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); + let body: serde_json::Value = serde_json::from_str(&body).unwrap(); + assert_eq!(body["error"], "INVALID_ARGUMENT"); + assert_eq!( + body["message"], + "header `x-proof` has a value gRPC metadata cannot carry" + ); + assert_eq!(calls.load(Ordering::SeqCst), 0); + let seen = refusal.seen.lock().unwrap(); + assert_eq!(seen.len(), 1); + assert_eq!(seen[0].header, "x-proof"); +} + +async fn a_refusal_hook_is_not_asked_about_carriable_values() { + // Values gRPC metadata carries are forwarded as before, the hook set or + // not: it is never consulted, and the upstream sees every value. + let seen = Seen::new(); + let calls = seen.calls.clone(); + let refusal = Arc::new(Refusal::default()); + let app = proxy_with_refusal(UPSTREAM, seen, refusal.clone()).await; + let request = request_with( + "dpop", + &[HeaderValue::from_static("proof-a"), HeaderValue::from_static("proof-b")], + ); + let (status, body) = common::send(&app, request).await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert_eq!( + serde_json::from_str::(&body).unwrap()["name"], + "proof-a|proof-b" + ); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert!(refusal.seen.lock().unwrap().is_empty()); +} + async fn a_single_value_is_unchanged() { let app = proxy(UPSTREAM).await; let request = http::Request::get("/v1/seen")