plexus_auth_core/oidc/
fetch.rs1use async_trait::async_trait;
11use std::fmt;
12use url::Url;
13
14#[derive(Debug, Clone)]
21pub struct FetchedDocument {
22 pub body: String,
25 pub cache_control: Option<String>,
29}
30
31#[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_trait]
52pub trait JwksFetcher: Send + Sync + 'static {
53 async fn fetch(&self, url: &Url) -> Result<FetchedDocument, FetchError>;
58}
59
60pub const MAX_DOCUMENT_BYTES: usize = 1024 * 1024;
63
64#[cfg(feature = "oidc-reqwest")]
72pub struct ReqwestJwksFetcher {
73 client: reqwest::Client,
74}
75
76#[cfg(feature = "oidc-reqwest")]
77impl ReqwestJwksFetcher {
78 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 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 use super::*;
144 use tokio::io::{AsyncReadExt, AsyncWriteExt};
145 use tokio::net::TcpListener;
146
147 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 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 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}