rs-identity-model 0.8.0

Production-grade, RFC-compliant OIDC/OAuth2 client library for Rust
Documentation
//! Shared HTTP client construction for identity-model's fetch clients.
//!
//! Every client that builds its own default `reqwest::Client` — discovery,
//! JWKS, token, and UserInfo — does so through [`secure_client`] so they share
//! one hardened default: a redirect policy that follows ordinary redirects but
//! **refuses any hop that downgrades the transport from `https` to `http`**. A
//! malicious or misconfigured server must not be able to `3xx` a secure request
//! onto a plaintext URL, where a bearer token, discovery document, or JWK Set
//! could be observed or tampered with (issue #22). Redirects are bounded to
//! [`MAX_REDIRECTS`] hops, matching reqwest's default limit (which a custom
//! policy would otherwise replace).
//!
//! A caller who supplies their own client via a `*Builder::http_client` opts
//! out of this default and is responsible for their own redirect policy.

use std::error::Error;
use std::fmt;

use reqwest::redirect::Policy;
use reqwest::{Client, Url};

/// Maximum number of redirect hops followed before erroring. Matches reqwest's
/// default limit, which the custom policy replaces.
const MAX_REDIRECTS: usize = 10;

/// Builds the hardened default [`reqwest::Client`] shared by the fetch clients.
///
/// Panics only if the underlying TLS backend fails to initialise, matching the
/// behaviour of [`reqwest::Client::new`] / [`reqwest::Client::default`].
pub(crate) fn secure_client() -> Client {
    Client::builder()
        .redirect(no_downgrade_policy())
        .build()
        .expect("build identity-model HTTP client")
}

/// Builds a [`reqwest::Client`] that follows **no** redirects.
///
/// For endpoints that carry a credential or a token in the request body, a
/// followed redirect is not a convenience — it is a correctness and disclosure
/// bug. On a 301/302/303 reqwest rewrites the POST to a GET and drops the body,
/// so the final 2xx reports success for a request whose payload was never
/// delivered. On a 307/308 it preserves both, replaying the form — including
/// `client_secret` on the `client_secret_post` path — to the redirect target;
/// reqwest strips the `Authorization` header across hosts but not the body.
///
/// RFC 7009 defines no redirect semantics for the revocation endpoint, so
/// refusing to follow one and surfacing the 3xx as an error is the honest
/// behaviour.
pub(crate) fn no_redirect_client() -> Client {
    Client::builder()
        .redirect(Policy::none())
        .build()
        .expect("build identity-model non-redirecting HTTP client")
}

/// Returns a [`reqwest::ClientBuilder`] carrying this crate's redirect hardening,
/// so a caller who needs their own client does not silently lose it.
///
/// Supplying a client to `TokenClientBuilder::http_client` (or the discovery and
/// JWKS equivalents) *replaces* the hardened default, including the `https` →
/// `http` redirect refusal. That matters most on the token request, which carries
/// the client secret: an authorization server answering `307 Location:
/// http://issuer/token` would otherwise be followed, and because the host is
/// unchanged reqwest does not strip the `Authorization` header. `allow_http(false)`
/// does not cover this — it validates the configured endpoint scheme, never a
/// redirect target.
///
/// Start from this builder whenever you need to add default headers — attaching a
/// DPoP proof, say — and you keep the defence. This builder also refuses a
/// redirect to a different origin (scheme, host, or port): reqwest forwards
/// default headers such as `DPoP` to the redirect target, and a 307/308 replays
/// the request body with them, which on the `client_secret_post` path includes
/// the client secret.
///
/// ```no_run
/// # use reqwest::header::{HeaderMap, HeaderValue};
/// let mut headers = HeaderMap::new();
/// headers.insert("DPoP", HeaderValue::from_static("..."));
/// let http = rs_identity_model::secure_client_builder()
///     .default_headers(headers)
///     .build()?;
/// # Ok::<(), reqwest::Error>(())
/// ```
pub fn secure_client_builder() -> reqwest::ClientBuilder {
    Client::builder().redirect(same_origin_policy())
}

/// [`no_downgrade_policy`] that also refuses a hop to a different origin, for
/// clients carrying caller-supplied default headers.
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()
    })
}

/// A redirect policy that refuses an `https` → `http` downgrade and bounds the
/// redirect chain to [`MAX_REDIRECTS`] hops.
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()
    })
}

/// Reports whether following `next` from the most recent URL in `previous`
/// would downgrade the transport from `https` to `http`. An upgrade
/// (`http` → `https`) and any same-scheme hop are allowed.
fn is_tls_downgrade(previous: &[Url], next: &Url) -> bool {
    matches!(previous.last(), Some(prev) if prev.scheme() == "https" && next.scheme() == "http")
}

/// Reports whether `next` has a different origin (scheme, host, or port) from
/// the most recent URL in `previous`.
fn is_cross_origin(previous: &[Url], next: &Url) -> bool {
    matches!(previous.last(), Some(prev) if prev.origin() != next.origin())
}

/// Why the redirect policy refused to follow a hop. Surfaced to the caller as
/// the source of the resulting `reqwest` error.
#[derive(Debug)]
enum RedirectBlocked {
    /// The redirect target downgraded the transport from `https` to `http`.
    TlsDowngrade,
    /// The redirect chain exceeded [`MAX_REDIRECTS`] hops.
    TooManyRedirects,
    /// The redirect target is on a different origin.
    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")
    }

    // #22: an https origin redirecting to an http target is a downgrade.
    #[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")
        ));
    }

    // Same-scheme hops and an http->https upgrade are not downgrades.
    #[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")));
        // http -> https is an upgrade, never blocked.
        assert!(!is_tls_downgrade(&http, &url("https://localhost/b")));
    }

    // A different host, scheme, or port is another origin; a path change is not.
    #[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")));
    }

    // With no prior hop there is nothing to downgrade from.
    #[test]
    fn no_previous_hop_is_not_a_downgrade() {
        assert!(!is_tls_downgrade(&[], &url("http://issuer.example.com/a")));
    }

    // The hardened client builds successfully (TLS backend initialises).
    #[test]
    fn secure_client_builds() {
        let _ = secure_client();
    }

    // A same-scheme (http -> http) redirect is still followed: the downgrade
    // guard must not disable ordinary redirect following.
    #[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");

        // The public builder carries caller headers, so it refuses the same hop:
        // the two mock servers listen on different ports, a different origin.
        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:?}"
        );

        // A same-origin hop is still followed.
        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);
    }
}