Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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

Expand Down
17 changes: 12 additions & 5 deletions src/embed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand All @@ -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
Expand Down
60 changes: 58 additions & 2 deletions src/hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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<RouteResponse> {
/// 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<RouteResponse>;
}

/// A static JSON document served at a fixed path (an OIDC metadata document or a
/// JWKS document).
#[derive(Debug, Clone)]
Expand Down Expand Up @@ -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.
Expand Down
13 changes: 13 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<dyn hooks::ForwardedHeaderRefusal>,
) -> 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,
Expand Down
Loading