a2a_protocol_server/agent_card/
static_handler.rs1use std::time::SystemTime;
14
15use a2a_protocol_types::agent_card::AgentCard;
16use bytes::Bytes;
17use http_body_util::Full;
18
19use crate::agent_card::CORS_ALLOW_ALL;
20use crate::agent_card::caching::{
21 CacheConfig, ConditionalResult, card_body_and_etag, check_conditional, format_http_date,
22};
23use crate::error::ServerResult;
24
25#[derive(Debug, Clone)]
27pub struct StaticAgentCardHandler {
28 card_json: Bytes,
29 etag: String,
30 last_modified: String,
31 cache_config: CacheConfig,
32}
33
34fn modified_at(executable: Option<SystemTime>, now: SystemTime) -> SystemTime {
40 executable.map_or(now, |time| time.min(now))
41}
42
43fn executable_modified() -> Option<SystemTime> {
45 std::fs::metadata(std::env::current_exe().ok()?)
46 .ok()?
47 .modified()
48 .ok()
49}
50
51impl StaticAgentCardHandler {
52 pub fn new(card: &AgentCard) -> ServerResult<Self> {
72 super::lint::publishable(card).map_err(crate::error::ServerError::InvalidParams)?;
73 Self::built_at(card, SystemTime::now())
74 }
75
76 fn built_at(card: &AgentCard, now: SystemTime) -> ServerResult<Self> {
79 let (json, etag) = card_body_and_etag(card)?;
80 Ok(Self {
81 card_json: Bytes::from(json),
82 etag,
83 last_modified: format_http_date(modified_at(executable_modified(), now)),
84 cache_config: CacheConfig::default(),
85 })
86 }
87
88 #[must_use]
93 pub fn with_last_modified(mut self, time: SystemTime) -> Self {
94 self.last_modified = format_http_date(time);
95 self
96 }
97
98 #[must_use]
100 pub const fn with_max_age(mut self, seconds: u32) -> Self {
101 self.cache_config = CacheConfig::with_max_age(seconds);
102 self
103 }
104
105 #[must_use]
113 pub fn handle(
114 &self,
115 req: &hyper::Request<impl hyper::body::Body>,
116 ) -> hyper::Response<Full<Bytes>> {
117 if !super::performs(req.method()) {
118 return super::method_not_allowed();
119 }
120 let result = check_conditional(req, &self.etag, &self.last_modified);
121 match result {
122 ConditionalResult::NotModified => self.not_modified_response(),
123 ConditionalResult::SendFull => self.full_response(),
124 }
125 }
126
127 #[must_use]
129 pub fn handle_unconditional(&self) -> hyper::Response<Full<Bytes>> {
130 self.full_response()
131 }
132
133 fn full_response(&self) -> hyper::Response<Full<Bytes>> {
134 hyper::Response::builder()
135 .status(200)
136 .header("content-type", "application/json")
137 .header("access-control-allow-origin", CORS_ALLOW_ALL)
138 .header("etag", &self.etag)
139 .header("last-modified", &self.last_modified)
140 .header("cache-control", self.cache_config.header_value())
141 .body(Full::new(self.card_json.clone()))
142 .unwrap_or_else(|_| hyper::Response::new(Full::new(Bytes::new())))
143 }
144
145 fn not_modified_response(&self) -> hyper::Response<Full<Bytes>> {
146 hyper::Response::builder()
147 .status(304)
148 .header("etag", &self.etag)
149 .header("last-modified", &self.last_modified)
150 .header("cache-control", self.cache_config.header_value())
151 .body(Full::new(Bytes::new()))
152 .unwrap_or_else(|_| hyper::Response::new(Full::new(Bytes::new())))
153 }
154}
155
156#[cfg(test)]
157mod tests {
158 use super::*;
159 use crate::agent_card::caching::tests::minimal_agent_card;
160
161 #[test]
165 fn a_card_that_does_not_validate_is_refused() {
166 let mut skillless = minimal_agent_card();
167 skillless.skills.clear();
168 let mut keyless = serde_json::to_value(minimal_agent_card()).unwrap();
169 keyless["securitySchemes"] = serde_json::json!(
170 {"key": {"apiKeySecurityScheme": {"location": "header", "name": ""}}}
171 );
172 let keyless: AgentCard = serde_json::from_value(keyless).unwrap();
173 for (card, why) in [
174 (skillless, "skill"),
175 (keyless, "apiKeySecurityScheme needs a name"),
176 ] {
177 let Err(err) = StaticAgentCardHandler::new(&card) else {
178 panic!("served a card without a valid {why}");
179 };
180 assert!(
181 matches!(err, crate::error::ServerError::InvalidParams(ref m) if m.contains(why)),
182 "{err:?}"
183 );
184 }
185 }
186
187 fn at(secs: u64) -> SystemTime {
188 SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(secs)
189 }
190
191 fn last_modified_of(handler: &StaticAgentCardHandler) -> String {
192 let req = hyper::Request::builder()
193 .method("GET")
194 .uri("/.well-known/agent-card.json")
195 .body(Full::new(Bytes::new()))
196 .unwrap();
197 handler
198 .handle(&req)
199 .headers()
200 .get("last-modified")
201 .unwrap()
202 .to_str()
203 .unwrap()
204 .to_owned()
205 }
206
207 #[test]
211 fn last_modified_is_the_executables_time_unless_that_is_missing_or_ahead() {
212 assert_eq!(modified_at(Some(at(100)), at(200)), at(100));
213 assert_eq!(modified_at(Some(at(200)), at(200)), at(200));
214 assert_eq!(
215 modified_at(Some(at(300)), at(200)),
216 at(200),
217 "ahead of the clock"
218 );
219 assert_eq!(modified_at(None, at(200)), at(200), "unreadable");
220 }
221
222 #[test]
225 fn replicas_started_at_different_times_send_the_same_last_modified() {
226 let card = minimal_agent_card();
227 let executable = executable_modified().expect("the test executable has a time");
228 let one = StaticAgentCardHandler::built_at(
229 &card,
230 executable + std::time::Duration::from_hours(24),
231 )
232 .unwrap();
233 let other = StaticAgentCardHandler::built_at(
234 &card,
235 executable + std::time::Duration::from_hours(48),
236 )
237 .unwrap();
238 assert_eq!(last_modified_of(&one), format_http_date(executable));
239 assert_eq!(last_modified_of(&one), last_modified_of(&other));
240 }
241
242 #[test]
245 fn new_sends_the_running_executables_time() {
246 let handler = StaticAgentCardHandler::new(&minimal_agent_card()).unwrap();
247 let executable = executable_modified().expect("the test executable has a time");
248 assert_eq!(last_modified_of(&handler), format_http_date(executable));
249 }
250
251 #[test]
254 fn an_explicit_last_modified_is_sent_and_revalidates() {
255 let handler = StaticAgentCardHandler::new(&minimal_agent_card())
256 .unwrap()
257 .with_last_modified(at(1_700_000_000));
258 assert_eq!(last_modified_of(&handler), "Tue, 14 Nov 2023 22:13:20 GMT");
259 let req = hyper::Request::builder()
260 .method("GET")
261 .uri("/.well-known/agent-card.json")
262 .header("if-modified-since", "Tue, 14 Nov 2023 22:13:20 GMT")
263 .body(Full::new(Bytes::new()))
264 .unwrap();
265 assert_eq!(handler.handle(&req).status(), 304);
266 }
267
268 #[test]
269 fn static_handler_returns_etag_and_cache_headers() {
270 let card = minimal_agent_card();
271 let handler = StaticAgentCardHandler::new(&card).unwrap();
272 let req = hyper::Request::builder()
273 .method("GET")
274 .uri("/.well-known/agent-card.json")
275 .body(Full::new(Bytes::new()))
276 .unwrap();
277 let resp = handler.handle(&req);
278 assert_eq!(resp.status(), 200);
279 assert!(resp.headers().contains_key("etag"));
280 assert!(resp.headers().contains_key("last-modified"));
281 assert!(resp.headers().contains_key("cache-control"));
282 }
283
284 #[test]
285 fn static_handler_304_on_matching_etag() {
286 let card = minimal_agent_card();
287 let handler = StaticAgentCardHandler::new(&card).unwrap();
288 let req1 = hyper::Request::builder()
290 .method("GET")
291 .uri("/.well-known/agent-card.json")
292 .body(Full::new(Bytes::new()))
293 .unwrap();
294 let resp1 = handler.handle(&req1);
295 let etag = resp1
296 .headers()
297 .get("etag")
298 .unwrap()
299 .to_str()
300 .unwrap()
301 .to_owned();
302
303 let req2 = hyper::Request::builder()
305 .method("GET")
306 .uri("/.well-known/agent-card.json")
307 .header("if-none-match", &etag)
308 .body(Full::new(Bytes::new()))
309 .unwrap();
310 let resp2 = handler.handle(&req2);
311 assert_eq!(resp2.status(), 304);
312 }
313
314 #[test]
315 fn static_handler_200_on_mismatched_etag() {
316 let card = minimal_agent_card();
317 let handler = StaticAgentCardHandler::new(&card).unwrap();
318 let req = hyper::Request::builder()
319 .method("GET")
320 .uri("/.well-known/agent-card.json")
321 .header("if-none-match", "\"wrong-etag\"")
322 .body(Full::new(Bytes::new()))
323 .unwrap();
324 let resp = handler.handle(&req);
325 assert_eq!(resp.status(), 200);
326 }
327
328 #[test]
332 fn another_method_is_405_with_allow() {
333 let handler = StaticAgentCardHandler::new(&minimal_agent_card()).unwrap();
334 for method in ["POST", "PUT", "DELETE", "PATCH", "OPTIONS"] {
335 for inm in [None, Some("*")] {
336 let mut req = hyper::Request::builder()
337 .method(method)
338 .uri("/.well-known/agent-card.json");
339 if let Some(inm) = inm {
340 req = req.header("if-none-match", inm);
341 }
342 let resp = handler.handle(&req.body(Full::new(Bytes::new())).unwrap());
343 assert_eq!(resp.status(), 405, "{method} {inm:?}");
344 assert_eq!(resp.headers()["allow"], "GET, HEAD", "{method} {inm:?}");
345 assert!(!resp.headers().contains_key("etag"), "{method} {inm:?}");
346 }
347 }
348 }
349
350 #[test]
352 fn static_handler_unconditional_returns_200() {
353 let card = minimal_agent_card();
354 let handler = StaticAgentCardHandler::new(&card).unwrap();
355 let resp = handler.handle_unconditional();
356 assert_eq!(resp.status(), 200);
357 assert!(resp.headers().contains_key("etag"));
358 assert!(resp.headers().contains_key("content-type"));
359 assert_eq!(
360 resp.headers().get("access-control-allow-origin").unwrap(),
361 "*"
362 );
363 }
364
365 #[test]
366 fn static_handler_custom_max_age() {
367 let card = minimal_agent_card();
368 let handler = StaticAgentCardHandler::new(&card)
369 .unwrap()
370 .with_max_age(7200);
371 let req = hyper::Request::builder()
372 .method("GET")
373 .uri("/.well-known/agent-card.json")
374 .body(Full::new(Bytes::new()))
375 .unwrap();
376 let resp = handler.handle(&req);
377 let cc = resp
378 .headers()
379 .get("cache-control")
380 .unwrap()
381 .to_str()
382 .unwrap();
383 assert!(cc.contains("max-age=7200"));
384 }
385}