Skip to main content

plexus_auth_core/oidc/
fetch.rs

1//! `JwksFetcher` — the validator's HTTP seam (UT-1).
2//!
3//! The OIDC validator never talks HTTP directly; it asks a `JwksFetcher`
4//! for documents. This is what makes the AUTH-2 test matrix runnable with
5//! **no network**: tests inject a fixture fetcher serving a canned
6//! discovery document and JWKS. Production deployments either enable the
7//! `oidc-reqwest` feature for the batteries-included
8//! [`ReqwestJwksFetcher`] or adapt their own HTTP stack to the trait.
9
10use async_trait::async_trait;
11use std::fmt;
12use url::Url;
13
14/// A fetched HTTP document plus the caching metadata the AUTH-8 policy
15/// needs.
16///
17/// Plain-data DTO (public fields, like `AuthContext`): it carries no
18/// authority — the validator independently validates everything it reads
19/// from the body.
20#[derive(Debug, Clone)]
21pub struct FetchedDocument {
22    /// The response body (UTF-8 text; both discovery docs and JWKS are
23    /// JSON).
24    pub body: String,
25    /// The raw `Cache-Control` response header, if the server sent one.
26    /// The validator derives the JWKS TTL from its `max-age` directive,
27    /// clamped to 3600 s (AUTH-8).
28    pub cache_control: Option<String>,
29}
30
31/// A fetch failure. Single-variant-with-message by design: the validator
32/// treats every fetch failure identically (degrade if a cache exists,
33/// reject otherwise) — distinguishing DNS from TLS from 503 buys nothing
34/// at this layer, and the message is preserved for the operator log.
35#[derive(Debug, Clone)]
36pub struct FetchError(pub String);
37
38impl fmt::Display for FetchError {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        write!(f, "fetch failed: {}", self.0)
41    }
42}
43
44impl std::error::Error for FetchError {}
45
46/// Async document fetcher for OIDC discovery and JWKS documents.
47///
48/// `Send + Sync + 'static` because the validator is shared across
49/// concurrent requests (same bounds rationale as
50/// [`SessionValidator`](crate::SessionValidator)).
51#[async_trait]
52pub trait JwksFetcher: Send + Sync + 'static {
53    /// GET the document at `url`.
54    ///
55    /// Implementations should treat non-2xx statuses as `Err` — the
56    /// validator never wants an error page parsed as a key set.
57    async fn fetch(&self, url: &Url) -> Result<FetchedDocument, FetchError>;
58}
59
60/// The most a discovery document or JWKS may weigh (IDENTITY-27). Real
61/// ones are a few KiB; anything past this is refused rather than read.
62pub const MAX_DOCUMENT_BYTES: usize = 1024 * 1024;
63
64/// Batteries-included fetcher over `reqwest` (feature `oidc-reqwest`).
65///
66/// Uses rustls; a 10-second total timeout keeps a wedged IdP from
67/// stalling the request path longer than the degraded-cache policy
68/// already tolerates. IDENTITY-27: redirects are not followed (a 3xx is a
69/// failure — the issuer's documents live where discovery says), and a body
70/// over [`MAX_DOCUMENT_BYTES`] is refused without being read past the cap.
71#[cfg(feature = "oidc-reqwest")]
72pub struct ReqwestJwksFetcher {
73    client: reqwest::Client,
74}
75
76#[cfg(feature = "oidc-reqwest")]
77impl ReqwestJwksFetcher {
78    /// Build with a default 10 s timeout client.
79    pub fn new() -> Self {
80        Self {
81            client: reqwest::Client::builder()
82                .timeout(std::time::Duration::from_secs(10))
83                .redirect(reqwest::redirect::Policy::none())
84                .build()
85                .expect("reqwest client with static config always builds"),
86        }
87    }
88
89    /// Build over a caller-supplied client (custom proxy/timeout/TLS
90    /// posture). The body cap still applies; the redirect policy is the
91    /// client's — build it with `redirect::Policy::none()` to keep the
92    /// default's posture.
93    pub fn with_client(client: reqwest::Client) -> Self {
94        Self { client }
95    }
96}
97
98#[cfg(feature = "oidc-reqwest")]
99impl Default for ReqwestJwksFetcher {
100    fn default() -> Self {
101        Self::new()
102    }
103}
104
105#[cfg(feature = "oidc-reqwest")]
106#[async_trait]
107impl JwksFetcher for ReqwestJwksFetcher {
108    async fn fetch(&self, url: &Url) -> Result<FetchedDocument, FetchError> {
109        let resp = self
110            .client
111            .get(url.clone())
112            .send()
113            .await
114            .map_err(|e| FetchError(e.to_string()))?;
115        if !resp.status().is_success() {
116            return Err(FetchError(format!("{url}: HTTP {}", resp.status())));
117        }
118        let cache_control = resp
119            .headers()
120            .get(reqwest::header::CACHE_CONTROL)
121            .and_then(|v| v.to_str().ok())
122            .map(str::to_string);
123        if resp.content_length().is_some_and(|n| n > MAX_DOCUMENT_BYTES as u64) {
124            return Err(FetchError(format!("{url}: body over {MAX_DOCUMENT_BYTES} bytes")));
125        }
126        let mut resp = resp;
127        let mut bytes = Vec::new();
128        while let Some(chunk) = resp.chunk().await.map_err(|e| FetchError(e.to_string()))? {
129            if bytes.len() + chunk.len() > MAX_DOCUMENT_BYTES {
130                return Err(FetchError(format!("{url}: body over {MAX_DOCUMENT_BYTES} bytes")));
131            }
132            bytes.extend_from_slice(&chunk);
133        }
134        let body = String::from_utf8(bytes).map_err(|e| FetchError(format!("{url}: {e}")))?;
135        Ok(FetchedDocument { body, cache_control })
136    }
137}
138
139#[cfg(all(test, feature = "oidc-reqwest"))]
140mod tests {
141    //! IDENTITY-27: the reqwest fetcher against a one-shot local HTTP
142    //! server (an ephemeral loopback port).
143    use super::*;
144    use tokio::io::{AsyncReadExt, AsyncWriteExt};
145    use tokio::net::TcpListener;
146
147    /// Serve `response` (status line, headers and body) to every
148    /// connection; count the connections.
149    async fn serve(response: Vec<u8>) -> (Url, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
150        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
151        let addr = listener.local_addr().unwrap();
152        let hits = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
153        let counted = hits.clone();
154        tokio::spawn(async move {
155            loop {
156                let Ok((mut sock, _)) = listener.accept().await else { return };
157                counted.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
158                let response = response.clone();
159                tokio::spawn(async move {
160                    let mut buf = [0u8; 4096];
161                    let _ = sock.read(&mut buf).await;
162                    let _ = sock.write_all(&response).await;
163                    let _ = sock.shutdown().await;
164                });
165            }
166        });
167        (format!("http://{addr}/jwks.json").parse().unwrap(), hits)
168    }
169
170    fn http(status: &str, headers: &str, body: &[u8], length: bool) -> Vec<u8> {
171        let mut r = format!("HTTP/1.1 {status}\r\nConnection: close\r\n{headers}");
172        if length {
173            r.push_str(&format!("Content-Length: {}\r\n", body.len()));
174        }
175        r.push_str("\r\n");
176        let mut r = r.into_bytes();
177        r.extend_from_slice(body);
178        r
179    }
180
181    #[tokio::test]
182    async fn a_small_document_is_read_with_its_cache_control() {
183        let (url, _) = serve(http("200 OK", "Cache-Control: max-age=120\r\n", br#"{"keys":[]}"#, true)).await;
184        let doc = ReqwestJwksFetcher::new().fetch(&url).await.unwrap();
185        assert_eq!(doc.body, r#"{"keys":[]}"#);
186        assert_eq!(doc.cache_control.as_deref(), Some("max-age=120"));
187    }
188
189    #[tokio::test]
190    async fn an_oversized_body_is_refused() {
191        let big = vec![b' '; MAX_DOCUMENT_BYTES + 1];
192        // Declared too large…
193        let (url, _) = serve(http("200 OK", "", &big, true)).await;
194        let err = ReqwestJwksFetcher::new().fetch(&url).await.unwrap_err();
195        assert!(err.0.contains("bytes"), "{err}");
196        // …and undeclared (read until the connection closes): cut at the cap.
197        let (url, _) = serve(http("200 OK", "", &big, false)).await;
198        let err = ReqwestJwksFetcher::new().fetch(&url).await.unwrap_err();
199        assert!(err.0.contains("bytes"), "{err}");
200    }
201
202    #[tokio::test]
203    async fn a_redirect_is_not_followed() {
204        let (target, target_hits) = serve(http("200 OK", "", br#"{"keys":[]}"#, true)).await;
205        let (url, _) = serve(http("302 Found", &format!("Location: {target}\r\n"), b"", true)).await;
206        let err = ReqwestJwksFetcher::new().fetch(&url).await.unwrap_err();
207        assert!(err.0.contains("302"), "{err}");
208        assert_eq!(target_hits.load(std::sync::atomic::Ordering::SeqCst), 0, "the redirect target was fetched");
209    }
210}