use async_trait::async_trait;
use std::fmt;
use url::Url;
#[derive(Debug, Clone)]
pub struct FetchedDocument {
pub body: String,
pub cache_control: Option<String>,
}
#[derive(Debug, Clone)]
pub struct FetchError(pub String);
impl fmt::Display for FetchError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "fetch failed: {}", self.0)
}
}
impl std::error::Error for FetchError {}
#[async_trait]
pub trait JwksFetcher: Send + Sync + 'static {
async fn fetch(&self, url: &Url) -> Result<FetchedDocument, FetchError>;
}
pub const MAX_DOCUMENT_BYTES: usize = 1024 * 1024;
#[cfg(feature = "oidc-reqwest")]
pub struct ReqwestJwksFetcher {
client: reqwest::Client,
}
#[cfg(feature = "oidc-reqwest")]
impl ReqwestJwksFetcher {
pub fn new() -> Self {
Self {
client: reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(10))
.redirect(reqwest::redirect::Policy::none())
.build()
.expect("reqwest client with static config always builds"),
}
}
pub fn with_client(client: reqwest::Client) -> Self {
Self { client }
}
}
#[cfg(feature = "oidc-reqwest")]
impl Default for ReqwestJwksFetcher {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "oidc-reqwest")]
#[async_trait]
impl JwksFetcher for ReqwestJwksFetcher {
async fn fetch(&self, url: &Url) -> Result<FetchedDocument, FetchError> {
let resp = self
.client
.get(url.clone())
.send()
.await
.map_err(|e| FetchError(e.to_string()))?;
if !resp.status().is_success() {
return Err(FetchError(format!("{url}: HTTP {}", resp.status())));
}
let cache_control = resp
.headers()
.get(reqwest::header::CACHE_CONTROL)
.and_then(|v| v.to_str().ok())
.map(str::to_string);
if resp.content_length().is_some_and(|n| n > MAX_DOCUMENT_BYTES as u64) {
return Err(FetchError(format!("{url}: body over {MAX_DOCUMENT_BYTES} bytes")));
}
let mut resp = resp;
let mut bytes = Vec::new();
while let Some(chunk) = resp.chunk().await.map_err(|e| FetchError(e.to_string()))? {
if bytes.len() + chunk.len() > MAX_DOCUMENT_BYTES {
return Err(FetchError(format!("{url}: body over {MAX_DOCUMENT_BYTES} bytes")));
}
bytes.extend_from_slice(&chunk);
}
let body = String::from_utf8(bytes).map_err(|e| FetchError(format!("{url}: {e}")))?;
Ok(FetchedDocument { body, cache_control })
}
}
#[cfg(all(test, feature = "oidc-reqwest"))]
mod tests {
use super::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
async fn serve(response: Vec<u8>) -> (Url, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let hits = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let counted = hits.clone();
tokio::spawn(async move {
loop {
let Ok((mut sock, _)) = listener.accept().await else { return };
counted.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let response = response.clone();
tokio::spawn(async move {
let mut buf = [0u8; 4096];
let _ = sock.read(&mut buf).await;
let _ = sock.write_all(&response).await;
let _ = sock.shutdown().await;
});
}
});
(format!("http://{addr}/jwks.json").parse().unwrap(), hits)
}
fn http(status: &str, headers: &str, body: &[u8], length: bool) -> Vec<u8> {
let mut r = format!("HTTP/1.1 {status}\r\nConnection: close\r\n{headers}");
if length {
r.push_str(&format!("Content-Length: {}\r\n", body.len()));
}
r.push_str("\r\n");
let mut r = r.into_bytes();
r.extend_from_slice(body);
r
}
#[tokio::test]
async fn a_small_document_is_read_with_its_cache_control() {
let (url, _) = serve(http("200 OK", "Cache-Control: max-age=120\r\n", br#"{"keys":[]}"#, true)).await;
let doc = ReqwestJwksFetcher::new().fetch(&url).await.unwrap();
assert_eq!(doc.body, r#"{"keys":[]}"#);
assert_eq!(doc.cache_control.as_deref(), Some("max-age=120"));
}
#[tokio::test]
async fn an_oversized_body_is_refused() {
let big = vec![b' '; MAX_DOCUMENT_BYTES + 1];
let (url, _) = serve(http("200 OK", "", &big, true)).await;
let err = ReqwestJwksFetcher::new().fetch(&url).await.unwrap_err();
assert!(err.0.contains("bytes"), "{err}");
let (url, _) = serve(http("200 OK", "", &big, false)).await;
let err = ReqwestJwksFetcher::new().fetch(&url).await.unwrap_err();
assert!(err.0.contains("bytes"), "{err}");
}
#[tokio::test]
async fn a_redirect_is_not_followed() {
let (target, target_hits) = serve(http("200 OK", "", br#"{"keys":[]}"#, true)).await;
let (url, _) = serve(http("302 Found", &format!("Location: {target}\r\n"), b"", true)).await;
let err = ReqwestJwksFetcher::new().fetch(&url).await.unwrap_err();
assert!(err.0.contains("302"), "{err}");
assert_eq!(target_hits.load(std::sync::atomic::Ordering::SeqCst), 0, "the redirect target was fetched");
}
}