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
19 changes: 17 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -463,7 +476,9 @@ verified token answers as if no token was sent.
The verifier finds the provider's JWKS from `<issuer>/.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`,
Expand Down
1 change: 1 addition & 0 deletions src/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
1 change: 1 addition & 0 deletions src/guard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,7 @@ impl Inner {
.config
.http_client
.get(url)
.timeout(self.config.http_timeout)
.header("accept", "application/json")
.bearer_auth(token)
.send()
Expand Down
59 changes: 44 additions & 15 deletions src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,25 @@ impl SameSite {
}
}

pub(crate) type ConfigureClientFn =
Box<dyn FnOnce(reqwest::ClientBuilder) -> 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<ConfigureClientFn>,
timeout: Duration,
) -> Result<reqwest::Client, reqwest::Error> {
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<dyn Fn(Delivery) -> DeliveryFuture + Send + Sync>;
pub(crate) type ClientIpFn =
Arc<dyn Fn(&HeaderMap, Option<IpAddr>) -> Option<IpAddr> + Send + Sync>;
Expand Down Expand Up @@ -125,7 +144,8 @@ pub struct Builder {
deliver_account_notices: bool,
client_ip: Option<ClientIpFn>,
disable_manifest_fetch: bool,
http_client: Option<reqwest::Client>,
configure_http_client: Option<ConfigureClientFn>,
http_timeout: Duration,
}

impl fmt::Debug for Builder {
Expand Down Expand Up @@ -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,
}
}

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

Expand Down Expand Up @@ -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,
Expand All @@ -417,6 +444,7 @@ impl Builder {
client_ip: self.client_ip,
fetch_manifest: !self.disable_manifest_fetch,
http_client,
http_timeout: self.http_timeout,
}))
}
}
Expand Down Expand Up @@ -447,6 +475,7 @@ pub(crate) struct Config {
pub client_ip: Option<ClientIpFn>,
pub fetch_manifest: bool,
pub http_client: reqwest::Client,
pub http_timeout: Duration,
}

impl Config {
Expand Down
36 changes: 36 additions & 0 deletions src/tests/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
6 changes: 1 addition & 5 deletions src/tests/permission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
6 changes: 1 addition & 5 deletions src/tests/refresh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Expand Down
28 changes: 14 additions & 14 deletions src/verifier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -117,7 +118,7 @@ pub struct VerifierBuilder {
issuer: String,
audience: Option<String>,
jwks_uri: Option<String>,
http_client: Option<reqwest::Client>,
configure_http_client: Option<ConfigureClientFn>,
confirm: Option<ConfirmFn>,
now: Option<ClockFn>,
}
Expand All @@ -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,
}
Expand All @@ -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<F>(mut self, configure: F) -> Self
where
F: FnOnce(reqwest::ClientBuilder) -> reqwest::ClientBuilder + Send + Sync + 'static,
{
self.configure_http_client = Some(Box::new(configure));
self
}

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