From a6a77d7317f0cf3e7819a630e218658c6f56e03b Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Fri, 20 Nov 2026 22:18:20 -0500 Subject: [PATCH] fix!: refuse redirects and set a timeout on every outbound request A caller-supplied reqwest::Client was used as-is, so a default client followed up to 10 redirects with no timeout. reqwest strips Authorization across hosts but not x-seamless-service-token, whose refresh variant carries the user's refresh token. The adapter and the verifier now always build their own client and apply redirect::Policy::none() after any caller hook. Calls to the auth API also carry a per-request timeout (15 seconds by default, set with http_timeout), matching the Go adapter. Fixes #44 BREAKING CHANGE: Builder::http_client(reqwest::Client) and VerifierBuilder::http_client(reqwest::Client) are removed, because a built client's redirect policy cannot be changed. Use configure_http_client(|b| ...) to adjust the reqwest::ClientBuilder (proxy, TLS roots, DNS), and Builder::http_timeout(Duration) for the timeout. --- README.md | 19 +++++++++++-- src/adapter.rs | 1 + src/guard.rs | 1 + src/options.rs | 59 ++++++++++++++++++++++++++++++----------- src/tests/adapter.rs | 36 +++++++++++++++++++++++++ src/tests/permission.rs | 6 +---- src/tests/refresh.rs | 6 +---- src/verifier.rs | 28 +++++++++---------- 8 files changed, 115 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index 41ac296..be064e9 100644 --- a/README.md +++ b/README.md @@ -286,7 +286,20 @@ API cannot be reached. | `deliver_account_notices` | `false` | Your `deliver` also sends account notices (see Delivery) | | `trusted_proxies`, `resolve_client_ip` | the connecting peer | The end user's address. See below | | `disable_manifest_fetch` | `false` | Use only the manifest bundled with this version | -| `http_client` | 15 second timeout, no redirects | Outbound `reqwest::Client` | +| `http_timeout` | 15 seconds | Limit on each call to the auth API, set per request | +| `configure_http_client` | none | Adjusts the outbound `reqwest::ClientBuilder` (proxy, TLS roots, DNS) | + +The outbound client never follows redirects: a followed redirect would carry the service token, +and the refresh token inside it, to the redirect target. The adapter builds the client itself and +applies `redirect::Policy::none()` after your hook, so a finished `reqwest::Client` is not +accepted (its redirect policy cannot be changed once built): + +```rust +let auth = Adapter::builder(url) + // ... + .configure_http_client(|b| b.proxy(reqwest::Proxy::https("http://proxy:3128").unwrap())) + .build()?; +``` ### Client IP @@ -463,7 +476,9 @@ verified token answers as if no token was sent. The verifier finds the provider's JWKS from `/.well-known/openid-configuration` on the first request (the document's `issuer` must equal yours, and its `jwks_uri` must be https under an https issuer), or uses `jwks_uri(...)` when you set one. If discovery or the key fetch fails, the -request answers 401 and discovery is tried again at most every 5 seconds. +request answers 401 and discovery is tried again at most every 5 seconds. Discovery and key fetches +follow no redirects and time out after 5 seconds; `configure_http_client` adjusts their client the +same way it does the adapter's. A token is accepted only when it is RS256 under a published signing key (`kid` required, the key's `use` and `alg` when present must be `sig` and `RS256`), with header `typ` `at+jwt`, no `crit`, diff --git a/src/adapter.rs b/src/adapter.rs index 3b04189..86d5421 100644 --- a/src/adapter.rs +++ b/src/adapter.rs @@ -319,6 +319,7 @@ impl Inner { .config .http_client .request(call.method.clone(), url) + .timeout(self.config.http_timeout) .header("accept", "application/json"); if let Some(body) = call.body.filter(|_| call.method != Method::GET) { req = req.header("content-type", "application/json").body(body); diff --git a/src/guard.rs b/src/guard.rs index 779fe13..cbb4ff6 100644 --- a/src/guard.rs +++ b/src/guard.rs @@ -351,6 +351,7 @@ impl Inner { .config .http_client .get(url) + .timeout(self.config.http_timeout) .header("accept", "application/json") .bearer_auth(token) .send() diff --git a/src/options.rs b/src/options.rs index 7e6c79b..7d14d42 100644 --- a/src/options.rs +++ b/src/options.rs @@ -42,6 +42,25 @@ impl SameSite { } } +pub(crate) type ConfigureClientFn = + Box reqwest::ClientBuilder + Send + Sync>; + +pub(crate) const DEFAULT_HTTP_TIMEOUT: Duration = Duration::from_secs(15); + +/// Builds an outbound client from the caller's settings. The redirect policy is +/// applied last so no hook can turn redirects back on: a followed redirect would +/// carry the service token, and the refresh token inside it, to the target. +pub(crate) fn build_client( + configure: Option, + timeout: Duration, +) -> Result { + let mut builder = reqwest::Client::builder().timeout(timeout); + if let Some(configure) = configure { + builder = configure(builder); + } + builder.redirect(reqwest::redirect::Policy::none()).build() +} + pub(crate) type DeliverFn = Arc DeliveryFuture + Send + Sync>; pub(crate) type ClientIpFn = Arc) -> Option + Send + Sync>; @@ -125,7 +144,8 @@ pub struct Builder { deliver_account_notices: bool, client_ip: Option, disable_manifest_fetch: bool, - http_client: Option, + configure_http_client: Option, + http_timeout: Duration, } impl fmt::Debug for Builder { @@ -160,7 +180,8 @@ impl Builder { deliver_account_notices: false, client_ip: None, disable_manifest_fetch: false, - http_client: None, + configure_http_client: None, + http_timeout: DEFAULT_HTTP_TIMEOUT, } } @@ -306,11 +327,23 @@ impl Builder { self } - /// The client for calls to the auth API. The default has a 15 second timeout - /// and follows no redirects. A client that follows redirects would carry the - /// service token to wherever the auth API pointed it. - pub fn http_client(mut self, client: reqwest::Client) -> Self { - self.http_client = Some(client); + /// Adjusts the client for calls to the auth API (proxy, TLS roots, DNS). + /// Whatever the hook sets, the client follows no redirects: one would carry + /// the service token to wherever the response pointed. A finished + /// `reqwest::Client` is not accepted because its redirect policy cannot be + /// changed after it is built. + pub fn configure_http_client(mut self, configure: F) -> Self + where + F: FnOnce(reqwest::ClientBuilder) -> reqwest::ClientBuilder + Send + Sync + 'static, + { + self.configure_http_client = Some(Box::new(configure)); + self + } + + /// The limit on each call to the auth API. Defaults to 15 seconds, and is set + /// on every request so a hook cannot remove it. + pub fn http_timeout(mut self, timeout: Duration) -> Self { + self.http_timeout = timeout; self } @@ -388,14 +421,8 @@ impl Builder { }); let same_site = self.same_site.unwrap_or(SameSite::Lax); - let http_client = match self.http_client { - Some(client) => client, - None => reqwest::Client::builder() - .timeout(Duration::from_secs(15)) - .redirect(reqwest::redirect::Policy::none()) - .build() - .map_err(|e| BuildError::HttpClient(e.to_string()))?, - }; + let http_client = build_client(self.configure_http_client, self.http_timeout) + .map_err(|e| BuildError::HttpClient(e.to_string()))?; Ok(Adapter::from_config(Config { auth_server_url, @@ -417,6 +444,7 @@ impl Builder { client_ip: self.client_ip, fetch_manifest: !self.disable_manifest_fetch, http_client, + http_timeout: self.http_timeout, })) } } @@ -447,6 +475,7 @@ pub(crate) struct Config { pub client_ip: Option, pub fetch_manifest: bool, pub http_client: reqwest::Client, + pub http_timeout: Duration, } impl Config { diff --git a/src/tests/adapter.rs b/src/tests/adapter.rs index f69b4fe..e402478 100644 --- a/src/tests/adapter.rs +++ b/src/tests/adapter.rs @@ -1041,6 +1041,42 @@ async fn redirects_from_the_api_are_not_followed() { assert!(api.calls_to("POST", "/elsewhere").is_empty()); } +// A hook that asks for redirects still gets none: the service token, and the +// refresh token inside it, must never reach the listener a 302 points at. +#[tokio::test] +async fn a_302_to_another_listener_never_receives_the_service_token() { + let api = FakeApi::start().await; + let elsewhere = FakeApi::start().await; + elsewhere.on("POST", "/stolen", respond(200, json!({}))); + elsewhere.on("GET", "/stolen", respond(200, json!({}))); + let target = format!("{}/stolen", elsewhere.url); + api.on( + "POST", + "/login", + Arc::new(move |_| { + let mut res = Response::new(Body::empty()); + *res.status_mut() = axum::http::StatusCode::FOUND; + res.headers_mut() + .insert("location", HeaderValue::from_str(&target).unwrap()); + res + }), + ); + let adapter = api.adapter(|b| { + b.configure_http_client(|c| c.redirect(reqwest::redirect::Policy::limited(10))) + }); + + let r = call("POST", "/login").body("{}").to(&adapter).await; + + assert_eq!(r.status, 302); + assert!( + !api.calls_to("POST", "/login")[0] + .header("x-seamless-service-token") + .is_empty() + ); + assert!(elsewhere.calls_to("POST", "/stolen").is_empty()); + assert!(elsewhere.calls_to("GET", "/stolen").is_empty()); +} + #[tokio::test] async fn cookies_only_count_in_their_own_slot() { let api = FakeApi::start().await; diff --git a/src/tests/permission.rs b/src/tests/permission.rs index ba0a167..571d1b0 100644 --- a/src/tests/permission.rs +++ b/src/tests/permission.rs @@ -892,11 +892,7 @@ async fn a_401_from_the_live_read_is_the_existing_401() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_live_read_timeout_fails_closed() { let api = FakeApi::start().await; - let client = reqwest::Client::builder() - .timeout(Duration::from_millis(200)) - .build() - .unwrap(); - let adapter = api.adapter(|b| b.http_client(client)); + let adapter = api.adapter(|b| b.http_timeout(Duration::from_millis(200))); api.on( "GET", LIVE, diff --git a/src/tests/refresh.rs b/src/tests/refresh.rs index 93c68ba..1c819a9 100644 --- a/src/tests/refresh.rs +++ b/src/tests/refresh.rs @@ -390,15 +390,11 @@ impl reqwest::dns::Resolve for BrokenResolver { } fn broken_adapter(panics: bool) -> crate::Adapter { - let client = reqwest::Client::builder() - .dns_resolver(BrokenResolver { panics }) - .build() - .unwrap(); crate::Adapter::builder("http://auth.invalid") .cookie_secret(TEST_SECRET) .service_secret(TEST_SERVICE) .disable_manifest_fetch(true) - .http_client(client) + .configure_http_client(move |b| b.dns_resolver(BrokenResolver { panics })) .build() .unwrap() } diff --git a/src/verifier.rs b/src/verifier.rs index b704b56..3ac37ac 100644 --- a/src/verifier.rs +++ b/src/verifier.rs @@ -18,6 +18,7 @@ use tokio::sync::Mutex; use crate::adapter::{json_response, read_limited}; use crate::jwks::JwksCache; use crate::jwt::CLOCK_SKEW_SECS; +use crate::options::{ConfigureClientFn, DEFAULT_HTTP_TIMEOUT, build_client}; use crate::permission::{permissions_omitted, string_list}; const DISCOVERY_TIMEOUT: Duration = Duration::from_secs(5); @@ -117,7 +118,7 @@ pub struct VerifierBuilder { issuer: String, audience: Option, jwks_uri: Option, - http_client: Option, + configure_http_client: Option, confirm: Option, now: Option, } @@ -140,7 +141,7 @@ impl Verifier { issuer: issuer.into(), audience: None, jwks_uri: None, - http_client: None, + configure_http_client: None, confirm: None, now: None, } @@ -162,10 +163,15 @@ impl VerifierBuilder { self } - /// The client for discovery and key fetches. The default follows no - /// redirects. - pub fn http_client(mut self, client: reqwest::Client) -> Self { - self.http_client = Some(client); + /// Adjusts the client for discovery and key fetches (proxy, TLS roots, DNS). + /// Whatever the hook sets, the client follows no redirects. A finished + /// `reqwest::Client` is not accepted because its redirect policy cannot be + /// changed after it is built. + pub fn configure_http_client(mut self, configure: F) -> Self + where + F: FnOnce(reqwest::ClientBuilder) -> reqwest::ClientBuilder + Send + Sync + 'static, + { + self.configure_http_client = Some(Box::new(configure)); self } @@ -201,14 +207,8 @@ impl VerifierBuilder { { return Err(VerifierBuildError::InvalidJwksUri); } - let client = match self.http_client { - Some(client) => client, - None => reqwest::Client::builder() - .timeout(Duration::from_secs(15)) - .redirect(reqwest::redirect::Policy::none()) - .build() - .map_err(|e| VerifierBuildError::HttpClient(e.to_string()))?, - }; + let client = build_client(self.configure_http_client, DEFAULT_HTTP_TIMEOUT) + .map_err(|e| VerifierBuildError::HttpClient(e.to_string()))?; let keys = KeySource { jwks: self .jwks_uri