a2a_protocol_client/token_provider/
trusted_hosts.rs1use a2a_protocol_types::agent_card::AgentCard;
17
18use super::{OAuth2ClientCredentials, card_token_url, check_endpoint_secure};
19use crate::error::{ClientError, ClientResult};
20
21impl OAuth2ClientCredentials {
22 pub fn from_agent_card_trusting(
43 card: &AgentCard,
44 scheme_name: &str,
45 client_id: impl Into<String>,
46 client_secret: impl Into<String>,
47 trusted_token_hosts: &[&str],
48 ) -> ClientResult<Self> {
49 let token_url = card_token_url(card, scheme_name)?;
50 if !host_is_trusted(&token_url, trusted_token_hosts) {
51 return Err(ClientError::InvalidEndpoint(format!(
52 "the agent card's tokenUrl {} is not on a host you trust ({}), so the client \
53 secret was not sent there; if the identity provider really is that host, name \
54 it in the list, otherwise the card is not what you expected",
55 crate::loopback::origin(&token_url),
56 if trusted_token_hosts.is_empty() {
57 "none given".to_owned()
58 } else {
59 trusted_token_hosts.join(", ")
60 },
61 )));
62 }
63 check_endpoint_secure(&token_url, "the agent card's tokenUrl", false)?;
64 Ok(Self::new(token_url, client_id, client_secret))
65 }
66}
67
68fn comparable(host: &str) -> String {
71 let bare = host
72 .strip_prefix('[')
73 .and_then(|h| h.strip_suffix(']'))
74 .unwrap_or(host);
75 bare.strip_suffix('.').unwrap_or(bare).to_ascii_lowercase()
76}
77
78fn host_is_trusted(url: &str, trusted: &[&str]) -> bool {
81 let Some(host) = url
82 .parse::<hyper::Uri>()
83 .ok()
84 .and_then(|uri| uri.host().map(comparable))
85 else {
86 return false;
87 };
88 !host.is_empty() && trusted.iter().any(|t| comparable(t) == host)
89}
90
91#[cfg(test)]
92mod tests {
93 use a2a_protocol_types::security::{ClientCredentialsFlow, OAuthFlows};
94
95 use super::super::tests::card_with_oauth2;
96 use super::*;
97
98 fn card_naming(token_url: &str) -> AgentCard {
99 card_with_oauth2(OAuthFlows::ClientCredentials(ClientCredentialsFlow::new(
100 token_url,
101 )))
102 }
103
104 fn trusting(token_url: &str, hosts: &[&str]) -> ClientResult<OAuth2ClientCredentials> {
105 OAuth2ClientCredentials::from_agent_card_trusting(
106 &card_naming(token_url),
107 "oauth",
108 "id",
109 "s3cret",
110 hosts,
111 )
112 }
113
114 #[test]
115 fn a_token_url_on_a_trusted_host_is_accepted() {
116 for (url, hosts) in [
117 ("https://auth.example.com/token", &["auth.example.com"][..]),
118 ("https://AUTH.Example.COM/token", &["auth.example.com"]),
119 ("https://auth.example.com./token", &["auth.example.com"]),
120 ("https://auth.example.com/token", &["Auth.Example.Com."]),
121 (
122 "https://auth.example.com:8443/oauth/token",
123 &["auth.example.com"],
124 ),
125 (
126 "https://other.example/t",
127 &["auth.example.com", "other.example"],
128 ),
129 ("https://[2001:db8::1]/token", &["2001:db8::1"]),
130 ("http://127.0.0.1:9/token", &["127.0.0.1"]),
131 ] {
132 let p = trusting(url, hosts).unwrap_or_else(|e| panic!("{url} with {hosts:?}: {e}"));
133 assert_eq!(p.token_url, url);
134 }
135 }
136
137 #[test]
138 fn a_token_url_on_any_other_host_is_refused_and_the_secret_is_not_in_the_message() {
139 for url in [
140 "https://attacker.example/token",
141 "https://auth.example.com.attacker.example/token",
143 "https://evil-auth.example.com/token",
144 "https://notauth.example.com/token",
145 "https://example.com/token",
146 "https://[email protected]/token",
148 "https://auth.example.com:[email protected]/token",
149 "https://attacker.example/auth.example.com",
151 "https://attacker.example/token?h=auth.example.com",
152 ] {
153 let err = trusting(url, &["auth.example.com"]).expect_err(url);
154 let msg = err.to_string();
155 assert!(
156 matches!(err, ClientError::InvalidEndpoint(_)),
157 "{url}: {err:?}"
158 );
159 assert!(
160 msg.contains("auth.example.com"),
161 "names what would be accepted: {msg}"
162 );
163 assert!(!msg.contains("s3cret"), "{msg}");
164 }
165 }
166
167 #[test]
168 fn an_empty_list_trusts_nothing() {
169 let err = trusting("https://auth.example.com/token", &[]).expect_err("fail closed");
170 assert!(err.to_string().contains("none given"), "{err}");
171 }
172
173 #[test]
174 fn a_url_without_a_host_is_on_no_list() {
175 for url in ["not a url", "/token", "https:///token"] {
176 assert!(!host_is_trusted(url, &["auth.example.com", ""]), "{url}");
177 }
178 }
179
180 #[test]
181 fn the_checks_of_from_agent_card_still_apply() {
182 let err = trusting("http://auth.example.com/token", &["auth.example.com"])
184 .expect_err("plaintext to a remote host");
185 assert!(err.to_string().contains("plaintext"), "{err}");
186 let err = OAuth2ClientCredentials::from_agent_card_trusting(
188 &card_naming("https://auth.example.com/token"),
189 "nope",
190 "id",
191 "sec",
192 &["auth.example.com"],
193 )
194 .expect_err("no such scheme");
195 assert!(err.to_string().contains("no security scheme"), "{err}");
196 }
197}