1use std::fmt;
61use std::future::Future;
62use std::pin::Pin;
63use std::sync::Arc;
64use std::time::Duration;
65
66#[cfg(not(feature = "tls-rustls"))]
67use crate::transport::connector::TcpConnector;
68use base64::Engine;
69use base64::engine::general_purpose::STANDARD;
70use http_body_util::Full;
71use hyper::body::Bytes;
72#[cfg(not(feature = "tls-rustls"))]
73use hyper_util::client::legacy::Client;
74#[cfg(not(feature = "tls-rustls"))]
75use hyper_util::rt::TokioExecutor;
76
77use crate::error::{ClientError, ClientResult};
78use crate::interceptor::{CallInterceptor, ClientRequest, ClientResponse};
79
80#[cfg(not(feature = "tls-rustls"))]
81type TokenHttpClient = Client<TcpConnector, Full<Bytes>>;
82#[cfg(feature = "tls-rustls")]
83type TokenHttpClient = crate::tls::HttpsClient;
84
85const MAX_TOKEN_RESPONSE_SIZE: usize = 64 * 1024;
87
88const DEFAULT_TOKEN_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
90
91const DEFAULT_REFRESH_LEEWAY: Duration = Duration::from_secs(30);
93
94const DEFAULT_FAILURE_BACKOFF: Duration = Duration::from_secs(1);
103
104mod exchange;
105pub(crate) mod flight;
106mod trusted_hosts;
107
108pub use exchange::{
109 ACCESS_TOKEN_TYPE, ExchangeRequest, ExchangedToken, JWT_TOKEN_TYPE, TOKEN_EXCHANGE_GRANT,
110 TokenExchange,
111};
112
113const NO_EXPIRY_CACHE_TTL: Duration = Duration::from_secs(60);
117
118fn cache_ttl(expires_in: Option<u64>, leeway: Duration) -> Duration {
127 expires_in.map_or(NO_EXPIRY_CACHE_TTL, |secs| {
128 let lifetime = Duration::from_secs(secs);
129 lifetime.saturating_sub(leeway.min(lifetime / 2))
130 })
131}
132
133pub trait TokenProvider: Send + Sync + 'static {
141 fn access_token(&self) -> Pin<Box<dyn Future<Output = ClientResult<String>> + Send + '_>>;
148
149 fn invalidate(&self, _token: &str) {}
164}
165
166pub struct StaticTokenProvider {
171 token: String,
172}
173
174impl StaticTokenProvider {
175 #[must_use]
177 pub fn new(token: impl Into<String>) -> Self {
178 Self {
179 token: token.into(),
180 }
181 }
182}
183
184impl fmt::Debug for StaticTokenProvider {
185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186 f.debug_struct("StaticTokenProvider")
187 .field("token", &"<redacted>")
188 .finish()
189 }
190}
191
192impl TokenProvider for StaticTokenProvider {
193 fn access_token(&self) -> Pin<Box<dyn Future<Output = ClientResult<String>> + Send + '_>> {
194 Box::pin(async move { Ok(self.token.clone()) })
195 }
196}
197
198pub struct BearerAuthInterceptor {
219 provider: Arc<dyn TokenProvider>,
220}
221
222impl BearerAuthInterceptor {
223 #[must_use]
225 pub fn new(provider: Arc<dyn TokenProvider>) -> Self {
226 Self { provider }
227 }
228}
229
230impl fmt::Debug for BearerAuthInterceptor {
231 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232 f.debug_struct("BearerAuthInterceptor").finish()
233 }
234}
235
236impl CallInterceptor for BearerAuthInterceptor {
237 #[allow(clippy::manual_async_fn)]
238 fn before<'a>(
239 &'a self,
240 req: &'a mut ClientRequest,
241 ) -> impl Future<Output = ClientResult<()>> + Send + 'a {
242 async move {
243 let token = self.provider.access_token().await?;
244 req.extra_headers
245 .insert("authorization".to_owned(), format!("Bearer {token}"));
246 Ok(())
247 }
248 }
249
250 #[allow(clippy::manual_async_fn)]
251 fn after<'a>(
252 &'a self,
253 _resp: &'a ClientResponse,
254 ) -> impl Future<Output = ClientResult<()>> + Send + 'a {
255 async move { Ok(()) }
256 }
257
258 fn on_error<'a>(
263 &'a self,
264 req: &'a ClientRequest,
265 err: &'a ClientError,
266 ) -> impl Future<Output = ()> + Send + 'a {
267 if matches!(err, ClientError::UnexpectedStatus { status: 401, .. })
268 && let Some(token) = req
269 .extra_headers
270 .get("authorization")
271 .and_then(|v| v.strip_prefix("Bearer "))
272 {
273 self.provider.invalidate(token);
274 }
275 std::future::ready(())
276 }
277}
278
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
283pub enum TokenEndpointAuthStyle {
284 Basic,
288 Post,
291}
292
293pub struct OAuth2ClientCredentials {
317 token_url: String,
318 client_id: String,
319 client_secret: zeroize::Zeroizing<String>,
322 scopes: Vec<String>,
323 audience: Option<String>,
324 extra_params: Vec<(String, String)>,
325 auth_style: TokenEndpointAuthStyle,
326 refresh_leeway: Duration,
327 request_timeout: Duration,
328 failure_backoff: Duration,
329 allow_insecure: bool,
332 client: TokenHttpClient,
333 tokens: flight::TokenCache,
334}
335
336impl fmt::Debug for OAuth2ClientCredentials {
337 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338 f.debug_struct("OAuth2ClientCredentials")
339 .field("token_url", &self.token_url)
340 .field("client_id", &self.client_id)
341 .field("client_secret", &"<redacted>")
342 .field("scopes", &self.scopes)
343 .field("audience", &self.audience)
344 .field("auth_style", &self.auth_style)
345 .finish_non_exhaustive()
346 }
347}
348
349impl OAuth2ClientCredentials {
350 #[must_use]
352 pub fn new(
353 token_url: impl Into<String>,
354 client_id: impl Into<String>,
355 client_secret: impl Into<String>,
356 ) -> Self {
357 Self {
358 token_url: token_url.into(),
359 client_id: client_id.into(),
360 client_secret: zeroize::Zeroizing::new(client_secret.into()),
361 scopes: Vec::new(),
362 audience: None,
363 extra_params: Vec::new(),
364 auth_style: TokenEndpointAuthStyle::Basic,
365 refresh_leeway: DEFAULT_REFRESH_LEEWAY,
366 request_timeout: DEFAULT_TOKEN_REQUEST_TIMEOUT,
367 failure_backoff: DEFAULT_FAILURE_BACKOFF,
368 allow_insecure: false,
369 client: build_token_http_client(),
370 tokens: flight::TokenCache::default(),
371 }
372 }
373
374 pub fn from_agent_card(
401 card: &a2a_protocol_types::agent_card::AgentCard,
402 scheme_name: &str,
403 client_id: impl Into<String>,
404 client_secret: impl Into<String>,
405 ) -> ClientResult<Self> {
406 let token_url = card_token_url(card, scheme_name)?;
407 check_endpoint_secure(&token_url, "the agent card's tokenUrl", false)?;
412 Ok(Self::new(token_url, client_id, client_secret))
413 }
414
415 pub async fn from_oidc_issuer(
424 issuer: &str,
425 client_id: impl Into<String>,
426 client_secret: impl Into<String>,
427 ) -> ClientResult<Self> {
428 let token_url = discover_token_endpoint(issuer).await?;
429 Ok(Self::new(token_url, client_id, client_secret))
430 }
431
432 #[must_use]
437 pub const fn allow_insecure_token_endpoint(mut self) -> Self {
438 self.allow_insecure = true;
439 self
440 }
441
442 #[cfg(feature = "tls-rustls")]
453 #[must_use]
454 pub fn with_tls_config(mut self, tls: rustls::ClientConfig) -> Self {
455 self.client = token_http_client_with(tls);
456 self
457 }
458
459 #[must_use]
461 pub fn with_scopes<I, S>(mut self, scopes: I) -> Self
462 where
463 I: IntoIterator<Item = S>,
464 S: Into<String>,
465 {
466 self.scopes = scopes.into_iter().map(Into::into).collect();
467 self
468 }
469
470 #[must_use]
473 pub fn with_audience(mut self, audience: impl Into<String>) -> Self {
474 self.audience = Some(audience.into());
475 self
476 }
477
478 #[must_use]
480 pub fn with_extra_param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
481 self.extra_params.push((key.into(), value.into()));
482 self
483 }
484
485 #[must_use]
488 pub const fn with_auth_style(mut self, style: TokenEndpointAuthStyle) -> Self {
489 self.auth_style = style;
490 self
491 }
492
493 #[must_use]
498 pub const fn with_refresh_leeway(mut self, leeway: Duration) -> Self {
499 self.refresh_leeway = leeway;
500 self
501 }
502
503 #[must_use]
505 pub const fn with_request_timeout(mut self, timeout: Duration) -> Self {
506 self.request_timeout = timeout;
507 self
508 }
509
510 #[must_use]
517 pub const fn with_failure_backoff(mut self, backoff: Duration) -> Self {
518 self.failure_backoff = backoff;
519 self
520 }
521
522 async fn refresh(&self) -> ClientResult<(String, Duration)> {
525 check_endpoint_secure(&self.token_url, "token endpoint", self.allow_insecure)?;
526 check_endpoint_reachable(
527 cfg!(feature = "tls-rustls"),
528 &self.token_url,
529 "token endpoint",
530 )?;
531
532 let req = self.build_token_request()?;
533 let deadline = tokio::time::Instant::now() + self.request_timeout;
539 let resp = tokio::time::timeout_at(deadline, self.client.request(req))
540 .await
541 .map_err(|_| ClientError::Timeout("token endpoint request timed out".into()))?
542 .map_err(|e| {
547 ClientError::HttpClient(format!(
548 "token endpoint request failed: {}",
549 crate::error::chain(&e)
550 ))
551 })?;
552
553 let status = resp.status();
554 let body = crate::transport::collect_response_limited(
555 resp,
556 MAX_TOKEN_RESPONSE_SIZE,
557 deadline.saturating_duration_since(tokio::time::Instant::now()),
558 )
559 .await?;
560 if !status.is_success() {
561 return Err(token_error(status, &body));
562 }
563
564 let token_resp: TokenResponse = serde_json::from_slice(&body).map_err(|e| {
565 ClientError::Transport(format!("token endpoint returned invalid JSON: {e}"))
566 })?;
567 if let Some(ref tt) = token_resp.token_type
568 && !tt.eq_ignore_ascii_case("bearer")
569 {
570 return Err(ClientError::Transport(format!(
571 "token endpoint returned unsupported token_type {tt:?} (expected \"Bearer\")"
572 )));
573 }
574
575 let ttl = cache_ttl(token_resp.expires_in, self.refresh_leeway);
576 Ok((token_resp.access_token, ttl))
577 }
578
579 fn build_token_request(&self) -> ClientResult<hyper::Request<Full<Bytes>>> {
581 let mut form: Vec<(String, String)> =
582 vec![("grant_type".to_owned(), "client_credentials".to_owned())];
583 if !self.scopes.is_empty() {
584 form.push(("scope".to_owned(), self.scopes.join(" ")));
585 }
586 if let Some(ref aud) = self.audience {
587 form.push(("audience".to_owned(), aud.clone()));
588 }
589 for (k, v) in &self.extra_params {
590 form.push((k.clone(), v.clone()));
591 }
592 if self.auth_style == TokenEndpointAuthStyle::Post {
593 form.push(("client_id".to_owned(), self.client_id.clone()));
594 form.push(("client_secret".to_owned(), (*self.client_secret).clone()));
595 }
596
597 let mut builder = hyper::Request::builder()
598 .method(hyper::Method::POST)
599 .uri(&self.token_url)
600 .header("content-type", "application/x-www-form-urlencoded")
601 .header("accept", "application/json");
602 if self.auth_style == TokenEndpointAuthStyle::Basic {
603 let credentials = format!(
605 "{}:{}",
606 form_urlencode(&self.client_id),
607 form_urlencode(&self.client_secret)
608 );
609 builder = builder.header(
610 "authorization",
611 format!("Basic {}", STANDARD.encode(credentials)),
612 );
613 }
614 builder
615 .body(Full::new(Bytes::from(encode_form(&form))))
616 .map_err(|e| ClientError::Transport(format!("token request build failed: {e}")))
617 }
618}
619
620fn token_error(status: hyper::StatusCode, body: &[u8]) -> ClientError {
623 let detail = serde_json::from_slice::<OAuth2ErrorBody>(body).map_or_else(
624 |_| String::from_utf8_lossy(&body[..body.len().min(256)]).into_owned(),
625 |e| match e.error_description {
626 Some(desc) => format!("{}: {desc}", e.error),
627 None => e.error,
628 },
629 );
630 ClientError::Transport(format!("token endpoint returned HTTP {status}: {detail}"))
631}
632
633impl TokenProvider for OAuth2ClientCredentials {
634 fn access_token(&self) -> Pin<Box<dyn Future<Output = ClientResult<String>> + Send + '_>> {
635 Box::pin(self.tokens.get(self.failure_backoff, || self.refresh()))
638 }
639
640 fn invalidate(&self, token: &str) {
641 self.tokens.invalidate(token);
642 }
643}
644
645#[derive(serde::Deserialize)]
647struct TokenResponse {
648 access_token: String,
649 #[serde(default)]
650 token_type: Option<String>,
651 #[serde(default)]
652 expires_in: Option<u64>,
653}
654
655#[derive(serde::Deserialize)]
657struct OAuth2ErrorBody {
658 error: String,
659 #[serde(default)]
660 error_description: Option<String>,
661}
662
663pub async fn discover_token_endpoint(issuer: &str) -> ClientResult<String> {
673 discover_token_endpoint_within(issuer, DEFAULT_TOKEN_REQUEST_TIMEOUT).await
674}
675
676#[cfg(feature = "tls-rustls")]
685pub async fn discover_token_endpoint_with_tls_config(
686 issuer: &str,
687 tls: rustls::ClientConfig,
688) -> ClientResult<String> {
689 discover_using(
690 &token_http_client_with(tls),
691 issuer,
692 DEFAULT_TOKEN_REQUEST_TIMEOUT,
693 )
694 .await
695}
696
697pub(crate) async fn discover_token_endpoint_within(
703 issuer: &str,
704 budget: Duration,
705) -> ClientResult<String> {
706 discover_using(&build_token_http_client(), issuer, budget).await
707}
708
709async fn discover_using(
711 client: &TokenHttpClient,
712 issuer: &str,
713 budget: Duration,
714) -> ClientResult<String> {
715 #[derive(serde::Deserialize)]
716 struct Discovery {
717 issuer: Option<String>,
718 token_endpoint: Option<String>,
719 }
720 let url = format!(
721 "{}/.well-known/openid-configuration",
722 issuer.trim_end_matches('/')
723 );
724 check_endpoint_secure(&url, "OIDC discovery URL", false)?;
727 check_endpoint_reachable(cfg!(feature = "tls-rustls"), &url, "OIDC discovery")?;
728
729 let req = hyper::Request::builder()
730 .method(hyper::Method::GET)
731 .uri(&url)
732 .header("accept", "application/json")
733 .body(Full::new(Bytes::new()))
734 .map_err(|e| ClientError::Transport(format!("discovery request build failed: {e}")))?;
735
736 let deadline = tokio::time::Instant::now() + budget;
737 let resp = tokio::time::timeout_at(deadline, client.request(req))
738 .await
739 .map_err(|_| ClientError::Timeout("OIDC discovery request timed out".into()))?
740 .map_err(|e| {
741 ClientError::HttpClient(format!(
742 "OIDC discovery request failed: {}",
743 crate::error::chain(&e)
744 ))
745 })?;
746
747 let status = resp.status();
748 let body = crate::transport::collect_response_limited(
749 resp,
750 MAX_TOKEN_RESPONSE_SIZE,
751 deadline.saturating_duration_since(tokio::time::Instant::now()),
752 )
753 .await?;
754 if !status.is_success() {
755 return Err(ClientError::Transport(format!(
756 "OIDC discovery returned HTTP {status}"
757 )));
758 }
759
760 let doc: Discovery = serde_json::from_slice(&body).map_err(|e| {
761 ClientError::Transport(format!("OIDC discovery returned invalid JSON: {e}"))
762 })?;
763 check_issuer(doc.issuer.as_deref(), issuer)?;
764 doc.token_endpoint.ok_or_else(|| {
765 ClientError::Transport("OIDC discovery document has no token_endpoint".into())
766 })
767}
768
769fn check_issuer(found: Option<&str>, asked: &str) -> ClientResult<()> {
774 match found {
775 Some(found) if found.trim_end_matches('/') == asked.trim_end_matches('/') => Ok(()),
776 Some(found) => Err(ClientError::Transport(format!(
777 "OIDC discovery document is for issuer {found:?}, not {asked:?}"
778 ))),
779 None => Err(ClientError::Transport(
780 "OIDC discovery document has no issuer to check against".into(),
781 )),
782 }
783}
784
785const TOKEN_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
789
790#[cfg(feature = "tls-rustls")]
793fn token_http_client_with(tls: rustls::ClientConfig) -> TokenHttpClient {
794 crate::tls::build_https_client_with_connect_timeout(tls, TOKEN_CONNECT_TIMEOUT)
795}
796
797fn build_token_http_client() -> TokenHttpClient {
798 #[cfg(not(feature = "tls-rustls"))]
799 {
800 Client::builder(TokioExecutor::new()).build(crate::transport::connector::http_connector(
802 TOKEN_CONNECT_TIMEOUT,
803 ))
804 }
805 #[cfg(feature = "tls-rustls")]
806 {
807 token_http_client_with(crate::tls::default_tls_config())
808 }
809}
810
811fn check_endpoint_reachable(tls: bool, url: &str, what: &str) -> ClientResult<()> {
817 let is_https = url
818 .split_once("://")
819 .is_some_and(|(scheme, _)| scheme.eq_ignore_ascii_case("https"));
820 if is_https && !tls {
821 return Err(ClientError::Transport(format!(
822 "{what} URL {url} is https:// but this build has no TLS; enable the \
823 `tls-rustls` feature (on by default)"
824 )));
825 }
826 Ok(())
827}
828
829fn card_token_url(
832 card: &a2a_protocol_types::agent_card::AgentCard,
833 scheme_name: &str,
834) -> ClientResult<String> {
835 use a2a_protocol_types::security::{OAuthFlows, SecurityScheme};
836
837 let scheme = card
838 .security_schemes
839 .as_ref()
840 .and_then(|schemes| schemes.get(scheme_name))
841 .ok_or_else(|| {
842 ClientError::InvalidEndpoint(format!(
843 "agent card has no security scheme named {scheme_name:?}"
844 ))
845 })?;
846 let SecurityScheme::OAuth2(oauth2) = scheme else {
847 return Err(ClientError::InvalidEndpoint(format!(
848 "security scheme {scheme_name:?} is not an OAuth 2.0 scheme"
849 )));
850 };
851 let OAuthFlows::ClientCredentials(flow) = &oauth2.flows else {
852 return Err(ClientError::InvalidEndpoint(format!(
853 "security scheme {scheme_name:?} has no client-credentials flow \
854 (interactive flows need a custom TokenProvider)"
855 )));
856 };
857 Ok(flow.token_url.clone())
858}
859
860fn check_endpoint_secure(url: &str, what: &str, allow_insecure: bool) -> ClientResult<()> {
868 if !allow_insecure && crate::loopback::is_plaintext_to_remote(url) {
869 return Err(ClientError::InvalidEndpoint(format!(
870 "{what} {} is plaintext http:// to a remote host, so a client secret or token \
871 sent to it would cross the network in the clear; use https://, or call \
872 `allow_insecure_token_endpoint()` for a network you trust",
873 crate::loopback::origin(url)
874 )));
875 }
876 Ok(())
877}
878
879fn form_urlencode(value: &str) -> String {
881 let mut out = String::with_capacity(value.len());
882 for byte in value.bytes() {
883 match byte {
884 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
885 out.push(byte as char);
886 }
887 b' ' => out.push('+'),
888 other => {
889 out.push('%');
890 out.push(
891 char::from_digit(u32::from(other >> 4), 16)
892 .unwrap_or('0')
893 .to_ascii_uppercase(),
894 );
895 out.push(
896 char::from_digit(u32::from(other & 0xf), 16)
897 .unwrap_or('0')
898 .to_ascii_uppercase(),
899 );
900 }
901 }
902 }
903 out
904}
905
906fn encode_form(pairs: &[(String, String)]) -> String {
908 pairs
909 .iter()
910 .map(|(k, v)| format!("{}={}", form_urlencode(k), form_urlencode(v)))
911 .collect::<Vec<_>>()
912 .join("&")
913}
914
915#[cfg(test)]
918mod bearer_tests;
919
920#[cfg(test)]
921mod tests {
922 use super::*;
923 use std::sync::atomic::{AtomicUsize, Ordering};
924 use std::time::Instant;
925
926 #[test]
929 fn form_urlencode_passes_unreserved() {
930 assert_eq!(form_urlencode("Abc-123._~"), "Abc-123._~");
931 }
932
933 #[test]
934 fn form_urlencode_escapes_reserved_and_space() {
935 assert_eq!(form_urlencode("a b&c=d%"), "a+b%26c%3Dd%25");
936 assert_eq!(form_urlencode("秘"), "%E7%A7%98");
937 }
938
939 #[test]
940 fn encode_form_joins_pairs() {
941 let pairs = vec![
942 ("grant_type".to_owned(), "client_credentials".to_owned()),
943 ("scope".to_owned(), "a b".to_owned()),
944 ];
945 assert_eq!(
946 encode_form(&pairs),
947 "grant_type=client_credentials&scope=a+b"
948 );
949 }
950
951 #[test]
957 fn https_endpoints_are_refused_by_a_build_without_tls() {
958 let err =
959 check_endpoint_reachable(false, "HTTPS://auth.example.com/token", "token endpoint")
960 .expect_err("no TLS");
961 assert!(
962 matches!(&err, ClientError::Transport(m) if m.contains("tls-rustls")),
963 "{err:?}"
964 );
965 assert!(
966 check_endpoint_reachable(false, "http://auth.example.com/token", "token endpoint")
967 .is_ok()
968 );
969 assert!(
970 check_endpoint_reachable(true, "https://auth.example.com/token", "token endpoint")
971 .is_ok()
972 );
973 assert!(
974 check_endpoint_reachable(true, "http://auth.example.com/token", "token endpoint")
975 .is_ok()
976 );
977 }
978
979 #[test]
982 fn debug_redacts_secrets() {
983 let p = StaticTokenProvider::new("super-secret");
984 let dbg = format!("{p:?}");
985 assert!(!dbg.contains("super-secret"), "secret leaked: {dbg}");
986 assert!(
991 dbg.contains("StaticTokenProvider"),
992 "Debug must name the type; empty output would pass the redaction \
993 check while telling a reader nothing: {dbg}"
994 );
995 assert!(
996 dbg.contains("<redacted>"),
997 "the token field must be present and redacted, not omitted: {dbg}"
998 );
999
1000 let o = OAuth2ClientCredentials::new("http://localhost/token", "id", "very-secret");
1001 let dbg = format!("{o:?}");
1002 assert!(!dbg.contains("very-secret"), "secret leaked: {dbg}");
1003 assert!(dbg.contains("id"), "client_id should be visible");
1004 }
1005
1006 #[test]
1009 fn bearer_interceptor_debug_names_the_type() {
1010 let interceptor = BearerAuthInterceptor::new(Arc::new(StaticTokenProvider::new("t")));
1011 let dbg = format!("{interceptor:?}");
1012 assert!(
1013 dbg.contains("BearerAuthInterceptor"),
1014 "Debug must name the type, got: {dbg:?}"
1015 );
1016 }
1017
1018 #[tokio::test]
1021 async fn static_provider_returns_token() {
1022 let p = StaticTokenProvider::new("tok-1");
1023 assert_eq!(p.access_token().await.unwrap(), "tok-1");
1024 }
1025
1026 #[tokio::test]
1027 async fn bearer_interceptor_injects_header() {
1028 let p: Arc<dyn TokenProvider> = Arc::new(StaticTokenProvider::new("tok-xyz"));
1029 let interceptor = BearerAuthInterceptor::new(p);
1030 let mut req = ClientRequest::new("message/send", serde_json::json!({}));
1031 interceptor.before(&mut req).await.unwrap();
1032 assert_eq!(
1033 req.extra_headers.get("authorization").map(String::as_str),
1034 Some("Bearer tok-xyz")
1035 );
1036 }
1037
1038 #[test]
1044 fn a_plaintext_token_endpoint_on_another_machine_is_refused() {
1045 for url in [
1046 "http://auth.example.com/token",
1047 "http://198.51.100.1/token",
1048 "HTTP://auth.example.com/token",
1049 "http://[email protected]/token",
1050 "http://10.0.0.5:8080/token",
1051 ] {
1052 let err = check_endpoint_secure(url, "token endpoint", false).expect_err(url);
1053 assert!(
1054 matches!(err, ClientError::InvalidEndpoint(_)),
1055 "{url}: {err:?}"
1056 );
1057 assert!(
1058 check_endpoint_secure(url, "token endpoint", true).is_ok(),
1059 "the opt-out lets {url} through"
1060 );
1061 }
1062 for url in [
1063 "https://auth.example.com/token",
1064 "http://127.0.0.1:9000/token",
1065 "http://localhost/token",
1066 "http://[::1]:8080/token",
1067 ] {
1068 assert!(
1069 check_endpoint_secure(url, "token endpoint", false).is_ok(),
1070 "{url}"
1071 );
1072 }
1073 }
1074
1075 #[test]
1076 fn the_refusal_names_the_origin_and_not_the_path_or_the_query() {
1077 let err = check_endpoint_secure(
1078 "http://auth.example.com/token?client_secret=hunter2",
1079 "token endpoint",
1080 false,
1081 )
1082 .expect_err("refused");
1083 let text = err.to_string();
1084 assert!(text.contains("http://auth.example.com"), "{text}");
1085 assert!(
1086 !text.contains("hunter2") && !text.contains("/token"),
1087 "{text}"
1088 );
1089 }
1090
1091 #[tokio::test]
1092 async fn a_provider_aimed_at_a_plaintext_remote_endpoint_sends_nothing() {
1093 let provider = OAuth2ClientCredentials::new("http://198.51.100.1/token", "id", "sec");
1096 let started = std::time::Instant::now();
1097 let err = provider.access_token().await.expect_err("refused");
1098 assert!(matches!(err, ClientError::InvalidEndpoint(_)), "{err:?}");
1099 assert!(
1100 started.elapsed() < Duration::from_secs(2),
1101 "no connection was tried"
1102 );
1103 }
1104
1105 #[test]
1106 fn the_opt_out_is_off_by_default_and_the_setter_turns_it_on() {
1107 let p = OAuth2ClientCredentials::new("http://x.example/t", "id", "sec");
1108 assert!(!p.allow_insecure);
1109 assert!(p.allow_insecure_token_endpoint().allow_insecure);
1110 }
1111
1112 #[test]
1113 fn a_card_that_names_a_plaintext_remote_token_url_is_refused() {
1114 use a2a_protocol_types::security::{ClientCredentialsFlow, OAuthFlows};
1115 let flow = |url: &str| {
1116 card_with_oauth2(OAuthFlows::ClientCredentials(ClientCredentialsFlow::new(
1117 url,
1118 )))
1119 };
1120 let err = OAuth2ClientCredentials::from_agent_card(
1121 &flow("http://idp.example/token"),
1122 "oauth",
1123 "id",
1124 "sec",
1125 )
1126 .expect_err("a card cannot send the secret in the clear");
1127 assert!(matches!(err, ClientError::InvalidEndpoint(_)), "{err:?}");
1128 for ok in ["https://idp.example/token", "http://127.0.0.1:9/token"] {
1129 OAuth2ClientCredentials::from_agent_card(&flow(ok), "oauth", "id", "sec")
1130 .unwrap_or_else(|e| panic!("{ok}: {e}"));
1131 }
1132 }
1133
1134 async fn discovery_server(body: &str) -> (std::net::SocketAddr, Arc<AtomicUsize>) {
1137 let hits = Arc::new(AtomicUsize::new(0));
1138 let addr = spawn_token_server(
1139 vec![(200, body.to_owned())],
1140 Arc::new(std::sync::Mutex::new(Vec::new())),
1141 Arc::clone(&hits),
1142 )
1143 .await;
1144 (addr, hits)
1145 }
1146
1147 #[tokio::test]
1150 async fn a_discovery_document_for_another_issuer_is_refused() {
1151 let (addr, _) = discovery_server(
1152 r#"{"issuer":"https://elsewhere.example","token_endpoint":"https://elsewhere.example/t"}"#,
1153 )
1154 .await;
1155 let err = discover_token_endpoint(&format!("http://{addr}"))
1156 .await
1157 .expect_err("wrong issuer");
1158 let text = err.to_string();
1159 assert!(
1160 text.contains("elsewhere.example") && text.contains("not"),
1161 "{text}"
1162 );
1163 }
1164
1165 #[tokio::test]
1166 async fn a_discovery_document_without_an_issuer_is_refused() {
1167 let (addr, _) = discovery_server(r#"{"token_endpoint":"https://idp.example/t"}"#).await;
1168 let err = discover_token_endpoint(&format!("http://{addr}"))
1169 .await
1170 .expect_err("no issuer to check");
1171 assert!(err.to_string().contains("no issuer"), "{err}");
1172 }
1173
1174 #[tokio::test]
1175 async fn a_trailing_slash_on_either_side_is_not_a_different_issuer() {
1176 let (addr, _) =
1178 discovery_server(r#"{"issuer":"http://{ADDR}/","token_endpoint":"https://i/t"}"#).await;
1179 assert_eq!(
1180 discover_token_endpoint(&format!("http://{addr}"))
1181 .await
1182 .unwrap(),
1183 "https://i/t"
1184 );
1185 let (addr, _) =
1186 discovery_server(r#"{"issuer":"http://{ADDR}","token_endpoint":"https://i/t"}"#).await;
1187 assert_eq!(
1188 discover_token_endpoint(&format!("http://{addr}/"))
1189 .await
1190 .unwrap(),
1191 "https://i/t"
1192 );
1193 }
1194
1195 #[tokio::test]
1196 async fn discovery_over_plaintext_to_another_machine_is_refused_without_a_connection() {
1197 let started = std::time::Instant::now();
1198 let err = discover_token_endpoint("http://198.51.100.1")
1199 .await
1200 .expect_err("refused");
1201 assert!(matches!(err, ClientError::InvalidEndpoint(_)), "{err:?}");
1202 assert!(started.elapsed() < Duration::from_secs(2));
1203 }
1204
1205 pub(super) fn card_with_oauth2(
1208 flows: a2a_protocol_types::security::OAuthFlows,
1209 ) -> a2a_protocol_types::agent_card::AgentCard {
1210 use a2a_protocol_types::agent_card::{AgentCapabilities, AgentCard};
1211 use a2a_protocol_types::security::{OAuth2SecurityScheme, SecurityScheme};
1212 let mut schemes = std::collections::HashMap::new();
1213 schemes.insert(
1214 "oauth".to_owned(),
1215 SecurityScheme::OAuth2(Box::new(OAuth2SecurityScheme::new(flows))),
1216 );
1217 {
1218 let mut built = AgentCard::new(
1219 "a",
1220 "1",
1221 a2a_protocol_types::AgentInterface::jsonrpc(String::new()),
1222 );
1223 built.url = None;
1224 built.description = "d".into();
1225 built.supported_interfaces = vec![];
1226 built.default_input_modes = vec![];
1227 built.default_output_modes = vec![];
1228 built.skills = vec![];
1229 built.capabilities = AgentCapabilities::none();
1230 built.provider = None;
1231 built.icon_url = None;
1232 built.documentation_url = None;
1233 built.security_schemes = Some(schemes);
1234 built.security_requirements = None;
1235 built.signatures = None;
1236 built
1237 }
1238 }
1239
1240 #[test]
1241 fn from_agent_card_reads_token_url() {
1242 use a2a_protocol_types::security::{ClientCredentialsFlow, OAuthFlows};
1243 let card = card_with_oauth2(OAuthFlows::ClientCredentials(ClientCredentialsFlow::new(
1244 "https://auth.example.com/token",
1245 )));
1246 let p = OAuth2ClientCredentials::from_agent_card(&card, "oauth", "id", "sec").unwrap();
1247 assert_eq!(p.token_url, "https://auth.example.com/token");
1248 }
1249
1250 #[test]
1251 fn from_agent_card_missing_scheme_errors() {
1252 use a2a_protocol_types::security::{ClientCredentialsFlow, OAuthFlows};
1253 let card = card_with_oauth2(OAuthFlows::ClientCredentials(ClientCredentialsFlow::new(
1254 "https://auth.example.com/token",
1255 )));
1256 let err = OAuth2ClientCredentials::from_agent_card(&card, "nope", "id", "sec")
1257 .expect_err("missing scheme");
1258 assert!(err.to_string().contains("no security scheme"));
1259 }
1260
1261 #[test]
1262 #[allow(deprecated)] fn from_agent_card_wrong_flow_errors() {
1264 use a2a_protocol_types::security::{ImplicitFlow, OAuthFlows};
1265 let card = card_with_oauth2(OAuthFlows::Implicit(ImplicitFlow::new(
1266 "https://auth.example.com/authz",
1267 )));
1268 let err = OAuth2ClientCredentials::from_agent_card(&card, "oauth", "id", "sec")
1269 .expect_err("implicit flow is not client-credentials");
1270 assert!(err.to_string().contains("client-credentials"));
1271 }
1272
1273 async fn spawn_token_server(
1278 responses: Vec<(u16, String)>,
1279 captured: Arc<std::sync::Mutex<Vec<(String, String)>>>,
1280 hits: Arc<AtomicUsize>,
1281 ) -> std::net::SocketAddr {
1282 use http_body_util::BodyExt;
1283 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1284 let addr = listener.local_addr().unwrap();
1285 let responses: Vec<(u16, String)> = responses
1288 .into_iter()
1289 .map(|(status, body)| (status, body.replace("{ADDR}", &addr.to_string())))
1290 .collect();
1291 tokio::spawn(async move {
1292 loop {
1293 let Ok((stream, _)) = listener.accept().await else {
1294 break;
1295 };
1296 let responses = responses.clone();
1297 let captured = Arc::clone(&captured);
1298 let hits = Arc::clone(&hits);
1299 tokio::spawn(async move {
1300 let io = hyper_util::rt::TokioIo::new(stream);
1301 let svc = hyper::service::service_fn(
1302 move |req: hyper::Request<hyper::body::Incoming>| {
1303 let responses = responses.clone();
1304 let captured = Arc::clone(&captured);
1305 let hits = Arc::clone(&hits);
1306 async move {
1307 let n = hits.fetch_add(1, Ordering::SeqCst);
1308 let auth = req
1309 .headers()
1310 .get("authorization")
1311 .and_then(|v| v.to_str().ok())
1312 .unwrap_or("")
1313 .to_owned();
1314 let body = req.into_body().collect().await.unwrap().to_bytes();
1315 captured
1316 .lock()
1317 .unwrap()
1318 .push((auth, String::from_utf8_lossy(&body).into_owned()));
1319 let (status, body) = responses
1320 .get(n)
1321 .or_else(|| responses.last())
1322 .unwrap()
1323 .clone();
1324 Ok::<_, std::convert::Infallible>(
1325 hyper::Response::builder()
1326 .status(status)
1327 .header("content-type", "application/json")
1328 .body(Full::new(Bytes::from(body)))
1329 .unwrap(),
1330 )
1331 }
1332 },
1333 );
1334 let _ = hyper::server::conn::http1::Builder::new()
1335 .serve_connection(io, svc)
1336 .await;
1337 });
1338 }
1339 });
1340 addr
1341 }
1342
1343 use crate::transport::test_support::spawn_stalling_server;
1344
1345 async fn timed_failure<T: std::fmt::Debug>(
1348 fut: impl std::future::Future<Output = ClientResult<T>>,
1349 ) -> (ClientError, Duration) {
1350 let started = Instant::now();
1351 let err = fut.await.expect_err("a stalled body must not succeed");
1352 (err, started.elapsed())
1353 }
1354
1355 #[tokio::test]
1361 async fn a_stalled_token_body_is_bounded_by_one_request_timeout() {
1362 let timeout = Duration::from_millis(600);
1363 let addr = spawn_stalling_server("HTTP/1.1 200 OK", timeout * 2 / 3).await;
1364 let p = OAuth2ClientCredentials::new(format!("http://{addr}/token"), "cid", "csec")
1365 .with_request_timeout(timeout);
1366
1367 let (err, elapsed) = timed_failure(p.refresh()).await;
1368 assert!(matches!(err, ClientError::Timeout(_)), "{err:?}");
1369 assert!(
1370 elapsed >= timeout && elapsed < timeout * 3 / 2,
1371 "one budget, not two: took {elapsed:?} against {timeout:?}"
1372 );
1373 }
1374
1375 #[tokio::test]
1378 async fn a_stalled_discovery_body_is_bounded_by_one_budget() {
1379 let budget = Duration::from_millis(600);
1380 let addr = spawn_stalling_server("HTTP/1.1 200 OK", budget * 2 / 3).await;
1381
1382 let (err, elapsed) = timed_failure(discover_token_endpoint_within(
1383 &format!("http://{addr}"),
1384 budget,
1385 ))
1386 .await;
1387 assert!(matches!(err, ClientError::Timeout(_)), "{err:?}");
1388 assert!(
1389 elapsed >= budget && elapsed < budget * 3 / 2,
1390 "one budget, not two: took {elapsed:?} against {budget:?}"
1391 );
1392 }
1393
1394 fn token_body(token: &str, expires_in: Option<u64>) -> String {
1395 expires_in.map_or_else(
1396 || format!(r#"{{"access_token":"{token}","token_type":"Bearer"}}"#),
1397 |e| format!(r#"{{"access_token":"{token}","token_type":"Bearer","expires_in":{e}}}"#),
1398 )
1399 }
1400
1401 #[tokio::test]
1402 async fn fetches_and_caches_token() {
1403 let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
1404 let hits = Arc::new(AtomicUsize::new(0));
1405 let addr = spawn_token_server(
1406 vec![(200, token_body("tok-a", Some(3600)))],
1407 Arc::clone(&captured),
1408 Arc::clone(&hits),
1409 )
1410 .await;
1411
1412 let p = OAuth2ClientCredentials::new(format!("http://{addr}/token"), "cid", "csec")
1413 .with_scopes(["read", "write"]);
1414 assert_eq!(p.access_token().await.unwrap(), "tok-a");
1415 assert_eq!(p.access_token().await.unwrap(), "tok-a");
1416 assert_eq!(
1417 hits.load(Ordering::SeqCst),
1418 1,
1419 "second call must be served from cache"
1420 );
1421
1422 let (auth, body) = { captured.lock().unwrap()[0].clone() };
1423 assert!(auth.starts_with("Basic "), "default auth style is Basic");
1424 let decoded =
1425 String::from_utf8(STANDARD.decode(auth.trim_start_matches("Basic ")).unwrap()).unwrap();
1426 assert_eq!(decoded, "cid:csec");
1427 assert!(body.contains("grant_type=client_credentials"), "{body}");
1428 assert!(body.contains("scope=read+write"), "{body}");
1429 assert!(
1430 !body.contains("client_secret"),
1431 "Basic style must not put the secret in the body: {body}"
1432 );
1433 }
1434
1435 #[tokio::test]
1436 async fn post_auth_style_puts_credentials_in_body() {
1437 let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
1438 let hits = Arc::new(AtomicUsize::new(0));
1439 let addr = spawn_token_server(
1440 vec![(200, token_body("tok-b", Some(3600)))],
1441 Arc::clone(&captured),
1442 Arc::clone(&hits),
1443 )
1444 .await;
1445
1446 let p = OAuth2ClientCredentials::new(format!("http://{addr}/token"), "cid", "csec")
1447 .with_auth_style(TokenEndpointAuthStyle::Post);
1448 assert_eq!(p.access_token().await.unwrap(), "tok-b");
1449
1450 let (auth, body) = { captured.lock().unwrap()[0].clone() };
1451 assert!(auth.is_empty(), "no Authorization header in Post style");
1452 assert!(body.contains("client_id=cid"), "{body}");
1453 assert!(body.contains("client_secret=csec"), "{body}");
1454 }
1455
1456 #[tokio::test]
1457 async fn expired_token_is_refreshed() {
1458 let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
1459 let hits = Arc::new(AtomicUsize::new(0));
1460 let addr = spawn_token_server(
1461 vec![
1462 (200, token_body("tok-1", Some(0))),
1465 (200, token_body("tok-2", Some(3600))),
1466 ],
1467 Arc::clone(&captured),
1468 Arc::clone(&hits),
1469 )
1470 .await;
1471
1472 let p = OAuth2ClientCredentials::new(format!("http://{addr}/token"), "cid", "csec");
1473 assert_eq!(p.access_token().await.unwrap(), "tok-1");
1474 assert_eq!(p.access_token().await.unwrap(), "tok-2");
1475 assert_eq!(hits.load(Ordering::SeqCst), 2);
1476 }
1477
1478 #[tokio::test]
1482 async fn a_token_shorter_than_the_leeway_is_still_cached() {
1483 let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
1484 let hits = Arc::new(AtomicUsize::new(0));
1485 let addr = spawn_token_server(
1486 vec![(200, token_body("short", Some(20)))],
1487 Arc::clone(&captured),
1488 Arc::clone(&hits),
1489 )
1490 .await;
1491
1492 let p = OAuth2ClientCredentials::new(format!("http://{addr}/token"), "cid", "csec");
1493 assert_eq!(p.access_token().await.unwrap(), "short");
1494 assert_eq!(p.access_token().await.unwrap(), "short");
1495 assert_eq!(
1496 hits.load(Ordering::SeqCst),
1497 1,
1498 "a 20 s token must not be refetched on the next call"
1499 );
1500 }
1501
1502 #[test]
1503 fn cache_ttl_keeps_at_least_half_the_lifetime() {
1504 let leeway = Duration::from_secs(30);
1505 let secs = Duration::from_secs;
1506 assert_eq!(cache_ttl(Some(3600), leeway), secs(3570));
1508 assert_eq!(cache_ttl(Some(61), leeway), secs(31));
1509 assert_eq!(cache_ttl(Some(60), leeway), secs(30));
1511 assert_eq!(cache_ttl(Some(40), leeway), secs(20));
1513 assert_eq!(cache_ttl(Some(30), leeway), secs(15));
1514 assert_eq!(cache_ttl(Some(20), leeway), secs(10));
1515 assert_eq!(cache_ttl(Some(1), leeway), Duration::from_millis(500));
1516 assert_eq!(cache_ttl(Some(0), leeway), Duration::ZERO);
1517 assert_eq!(cache_ttl(Some(100), Duration::ZERO), secs(100));
1519 assert_eq!(cache_ttl(None, leeway), NO_EXPIRY_CACHE_TTL);
1521 }
1522
1523 #[tokio::test]
1524 async fn concurrent_refreshes_single_flight() {
1525 let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
1526 let hits = Arc::new(AtomicUsize::new(0));
1527 let addr = spawn_token_server(
1528 vec![(200, token_body("tok-sf", Some(3600)))],
1529 Arc::clone(&captured),
1530 Arc::clone(&hits),
1531 )
1532 .await;
1533
1534 let p = Arc::new(OAuth2ClientCredentials::new(
1535 format!("http://{addr}/token"),
1536 "cid",
1537 "csec",
1538 ));
1539 let tasks: Vec<_> = (0..8)
1540 .map(|_| {
1541 let p = Arc::clone(&p);
1542 tokio::spawn(async move { p.access_token().await.unwrap() })
1543 })
1544 .collect();
1545 for t in tasks {
1546 assert_eq!(t.await.unwrap(), "tok-sf");
1547 }
1548 assert_eq!(
1549 hits.load(Ordering::SeqCst),
1550 1,
1551 "8 concurrent callers must produce exactly one token request"
1552 );
1553 }
1554
1555 #[tokio::test]
1559 async fn concurrent_failures_share_one_attempt() {
1560 let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
1561 let hits = Arc::new(AtomicUsize::new(0));
1562 let addr = spawn_token_server(
1563 vec![(500, r#"{"error":"temporarily_unavailable"}"#.to_owned())],
1564 Arc::clone(&captured),
1565 Arc::clone(&hits),
1566 )
1567 .await;
1568
1569 let p = Arc::new(OAuth2ClientCredentials::new(
1570 format!("http://{addr}/token"),
1571 "cid",
1572 "csec",
1573 ));
1574 let tasks: Vec<_> = (0..5)
1575 .map(|_| {
1576 let p = Arc::clone(&p);
1577 tokio::spawn(async move { p.access_token().await })
1578 })
1579 .collect();
1580 for t in tasks {
1581 let err = t.await.unwrap().expect_err("the endpoint only fails");
1582 assert!(err.to_string().contains("HTTP 500"), "{err}");
1583 }
1584 assert_eq!(
1585 hits.load(Ordering::SeqCst),
1586 1,
1587 "5 concurrent callers must share one failed token request"
1588 );
1589 }
1590
1591 #[tokio::test]
1594 async fn concurrent_timeouts_cost_one_timeout_not_one_each() {
1595 let timeout = Duration::from_millis(300);
1596 let addr = spawn_stalling_server("HTTP/1.1 200 OK", Duration::ZERO).await;
1597 let p = Arc::new(
1598 OAuth2ClientCredentials::new(format!("http://{addr}/token"), "cid", "csec")
1599 .with_request_timeout(timeout),
1600 );
1601
1602 let started = Instant::now();
1603 let tasks: Vec<_> = (0..5)
1604 .map(|_| {
1605 let p = Arc::clone(&p);
1606 tokio::spawn(async move { p.access_token().await })
1607 })
1608 .collect();
1609 for t in tasks {
1610 let err = t.await.unwrap().expect_err("a stalled endpoint must fail");
1611 assert!(matches!(err, ClientError::Timeout(_)), "{err:?}");
1612 }
1613 let elapsed = started.elapsed();
1614 assert!(
1615 elapsed < timeout * 2,
1616 "5 callers must wait out one shared timeout, took {elapsed:?} against {timeout:?}"
1617 );
1618 }
1619
1620 #[tokio::test]
1621 async fn error_response_surfaces_rfc6749_error_without_secret() {
1622 let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
1623 let hits = Arc::new(AtomicUsize::new(0));
1624 let addr = spawn_token_server(
1625 vec![(
1626 400,
1627 r#"{"error":"invalid_client","error_description":"bad credentials"}"#.to_owned(),
1628 )],
1629 Arc::clone(&captured),
1630 Arc::clone(&hits),
1631 )
1632 .await;
1633
1634 let p = OAuth2ClientCredentials::new(format!("http://{addr}/token"), "cid", "super-secret");
1635 let err = p.access_token().await.expect_err("400 must fail");
1636 let msg = err.to_string();
1637 assert!(msg.contains("invalid_client"), "{msg}");
1638 assert!(msg.contains("bad credentials"), "{msg}");
1639 assert!(!msg.contains("super-secret"), "secret leaked: {msg}");
1640 }
1641
1642 #[tokio::test]
1643 async fn non_bearer_token_type_is_rejected() {
1644 let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
1645 let hits = Arc::new(AtomicUsize::new(0));
1646 let addr = spawn_token_server(
1647 vec![(200, r#"{"access_token":"t","token_type":"MAC"}"#.to_owned())],
1648 Arc::clone(&captured),
1649 Arc::clone(&hits),
1650 )
1651 .await;
1652
1653 let p = OAuth2ClientCredentials::new(format!("http://{addr}/token"), "cid", "csec");
1654 let err = p.access_token().await.expect_err("MAC tokens unsupported");
1655 assert!(err.to_string().contains("token_type"));
1656 }
1657
1658 #[tokio::test]
1661 async fn oidc_discovery_finds_token_endpoint() {
1662 let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
1663 let hits = Arc::new(AtomicUsize::new(0));
1664 let addr = spawn_token_server(
1665 vec![(
1666 200,
1667 r#"{"issuer":"http://{ADDR}","token_endpoint":"http://i/oauth/token"}"#.to_owned(),
1668 )],
1669 Arc::clone(&captured),
1670 Arc::clone(&hits),
1671 )
1672 .await;
1673
1674 let url = discover_token_endpoint(&format!("http://{addr}"))
1675 .await
1676 .unwrap();
1677 assert_eq!(url, "http://i/oauth/token");
1678
1679 let url = discover_token_endpoint(&format!("http://{addr}/"))
1681 .await
1682 .unwrap();
1683 assert_eq!(url, "http://i/oauth/token");
1684 }
1685
1686 #[tokio::test]
1690 async fn from_oidc_issuer_targets_the_discovered_token_endpoint() {
1691 let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
1692 let hits = Arc::new(AtomicUsize::new(0));
1693 let addr = spawn_token_server(
1694 vec![(
1695 200,
1696 r#"{"issuer":"http://{ADDR}","token_endpoint":"http://i/oauth/token"}"#.to_owned(),
1697 )],
1698 Arc::clone(&captured),
1699 Arc::clone(&hits),
1700 )
1701 .await;
1702
1703 let provider =
1704 OAuth2ClientCredentials::from_oidc_issuer(&format!("http://{addr}"), "cid", "csec")
1705 .await
1706 .expect("discovery succeeds");
1707 assert_eq!(provider.token_url, "http://i/oauth/token");
1708 assert_eq!(hits.load(Ordering::SeqCst), 1, "one discovery request");
1709 }
1710
1711 #[tokio::test]
1712 async fn oidc_discovery_without_token_endpoint_errors() {
1713 let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
1714 let hits = Arc::new(AtomicUsize::new(0));
1715 let addr = spawn_token_server(
1716 vec![(200, r#"{"issuer":"http://{ADDR}"}"#.to_owned())],
1717 Arc::clone(&captured),
1718 Arc::clone(&hits),
1719 )
1720 .await;
1721
1722 let err = discover_token_endpoint(&format!("http://{addr}"))
1723 .await
1724 .expect_err("no token_endpoint");
1725 assert!(err.to_string().contains("token_endpoint"));
1726 }
1727
1728 #[tokio::test]
1735 async fn token_response_larger_than_the_mutated_ceiling_is_accepted() {
1736 let filler = "s".repeat(4096);
1741 let body = format!(
1742 r#"{{"access_token":"tok-big","token_type":"Bearer","expires_in":3600,"scope":"{filler}"}}"#
1743 );
1744 assert!(
1745 body.len() > 1088 && body.len() < 64 * 1024,
1746 "body must sit strictly between the mutated and real ceilings to \
1747 discriminate; got {} bytes",
1748 body.len()
1749 );
1750
1751 let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
1752 let hits = Arc::new(AtomicUsize::new(0));
1753 let addr =
1754 spawn_token_server(vec![(200, body)], Arc::clone(&captured), Arc::clone(&hits)).await;
1755
1756 let p = OAuth2ClientCredentials::new(format!("http://{addr}/token"), "cid", "csec");
1757 assert_eq!(
1758 p.access_token()
1759 .await
1760 .expect("a 4 KiB token response is well within the 64 KiB limit"),
1761 "tok-big"
1762 );
1763 }
1764}