use std::error::Error;
use std::fmt;
use reqwest::redirect::Policy;
use reqwest::{Client, Url};
const MAX_REDIRECTS: usize = 10;
pub(crate) fn secure_client() -> Client {
Client::builder()
.redirect(no_downgrade_policy())
.build()
.expect("build identity-model HTTP client")
}
pub(crate) fn no_redirect_client() -> Client {
Client::builder()
.redirect(Policy::none())
.build()
.expect("build identity-model non-redirecting HTTP client")
}
pub fn secure_client_builder() -> reqwest::ClientBuilder {
Client::builder().redirect(same_origin_policy())
}
fn same_origin_policy() -> Policy {
Policy::custom(|attempt| {
if attempt.previous().len() >= MAX_REDIRECTS {
return attempt.error(RedirectBlocked::TooManyRedirects);
}
if is_tls_downgrade(attempt.previous(), attempt.url()) {
return attempt.error(RedirectBlocked::TlsDowngrade);
}
if is_cross_origin(attempt.previous(), attempt.url()) {
return attempt.error(RedirectBlocked::CrossOrigin);
}
attempt.follow()
})
}
fn no_downgrade_policy() -> Policy {
Policy::custom(|attempt| {
if attempt.previous().len() >= MAX_REDIRECTS {
return attempt.error(RedirectBlocked::TooManyRedirects);
}
if is_tls_downgrade(attempt.previous(), attempt.url()) {
return attempt.error(RedirectBlocked::TlsDowngrade);
}
attempt.follow()
})
}
fn is_tls_downgrade(previous: &[Url], next: &Url) -> bool {
matches!(previous.last(), Some(prev) if prev.scheme() == "https" && next.scheme() == "http")
}
fn is_cross_origin(previous: &[Url], next: &Url) -> bool {
matches!(previous.last(), Some(prev) if prev.origin() != next.origin())
}
#[derive(Debug)]
enum RedirectBlocked {
TlsDowngrade,
TooManyRedirects,
CrossOrigin,
}
impl fmt::Display for RedirectBlocked {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::TlsDowngrade => {
f.write_str("refusing to follow an https->http redirect (TLS downgrade)")
}
Self::TooManyRedirects => write!(f, "too many redirects (limit {MAX_REDIRECTS})"),
Self::CrossOrigin => f.write_str(
"refusing to follow a redirect to another origin with caller-supplied headers",
),
}
}
}
impl Error for RedirectBlocked {}
#[cfg(test)]
mod tests {
use super::*;
fn url(s: &str) -> Url {
Url::parse(s).expect("valid url")
}
#[test]
fn detects_https_to_http_downgrade() {
let previous = [url("https://issuer.example.com/a")];
assert!(is_tls_downgrade(
&previous,
&url("http://issuer.example.com/b")
));
}
#[test]
fn allows_same_scheme_and_upgrade() {
let https = [url("https://issuer.example.com/a")];
assert!(!is_tls_downgrade(
&https,
&url("https://issuer.example.com/b")
));
let http = [url("http://localhost/a")];
assert!(!is_tls_downgrade(&http, &url("http://localhost/b")));
assert!(!is_tls_downgrade(&http, &url("https://localhost/b")));
}
#[test]
fn detects_cross_origin_hops() {
let previous = [url("https://issuer.example.com/token")];
for other in [
"https://attacker.example/t",
"http://issuer.example.com/token",
"https://issuer.example.com:8443/token",
] {
assert!(is_cross_origin(&previous, &url(other)), "{other}");
}
assert!(!is_cross_origin(
&previous,
&url("https://issuer.example.com/other")
));
assert!(!is_cross_origin(&[], &url("https://attacker.example/t")));
}
#[test]
fn no_previous_hop_is_not_a_downgrade() {
assert!(!is_tls_downgrade(&[], &url("http://issuer.example.com/a")));
}
#[test]
fn secure_client_builds() {
let _ = secure_client();
}
#[tokio::test]
async fn follows_same_scheme_redirect() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let dest = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/final"))
.respond_with(ResponseTemplate::new(200).set_body_string("ok"))
.mount(&dest)
.await;
let start = MockServer::start().await;
let location = format!("{}/final", dest.uri());
Mock::given(method("GET"))
.and(path("/start"))
.respond_with(ResponseTemplate::new(302).insert_header("location", location.as_str()))
.mount(&start)
.await;
let resp = secure_client()
.get(format!("{}/start", start.uri()))
.send()
.await
.expect("request succeeds");
assert_eq!(resp.status(), 200);
assert_eq!(resp.text().await.unwrap(), "ok");
let err = secure_client_builder()
.build()
.expect("build client")
.get(format!("{}/start", start.uri()))
.send()
.await
.expect_err("a cross-origin redirect is refused");
assert!(err.is_redirect(), "{err:?}");
assert!(
err.source()
.and_then(|source| source.downcast_ref::<RedirectBlocked>())
.is_some_and(|blocked| matches!(blocked, RedirectBlocked::CrossOrigin)),
"{err:?}"
);
assert!(
RedirectBlocked::CrossOrigin
.to_string()
.contains("redirect to another origin"),
"{err:?}"
);
Mock::given(method("GET"))
.and(path("/moved"))
.respond_with(ResponseTemplate::new(302).insert_header("location", "/here"))
.mount(&dest)
.await;
Mock::given(method("GET"))
.and(path("/here"))
.respond_with(ResponseTemplate::new(200))
.mount(&dest)
.await;
let resp = secure_client_builder()
.build()
.expect("build client")
.get(format!("{}/moved", dest.uri()))
.send()
.await
.expect("same-origin redirect");
assert_eq!(resp.status(), 200);
}
}