a2a_protocol_client/
jwks.rs1use http_body_util::{BodyExt, Full, LengthLimitError, Limited};
34use hyper::body::Bytes;
35use hyper::header;
36
37use a2a_protocol_types::signing::Jwks;
38
39use crate::discovery::CardFetchOptions;
40use crate::error::{ClientError, ClientResult};
41
42pub const MAX_JWKS_BODY_SIZE: usize = 256 * 1024;
44
45pub async fn fetch_jwks(url: &str, options: &CardFetchOptions) -> ClientResult<Jwks> {
64 if !is_trustworthy_url(url) {
65 return Err(ClientError::InvalidEndpoint(format!(
66 "a JWK Set must be fetched over https://, or http:// to a loopback host: {url}"
67 )));
68 }
69
70 #[cfg(not(feature = "tls-rustls"))]
71 let client = {
72 let connector =
74 crate::transport::connector::http_connector(std::time::Duration::from_secs(10));
75 hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new())
76 .build::<_, Full<Bytes>>(connector)
77 };
78 #[cfg(feature = "tls-rustls")]
79 let client = options.https_client();
80
81 let mut builder = hyper::Request::builder()
82 .method(hyper::Method::GET)
83 .uri(crate::redact::without_userinfo(url))
84 .header(header::ACCEPT, "application/jwk-set+json, application/json");
85 for (name, value) in options.jwks_headers() {
86 builder = builder.header(name.as_str(), value.as_str());
87 }
88 let req = builder
89 .body(Full::new(Bytes::new()))
90 .map_err(|e| ClientError::Transport(e.to_string()))?;
91
92 let deadline = tokio::time::Instant::now() + options.timeout();
93 let resp = tokio::time::timeout_at(deadline, client.request(req))
94 .await
95 .map_err(|_| ClientError::Transport("JWK Set fetch timed out".into()))?
96 .map_err(|e| ClientError::HttpClient(crate::error::chain(&e)))?;
97 let status = resp.status();
98 let retry_after = crate::error::parse_retry_after(resp.headers());
99
100 let body = match tokio::time::timeout_at(
101 deadline,
102 Limited::new(resp.into_body(), MAX_JWKS_BODY_SIZE).collect(),
103 )
104 .await
105 {
106 Err(_) => return Err(ClientError::Transport("JWK Set body read timed out".into())),
107 Ok(Ok(collected)) => collected.to_bytes(),
108 Ok(Err(err)) => {
109 return Err(ClientError::Transport(
110 if err.downcast_ref::<LengthLimitError>().is_some() {
111 format!("JWK Set exceeds {MAX_JWKS_BODY_SIZE} bytes")
112 } else {
113 format!("JWK Set body read failed: {err}")
114 },
115 ));
116 }
117 };
118 if !status.is_success() {
119 return Err(ClientError::UnexpectedStatus {
120 status: status.as_u16(),
121 body: String::from_utf8_lossy(&body).into_owned(),
122 retry_after,
123 });
124 }
125 serde_json::from_slice(&body).map_err(ClientError::Serialization)
126}
127
128fn is_trustworthy_url(url: &str) -> bool {
130 if url.starts_with("https://") {
131 return true;
132 }
133 let Some(rest) = url.strip_prefix("http://") else {
134 return false;
135 };
136 let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
137 if authority.contains('@') {
139 return false;
140 }
141 let host = if authority.starts_with('[') {
142 authority.split(']').next().map(|h| format!("{h}]"))
143 } else {
144 authority.split(':').next().map(str::to_owned)
145 };
146 matches!(host.as_deref(), Some("localhost" | "127.0.0.1" | "[::1]"))
147}
148
149#[cfg(test)]
150mod tests {
151 use super::is_trustworthy_url;
152
153 #[test]
154 fn only_https_or_loopback_http_is_fetched() {
155 for ok in [
156 "https://keys.example.com/jwks.json",
157 "http://localhost:8080/jwks.json",
158 "http://127.0.0.1/jwks.json",
159 "http://[::1]:9000/jwks.json",
160 ] {
161 assert!(is_trustworthy_url(ok), "{ok}");
162 }
163 for bad in [
164 "http://keys.example.com/jwks.json",
165 "http://[email protected]/jwks.json",
166 "http://localhost.evil.example/jwks.json",
167 "http://127.0.0.2/jwks.json",
168 "ftp://localhost/jwks.json",
169 "localhost/jwks.json",
170 ] {
171 assert!(!is_trustworthy_url(bad), "{bad}");
172 }
173 }
174}