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")
}
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")
}
#[derive(Debug)]
enum RedirectBlocked {
TlsDowngrade,
TooManyRedirects,
}
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})"),
}
}
}
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 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");
}
}