1use std::sync::Arc;
5
6use a2a::*;
7use a2a_pb::protojson_conv::{self, ProtoJsonPayload, ProtoJsonPayloadError};
8use axum::{
9 Json,
10 body::Bytes,
11 extract::{
12 OriginalUri, Path, Query, Request, State,
13 rejection::{JsonRejection, QueryRejection},
14 },
15 http::{HeaderMap, HeaderValue, StatusCode, header},
16 middleware::Next,
17 response::{IntoResponse, Response},
18};
19use chrono::{DateTime, Utc};
20use futures::{StreamExt, stream::BoxStream};
21use percent_encoding::percent_decode_str;
22use serde::{Deserialize, Serialize};
23use serde_json::Value;
24use std::collections::HashMap;
25
26use crate::handler::RequestHandler;
27use crate::middleware::{
28 ServiceParams, add_query_version, check_a2a_version, extract_service_params,
29};
30use crate::sse;
31
32const REST_SEND_MESSAGE_PATH: &str = "/message:send";
33const REST_SEND_MESSAGE_LEGACY_PATH: &str = "/message/send";
34const REST_STREAM_MESSAGE_PATH: &str = "/message:stream";
35const REST_STREAM_MESSAGE_LEGACY_PATH: &str = "/message/stream";
36const REST_EXTENDED_AGENT_CARD_PATH: &str = "/extendedAgentCard";
37const REST_EXTENDED_AGENT_CARD_LEGACY_PATH: &str = "/agent-card/extended";
38const REST_PUSH_CONFIGS_PATH: &str = "/tasks/{id}/pushNotificationConfigs";
39const REST_PUSH_CONFIGS_LEGACY_PATH: &str = "/tasks/{id}/push-configs";
40const REST_PUSH_CONFIG_PATH: &str = "/tasks/{id}/pushNotificationConfigs/{config_id}";
41const REST_PUSH_CONFIG_LEGACY_PATH: &str = "/tasks/{id}/push-configs/{config_id}";
42#[derive(Serialize)]
43struct RestErrorEnvelope {
44 error: RestErrorStatus,
45}
46
47#[derive(Serialize)]
48struct RestErrorStatus {
49 code: u16,
50 status: &'static str,
51 message: String,
52 details: Vec<TypedDetail>,
53}
54
55pub struct RestState<H: RequestHandler> {
57 pub handler: Arc<H>,
58}
59
60impl<H: RequestHandler> Clone for RestState<H> {
61 fn clone(&self) -> Self {
62 RestState {
63 handler: self.handler.clone(),
64 }
65 }
66}
67
68pub fn rest_router<H: RequestHandler>(handler: Arc<H>) -> axum::Router {
80 let state = RestState { handler };
81 axum::Router::new()
82 .route(
83 REST_SEND_MESSAGE_PATH,
84 axum::routing::post(handle_send_message::<H>),
85 )
86 .route(
87 REST_SEND_MESSAGE_LEGACY_PATH,
88 axum::routing::post(handle_send_message::<H>),
89 )
90 .route(
91 REST_STREAM_MESSAGE_PATH,
92 axum::routing::post(handle_stream_message::<H>),
93 )
94 .route(
95 REST_STREAM_MESSAGE_LEGACY_PATH,
96 axum::routing::post(handle_stream_message::<H>),
97 )
98 .route(
99 "/tasks/{id}",
100 axum::routing::get(handle_get_task_or_subscribe::<H>)
101 .post(handle_post_task_action::<H>),
102 )
103 .route("/tasks", axum::routing::get(handle_list_tasks::<H>))
104 .route(
105 "/tasks/{id}/cancel",
106 axum::routing::post(handle_cancel_task_legacy::<H>),
107 )
108 .route(
109 "/tasks/{id}/subscribe",
110 axum::routing::get(handle_subscribe_to_task_legacy::<H>)
111 .post(handle_subscribe_to_task_legacy::<H>),
112 )
113 .route(
114 REST_PUSH_CONFIGS_PATH,
115 axum::routing::post(handle_create_push_config::<H>).get(handle_list_push_configs::<H>),
116 )
117 .route(
118 REST_PUSH_CONFIGS_LEGACY_PATH,
119 axum::routing::post(handle_create_push_config::<H>).get(handle_list_push_configs::<H>),
120 )
121 .route(
122 REST_PUSH_CONFIG_PATH,
123 axum::routing::get(handle_get_push_config::<H>).delete(handle_delete_push_config::<H>),
124 )
125 .route(
126 REST_PUSH_CONFIG_LEGACY_PATH,
127 axum::routing::get(handle_get_push_config::<H>).delete(handle_delete_push_config::<H>),
128 )
129 .route(
130 REST_EXTENDED_AGENT_CARD_PATH,
131 axum::routing::get(handle_get_extended_agent_card::<H>),
132 )
133 .route(
134 REST_EXTENDED_AGENT_CARD_LEGACY_PATH,
135 axum::routing::get(handle_get_extended_agent_card::<H>),
136 )
137 .route(
139 "/{tenant}/message:send",
140 axum::routing::post(handle_send_message::<H>),
141 )
142 .route(
143 "/{tenant}/message:stream",
144 axum::routing::post(handle_stream_message::<H>),
145 )
146 .route(
150 "/{tenant}/tasks/{id}",
151 axum::routing::get(handle_get_task_or_subscribe::<H>)
152 .post(handle_post_task_action::<H>),
153 )
154 .route(
155 "/{tenant}/tasks",
156 axum::routing::get(handle_list_tasks::<H>),
157 )
158 .route(
159 "/{tenant}/tasks/{id}/pushNotificationConfigs",
160 axum::routing::post(handle_create_push_config::<H>).get(handle_list_push_configs::<H>),
161 )
162 .route(
163 "/{tenant}/tasks/{id}/pushNotificationConfigs/{config_id}",
164 axum::routing::get(handle_get_push_config::<H>).delete(handle_delete_push_config::<H>),
165 )
166 .route(
167 "/{tenant}/extendedAgentCard",
168 axum::routing::get(handle_get_extended_agent_card::<H>),
169 )
170 .route_layer(axum::middleware::from_fn(validate_protocol_version))
171 .layer(axum::extract::DefaultBodyLimit::max(
172 crate::jsonrpc::MAX_REQUEST_BODY_BYTES,
173 ))
174 .with_state(state)
175}
176
177async fn validate_protocol_version(request: Request, next: Next) -> Response {
179 let mut params = extract_service_params(request.headers());
180 add_query_version(&mut params, request.uri());
181 match check_a2a_version(¶ms) {
182 Ok(()) => next.run(request).await,
183 Err(error) => rest_error_response(error),
184 }
185}
186
187#[derive(Deserialize)]
189struct TaskPath {
190 tenant: Option<String>,
191 id: String,
192}
193
194fn task_id_for_action<'a>(
197 uri: &axum::http::Uri,
198 decoded_id: &'a str,
199 action: &str,
200) -> Option<&'a str> {
201 let actual_action = uri
202 .path()
203 .rsplit('/')
204 .next()
205 .and_then(|segment| segment.rsplit_once(':'))
206 .and_then(|(_, action)| percent_decode_str(action).decode_utf8().ok())?;
207 if actual_action != action {
208 return None;
209 }
210 decoded_id.strip_suffix(action)?.strip_suffix(':')
211}
212
213#[derive(Deserialize)]
215struct PushConfigPath {
216 tenant: Option<String>,
217 id: String,
218 config_id: String,
219}
220
221fn reconcile_tenant(
226 path: Option<String>,
227 body: Option<String>,
228) -> Result<Option<String>, Box<axum::response::Response>> {
229 match (path, body) {
230 (Some(path), Some(body)) if path != body => {
231 let violation = FieldViolation {
232 field: "tenant".to_string(),
233 description: format!(
234 "tenant in the body ({body}) does not match the tenant in the path ({path})"
235 ),
236 };
237 Err(Box::new(rest_error_response(
238 A2AError::invalid_params("invalid request body")
239 .with_details(vec![TypedDetail::bad_request(vec![violation])]),
240 )))
241 }
242 (Some(path), _) => Ok(Some(path)),
243 (None, body) => Ok(body),
244 }
245}
246
247async fn handle_send_message<H: RequestHandler>(
248 State(state): State<RestState<H>>,
249 tenant: Option<Path<String>>,
252 headers: HeaderMap,
253 body: Result<Json<Value>, JsonRejection>,
254) -> impl IntoResponse {
255 let tenant = tenant.map(|Path(tenant)| tenant);
256 let Json(raw_req) = match body {
257 Ok(body) => body,
258 Err(rejection) => return json_rejection_response(rejection),
259 };
260 let mut req = match protojson_conv::from_value::<SendMessageRequest>(raw_req) {
261 Ok(req) => req,
262 Err(e) => return protojson_error_response(e),
263 };
264 req.tenant = match reconcile_tenant(tenant, req.tenant.take()) {
265 Ok(tenant) => tenant,
266 Err(response) => return *response,
267 };
268 let params = extract_service_params(&headers);
269 match state.handler.send_message(¶ms, req).await {
270 Ok(resp) => protojson_json_response(&resp),
271 Err(e) => rest_error_response(e),
272 }
273}
274
275async fn handle_stream_message<H: RequestHandler>(
276 State(state): State<RestState<H>>,
277 tenant: Option<Path<String>>,
278 headers: HeaderMap,
279 body: Result<Json<Value>, JsonRejection>,
280) -> impl IntoResponse {
281 let tenant = tenant.map(|Path(tenant)| tenant);
282 let Json(raw_req) = match body {
283 Ok(body) => body,
284 Err(rejection) => return json_rejection_response(rejection),
285 };
286 let mut req = match protojson_conv::from_value::<SendMessageRequest>(raw_req) {
287 Ok(req) => req,
288 Err(e) => return protojson_error_response(e),
289 };
290 req.tenant = match reconcile_tenant(tenant, req.tenant.take()) {
291 Ok(tenant) => tenant,
292 Err(response) => return *response,
293 };
294 let params = extract_service_params(&headers);
295 match state.handler.send_streaming_message(¶ms, req).await {
296 Ok(stream) => rest_sse(protojson_stream(stream)),
297 Err(e) => rest_error_response(e),
298 }
299}
300
301#[derive(Deserialize)]
302pub struct GetTaskQuery {
303 #[serde(default, rename = "historyLength")]
304 pub history_length: Option<i32>,
305}
306
307async fn handle_get_task_inner<H: RequestHandler>(
308 state: RestState<H>,
309 params: ServiceParams,
310 TaskPath { tenant, id }: TaskPath,
311 query: GetTaskQuery,
312) -> axum::response::Response {
313 let req = GetTaskRequest {
314 id,
315 history_length: query.history_length,
316 tenant,
317 };
318 match state.handler.get_task(¶ms, req).await {
319 Ok(task) => protojson_json_response(&task),
320 Err(e) => rest_error_response(e),
321 }
322}
323
324async fn handle_get_task_or_subscribe<H: RequestHandler>(
325 State(state): State<RestState<H>>,
326 OriginalUri(original_uri): OriginalUri,
327 Path(path): Path<TaskPath>,
328 query: Result<Query<GetTaskQuery>, QueryRejection>,
329 headers: HeaderMap,
330) -> impl IntoResponse {
331 let Query(query) = match query {
332 Ok(query) => query,
333 Err(rejection) => return rest_payload_error_response(rejection.body_text()),
334 };
335 let params = extract_service_params(&headers);
336 if let Some(task_id) = task_id_for_action(&original_uri, &path.id, "subscribe") {
339 let id = task_id.to_string();
340 return handle_subscribe_to_task_inner(state, params, id, path.tenant).await;
341 }
342
343 handle_get_task_inner(state, params, path, query).await
344}
345
346#[derive(Deserialize)]
347pub struct ListTasksQuery {
348 #[serde(default, rename = "contextId")]
349 pub context_id: Option<String>,
350 #[serde(default)]
351 pub status: Option<String>,
352 #[serde(default, rename = "pageSize")]
353 pub page_size: Option<i32>,
354 #[serde(default, rename = "pageToken")]
355 pub page_token: Option<String>,
356 #[serde(default, rename = "historyLength")]
357 pub history_length: Option<i32>,
358
359 #[serde(default, rename = "statusTimestampAfter")]
360 pub status_timestamp_after: Option<DateTime<Utc>>,
361
362 #[serde(default, rename = "includeArtifacts")]
363 pub include_artifacts: Option<bool>,
364}
365
366async fn handle_list_tasks<H: RequestHandler>(
367 State(state): State<RestState<H>>,
368 tenant: Option<Path<String>>,
369 query: Result<Query<ListTasksQuery>, QueryRejection>,
370 headers: HeaderMap,
371) -> impl IntoResponse {
372 let tenant = tenant.map(|Path(tenant)| tenant);
373 let Query(query) = match query {
374 Ok(query) => query,
375 Err(rejection) => return rest_payload_error_response(rejection.body_text()),
376 };
377 let params = extract_service_params(&headers);
378 let status = match query.status {
379 Some(s) => match serde_json::from_value::<TaskState>(serde_json::Value::String(s)) {
380 Ok(TaskState::Unspecified) => None,
383 Ok(state) => Some(state),
384 Err(_) => {
385 return rest_error_response(A2AError::invalid_params("invalid status filter"));
386 }
387 },
388 None => None,
389 };
390 let req = ListTasksRequest {
391 context_id: query.context_id,
392 status,
393 page_size: query.page_size,
394 page_token: query.page_token,
395 history_length: query.history_length,
396 status_timestamp_after: query.status_timestamp_after,
397 include_artifacts: query.include_artifacts,
398 tenant,
399 };
400 match state.handler.list_tasks(¶ms, req).await {
401 Ok(resp) => protojson_json_response(&resp),
402 Err(e) => rest_error_response(e),
403 }
404}
405
406async fn handle_cancel_task_inner<H: RequestHandler>(
407 state: RestState<H>,
408 params: ServiceParams,
409 id: String,
410 tenant: Option<String>,
411 body: Bytes,
412) -> axum::response::Response {
413 let mut req = if body.is_empty() {
417 CancelTaskRequest {
418 id: String::new(),
419 metadata: None,
420 tenant: None,
421 }
422 } else {
423 match serde_json::from_slice::<Value>(&body)
424 .map_err(|e| e.to_string())
425 .and_then(|raw| {
426 protojson_conv::from_value::<CancelTaskRequest>(raw).map_err(|e| e.to_string())
427 }) {
428 Ok(req) => req,
429 Err(e) => return rest_payload_error_response(e),
430 }
431 };
432 req.id = id;
433 req.tenant = match reconcile_tenant(tenant, req.tenant.take()) {
434 Ok(tenant) => tenant,
435 Err(response) => return *response,
436 };
437 match state.handler.cancel_task(¶ms, req).await {
438 Ok(task) => protojson_json_response(&task),
439 Err(e) => rest_error_response(e),
440 }
441}
442
443async fn handle_post_task_action<H: RequestHandler>(
444 State(state): State<RestState<H>>,
445 OriginalUri(original_uri): OriginalUri,
446 Path(TaskPath { tenant, id }): Path<TaskPath>,
447 headers: HeaderMap,
448 body: Bytes,
449) -> impl IntoResponse {
450 let params = extract_service_params(&headers);
451 if let Some(task_id) = task_id_for_action(&original_uri, &id, "cancel") {
453 return handle_cancel_task_inner(state, params, task_id.to_string(), tenant, body).await;
454 }
455 if let Some(task_id) = task_id_for_action(&original_uri, &id, "subscribe") {
456 return handle_subscribe_to_task_inner(state, params, task_id.to_string(), tenant).await;
457 }
458
459 rest_error_response(A2AError::invalid_request("unsupported task action"))
460}
461
462async fn handle_cancel_task_legacy<H: RequestHandler>(
463 State(state): State<RestState<H>>,
464 Path(id): Path<String>,
465 headers: HeaderMap,
466 body: Bytes,
467) -> impl IntoResponse {
468 let params = extract_service_params(&headers);
469 handle_cancel_task_inner(state, params, id, None, body).await
470}
471
472async fn handle_subscribe_to_task_inner<H: RequestHandler>(
473 state: RestState<H>,
474 params: ServiceParams,
475 id: String,
476 tenant: Option<String>,
477) -> axum::response::Response {
478 let req = SubscribeToTaskRequest { id, tenant };
479 match state.handler.subscribe_to_task(¶ms, req).await {
480 Ok(stream) => rest_sse(protojson_stream(stream)),
481 Err(e) => rest_error_response(e),
482 }
483}
484
485async fn handle_subscribe_to_task_legacy<H: RequestHandler>(
486 State(state): State<RestState<H>>,
487 Path(id): Path<String>,
488 headers: HeaderMap,
489) -> impl IntoResponse {
490 let params = extract_service_params(&headers);
491 handle_subscribe_to_task_inner(state, params, id, None).await
492}
493
494#[derive(Deserialize)]
495pub struct ListPushConfigsQuery {
496 #[serde(default, rename = "pageSize")]
497 pub page_size: Option<i32>,
498
499 #[serde(default, rename = "pageToken")]
500 pub page_token: Option<String>,
501}
502
503async fn handle_create_push_config<H: RequestHandler>(
504 State(state): State<RestState<H>>,
505 Path(TaskPath { tenant, id }): Path<TaskPath>,
506 headers: HeaderMap,
507 body: Result<Json<Value>, JsonRejection>,
508) -> impl IntoResponse {
509 let Json(raw_config) = match body {
510 Ok(body) => body,
511 Err(rejection) => return json_rejection_response(rejection),
512 };
513 let mut req = match parse_create_push_config_request(id, raw_config) {
514 Ok(req) => req,
515 Err(e) => return rest_payload_error_response(e),
516 };
517 req.tenant = match reconcile_tenant(tenant, req.tenant.take()) {
518 Ok(tenant) => tenant,
519 Err(response) => return *response,
520 };
521 let params = extract_service_params(&headers);
522 match state.handler.create_push_config(¶ms, req).await {
523 Ok(resp) => protojson_json_response(&resp),
524 Err(e) => rest_error_response(e),
525 }
526}
527
528async fn handle_get_push_config<H: RequestHandler>(
529 State(state): State<RestState<H>>,
530 Path(PushConfigPath {
531 tenant,
532 id,
533 config_id,
534 }): Path<PushConfigPath>,
535 headers: HeaderMap,
536) -> impl IntoResponse {
537 let params = extract_service_params(&headers);
538 let req = GetTaskPushNotificationConfigRequest {
539 task_id: id,
540 id: config_id,
541 tenant,
542 };
543 match state.handler.get_push_config(¶ms, req).await {
544 Ok(resp) => protojson_json_response(&resp),
545 Err(e) => rest_error_response(e),
546 }
547}
548
549async fn handle_list_push_configs<H: RequestHandler>(
550 State(state): State<RestState<H>>,
551 Path(TaskPath { tenant, id }): Path<TaskPath>,
552 query: Result<Query<ListPushConfigsQuery>, QueryRejection>,
553 headers: HeaderMap,
554) -> impl IntoResponse {
555 let Query(query) = match query {
556 Ok(query) => query,
557 Err(rejection) => return rest_payload_error_response(rejection.body_text()),
558 };
559 let params = extract_service_params(&headers);
560 let req = ListTaskPushNotificationConfigsRequest {
561 task_id: id,
562 page_size: query.page_size,
563 page_token: query.page_token,
564 tenant,
565 };
566 match state.handler.list_push_configs(¶ms, req).await {
567 Ok(resp) => protojson_json_response(&resp),
568 Err(e) => rest_error_response(e),
569 }
570}
571
572async fn handle_delete_push_config<H: RequestHandler>(
573 State(state): State<RestState<H>>,
574 Path(PushConfigPath {
575 tenant,
576 id,
577 config_id,
578 }): Path<PushConfigPath>,
579 headers: HeaderMap,
580) -> impl IntoResponse {
581 let params = extract_service_params(&headers);
582 let req = DeleteTaskPushNotificationConfigRequest {
583 task_id: id,
584 id: config_id,
585 tenant,
586 };
587 match state.handler.delete_push_config(¶ms, req).await {
588 Ok(()) => with_content_type(
591 Json(Value::Object(Default::default())).into_response(),
592 "application/a2a+json",
593 ),
594 Err(e) => rest_error_response(e),
595 }
596}
597
598async fn handle_get_extended_agent_card<H: RequestHandler>(
599 State(state): State<RestState<H>>,
600 tenant: Option<Path<String>>,
601 headers: HeaderMap,
602) -> impl IntoResponse {
603 let tenant = tenant.map(|Path(tenant)| tenant);
604 let params = extract_service_params(&headers);
605 let req = GetExtendedAgentCardRequest { tenant };
606 match state.handler.get_extended_agent_card(¶ms, req).await {
607 Ok(card) => protojson_json_response(&card),
608 Err(e) => rest_error_response(e),
609 }
610}
611
612fn protojson_json_response<T: ProtoJsonPayload>(value: &T) -> axum::response::Response {
613 match protojson_conv::to_value(value) {
614 Ok(payload) => with_content_type(Json(payload).into_response(), "application/a2a+json"),
615 Err(e) => rest_error_response(crate::sanitized_internal_error(format!(
616 "failed to serialize ProtoJSON payload: {e}"
617 ))),
618 }
619}
620
621fn with_content_type(
624 mut response: axum::response::Response,
625 content_type: &'static str,
626) -> axum::response::Response {
627 response
628 .headers_mut()
629 .insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
630 response
631}
632
633fn protojson_stream<T: ProtoJsonPayload + 'static>(
634 stream: BoxStream<'static, Result<T, A2AError>>,
635) -> BoxStream<'static, Result<Value, A2AError>> {
636 Box::pin(stream.map(|item| {
637 item.and_then(|value| {
638 protojson_conv::to_value(&value).map_err(|e| {
639 crate::sanitized_internal_error(format!(
640 "failed to serialize ProtoJSON stream payload: {e}"
641 ))
642 })
643 })
644 }))
645}
646
647fn rest_sse(stream: BoxStream<'static, Result<Value, A2AError>>) -> axum::response::Response {
651 let events = stream.map(|item| item.map_err(|err| rest_error_envelope(err).1));
652 sse::sse_from_rest_stream(Box::pin(events)).into_response()
653}
654
655fn parse_create_push_config_request(
656 task_id: String,
657 raw_config: Value,
658) -> Result<TaskPushNotificationConfig, String> {
659 protojson_conv::from_value::<TaskPushNotificationConfig>(raw_config)
660 .map_err(|e| e.to_string())
661 .and_then(|mut config| {
662 if !config.task_id.is_empty() && config.task_id != task_id {
663 Err(format!(
664 "taskId in request body ({}) did not match task id in path ({task_id})",
665 config.task_id
666 ))
667 } else {
668 config.task_id = task_id;
669 Ok(config)
670 }
671 })
672}
673
674fn json_rejection_response(rejection: JsonRejection) -> axum::response::Response {
677 if rejection.status() == StatusCode::PAYLOAD_TOO_LARGE {
678 return rejection.into_response();
679 }
680 rest_payload_error_response(rejection.body_text())
681}
682
683fn rest_payload_error_response(error: impl std::fmt::Display) -> axum::response::Response {
684 rest_violation_response(FieldViolation {
685 field: String::new(),
686 description: error.to_string(),
687 })
688}
689
690fn protojson_error_response(error: ProtoJsonPayloadError) -> axum::response::Response {
693 match error {
694 ProtoJsonPayloadError::Invalid(violation) => rest_violation_response(violation),
695 error => rest_payload_error_response(error),
696 }
697}
698
699fn rest_violation_response(violation: FieldViolation) -> axum::response::Response {
700 rest_error_response(
701 A2AError::invalid_params("invalid request body")
702 .with_details(vec![TypedDetail::bad_request(vec![violation])]),
703 )
704}
705
706fn rest_error_response(err: A2AError) -> axum::response::Response {
707 let (status, body) = rest_error_envelope(err);
708 (status, Json(body)).into_response()
711}
712
713fn rest_error_envelope(err: A2AError) -> (StatusCode, RestErrorEnvelope) {
714 let status =
715 StatusCode::from_u16(err.http_status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
716 let reason = error_reason(err.code);
717 let grpc_status = rest_grpc_status(err.code);
718
719 let mut metadata =
720 HashMap::from([("timestamp".to_string(), a2a::format_timestamp(&Utc::now()))]);
721 let mut details = Vec::new();
722
723 if let Some(extra) = err.details {
724 for detail in extra {
725 if detail.type_url == errordetails::ERROR_INFO_TYPE {
726 if let Some(Value::Object(meta)) = detail.value.get("metadata") {
727 for (k, v) in meta {
728 if let Some(s) = v.as_str() {
729 metadata.entry(k.clone()).or_insert_with(|| s.to_string());
730 }
731 }
732 }
733 } else {
734 details.push(detail);
735 }
736 }
737 }
738
739 details.push(TypedDetail::error_info(
740 reason,
741 errordetails::PROTOCOL_DOMAIN,
742 Some(metadata),
743 ));
744
745 let body = RestErrorEnvelope {
746 error: RestErrorStatus {
747 code: status.as_u16(),
748 status: grpc_status,
749 message: err.message,
750 details,
751 },
752 };
753 (status, body)
754}
755
756fn rest_grpc_status(code: i32) -> &'static str {
757 match code {
758 error_code::TASK_NOT_FOUND => "NOT_FOUND",
759 error_code::METHOD_NOT_FOUND => "UNIMPLEMENTED",
760 error_code::TASK_NOT_CANCELABLE
761 | error_code::EXTENDED_CARD_NOT_CONFIGURED
762 | error_code::EXTENSION_SUPPORT_REQUIRED
763 | error_code::PUSH_NOTIFICATION_NOT_SUPPORTED
764 | error_code::UNSUPPORTED_OPERATION
765 | error_code::VERSION_NOT_SUPPORTED => "FAILED_PRECONDITION",
766 error_code::CONTENT_TYPE_NOT_SUPPORTED
767 | error_code::PARSE_ERROR
768 | error_code::INVALID_REQUEST
769 | error_code::INVALID_PARAMS => "INVALID_ARGUMENT",
770 _ => "INTERNAL",
771 }
772}
773
774#[cfg(test)]
775mod tests {
776 use super::*;
777 use crate::InMemoryPushConfigStore;
778 use crate::executor::ExecutorContext;
779 use crate::handler::DefaultRequestHandler;
780 use crate::task_store::InMemoryTaskStore;
781 use a2a_pb::protojson_conv;
782 use axum::body::Body;
783 use axum::http::Request;
784 use futures::stream::BoxStream;
785 use http_body_util::BodyExt;
786
787 use crate::test_util::{CapturingHandler, assert_header_captured, install_crypto_provider};
788 use tower::ServiceExt;
789
790 struct EchoExecutor;
791
792 impl crate::AgentExecutor for EchoExecutor {
793 fn execute(
794 &self,
795 ctx: ExecutorContext,
796 ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
797 let task = Task {
798 id: ctx.task_id.clone(),
799 context_id: ctx.context_id.clone(),
800 status: TaskStatus {
801 state: TaskState::Completed,
802 message: ctx.message,
803 timestamp: None,
804 },
805 artifacts: None,
806 history: None,
807 metadata: None,
808 };
809 Box::pin(futures::stream::once(async move {
810 Ok(StreamResponse::Task(task))
811 }))
812 }
813
814 fn cancel(
815 &self,
816 ctx: ExecutorContext,
817 ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
818 let task = Task {
819 id: ctx.task_id.clone(),
820 context_id: ctx.context_id.clone(),
821 status: TaskStatus {
822 state: TaskState::Canceled,
823 message: None,
824 timestamp: None,
825 },
826 artifacts: None,
827 history: None,
828 metadata: None,
829 };
830 Box::pin(futures::stream::once(async move {
831 Ok(StreamResponse::Task(task))
832 }))
833 }
834 }
835
836 fn make_app() -> axum::Router {
837 let handler = Arc::new(DefaultRequestHandler::new(
838 EchoExecutor,
839 InMemoryTaskStore::new(),
840 ));
841 rest_router(handler)
842 }
843
844 fn make_push_app() -> axum::Router {
845 install_crypto_provider();
846 let handler = Arc::new(
847 DefaultRequestHandler::new(EchoExecutor, InMemoryTaskStore::new())
848 .with_push_config_store(InMemoryPushConfigStore::new()),
849 );
850 rest_router(handler)
851 }
852
853 #[tokio::test]
854 async fn test_client_role_validation_through_rest() {
855 for path in [REST_SEND_MESSAGE_PATH, REST_STREAM_MESSAGE_PATH] {
856 for role in ["ROLE_AGENT", "ROLE_UNSPECIFIED"] {
857 let body = serde_json::json!({
858 "message": {
859 "messageId": "role-validation",
860 "role": role,
861 "parts": [{"text": "hello"}]
862 }
863 });
864 let req = Request::builder()
865 .header("a2a-version", "1.0")
866 .uri(path)
867 .method("POST")
868 .header("content-type", "application/json")
869 .body(Body::from(serde_json::to_string(&body).unwrap()))
870 .unwrap();
871 let response = make_app().oneshot(req).await.unwrap();
872 assert_eq!(response.status(), StatusCode::BAD_REQUEST);
873 let bytes = response.into_body().collect().await.unwrap().to_bytes();
874 let error: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
875 assert_eq!(error["error"]["status"], "INVALID_ARGUMENT");
876 assert!(error["error"]["message"].as_str().unwrap().contains(role));
877 }
878 }
879 }
880
881 #[tokio::test]
882 async fn test_send_message() {
883 let app = make_app();
884 let body = serde_json::json!({
885 "message": {
886 "messageId": "m1",
887 "role": "ROLE_USER",
888 "parts": [{"text": "hello"}]
889 }
890 });
891 let req = Request::builder()
892 .header("a2a-version", "1.0")
893 .uri(REST_SEND_MESSAGE_PATH)
894 .method("POST")
895 .header("content-type", "application/json")
896 .body(Body::from(serde_json::to_string(&body).unwrap()))
897 .unwrap();
898 let resp = app.oneshot(req).await.unwrap();
899 assert_eq!(resp.status(), StatusCode::OK);
900 }
901
902 #[tokio::test]
907 async fn test_send_message_rejects_a_missing_message_and_a_part_without_content() {
908 let cases = [
909 (
910 serde_json::json!({"message": {
911 "messageId": "m1",
912 "role": "ROLE_USER",
913 "parts": [{"text": "ok"}, {}]
914 }}),
915 "message.parts[1]",
916 "must have one of: text, raw, url, data",
917 ),
918 (serde_json::json!({}), "message", "is required"),
919 (
921 serde_json::json!({"message": 5}),
922 "",
923 "ProtoJSON error: invalid type: integer `5`, expected struct lf.a2a.v1.Message",
924 ),
925 ];
926 for path in [REST_SEND_MESSAGE_PATH, REST_STREAM_MESSAGE_PATH] {
927 for (body, field, description) in &cases {
928 let req = Request::builder()
929 .header("a2a-version", "1.0")
930 .uri(path)
931 .method("POST")
932 .header("content-type", "application/json")
933 .body(Body::from(serde_json::to_string(body).unwrap()))
934 .unwrap();
935 let resp = make_app().oneshot(req).await.unwrap();
936 assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{path}");
937
938 let body = resp.into_body().collect().await.unwrap().to_bytes();
939 let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
940 let violation = &payload["error"]["details"][0]["fieldViolations"][0];
941 assert_eq!(violation["field"], *field, "{path}");
942 assert_eq!(violation["description"], *description, "{path}");
943 }
944 }
945 }
946
947 #[tokio::test]
948 async fn test_send_message_response_content_type_is_a2a_json() {
949 let app = make_app();
952 let body = serde_json::json!({
953 "message": {
954 "messageId": "m1",
955 "role": "ROLE_USER",
956 "parts": [{"text": "hello"}]
957 }
958 });
959 let req = Request::builder()
960 .header("a2a-version", "1.0")
961 .uri(REST_SEND_MESSAGE_PATH)
962 .method("POST")
963 .header("content-type", "application/json")
964 .body(Body::from(serde_json::to_string(&body).unwrap()))
965 .unwrap();
966 let resp = app.oneshot(req).await.unwrap();
967 assert_eq!(resp.status(), StatusCode::OK);
968 assert_eq!(
969 resp.headers()
970 .get("content-type")
971 .unwrap()
972 .to_str()
973 .unwrap(),
974 "application/a2a+json"
975 );
976 }
977
978 #[tokio::test]
979 async fn test_rest_error_response_content_type_is_json() {
980 let resp = rest_error_response(A2AError::task_not_found("missing"));
982 assert_eq!(
983 resp.headers()
984 .get("content-type")
985 .unwrap()
986 .to_str()
987 .unwrap(),
988 "application/json"
989 );
990 }
991
992 #[tokio::test]
993 async fn test_send_message_legacy_alias() {
994 let app = make_app();
995 let body = serde_json::json!({
996 "message": {
997 "messageId": "m1",
998 "role": "ROLE_USER",
999 "parts": [{"text": "hello"}]
1000 }
1001 });
1002 let req = Request::builder()
1003 .header("a2a-version", "1.0")
1004 .uri(REST_SEND_MESSAGE_LEGACY_PATH)
1005 .method("POST")
1006 .header("content-type", "application/json")
1007 .body(Body::from(serde_json::to_string(&body).unwrap()))
1008 .unwrap();
1009 let resp = app.oneshot(req).await.unwrap();
1010 assert_eq!(resp.status(), StatusCode::OK);
1011 }
1012
1013 #[tokio::test]
1014 async fn test_get_task_not_found() {
1015 let app = make_app();
1016 let req = Request::builder()
1017 .header("a2a-version", "1.0")
1018 .uri("/tasks/nonexistent")
1019 .method("GET")
1020 .body(Body::empty())
1021 .unwrap();
1022 let resp = app.oneshot(req).await.unwrap();
1023 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
1024 }
1025
1026 #[tokio::test]
1027 async fn test_list_tasks_empty() {
1028 let app = make_app();
1029 let req = Request::builder()
1030 .header("a2a-version", "1.0")
1031 .uri("/tasks")
1032 .method("GET")
1033 .body(Body::empty())
1034 .unwrap();
1035 let resp = app.oneshot(req).await.unwrap();
1036 assert_eq!(resp.status(), StatusCode::OK);
1037 let body = resp.into_body().collect().await.unwrap().to_bytes();
1038 let list_resp =
1039 protojson_conv::from_str::<ListTasksResponse>(std::str::from_utf8(&body).unwrap())
1040 .unwrap();
1041 assert!(list_resp.tasks.is_empty());
1042 }
1043
1044 #[tokio::test]
1045 async fn test_cancel_task_not_found() {
1046 let app = make_app();
1047 let req = Request::builder()
1048 .header("a2a-version", "1.0")
1049 .uri("/tasks/nonexistent:cancel")
1050 .method("POST")
1051 .header("content-type", "application/json")
1052 .body(Body::empty())
1053 .unwrap();
1054 let resp = app.oneshot(req).await.unwrap();
1055 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
1056 }
1057
1058 #[tokio::test]
1059 async fn test_create_push_config_not_supported() {
1060 let app = make_app();
1061 let body = serde_json::json!({
1062 "url": "http://example.com/callback"
1063 });
1064 let req = Request::builder()
1065 .header("a2a-version", "1.0")
1066 .uri("/tasks/t1/pushNotificationConfigs")
1067 .method("POST")
1068 .header("content-type", "application/json")
1069 .body(Body::from(serde_json::to_string(&body).unwrap()))
1070 .unwrap();
1071 let resp = app.oneshot(req).await.unwrap();
1072 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1073 }
1074
1075 #[tokio::test]
1076 async fn test_create_push_config_accepts_raw_config_body() {
1077 let app = make_push_app();
1078 let body = serde_json::json!({
1079 "id": "cfg1",
1080 "url": "http://example.com/callback"
1081 });
1082 let req = Request::builder()
1083 .header("a2a-version", "1.0")
1084 .uri("/tasks/t1/pushNotificationConfigs")
1085 .method("POST")
1086 .header("content-type", "application/json")
1087 .body(Body::from(serde_json::to_string(&body).unwrap()))
1088 .unwrap();
1089 let resp = app.oneshot(req).await.unwrap();
1090 assert_eq!(resp.status(), StatusCode::OK);
1091 let body = resp.into_body().collect().await.unwrap().to_bytes();
1092 let payload = serde_json::from_slice::<TaskPushNotificationConfig>(&body).unwrap();
1093 assert_eq!(payload.task_id, "t1");
1094 assert_eq!(payload.id.as_deref(), Some("cfg1"));
1095 assert_eq!(payload.url, "http://example.com/callback");
1096 }
1097
1098 #[tokio::test]
1099 async fn test_create_push_config_accepts_flat_request_body() {
1100 let app = make_push_app();
1101 let body = serde_json::json!({
1102 "taskId": "t1",
1103 "id": "cfg1",
1104 "url": "http://example.com/callback"
1105 });
1106 let req = Request::builder()
1107 .header("a2a-version", "1.0")
1108 .uri("/tasks/t1/pushNotificationConfigs")
1109 .method("POST")
1110 .header("content-type", "application/json")
1111 .body(Body::from(serde_json::to_string(&body).unwrap()))
1112 .unwrap();
1113 let resp = app.oneshot(req).await.unwrap();
1114 assert_eq!(resp.status(), StatusCode::OK);
1115 let body = resp.into_body().collect().await.unwrap().to_bytes();
1116 let payload = serde_json::from_slice::<TaskPushNotificationConfig>(&body).unwrap();
1117 assert_eq!(payload.task_id, "t1");
1118 assert_eq!(payload.id.as_deref(), Some("cfg1"));
1119 assert_eq!(payload.url, "http://example.com/callback");
1120 }
1121
1122 #[tokio::test]
1123 async fn test_create_push_config_rejects_mismatched_task_id_in_body() {
1124 let app = make_push_app();
1125 let body = serde_json::json!({
1126 "taskId": "other-task",
1127 "url": "http://example.com/callback"
1128 });
1129 let req = Request::builder()
1130 .header("a2a-version", "1.0")
1131 .uri("/tasks/t1/pushNotificationConfigs")
1132 .method("POST")
1133 .header("content-type", "application/json")
1134 .body(Body::from(serde_json::to_string(&body).unwrap()))
1135 .unwrap();
1136 let resp = app.oneshot(req).await.unwrap();
1137 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1138 }
1139
1140 #[tokio::test]
1141 async fn test_get_extended_agent_card() {
1142 let app = make_app();
1143 let req = Request::builder()
1144 .header("a2a-version", "1.0")
1145 .uri(REST_EXTENDED_AGENT_CARD_PATH)
1146 .method("GET")
1147 .body(Body::empty())
1148 .unwrap();
1149 let resp = app.oneshot(req).await.unwrap();
1150 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1151 }
1152
1153 #[tokio::test]
1154 async fn test_rest_error_response_status_codes() {
1155 let resp = rest_error_response(A2AError::task_not_found("t1"));
1156 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
1157
1158 let body = resp.into_body().collect().await.unwrap().to_bytes();
1159 let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
1160 assert_eq!(payload["error"]["code"], 404);
1161 assert_eq!(payload["error"]["status"], "NOT_FOUND");
1162 assert_eq!(payload["error"]["details"][0]["reason"], "TASK_NOT_FOUND");
1163
1164 let resp = rest_error_response(A2AError::internal("boom"));
1165 assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
1166
1167 let resp = rest_error_response(A2AError::content_type_not_supported());
1168 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1169 }
1170
1171 #[tokio::test]
1172 async fn test_rest_error_response_boundary_does_not_rewrite_internal_errors() {
1173 let resp = rest_error_response(A2AError::internal("agent-reported failure detail"));
1179 assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
1180 let body = resp.into_body().collect().await.unwrap().to_bytes();
1181 let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
1182 assert_eq!(payload["error"]["message"], "agent-reported failure detail");
1183 }
1184
1185 #[test]
1186 fn test_sanitized_internal_error_hides_server_side_detail() {
1187 let err = crate::sanitized_internal_error("serde fault at /etc/server/keys.pem");
1188 assert_eq!(err.code, a2a::error_code::INTERNAL_ERROR);
1189 assert_eq!(err.message, "Internal error");
1190 assert!(!err.message.contains("/etc/server/keys.pem"));
1191
1192 let resp = rest_error_response(A2AError::task_not_found("t1"));
1194 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
1195 }
1196
1197 struct UnserializablePayload;
1200
1201 impl protojson_conv::ProtoJsonPayload for UnserializablePayload {
1202 type Proto = a2a_pb::proto::Task;
1203 type ProtoJson = a2a_pb::protojson::Task;
1204
1205 fn to_proto(_value: &Self) -> Self::Proto {
1206 a2a_pb::proto::Task {
1209 status: Some(a2a_pb::proto::TaskStatus {
1210 state: 9999,
1211 message: None,
1212 timestamp: None,
1213 }),
1214 ..Default::default()
1215 }
1216 }
1217
1218 fn try_from_proto(
1219 _value: &Self::Proto,
1220 ) -> Result<Self, a2a_pb::protojson_conv::ProtoJsonPayloadError> {
1221 Ok(Self)
1222 }
1223 }
1224
1225 #[test]
1226 fn test_unserializable_payload_double_round_trips() {
1227 let proto = <UnserializablePayload as protojson_conv::ProtoJsonPayload>::to_proto(
1230 &UnserializablePayload,
1231 );
1232 assert!(
1233 <UnserializablePayload as protojson_conv::ProtoJsonPayload>::try_from_proto(&proto)
1234 .is_ok()
1235 );
1236 }
1237
1238 #[tokio::test]
1239 async fn test_serialization_fault_is_sanitized_at_the_raise_site() {
1240 let resp = protojson_json_response(&UnserializablePayload);
1244 assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
1245 let body = resp.into_body().collect().await.unwrap().to_bytes();
1246 let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
1247 assert_eq!(payload["error"]["message"], "Internal error");
1248 }
1249
1250 #[tokio::test]
1251 async fn test_stream_serialization_fault_is_sanitized_at_the_raise_site() {
1252 let stream: BoxStream<'static, Result<UnserializablePayload, A2AError>> =
1255 Box::pin(futures::stream::iter(vec![Ok(UnserializablePayload)]));
1256 let mut mapped = protojson_stream(stream);
1257 let item = mapped.next().await.expect("one item");
1258 let err = item.expect_err("transcode must fail");
1259 assert_eq!(err.code, a2a::error_code::INTERNAL_ERROR);
1260 assert_eq!(err.message, "Internal error");
1261 }
1262
1263 #[tokio::test]
1264 async fn test_stream_error_event_is_a_google_rpc_status() {
1265 let stream: BoxStream<'static, Result<Value, A2AError>> =
1266 Box::pin(futures::stream::iter(vec![
1267 Ok(serde_json::json!({"statusUpdate": {}})),
1268 Err(A2AError::task_not_found("t1")),
1269 ]));
1270 let body = rest_sse(stream)
1271 .into_body()
1272 .collect()
1273 .await
1274 .unwrap()
1275 .to_bytes();
1276 let body = String::from_utf8(body.to_vec()).unwrap();
1277 let frames: Vec<Value> = body
1278 .lines()
1279 .filter_map(|line| line.strip_prefix("data: "))
1280 .map(|data| serde_json::from_str(data).unwrap())
1281 .collect();
1282 assert_eq!(frames.len(), 2);
1283 let error = &frames[1]["error"];
1284 assert_eq!(error["code"], 404);
1285 assert_eq!(error["status"], "NOT_FOUND");
1286 assert_eq!(error["details"][0]["reason"], "TASK_NOT_FOUND");
1287 let names: Vec<&str> = body
1290 .lines()
1291 .filter_map(|line| line.strip_prefix("event: "))
1292 .collect();
1293 assert_eq!(names, vec!["error"], "{body}");
1294 }
1295
1296 #[tokio::test]
1297 async fn test_rest_error_response_merges_error_info_metadata() {
1298 let existing_info = TypedDetail::error_info(
1299 "TASK_NOT_FOUND",
1300 errordetails::PROTOCOL_DOMAIN,
1301 Some(HashMap::from([("taskId".to_string(), "t99".to_string())])),
1302 );
1303 let err = A2AError::task_not_found("t99").with_details(vec![existing_info]);
1304 let resp = rest_error_response(err);
1305 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
1306
1307 let body = resp.into_body().collect().await.unwrap().to_bytes();
1308 let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
1309 let details = payload["error"]["details"].as_array().unwrap();
1310 assert_eq!(details.len(), 1);
1312 assert_eq!(details[0]["@type"], errordetails::ERROR_INFO_TYPE);
1313 assert_eq!(details[0]["reason"], "TASK_NOT_FOUND");
1314 assert_eq!(details[0]["metadata"]["taskId"], "t99");
1316 assert!(details[0]["metadata"]["timestamp"].is_string());
1317 }
1318
1319 #[tokio::test]
1322 async fn test_rest_error_info_timestamp_uses_the_z_designator() {
1323 let resp = rest_error_response(A2AError::task_not_found("t1"));
1324 let body = resp.into_body().collect().await.unwrap().to_bytes();
1325 let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
1326 let timestamp = payload["error"]["details"][0]["metadata"]["timestamp"]
1327 .as_str()
1328 .unwrap();
1329 assert!(timestamp.ends_with('Z'), "{timestamp}");
1330 assert!(timestamp.parse::<DateTime<Utc>>().is_ok());
1331 }
1332
1333 #[tokio::test]
1334 async fn test_rest_error_response_preserves_non_error_info_details() {
1335 let bad_req = TypedDetail::bad_request(vec![FieldViolation {
1336 field: "message.parts".into(),
1337 description: "required".into(),
1338 }]);
1339 let err = A2AError::invalid_params("bad request").with_details(vec![bad_req]);
1340 let resp = rest_error_response(err);
1341 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1342
1343 let body = resp.into_body().collect().await.unwrap().to_bytes();
1344 let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
1345 let details = payload["error"]["details"].as_array().unwrap();
1346 assert_eq!(details.len(), 2);
1348 assert_eq!(details[0]["@type"], errordetails::BAD_REQUEST_TYPE);
1349 assert_eq!(details[0]["fieldViolations"][0]["field"], "message.parts");
1350 assert_eq!(details[1]["@type"], errordetails::ERROR_INFO_TYPE);
1351 assert_eq!(details[1]["reason"], "INVALID_PARAMS");
1352 }
1353
1354 #[tokio::test]
1355 async fn test_rest_payload_error_response() {
1356 let resp = rest_payload_error_response("missing field 'parts'");
1357 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1358
1359 let body = resp.into_body().collect().await.unwrap().to_bytes();
1360 let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
1361 assert_eq!(
1362 payload["error"]["message"].as_str().unwrap(),
1363 "invalid request body"
1364 );
1365 let details = payload["error"]["details"].as_array().unwrap();
1366 assert_eq!(details.len(), 2);
1368 assert_eq!(details[0]["@type"], errordetails::BAD_REQUEST_TYPE);
1369 assert_eq!(
1370 details[0]["fieldViolations"][0]["description"],
1371 "missing field 'parts'"
1372 );
1373 assert_eq!(details[1]["@type"], errordetails::ERROR_INFO_TYPE);
1374 assert_eq!(details[1]["reason"], "INVALID_PARAMS");
1375 }
1376
1377 #[tokio::test]
1378 async fn test_subscribe_to_task_not_found() {
1379 let app = make_app();
1380 let req = Request::builder()
1381 .header("a2a-version", "1.0")
1382 .uri("/tasks/nonexistent:subscribe")
1383 .method("GET")
1384 .body(Body::empty())
1385 .unwrap();
1386 let resp = app.oneshot(req).await.unwrap();
1387 assert!(resp.status().is_client_error());
1388 }
1389
1390 #[tokio::test]
1391 async fn test_stream_message() {
1392 let app = make_app();
1393 let body = serde_json::json!({
1394 "message": {
1395 "messageId": "m1",
1396 "role": "ROLE_USER",
1397 "parts": [{"text": "hello"}]
1398 }
1399 });
1400 let req = Request::builder()
1401 .header("a2a-version", "1.0")
1402 .uri(REST_STREAM_MESSAGE_PATH)
1403 .method("POST")
1404 .header("content-type", "application/json")
1405 .header("accept", "text/event-stream")
1406 .body(Body::from(serde_json::to_string(&body).unwrap()))
1407 .unwrap();
1408 let resp = app.oneshot(req).await.unwrap();
1409 assert_eq!(resp.status(), StatusCode::OK);
1410 }
1411
1412 #[tokio::test]
1413 async fn test_get_push_config_not_found() {
1414 let app = make_app();
1415 let req = Request::builder()
1416 .header("a2a-version", "1.0")
1417 .uri("/tasks/t1/pushNotificationConfigs/cfg1")
1418 .method("GET")
1419 .body(Body::empty())
1420 .unwrap();
1421 let resp = app.oneshot(req).await.unwrap();
1422 assert!(resp.status().is_client_error());
1424 }
1425
1426 #[tokio::test]
1427 async fn test_list_push_configs() {
1428 let app = make_push_app();
1429 let req = Request::builder()
1430 .header("a2a-version", "1.0")
1431 .uri("/tasks/t1/pushNotificationConfigs")
1432 .method("GET")
1433 .body(Body::empty())
1434 .unwrap();
1435 let resp = app.oneshot(req).await.unwrap();
1436 assert_eq!(resp.status(), StatusCode::OK);
1437 let body = resp.into_body().collect().await.unwrap().to_bytes();
1438 let payload =
1439 serde_json::from_slice::<ListTaskPushNotificationConfigsResponse>(&body).unwrap();
1440 assert!(payload.configs.is_empty());
1441 }
1442
1443 #[tokio::test]
1444 async fn test_delete_push_config() {
1445 let app = make_app();
1446 let req = Request::builder()
1447 .header("a2a-version", "1.0")
1448 .uri("/tasks/t1/pushNotificationConfigs/cfg1")
1449 .method("DELETE")
1450 .body(Body::empty())
1451 .unwrap();
1452 let resp = app.oneshot(req).await.unwrap();
1453 assert!(resp.status().is_client_error());
1454 }
1455
1456 #[tokio::test]
1457 async fn test_delete_push_config_with_store_returns_ok() {
1458 let app = make_push_app();
1459 let create_body = serde_json::json!({
1460 "id": "cfg1",
1461 "url": "http://example.com/callback"
1462 });
1463 let create_req = Request::builder()
1464 .header("a2a-version", "1.0")
1465 .uri("/tasks/t1/pushNotificationConfigs")
1466 .method("POST")
1467 .header("content-type", "application/json")
1468 .body(Body::from(serde_json::to_string(&create_body).unwrap()))
1469 .unwrap();
1470 let create_resp = app.clone().oneshot(create_req).await.unwrap();
1471 assert_eq!(create_resp.status(), StatusCode::OK);
1472
1473 let delete_req = Request::builder()
1474 .header("a2a-version", "1.0")
1475 .uri("/tasks/t1/pushNotificationConfigs/cfg1")
1476 .method("DELETE")
1477 .body(Body::empty())
1478 .unwrap();
1479 let delete_resp = app.clone().oneshot(delete_req).await.unwrap();
1480 assert_eq!(delete_resp.status(), StatusCode::OK);
1481 assert_eq!(
1484 delete_resp.headers().get(header::CONTENT_TYPE).unwrap(),
1485 "application/a2a+json"
1486 );
1487 let body = delete_resp.into_body().collect().await.unwrap().to_bytes();
1488 assert_eq!(
1489 serde_json::from_slice::<serde_json::Value>(&body).unwrap(),
1490 serde_json::json!({})
1491 );
1492
1493 let list_req = Request::builder()
1494 .header("a2a-version", "1.0")
1495 .uri("/tasks/t1/pushNotificationConfigs")
1496 .method("GET")
1497 .body(Body::empty())
1498 .unwrap();
1499 let list_resp = app.oneshot(list_req).await.unwrap();
1500 assert_eq!(list_resp.status(), StatusCode::OK);
1501 let body = list_resp.into_body().collect().await.unwrap().to_bytes();
1502 let payload =
1503 serde_json::from_slice::<ListTaskPushNotificationConfigsResponse>(&body).unwrap();
1504 assert!(payload.configs.is_empty());
1505 }
1506
1507 #[tokio::test]
1508 async fn test_list_tasks_with_query_params() {
1509 let app = make_app();
1510 let req = Request::builder()
1511 .header("a2a-version", "1.0")
1512 .uri("/tasks?contextId=c1&pageSize=5&pageToken=0&historyLength=3&includeArtifacts=true&statusTimestampAfter=2025-01-01T00:00:00Z")
1513 .method("GET")
1514 .body(Body::empty())
1515 .unwrap();
1516 let resp = app.oneshot(req).await.unwrap();
1517 assert_eq!(resp.status(), StatusCode::OK);
1518 }
1519
1520 #[tokio::test]
1524 async fn test_list_tasks_status_unspecified_is_no_filter() {
1525 let app = make_app();
1526 let body = serde_json::json!({
1527 "message": {"messageId": "m1", "role": "ROLE_USER", "parts": [{"text": "hello"}]}
1528 });
1529 let req = Request::builder()
1530 .header("a2a-version", "1.0")
1531 .uri(REST_SEND_MESSAGE_PATH)
1532 .method("POST")
1533 .header("content-type", "application/json")
1534 .body(Body::from(serde_json::to_string(&body).unwrap()))
1535 .unwrap();
1536 assert_eq!(
1537 app.clone().oneshot(req).await.unwrap().status(),
1538 StatusCode::OK
1539 );
1540
1541 let req = Request::builder()
1542 .header("a2a-version", "1.0")
1543 .uri("/tasks?status=TASK_STATE_UNSPECIFIED")
1544 .method("GET")
1545 .body(Body::empty())
1546 .unwrap();
1547 let resp = app.oneshot(req).await.unwrap();
1548 assert_eq!(resp.status(), StatusCode::OK);
1549 let body = resp.into_body().collect().await.unwrap().to_bytes();
1550 let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
1551 assert_eq!(payload["totalSize"], 1, "{payload}");
1552 }
1553
1554 #[tokio::test]
1555 async fn test_list_tasks_invalid_status_returns_bad_request() {
1556 let app = make_app();
1557 let req = Request::builder()
1558 .header("a2a-version", "1.0")
1559 .uri("/tasks?status=invalid")
1560 .method("GET")
1561 .body(Body::empty())
1562 .unwrap();
1563 let resp = app.oneshot(req).await.unwrap();
1564 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1565 let body = resp.into_body().collect().await.unwrap().to_bytes();
1566 let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
1567 assert_eq!(payload["error"]["message"], "invalid status filter");
1568 }
1569
1570 #[tokio::test]
1571 async fn test_send_message_propagates_headers_as_service_params() {
1572 let (handler, captured) = CapturingHandler::new();
1573 let app = rest_router(handler);
1574
1575 let body = serde_json::json!({
1576 "message": {
1577 "messageId": "m1",
1578 "role": "ROLE_USER",
1579 "parts": [{"text": "hi"}]
1580 }
1581 });
1582 let req = Request::builder()
1583 .header("a2a-version", "1.0")
1584 .uri(REST_SEND_MESSAGE_PATH)
1585 .method("POST")
1586 .header("content-type", "application/json")
1587 .header("authorization", "Bearer test-token-abc")
1588 .header("x-tenant-id", "acme")
1589 .body(Body::from(serde_json::to_string(&body).unwrap()))
1590 .unwrap();
1591 let _ = app.oneshot(req).await.unwrap();
1592
1593 assert_header_captured(
1594 &captured,
1595 "send_message",
1596 "authorization",
1597 "Bearer test-token-abc",
1598 );
1599 assert_header_captured(&captured, "send_message", "x-tenant-id", "acme");
1600 }
1601
1602 #[tokio::test]
1603 async fn test_stream_message_propagates_headers_as_service_params() {
1604 let (handler, captured) = CapturingHandler::new();
1605 let app = rest_router(handler);
1606
1607 let body = serde_json::json!({
1608 "message": {
1609 "messageId": "m1",
1610 "role": "ROLE_USER",
1611 "parts": [{"text": "hi"}]
1612 }
1613 });
1614 let req = Request::builder()
1615 .header("a2a-version", "1.0")
1616 .uri(REST_STREAM_MESSAGE_PATH)
1617 .method("POST")
1618 .header("content-type", "application/json")
1619 .header("accept", "text/event-stream")
1620 .header("authorization", "Bearer streaming-token")
1621 .body(Body::from(serde_json::to_string(&body).unwrap()))
1622 .unwrap();
1623 let resp = app.oneshot(req).await.unwrap();
1624 let _ = resp.into_body().collect().await.unwrap().to_bytes();
1626
1627 assert_header_captured(
1628 &captured,
1629 "send_streaming_message",
1630 "authorization",
1631 "Bearer streaming-token",
1632 );
1633 }
1634
1635 #[tokio::test]
1636 async fn test_get_task_propagates_headers_as_service_params() {
1637 let (handler, captured) = CapturingHandler::new();
1638 let app = rest_router(handler);
1639 let req = Request::builder()
1640 .header("a2a-version", "1.0")
1641 .uri("/tasks/some-id")
1642 .method("GET")
1643 .header("authorization", "Bearer get-task-token")
1644 .header("x-tenant-id", "acme")
1645 .body(Body::empty())
1646 .unwrap();
1647 let _ = app.oneshot(req).await.unwrap();
1648 assert_header_captured(
1649 &captured,
1650 "get_task",
1651 "authorization",
1652 "Bearer get-task-token",
1653 );
1654 assert_header_captured(&captured, "get_task", "x-tenant-id", "acme");
1655 }
1656
1657 #[tokio::test]
1658 async fn test_list_tasks_propagates_headers_as_service_params() {
1659 let (handler, captured) = CapturingHandler::new();
1660 let app = rest_router(handler);
1661 let req = Request::builder()
1662 .header("a2a-version", "1.0")
1663 .uri("/tasks")
1664 .method("GET")
1665 .header("authorization", "Bearer list-tasks-token")
1666 .body(Body::empty())
1667 .unwrap();
1668 let _ = app.oneshot(req).await.unwrap();
1669 assert_header_captured(
1670 &captured,
1671 "list_tasks",
1672 "authorization",
1673 "Bearer list-tasks-token",
1674 );
1675 }
1676
1677 #[tokio::test]
1678 async fn test_cancel_task_propagates_headers_as_service_params() {
1679 let (handler, captured) = CapturingHandler::new();
1680 let app = rest_router(handler);
1681 let req = Request::builder()
1682 .header("a2a-version", "1.0")
1683 .uri("/tasks/some-id:cancel")
1684 .method("POST")
1685 .header("authorization", "Bearer cancel-token")
1686 .body(Body::empty())
1687 .unwrap();
1688 let _ = app.oneshot(req).await.unwrap();
1689 assert_header_captured(
1690 &captured,
1691 "cancel_task",
1692 "authorization",
1693 "Bearer cancel-token",
1694 );
1695 }
1696
1697 #[tokio::test]
1698 async fn test_cancel_task_legacy_propagates_headers_as_service_params() {
1699 let (handler, captured) = CapturingHandler::new();
1701 let app = rest_router(handler);
1702 let req = Request::builder()
1703 .header("a2a-version", "1.0")
1704 .uri("/tasks/some-id/cancel")
1705 .method("POST")
1706 .header("authorization", "Bearer cancel-legacy-token")
1707 .body(Body::empty())
1708 .unwrap();
1709 let _ = app.oneshot(req).await.unwrap();
1710 assert_header_captured(
1711 &captured,
1712 "cancel_task",
1713 "authorization",
1714 "Bearer cancel-legacy-token",
1715 );
1716 }
1717
1718 #[tokio::test]
1719 async fn test_create_push_config_propagates_headers_as_service_params() {
1720 let (handler, captured) = CapturingHandler::new();
1721 let app = rest_router(handler);
1722 let body = serde_json::json!({
1723 "id": "cfg1",
1724 "url": "http://example.com/callback"
1725 });
1726 let req = Request::builder()
1727 .header("a2a-version", "1.0")
1728 .uri("/tasks/t1/pushNotificationConfigs")
1729 .method("POST")
1730 .header("content-type", "application/json")
1731 .header("authorization", "Bearer push-create-token")
1732 .body(Body::from(serde_json::to_string(&body).unwrap()))
1733 .unwrap();
1734 let _ = app.oneshot(req).await.unwrap();
1735 assert_header_captured(
1736 &captured,
1737 "create_push_config",
1738 "authorization",
1739 "Bearer push-create-token",
1740 );
1741 }
1742
1743 #[tokio::test]
1744 async fn test_list_push_configs_propagates_headers_as_service_params() {
1745 let (handler, captured) = CapturingHandler::new();
1746 let app = rest_router(handler);
1747 let req = Request::builder()
1748 .header("a2a-version", "1.0")
1749 .uri("/tasks/t1/pushNotificationConfigs")
1750 .method("GET")
1751 .header("authorization", "Bearer push-list-token")
1752 .body(Body::empty())
1753 .unwrap();
1754 let _ = app.oneshot(req).await.unwrap();
1755 assert_header_captured(
1756 &captured,
1757 "list_push_configs",
1758 "authorization",
1759 "Bearer push-list-token",
1760 );
1761 }
1762
1763 #[tokio::test]
1764 async fn test_get_push_config_propagates_headers_as_service_params() {
1765 let (handler, captured) = CapturingHandler::new();
1766 let app = rest_router(handler);
1767 let req = Request::builder()
1768 .header("a2a-version", "1.0")
1769 .uri("/tasks/t1/pushNotificationConfigs/cfg1")
1770 .method("GET")
1771 .header("authorization", "Bearer push-get-token")
1772 .body(Body::empty())
1773 .unwrap();
1774 let _ = app.oneshot(req).await.unwrap();
1775 assert_header_captured(
1776 &captured,
1777 "get_push_config",
1778 "authorization",
1779 "Bearer push-get-token",
1780 );
1781 }
1782
1783 #[tokio::test]
1784 async fn test_delete_push_config_propagates_headers_as_service_params() {
1785 let (handler, captured) = CapturingHandler::new();
1786 let app = rest_router(handler);
1787 let req = Request::builder()
1788 .header("a2a-version", "1.0")
1789 .uri("/tasks/t1/pushNotificationConfigs/cfg1")
1790 .method("DELETE")
1791 .header("authorization", "Bearer push-delete-token")
1792 .body(Body::empty())
1793 .unwrap();
1794 let _ = app.oneshot(req).await.unwrap();
1795 assert_header_captured(
1796 &captured,
1797 "delete_push_config",
1798 "authorization",
1799 "Bearer push-delete-token",
1800 );
1801 }
1802
1803 #[tokio::test]
1804 async fn test_get_extended_agent_card_propagates_headers_as_service_params() {
1805 let (handler, captured) = CapturingHandler::new();
1806 let app = rest_router(handler);
1807 let req = Request::builder()
1808 .header("a2a-version", "1.0")
1809 .uri(REST_EXTENDED_AGENT_CARD_PATH)
1810 .method("GET")
1811 .header("authorization", "Bearer card-token")
1812 .body(Body::empty())
1813 .unwrap();
1814 let _ = app.oneshot(req).await.unwrap();
1815 assert_header_captured(
1816 &captured,
1817 "get_extended_agent_card",
1818 "authorization",
1819 "Bearer card-token",
1820 );
1821 }
1822
1823 #[tokio::test]
1824 async fn test_subscribe_to_task_propagates_headers_as_service_params() {
1825 let (handler, captured) = CapturingHandler::new();
1826 let app = rest_router(handler);
1827 let req = Request::builder()
1828 .header("a2a-version", "1.0")
1829 .uri("/tasks/some-id:subscribe")
1830 .method("GET")
1831 .header("authorization", "Bearer subscribe-token")
1832 .body(Body::empty())
1833 .unwrap();
1834 let resp = app.oneshot(req).await.unwrap();
1835 let _ = resp.into_body().collect().await.unwrap().to_bytes();
1836 assert_header_captured(
1837 &captured,
1838 "subscribe_to_task",
1839 "authorization",
1840 "Bearer subscribe-token",
1841 );
1842 }
1843
1844 #[tokio::test]
1845 async fn test_subscribe_to_task_legacy_propagates_headers_as_service_params() {
1846 let (handler, captured) = CapturingHandler::new();
1848 let app = rest_router(handler);
1849 let req = Request::builder()
1850 .header("a2a-version", "1.0")
1851 .uri("/tasks/some-id/subscribe")
1852 .method("GET")
1853 .header("authorization", "Bearer subscribe-legacy-token")
1854 .body(Body::empty())
1855 .unwrap();
1856 let resp = app.oneshot(req).await.unwrap();
1857 let _ = resp.into_body().collect().await.unwrap().to_bytes();
1858 assert_header_captured(
1859 &captured,
1860 "subscribe_to_task",
1861 "authorization",
1862 "Bearer subscribe-legacy-token",
1863 );
1864 }
1865
1866 #[tokio::test]
1867 async fn test_get_task_with_history_length() {
1868 let app = make_app();
1870 let body = serde_json::json!({
1872 "message": {
1873 "messageId": "m1",
1874 "role": "ROLE_USER",
1875 "parts": [{"text": "hello"}]
1876 }
1877 });
1878 let req = Request::builder()
1879 .header("a2a-version", "1.0")
1880 .uri(REST_SEND_MESSAGE_PATH)
1881 .method("POST")
1882 .header("content-type", "application/json")
1883 .body(Body::from(serde_json::to_string(&body).unwrap()))
1884 .unwrap();
1885 let resp = app.oneshot(req).await.unwrap();
1886 assert_eq!(resp.status(), StatusCode::OK);
1887 let resp_body = resp.into_body().collect().await.unwrap().to_bytes();
1888 let send_resp: serde_json::Value = serde_json::from_slice(&resp_body).unwrap();
1889 let task_id = send_resp["task"]["id"].as_str().unwrap();
1890
1891 let app = make_app();
1892 let req = Request::builder()
1893 .header("a2a-version", "1.0")
1894 .uri(format!("/tasks/{}?historyLength=5", task_id))
1895 .method("GET")
1896 .body(Body::empty())
1897 .unwrap();
1898 let resp = app.oneshot(req).await.unwrap();
1899 assert!(resp.status() == StatusCode::OK || resp.status() == StatusCode::NOT_FOUND);
1901 }
1902
1903 #[tokio::test]
1907 async fn test_request_body_over_the_limit_is_rejected() {
1908 let app = make_app();
1909 let oversized = Body::from("x".repeat(crate::jsonrpc::MAX_REQUEST_BODY_BYTES + 1));
1910 let req = Request::builder()
1911 .header("a2a-version", "1.0")
1912 .uri(REST_SEND_MESSAGE_PATH)
1913 .method("POST")
1914 .header("content-type", "application/json")
1915 .body(oversized)
1916 .unwrap();
1917
1918 let resp = app.oneshot(req).await.unwrap();
1919 assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
1920 }
1921
1922 async fn send_message_with_version(uri: &str, version: Option<&str>) -> Response {
1923 let body = serde_json::json!({
1924 "message": {"messageId": "m1", "role": "ROLE_USER", "parts": [{"text": "hi"}]}
1925 });
1926 let mut req = Request::builder()
1927 .uri(uri)
1928 .method("POST")
1929 .header("content-type", "application/json");
1930 if let Some(version) = version {
1931 req = req.header("a2a-version", version);
1932 }
1933 let req = req.body(Body::from(body.to_string())).unwrap();
1934 make_app().oneshot(req).await.unwrap()
1935 }
1936
1937 async fn assert_version_not_supported(resp: Response) {
1938 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1939 let body = resp.into_body().collect().await.unwrap().to_bytes();
1940 let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
1941 assert_eq!(
1942 payload["error"]["status"], "FAILED_PRECONDITION",
1943 "{payload}"
1944 );
1945 assert_eq!(
1946 payload["error"]["details"][0]["reason"], "VERSION_NOT_SUPPORTED",
1947 "{payload}"
1948 );
1949 }
1950
1951 #[tokio::test]
1952 async fn test_unsupported_a2a_version_is_rejected() {
1953 let resp = send_message_with_version(REST_SEND_MESSAGE_PATH, Some("99.0")).await;
1955 assert_version_not_supported(resp).await;
1956 }
1957
1958 #[tokio::test]
1959 async fn test_missing_a2a_version_is_rejected() {
1960 let resp = send_message_with_version(REST_SEND_MESSAGE_PATH, None).await;
1963 assert_version_not_supported(resp).await;
1964
1965 let req = Request::builder()
1966 .uri("/tasks/t1")
1967 .body(Body::empty())
1968 .unwrap();
1969 assert_version_not_supported(make_app().oneshot(req).await.unwrap()).await;
1970 }
1971
1972 #[tokio::test]
1973 async fn test_a2a_version_query_parameter_is_accepted() {
1974 let uri = format!("{REST_SEND_MESSAGE_PATH}?A2A-Version=1.0");
1976 let resp = send_message_with_version(&uri, None).await;
1977 assert_eq!(resp.status(), StatusCode::OK);
1978
1979 let uri = format!("{REST_SEND_MESSAGE_PATH}?A2A-Version=99.0");
1980 assert_version_not_supported(send_message_with_version(&uri, None).await).await;
1981 }
1982
1983 #[tokio::test]
1986 async fn test_extractor_rejections_answer_google_rpc_status() {
1987 let requests = [
1988 Request::builder()
1989 .uri("/tasks/t1?historyLength=abc")
1990 .method("GET")
1991 .header("a2a-version", "1.0")
1992 .body(Body::empty())
1993 .unwrap(),
1994 Request::builder()
1995 .uri("/tasks?pageSize=x")
1996 .method("GET")
1997 .header("a2a-version", "1.0")
1998 .body(Body::empty())
1999 .unwrap(),
2000 Request::builder()
2001 .uri(REST_SEND_MESSAGE_PATH)
2002 .method("POST")
2003 .header("a2a-version", "1.0")
2004 .header("content-type", "application/json")
2005 .body(Body::from("{"))
2006 .unwrap(),
2007 Request::builder()
2008 .uri(REST_SEND_MESSAGE_PATH)
2009 .method("POST")
2010 .header("a2a-version", "1.0")
2011 .body(Body::from("{}"))
2012 .unwrap(),
2013 Request::builder()
2014 .uri(REST_STREAM_MESSAGE_PATH)
2015 .method("POST")
2016 .header("a2a-version", "1.0")
2017 .header("content-type", "application/json")
2018 .body(Body::from("{"))
2019 .unwrap(),
2020 Request::builder()
2021 .uri("/tasks/t1/pushNotificationConfigs")
2022 .method("POST")
2023 .header("a2a-version", "1.0")
2024 .header("content-type", "application/json")
2025 .body(Body::from("{"))
2026 .unwrap(),
2027 Request::builder()
2028 .uri("/tasks/t1/pushNotificationConfigs?pageSize=x")
2029 .method("GET")
2030 .header("a2a-version", "1.0")
2031 .body(Body::empty())
2032 .unwrap(),
2033 ];
2034 for req in requests {
2035 let target = req.uri().to_string();
2036 let resp = make_app().oneshot(req).await.unwrap();
2037 assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{target}");
2038 assert_eq!(
2039 resp.headers().get("content-type").unwrap(),
2040 "application/json",
2041 "{target}"
2042 );
2043 let body = resp.into_body().collect().await.unwrap().to_bytes();
2044 let body: Value = serde_json::from_slice(&body).unwrap();
2045 assert_eq!(body["error"]["code"], 400, "{target}");
2046 assert_eq!(body["error"]["status"], "INVALID_ARGUMENT", "{target}");
2047 }
2048 }
2049
2050 struct CancelMetadataExecutor(Arc<std::sync::Mutex<Option<HashMap<String, Value>>>>);
2052
2053 impl crate::AgentExecutor for CancelMetadataExecutor {
2054 fn execute(
2055 &self,
2056 _: ExecutorContext,
2057 ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
2058 Box::pin(futures::stream::empty())
2059 }
2060
2061 fn cancel(
2062 &self,
2063 ctx: ExecutorContext,
2064 ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
2065 *self.0.lock().unwrap() = ctx.metadata.clone();
2066 let update = StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
2067 task_id: ctx.task_id,
2068 context_id: ctx.context_id,
2069 status: TaskStatus {
2070 state: TaskState::Canceled,
2071 message: None,
2072 timestamp: None,
2073 },
2074 metadata: None,
2075 });
2076 Box::pin(futures::stream::once(async move { Ok(update) }))
2077 }
2078 }
2079
2080 #[tokio::test]
2083 async fn test_cancel_task_passes_body_metadata_to_the_executor() {
2084 for (action, body, expected) in [
2085 (":cancel", r#"{"metadata":{"reason":"user"}}"#, Some("user")),
2086 (
2087 "/cancel",
2088 r#"{"metadata":{"reason":"legacy"}}"#,
2089 Some("legacy"),
2090 ),
2091 (":cancel", "", None),
2092 ] {
2093 let seen = Arc::new(std::sync::Mutex::new(None));
2094 let app = rest_router(Arc::new(DefaultRequestHandler::new(
2095 CancelMetadataExecutor(seen.clone()),
2096 InMemoryTaskStore::new(),
2097 )));
2098 let send = serde_json::json!({
2099 "message": {"messageId": "m1", "role": "ROLE_USER", "parts": [{"text": "hi"}]},
2100 "configuration": {"returnImmediately": true}
2101 });
2102 let req = Request::builder()
2103 .uri(REST_SEND_MESSAGE_PATH)
2104 .method("POST")
2105 .header("a2a-version", "1.0")
2106 .header("content-type", "application/json")
2107 .body(Body::from(send.to_string()))
2108 .unwrap();
2109 let resp = app.clone().oneshot(req).await.unwrap();
2110 let sent = resp.into_body().collect().await.unwrap().to_bytes();
2111 let sent: Value = serde_json::from_slice(&sent).unwrap();
2112 let id = sent["task"]["id"].as_str().unwrap().to_owned();
2113
2114 let uri = format!("/tasks/{id}{action}");
2115 let req = Request::builder()
2116 .uri(&uri)
2117 .method("POST")
2118 .header("a2a-version", "1.0")
2119 .header("content-type", "application/json")
2120 .body(Body::from(body))
2121 .unwrap();
2122 let resp = app.oneshot(req).await.unwrap();
2123 assert_eq!(resp.status(), StatusCode::OK, "{uri} {body}");
2124 let reason = seen
2125 .lock()
2126 .unwrap()
2127 .as_ref()
2128 .and_then(|metadata| metadata.get("reason").cloned());
2129 assert_eq!(reason, expected.map(Value::from), "{uri} {body}");
2130 }
2131 }
2132
2133 #[tokio::test]
2134 async fn test_cancel_task_rejects_a_body_that_is_not_a_request() {
2135 let req = Request::builder()
2136 .uri("/tasks/t1:cancel")
2137 .method("POST")
2138 .header("a2a-version", "1.0")
2139 .header("content-type", "application/json")
2140 .body(Body::from("{"))
2141 .unwrap();
2142 let resp = make_app().oneshot(req).await.unwrap();
2143 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2144 }
2145
2146 #[tokio::test]
2149 async fn test_every_method_is_routed_under_a_tenant() {
2150 let (handler, _) = CapturingHandler::new();
2151 let app = rest_router(handler.clone());
2152 let send = r#"{"message":{"messageId":"m1","role":"ROLE_USER","parts":[{"text":"hi"}]}}"#;
2153 let config = r#"{"url":"https://example.com/cb"}"#;
2154 for (method, uri, body, called, tenant) in [
2155 (
2156 "POST",
2157 "/acme/message:send",
2158 send,
2159 "send_message",
2160 Some("acme"),
2161 ),
2162 (
2163 "POST",
2164 "/acme/message:stream",
2165 send,
2166 "send_streaming_message",
2167 Some("acme"),
2168 ),
2169 ("GET", "/acme/tasks/t1", "", "get_task", Some("acme")),
2170 ("GET", "/acme/tasks", "", "list_tasks", Some("acme")),
2171 (
2172 "POST",
2173 "/acme/tasks/t1:cancel",
2174 "",
2175 "cancel_task",
2176 Some("acme"),
2177 ),
2178 (
2179 "GET",
2180 "/acme/tasks/t1:subscribe",
2181 "",
2182 "subscribe_to_task",
2183 Some("acme"),
2184 ),
2185 (
2186 "POST",
2187 "/acme/tasks/t1:subscribe",
2188 "",
2189 "subscribe_to_task",
2190 Some("acme"),
2191 ),
2192 (
2193 "POST",
2194 "/acme/tasks/t1/pushNotificationConfigs",
2195 config,
2196 "create_push_config",
2197 Some("acme"),
2198 ),
2199 (
2200 "GET",
2201 "/acme/tasks/t1/pushNotificationConfigs/c1",
2202 "",
2203 "get_push_config",
2204 Some("acme"),
2205 ),
2206 (
2207 "GET",
2208 "/acme/tasks/t1/pushNotificationConfigs",
2209 "",
2210 "list_push_configs",
2211 Some("acme"),
2212 ),
2213 (
2214 "DELETE",
2215 "/acme/tasks/t1/pushNotificationConfigs/c1",
2216 "",
2217 "delete_push_config",
2218 Some("acme"),
2219 ),
2220 (
2221 "GET",
2222 "/acme/extendedAgentCard",
2223 "",
2224 "get_extended_agent_card",
2225 Some("acme"),
2226 ),
2227 ("POST", REST_SEND_MESSAGE_PATH, send, "send_message", None),
2228 ] {
2229 let req = Request::builder()
2230 .uri(uri)
2231 .method(method)
2232 .header("a2a-version", "1.0")
2233 .header("content-type", "application/json")
2234 .body(Body::from(body))
2235 .unwrap();
2236 app.clone().oneshot(req).await.unwrap();
2237 assert_eq!(
2238 handler.take_tenant(called),
2239 Some(tenant.map(str::to_owned)),
2240 "{method} {uri}"
2241 );
2242 }
2243 }
2244
2245 #[tokio::test]
2248 async fn test_an_undecodable_tenant_is_rejected() {
2249 let (handler, _) = CapturingHandler::new();
2250 let app = rest_router(handler.clone());
2251 let send = r#"{"message":{"messageId":"m1","role":"ROLE_USER","parts":[{"text":"hi"}]}}"#;
2252 for (method, uri, body, called) in [
2253 ("POST", "/%FF/message:send", send, "send_message"),
2254 (
2255 "POST",
2256 "/%FF/message:stream",
2257 send,
2258 "send_streaming_message",
2259 ),
2260 ("GET", "/%FF/tasks", "", "list_tasks"),
2261 ("GET", "/%FF/tasks/t1", "", "get_task"),
2262 (
2263 "GET",
2264 "/%FF/extendedAgentCard",
2265 "",
2266 "get_extended_agent_card",
2267 ),
2268 ] {
2269 let req = Request::builder()
2270 .uri(uri)
2271 .method(method)
2272 .header("a2a-version", "1.0")
2273 .header("content-type", "application/json")
2274 .body(Body::from(body))
2275 .unwrap();
2276 let resp = app.clone().oneshot(req).await.unwrap();
2277 assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{method} {uri}");
2278 assert_eq!(handler.take_tenant(called), None, "{method} {uri}");
2279 }
2280 }
2281
2282 #[tokio::test]
2286 async fn test_path_and_body_tenant() {
2287 let (handler, _) = CapturingHandler::new();
2288 let app = rest_router(handler.clone());
2289 let send = r#"{"message":{"messageId":"m1","role":"ROLE_USER","parts":[{"text":"hi"}]}}"#;
2290 let send_acme = r#"{"tenant":"acme","message":{"messageId":"m1","role":"ROLE_USER","parts":[{"text":"hi"}]}}"#;
2291 let send_body = r#"{"tenant":"body","message":{"messageId":"m1","role":"ROLE_USER","parts":[{"text":"hi"}]}}"#;
2292 let cancel_acme = r#"{"tenant":"acme"}"#;
2293 let cancel_body = r#"{"tenant":"body"}"#;
2294 let config_acme = r#"{"tenant":"acme","url":"https://example.com/cb"}"#;
2295 let config_body = r#"{"tenant":"body","url":"https://example.com/cb"}"#;
2296 for (uri, body, called, tenant) in [
2298 ("/acme/message:send", send, "send_message", Some("acme")),
2299 (
2300 "/acme/message:send",
2301 send_acme,
2302 "send_message",
2303 Some("acme"),
2304 ),
2305 ("/acme/message:send", send_body, "send_message", None),
2306 (
2307 REST_SEND_MESSAGE_PATH,
2308 send_body,
2309 "send_message",
2310 Some("body"),
2311 ),
2312 (
2313 "/acme/message:stream",
2314 send_acme,
2315 "send_streaming_message",
2316 Some("acme"),
2317 ),
2318 (
2319 "/acme/message:stream",
2320 send_body,
2321 "send_streaming_message",
2322 None,
2323 ),
2324 (
2325 REST_STREAM_MESSAGE_PATH,
2326 send_body,
2327 "send_streaming_message",
2328 Some("body"),
2329 ),
2330 ("/acme/tasks/t1:cancel", "", "cancel_task", Some("acme")),
2331 (
2332 "/acme/tasks/t1:cancel",
2333 cancel_acme,
2334 "cancel_task",
2335 Some("acme"),
2336 ),
2337 ("/acme/tasks/t1:cancel", cancel_body, "cancel_task", None),
2338 ("/tasks/t1:cancel", cancel_body, "cancel_task", Some("body")),
2339 (
2340 "/acme/tasks/t1/pushNotificationConfigs",
2341 config_acme,
2342 "create_push_config",
2343 Some("acme"),
2344 ),
2345 (
2346 "/acme/tasks/t1/pushNotificationConfigs",
2347 config_body,
2348 "create_push_config",
2349 None,
2350 ),
2351 (
2352 "/tasks/t1/pushNotificationConfigs",
2353 config_body,
2354 "create_push_config",
2355 Some("body"),
2356 ),
2357 ] {
2358 let req = Request::builder()
2359 .uri(uri)
2360 .method("POST")
2361 .header("a2a-version", "1.0")
2362 .header("content-type", "application/json")
2363 .body(Body::from(body))
2364 .unwrap();
2365 let resp = app.clone().oneshot(req).await.unwrap();
2366 assert_eq!(
2367 resp.status() == StatusCode::BAD_REQUEST,
2368 tenant.is_none(),
2369 "POST {uri} {body}"
2370 );
2371 assert_eq!(
2372 handler.take_tenant(called),
2373 tenant.map(|tenant| Some(tenant.to_owned())),
2374 "POST {uri} {body}"
2375 );
2376 }
2377
2378 let req = Request::builder()
2379 .uri("/acme/tasks/t1:cancel")
2380 .method("POST")
2381 .header("a2a-version", "1.0")
2382 .header("content-type", "application/json")
2383 .body(Body::from(cancel_body))
2384 .unwrap();
2385 let resp = app.oneshot(req).await.unwrap();
2386 let body = resp.into_body().collect().await.unwrap().to_bytes();
2387 let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
2388 let violation = &payload["error"]["details"][0]["fieldViolations"][0];
2389 assert_eq!(violation["field"], "tenant");
2390 assert_eq!(
2391 violation["description"],
2392 "tenant in the body (body) does not match the tenant in the path (acme)"
2393 );
2394 }
2395}
2396
2397#[cfg(test)]
2398mod encoded_task_action_regression {
2399 use super::*;
2400 use crate::executor::ExecutorContext;
2401 use crate::handler::DefaultRequestHandler;
2402 use crate::task_store::InMemoryTaskStore;
2403 use crate::test_util::CapturingHandler;
2404 use axum::body::Body;
2405 use axum::http::Request;
2406 use http_body_util::BodyExt;
2407 use tower::ServiceExt;
2408
2409 struct CustomTaskIdExecutor {
2410 state: TaskState,
2411 }
2412
2413 impl crate::AgentExecutor for CustomTaskIdExecutor {
2414 fn execute(
2415 &self,
2416 ctx: ExecutorContext,
2417 ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
2418 let task = Task {
2419 id: "foo:subscribe".into(),
2420 context_id: ctx.context_id,
2421 status: TaskStatus {
2422 state: self.state.clone(),
2423 message: None,
2424 timestamp: None,
2425 },
2426 artifacts: None,
2427 history: None,
2428 metadata: None,
2429 };
2430 Box::pin(futures::stream::once(async move {
2431 Ok(StreamResponse::Task(task))
2432 }))
2433 }
2434
2435 fn cancel(
2436 &self,
2437 _ctx: ExecutorContext,
2438 ) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
2439 Box::pin(futures::stream::empty())
2440 }
2441 }
2442
2443 #[tokio::test]
2444 async fn get_task_with_encoded_colon_emitted_by_executor() {
2445 let app = rest_router(Arc::new(DefaultRequestHandler::new(
2446 CustomTaskIdExecutor {
2447 state: TaskState::Completed,
2448 },
2449 InMemoryTaskStore::new(),
2450 )));
2451 let message = serde_json::json!({ "message": {
2452 "messageId": "m1", "role": "ROLE_USER", "parts": [{"text": "hello"}]
2453 }});
2454 let request = Request::builder()
2455 .method("POST")
2456 .uri("/message:send")
2457 .header("a2a-version", "1.0")
2458 .header("content-type", "application/json")
2459 .body(Body::from(message.to_string()))
2460 .unwrap();
2461 let response = app.clone().oneshot(request).await.unwrap();
2462 assert_eq!(response.status(), StatusCode::OK);
2463 let body: Value =
2464 serde_json::from_slice(&response.into_body().collect().await.unwrap().to_bytes())
2465 .unwrap();
2466 assert_eq!(body["task"]["id"], "foo:subscribe");
2467
2468 let request = Request::builder()
2469 .uri("/tasks/foo%3Asubscribe")
2470 .header("a2a-version", "1.0")
2471 .body(Body::empty())
2472 .unwrap();
2473 let response = app.oneshot(request).await.unwrap();
2474 assert_eq!(response.status(), StatusCode::OK);
2475 let body: Value =
2476 serde_json::from_slice(&response.into_body().collect().await.unwrap().to_bytes())
2477 .unwrap();
2478 assert_eq!(body["id"], "foo:subscribe");
2479 }
2480
2481 #[tokio::test]
2482 async fn cancel_task_with_encoded_colon_emitted_by_executor() {
2483 use crate::task_store::TaskStore;
2484
2485 let store = InMemoryTaskStore::new();
2486 store
2487 .create(Task {
2488 id: "foo".into(),
2489 context_id: "unrelated".into(),
2490 status: TaskStatus {
2491 state: TaskState::InputRequired,
2492 message: None,
2493 timestamp: None,
2494 },
2495 artifacts: None,
2496 history: None,
2497 metadata: None,
2498 })
2499 .await
2500 .unwrap();
2501 let app = rest_router(Arc::new(DefaultRequestHandler::new(
2502 CustomTaskIdExecutor {
2503 state: TaskState::InputRequired,
2504 },
2505 store,
2506 )));
2507 let message = serde_json::json!({ "message": {
2508 "messageId": "m-cancel", "role": "ROLE_USER", "parts": [{"text": "hello"}]
2509 }});
2510 let request = Request::builder()
2511 .method("POST")
2512 .uri("/message:send")
2513 .header("a2a-version", "1.0")
2514 .header("content-type", "application/json")
2515 .body(Body::from(message.to_string()))
2516 .unwrap();
2517 let response = app.clone().oneshot(request).await.unwrap();
2518 assert_eq!(response.status(), StatusCode::OK);
2519 let body: Value =
2520 serde_json::from_slice(&response.into_body().collect().await.unwrap().to_bytes())
2521 .unwrap();
2522 assert_eq!(body["task"]["id"], "foo:subscribe");
2523
2524 let request = Request::builder()
2525 .method("POST")
2526 .uri("/tasks/foo%3Asubscribe:cancel")
2527 .header("a2a-version", "1.0")
2528 .header("content-type", "application/json")
2529 .body(Body::from("{}"))
2530 .unwrap();
2531 let response = app.clone().oneshot(request).await.unwrap();
2532 assert_eq!(response.status(), StatusCode::OK);
2533 let body: Value =
2534 serde_json::from_slice(&response.into_body().collect().await.unwrap().to_bytes())
2535 .unwrap();
2536 assert_eq!(body["id"], "foo:subscribe");
2537 assert_eq!(body["status"]["state"], "TASK_STATE_CANCELED");
2538
2539 for (uri, id, state) in [
2540 (
2541 "/tasks/foo%3Asubscribe",
2542 "foo:subscribe",
2543 "TASK_STATE_CANCELED",
2544 ),
2545 ("/tasks/foo", "foo", "TASK_STATE_INPUT_REQUIRED"),
2546 ] {
2547 let request = Request::builder()
2548 .uri(uri)
2549 .header("a2a-version", "1.0")
2550 .body(Body::empty())
2551 .unwrap();
2552 let response = app.clone().oneshot(request).await.unwrap();
2553 assert_eq!(response.status(), StatusCode::OK);
2554 let body: Value =
2555 serde_json::from_slice(&response.into_body().collect().await.unwrap().to_bytes())
2556 .unwrap();
2557 assert_eq!(body["id"], id);
2558 assert_eq!(body["status"]["state"], state);
2559 }
2560 }
2561
2562 #[tokio::test]
2563 async fn encoded_action_suffix_is_part_of_id() {
2564 for (uri, id) in [
2565 ("/tasks/foo%3Asubscribe", "foo:subscribe"),
2566 ("/tasks/foo%3As%75bscribe", "foo:subscribe"),
2567 ("/tasks/foo%3asubscribe?historyLength=1", "foo:subscribe"),
2568 ("/tasks/foo%253Asubscribe", "foo%3Asubscribe"),
2569 ] {
2570 let (handler, _) = CapturingHandler::new();
2571 let req = Request::builder()
2572 .uri(uri)
2573 .header("a2a-version", "1.0")
2574 .body(Body::empty())
2575 .unwrap();
2576 let _ = rest_router(handler.clone()).oneshot(req).await.unwrap();
2577 assert!(
2578 handler.take_tenant("get_task").is_some(),
2579 "{uri}: not dispatched to get_task"
2580 );
2581 assert_eq!(handler.take_id("get_task").as_deref(), Some(id));
2582 assert!(
2583 handler.take_tenant("subscribe_to_task").is_none(),
2584 "{uri}: dispatched to subscribe"
2585 );
2586 }
2587 }
2588
2589 #[tokio::test]
2590 async fn unencoded_action_suffix_subscribes() {
2591 for (uri, id) in [
2592 ("/tasks/foo:subscribe", "foo"),
2593 ("/tasks/foo:s%75bscribe", "foo"),
2594 ("/tasks/foo%3Asubscribe:s%75bscribe", "foo:subscribe"),
2595 ("/tasks/foo%3Asubscribe:subscribe", "foo:subscribe"),
2596 (
2597 "/tenant/tasks/foo%3Asubscribe:subscribe?x=y",
2598 "foo:subscribe",
2599 ),
2600 ] {
2601 let (handler, _) = CapturingHandler::new();
2602 let req = Request::builder()
2603 .uri(uri)
2604 .header("a2a-version", "1.0")
2605 .body(Body::empty())
2606 .unwrap();
2607 let _ = rest_router(handler.clone()).oneshot(req).await.unwrap();
2608 assert!(
2609 handler.take_tenant("subscribe_to_task").is_some(),
2610 "{uri}: not dispatched to subscribe"
2611 );
2612 assert_eq!(handler.take_id("subscribe_to_task").as_deref(), Some(id));
2613 }
2614 }
2615
2616 #[tokio::test]
2617 async fn post_encoded_action_suffix_does_not_cancel_other_task() {
2618 for uri in [
2619 "/tasks/foo%3Acancel",
2620 "/tasks/foo%3Ac%61ncel",
2621 "/tenant/tasks/foo%3acancel?x=y",
2622 "/tasks/foo%253Acancel",
2623 ] {
2624 let (handler, _) = CapturingHandler::new();
2625 let req = Request::builder()
2626 .method("POST")
2627 .uri(uri)
2628 .header("a2a-version", "1.0")
2629 .header("content-type", "application/json")
2630 .body(Body::from("{}"))
2631 .unwrap();
2632 let _ = rest_router(handler.clone()).oneshot(req).await.unwrap();
2633 assert!(
2634 handler.take_tenant("cancel_task").is_none(),
2635 "{uri}: incorrectly cancelled a different task"
2636 );
2637 }
2638 }
2639
2640 #[tokio::test]
2641 async fn post_literal_action_suffix_cancels() {
2642 for (uri, id) in [
2643 ("/tasks/foo:cancel", "foo"),
2644 ("/tasks/foo:c%61ncel", "foo"),
2645 ("/tenant/tasks/foo%3Acancel:c%61ncel?x=y", "foo:cancel"),
2646 ("/tenant/tasks/foo%3Acancel:cancel?x=y", "foo:cancel"),
2647 ] {
2648 let (handler, _) = CapturingHandler::new();
2649 let req = Request::builder()
2650 .method("POST")
2651 .uri(uri)
2652 .header("a2a-version", "1.0")
2653 .header("content-type", "application/json")
2654 .body(Body::from("{}"))
2655 .unwrap();
2656 let _ = rest_router(handler.clone()).oneshot(req).await.unwrap();
2657 assert!(
2658 handler.take_tenant("cancel_task").is_some(),
2659 "{uri}: not dispatched to cancel"
2660 );
2661 assert_eq!(handler.take_id("cancel_task").as_deref(), Some(id));
2662 }
2663 }
2664
2665 #[tokio::test]
2666 async fn post_subscribe_requires_literal_suffix_and_preserves_id() {
2667 for (uri, expected) in [
2668 ("/tasks/foo%3Asubscribe", None),
2669 ("/tasks/foo%253Asubscribe", None),
2670 ("/tasks/foo:s%75bscribe", Some("foo")),
2671 (
2672 "/tasks/foo%3Asubscribe:subscribe?x=y",
2673 Some("foo:subscribe"),
2674 ),
2675 ] {
2676 let (handler, _) = CapturingHandler::new();
2677 let req = Request::builder()
2678 .method("POST")
2679 .uri(uri)
2680 .header("a2a-version", "1.0")
2681 .header("content-type", "application/json")
2682 .body(Body::from("{}"))
2683 .unwrap();
2684 let _ = rest_router(handler.clone()).oneshot(req).await.unwrap();
2685 assert_eq!(
2686 handler.take_id("subscribe_to_task").as_deref(),
2687 expected,
2688 "{uri}"
2689 );
2690 }
2691 }
2692
2693 #[tokio::test]
2694 async fn routing_works_under_nested_base_path() {
2695 for (uri, method, id) in [
2696 (
2697 "/a2a/tasks/foo%3Asubscribe?x=:subscribe",
2698 "get_task",
2699 "foo:subscribe",
2700 ),
2701 (
2702 "/a2a/tasks/foo%3Asubscribe:subscribe",
2703 "subscribe_to_task",
2704 "foo:subscribe",
2705 ),
2706 ] {
2707 let (handler, _) = CapturingHandler::new();
2708 let app = axum::Router::new().nest("/a2a", rest_router(handler.clone()));
2709 let req = Request::builder()
2710 .uri(uri)
2711 .header("a2a-version", "1.0")
2712 .body(Body::empty())
2713 .unwrap();
2714 let _ = app.oneshot(req).await.unwrap();
2715 assert_eq!(handler.take_id(method).as_deref(), Some(id), "{uri}");
2716 }
2717 }
2718}