a2a_protocol_server/agent_card/
lint.rs1use a2a_protocol_types::agent_card::AgentCard;
20use a2a_protocol_types::security::SecurityScheme;
21
22const IANA_HTTP_AUTH_SCHEMES: &[&str] = &[
30 "Basic",
31 "Bearer",
32 "Concealed",
33 "Digest",
34 "DPoP",
35 "GNAP",
36 "HOBA",
37 "Mutual",
38 "Negotiate",
39 "OAuth",
40 "PrivateToken",
41 "SCRAM-SHA-1",
42 "SCRAM-SHA-256",
43 "vapid",
44];
45
46const CANONICAL_BINDINGS: &[&str] = &["JSONRPC", "GRPC", "HTTP+JSON"];
48
49#[must_use]
62pub fn card_warnings(card: &AgentCard) -> Vec<String> {
63 let mut out = Vec::new();
64 for iface in &card.supported_interfaces {
65 let url = iface.url.as_str();
66 let binding = iface.protocol_binding.as_str();
67 if !is_url(url) {
68 out.push(format!(
69 "supportedInterfaces: {binding} at {url:?} is not an absolute URL; a client \
70 cannot reach it from the card (a2a.proto AgentInterface.url)"
71 ));
72 } else if !is_https_url(url) && !is_loopback(url) {
73 out.push(format!(
74 "supportedInterfaces: {binding} at {url} is not https; production deployments \
75 MUST use encrypted communication (spec §7.1, a2a.proto AgentInterface.url)"
76 ));
77 }
78 if !CANONICAL_BINDINGS.contains(&binding) && !is_uri(binding) {
79 out.push(format!(
80 "supportedInterfaces: the custom binding {binding:?} is not a URI (spec §5.8: it \
81 SHOULD be a URI)"
82 ));
83 }
84 }
85 for (name, scheme) in card.security_schemes.iter().flatten() {
86 if let SecurityScheme::Http(http) = scheme
87 && !IANA_HTTP_AUTH_SCHEMES
88 .iter()
89 .any(|s| s.eq_ignore_ascii_case(&http.scheme))
90 {
91 out.push(format!(
92 "securitySchemes.{name}: the HTTP authentication scheme {:?} is not in the IANA \
93 registry (a2a.proto HTTPAuthSecurityScheme.scheme)",
94 http.scheme
95 ));
96 }
97 }
98 for (field, url) in card_urls(card) {
99 if let Some(host) = internal_host(&url) {
100 out.push(format!(
101 "{field}: {host} looks internal; a card SHOULD NOT include internal \
102 implementation details, nor an extended card internal service URLs (spec §14, \
103 §13.3)"
104 ));
105 }
106 }
107 for ext in card.capabilities.extensions.iter().flatten() {
108 if !ext.uri.chars().any(|c| c.is_ascii_digit()) {
109 out.push(format!(
110 "capabilities.extensions: {} carries no version (spec §4.6.3: extensions SHOULD \
111 include version information in their URI)",
112 ext.uri
113 ));
114 }
115 }
116 out
117}
118
119fn is_uri(s: &str) -> bool {
123 let Some((scheme, rest)) = s.split_once(':') else {
124 return false;
125 };
126 let mut chars = scheme.chars();
127 chars.next().is_some_and(|c| c.is_ascii_alphabetic())
128 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
129 && !rest.is_empty()
130 && !s.chars().any(|c| c.is_whitespace() || c.is_control())
131}
132
133fn is_url(s: &str) -> bool {
136 is_uri(s)
137 && s.split_once("://")
138 .is_some_and(|(_, rest)| !rest.is_empty() && !rest.starts_with('/'))
139}
140
141fn is_https_url(s: &str) -> bool {
146 is_url(s)
147 && ["https://", "wss://"].iter().any(|scheme| {
148 s.get(..scheme.len())
149 .is_some_and(|p| p.eq_ignore_ascii_case(scheme))
150 })
151}
152
153const SECRET_PARAMS: &[&str] = &[
155 "access_token",
156 "api_key",
157 "apikey",
158 "auth",
159 "client_secret",
160 "key",
161 "password",
162 "secret",
163 "sig",
164 "signature",
165 "token",
166];
167
168#[must_use]
177pub fn card_credentials(card: &AgentCard) -> Vec<String> {
178 card_urls(card)
179 .into_iter()
180 .filter(|(_, url)| carries_credential(url))
181 .map(|(field, _)| field)
182 .collect()
183}
184
185pub(crate) fn publishable(card: &AgentCard) -> Result<(), String> {
194 card.validate()
195 .and_then(|()| card.validate_security_schemes())
196 .map_err(str::to_owned)?;
197 let leaked = card_credentials(card);
198 if leaked.is_empty() {
199 Ok(())
200 } else {
201 Err(format!(
202 "it carries a credential in a URL ({}), which serving it would disclose \
203 (spec §14: the card SHOULD NOT include sensitive credentials)",
204 leaked.join(", ")
205 ))
206 }
207}
208
209fn card_urls(card: &AgentCard) -> Vec<(String, String)> {
214 fn walk(v: &serde_json::Value, path: &str, out: &mut Vec<(String, String)>) {
215 match v {
216 serde_json::Value::Object(map) => {
217 let mut entries: Vec<_> = map.iter().collect();
220 entries.sort_by(|a, b| a.0.cmp(b.0));
221 for (k, v) in entries {
222 let here = if path.is_empty() {
223 k.clone()
224 } else {
225 format!("{path}.{k}")
226 };
227 let lower = k.to_ascii_lowercase();
228 match v {
229 serde_json::Value::String(s)
230 if lower.ends_with("url") || lower.ends_with("uri") =>
231 {
232 out.push((here, s.clone()));
233 }
234 _ => walk(v, &here, out),
235 }
236 }
237 }
238 serde_json::Value::Array(items) => {
239 for (i, v) in items.iter().enumerate() {
240 walk(v, &format!("{path}[{i}]"), out);
241 }
242 }
243 _ => {}
244 }
245 }
246 let mut out = Vec::new();
247 if let Ok(v) = serde_json::to_value(card) {
248 walk(&v, "", &mut out);
249 }
250 out
251}
252
253fn carries_credential(url: &str) -> bool {
255 let Some((_, rest)) = url.split_once("://") else {
256 return false;
257 };
258 let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
259 if authority.contains('@') {
260 return true;
261 }
262 let query = url.split_once('?').map_or("", |(_, q)| q);
263 let query = query.split('#').next().unwrap_or_default();
264 query.split('&').any(|pair| {
265 let name = pair.split('=').next().unwrap_or_default();
266 SECRET_PARAMS.iter().any(|s| s.eq_ignore_ascii_case(name))
267 })
268}
269
270fn internal_host(url: &str) -> Option<String> {
275 let (_, rest) = url.split_once("://")?;
276 let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
277 let host = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
278 let host = host.strip_prefix('[').map_or_else(
279 || host.rsplit_once(':').map_or(host, |(h, _)| h),
280 |v6| v6.split(']').next().unwrap_or_default(),
281 );
282 let lower = host.to_ascii_lowercase();
283 let internal_name = [".internal", ".local", ".lan", ".corp", ".intranet"]
284 .iter()
285 .any(|suffix| lower.ends_with(suffix));
286 let private_ip = host
287 .parse::<std::net::IpAddr>()
288 .is_ok_and(|ip| !ip.is_loopback() && crate::url_guard::is_private_ip(ip));
289 (internal_name || private_ip).then(|| host.to_owned())
290}
291
292fn is_loopback(url: &str) -> bool {
295 let Some((_, rest)) = url.split_once("://") else {
296 return false;
297 };
298 let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
299 let host = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
300 let host = host.strip_prefix('[').map_or_else(
301 || host.rsplit_once(':').map_or(host, |(h, _)| h),
302 |v6| v6.split(']').next().unwrap_or_default(),
303 );
304 host.eq_ignore_ascii_case("localhost")
305 || host
306 .parse::<std::net::IpAddr>()
307 .is_ok_and(|ip| ip.is_loopback())
308}
309
310#[cfg(test)]
311#[path = "lint_tests.rs"]
312mod tests;