use std::sync::Arc;
use a2a::*;
use a2a_pb::protojson_conv::{self, ProtoJsonPayload, ProtoJsonPayloadError};
use axum::{
Json,
body::Bytes,
extract::{
OriginalUri, Path, Query, Request, State,
rejection::{JsonRejection, QueryRejection},
},
http::{HeaderMap, HeaderValue, StatusCode, header},
middleware::Next,
response::{IntoResponse, Response},
};
use chrono::{DateTime, Utc};
use futures::{StreamExt, stream::BoxStream};
use percent_encoding::percent_decode_str;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use crate::handler::RequestHandler;
use crate::middleware::{
ServiceParams, add_query_version, check_a2a_version, extract_service_params,
};
use crate::sse;
const REST_SEND_MESSAGE_PATH: &str = "/message:send";
const REST_SEND_MESSAGE_LEGACY_PATH: &str = "/message/send";
const REST_STREAM_MESSAGE_PATH: &str = "/message:stream";
const REST_STREAM_MESSAGE_LEGACY_PATH: &str = "/message/stream";
const REST_EXTENDED_AGENT_CARD_PATH: &str = "/extendedAgentCard";
const REST_EXTENDED_AGENT_CARD_LEGACY_PATH: &str = "/agent-card/extended";
const REST_PUSH_CONFIGS_PATH: &str = "/tasks/{id}/pushNotificationConfigs";
const REST_PUSH_CONFIGS_LEGACY_PATH: &str = "/tasks/{id}/push-configs";
const REST_PUSH_CONFIG_PATH: &str = "/tasks/{id}/pushNotificationConfigs/{config_id}";
const REST_PUSH_CONFIG_LEGACY_PATH: &str = "/tasks/{id}/push-configs/{config_id}";
#[derive(Serialize)]
struct RestErrorEnvelope {
error: RestErrorStatus,
}
#[derive(Serialize)]
struct RestErrorStatus {
code: u16,
status: &'static str,
message: String,
details: Vec<TypedDetail>,
}
pub struct RestState<H: RequestHandler> {
pub handler: Arc<H>,
}
impl<H: RequestHandler> Clone for RestState<H> {
fn clone(&self) -> Self {
RestState {
handler: self.handler.clone(),
}
}
}
pub fn rest_router<H: RequestHandler>(handler: Arc<H>) -> axum::Router {
let state = RestState { handler };
axum::Router::new()
.route(
REST_SEND_MESSAGE_PATH,
axum::routing::post(handle_send_message::<H>),
)
.route(
REST_SEND_MESSAGE_LEGACY_PATH,
axum::routing::post(handle_send_message::<H>),
)
.route(
REST_STREAM_MESSAGE_PATH,
axum::routing::post(handle_stream_message::<H>),
)
.route(
REST_STREAM_MESSAGE_LEGACY_PATH,
axum::routing::post(handle_stream_message::<H>),
)
.route(
"/tasks/{id}",
axum::routing::get(handle_get_task_or_subscribe::<H>)
.post(handle_post_task_action::<H>),
)
.route("/tasks", axum::routing::get(handle_list_tasks::<H>))
.route(
"/tasks/{id}/cancel",
axum::routing::post(handle_cancel_task_legacy::<H>),
)
.route(
"/tasks/{id}/subscribe",
axum::routing::get(handle_subscribe_to_task_legacy::<H>)
.post(handle_subscribe_to_task_legacy::<H>),
)
.route(
REST_PUSH_CONFIGS_PATH,
axum::routing::post(handle_create_push_config::<H>).get(handle_list_push_configs::<H>),
)
.route(
REST_PUSH_CONFIGS_LEGACY_PATH,
axum::routing::post(handle_create_push_config::<H>).get(handle_list_push_configs::<H>),
)
.route(
REST_PUSH_CONFIG_PATH,
axum::routing::get(handle_get_push_config::<H>).delete(handle_delete_push_config::<H>),
)
.route(
REST_PUSH_CONFIG_LEGACY_PATH,
axum::routing::get(handle_get_push_config::<H>).delete(handle_delete_push_config::<H>),
)
.route(
REST_EXTENDED_AGENT_CARD_PATH,
axum::routing::get(handle_get_extended_agent_card::<H>),
)
.route(
REST_EXTENDED_AGENT_CARD_LEGACY_PATH,
axum::routing::get(handle_get_extended_agent_card::<H>),
)
.route(
"/{tenant}/message:send",
axum::routing::post(handle_send_message::<H>),
)
.route(
"/{tenant}/message:stream",
axum::routing::post(handle_stream_message::<H>),
)
.route(
"/{tenant}/tasks/{id}",
axum::routing::get(handle_get_task_or_subscribe::<H>)
.post(handle_post_task_action::<H>),
)
.route(
"/{tenant}/tasks",
axum::routing::get(handle_list_tasks::<H>),
)
.route(
"/{tenant}/tasks/{id}/pushNotificationConfigs",
axum::routing::post(handle_create_push_config::<H>).get(handle_list_push_configs::<H>),
)
.route(
"/{tenant}/tasks/{id}/pushNotificationConfigs/{config_id}",
axum::routing::get(handle_get_push_config::<H>).delete(handle_delete_push_config::<H>),
)
.route(
"/{tenant}/extendedAgentCard",
axum::routing::get(handle_get_extended_agent_card::<H>),
)
.route_layer(axum::middleware::from_fn(validate_protocol_version))
.layer(axum::extract::DefaultBodyLimit::max(
crate::jsonrpc::MAX_REQUEST_BODY_BYTES,
))
.with_state(state)
}
async fn validate_protocol_version(request: Request, next: Next) -> Response {
let mut params = extract_service_params(request.headers());
add_query_version(&mut params, request.uri());
match check_a2a_version(¶ms) {
Ok(()) => next.run(request).await,
Err(error) => rest_error_response(error),
}
}
#[derive(Deserialize)]
struct TaskPath {
tenant: Option<String>,
id: String,
}
fn task_id_for_action<'a>(
uri: &axum::http::Uri,
decoded_id: &'a str,
action: &str,
) -> Option<&'a str> {
let actual_action = uri
.path()
.rsplit('/')
.next()
.and_then(|segment| segment.rsplit_once(':'))
.and_then(|(_, action)| percent_decode_str(action).decode_utf8().ok())?;
if actual_action != action {
return None;
}
decoded_id.strip_suffix(action)?.strip_suffix(':')
}
#[derive(Deserialize)]
struct PushConfigPath {
tenant: Option<String>,
id: String,
config_id: String,
}
fn reconcile_tenant(
path: Option<String>,
body: Option<String>,
) -> Result<Option<String>, Box<axum::response::Response>> {
match (path, body) {
(Some(path), Some(body)) if path != body => {
let violation = FieldViolation {
field: "tenant".to_string(),
description: format!(
"tenant in the body ({body}) does not match the tenant in the path ({path})"
),
};
Err(Box::new(rest_error_response(
A2AError::invalid_params("invalid request body")
.with_details(vec![TypedDetail::bad_request(vec![violation])]),
)))
}
(Some(path), _) => Ok(Some(path)),
(None, body) => Ok(body),
}
}
async fn handle_send_message<H: RequestHandler>(
State(state): State<RestState<H>>,
tenant: Option<Path<String>>,
headers: HeaderMap,
body: Result<Json<Value>, JsonRejection>,
) -> impl IntoResponse {
let tenant = tenant.map(|Path(tenant)| tenant);
let Json(raw_req) = match body {
Ok(body) => body,
Err(rejection) => return json_rejection_response(rejection),
};
let mut req = match protojson_conv::from_value::<SendMessageRequest>(raw_req) {
Ok(req) => req,
Err(e) => return protojson_error_response(e),
};
req.tenant = match reconcile_tenant(tenant, req.tenant.take()) {
Ok(tenant) => tenant,
Err(response) => return *response,
};
let params = extract_service_params(&headers);
match state.handler.send_message(¶ms, req).await {
Ok(resp) => protojson_json_response(&resp),
Err(e) => rest_error_response(e),
}
}
async fn handle_stream_message<H: RequestHandler>(
State(state): State<RestState<H>>,
tenant: Option<Path<String>>,
headers: HeaderMap,
body: Result<Json<Value>, JsonRejection>,
) -> impl IntoResponse {
let tenant = tenant.map(|Path(tenant)| tenant);
let Json(raw_req) = match body {
Ok(body) => body,
Err(rejection) => return json_rejection_response(rejection),
};
let mut req = match protojson_conv::from_value::<SendMessageRequest>(raw_req) {
Ok(req) => req,
Err(e) => return protojson_error_response(e),
};
req.tenant = match reconcile_tenant(tenant, req.tenant.take()) {
Ok(tenant) => tenant,
Err(response) => return *response,
};
let params = extract_service_params(&headers);
match state.handler.send_streaming_message(¶ms, req).await {
Ok(stream) => rest_sse(protojson_stream(stream)),
Err(e) => rest_error_response(e),
}
}
#[derive(Deserialize)]
pub struct GetTaskQuery {
#[serde(default, rename = "historyLength")]
pub history_length: Option<i32>,
}
async fn handle_get_task_inner<H: RequestHandler>(
state: RestState<H>,
params: ServiceParams,
TaskPath { tenant, id }: TaskPath,
query: GetTaskQuery,
) -> axum::response::Response {
let req = GetTaskRequest {
id,
history_length: query.history_length,
tenant,
};
match state.handler.get_task(¶ms, req).await {
Ok(task) => protojson_json_response(&task),
Err(e) => rest_error_response(e),
}
}
async fn handle_get_task_or_subscribe<H: RequestHandler>(
State(state): State<RestState<H>>,
OriginalUri(original_uri): OriginalUri,
Path(path): Path<TaskPath>,
query: Result<Query<GetTaskQuery>, QueryRejection>,
headers: HeaderMap,
) -> impl IntoResponse {
let Query(query) = match query {
Ok(query) => query,
Err(rejection) => return rest_payload_error_response(rejection.body_text()),
};
let params = extract_service_params(&headers);
if let Some(task_id) = task_id_for_action(&original_uri, &path.id, "subscribe") {
let id = task_id.to_string();
return handle_subscribe_to_task_inner(state, params, id, path.tenant).await;
}
handle_get_task_inner(state, params, path, query).await
}
#[derive(Deserialize)]
pub struct ListTasksQuery {
#[serde(default, rename = "contextId")]
pub context_id: Option<String>,
#[serde(default)]
pub status: Option<String>,
#[serde(default, rename = "pageSize")]
pub page_size: Option<i32>,
#[serde(default, rename = "pageToken")]
pub page_token: Option<String>,
#[serde(default, rename = "historyLength")]
pub history_length: Option<i32>,
#[serde(default, rename = "statusTimestampAfter")]
pub status_timestamp_after: Option<DateTime<Utc>>,
#[serde(default, rename = "includeArtifacts")]
pub include_artifacts: Option<bool>,
}
async fn handle_list_tasks<H: RequestHandler>(
State(state): State<RestState<H>>,
tenant: Option<Path<String>>,
query: Result<Query<ListTasksQuery>, QueryRejection>,
headers: HeaderMap,
) -> impl IntoResponse {
let tenant = tenant.map(|Path(tenant)| tenant);
let Query(query) = match query {
Ok(query) => query,
Err(rejection) => return rest_payload_error_response(rejection.body_text()),
};
let params = extract_service_params(&headers);
let status = match query.status {
Some(s) => match serde_json::from_value::<TaskState>(serde_json::Value::String(s)) {
Ok(TaskState::Unspecified) => None,
Ok(state) => Some(state),
Err(_) => {
return rest_error_response(A2AError::invalid_params("invalid status filter"));
}
},
None => None,
};
let req = ListTasksRequest {
context_id: query.context_id,
status,
page_size: query.page_size,
page_token: query.page_token,
history_length: query.history_length,
status_timestamp_after: query.status_timestamp_after,
include_artifacts: query.include_artifacts,
tenant,
};
match state.handler.list_tasks(¶ms, req).await {
Ok(resp) => protojson_json_response(&resp),
Err(e) => rest_error_response(e),
}
}
async fn handle_cancel_task_inner<H: RequestHandler>(
state: RestState<H>,
params: ServiceParams,
id: String,
tenant: Option<String>,
body: Bytes,
) -> axum::response::Response {
let mut req = if body.is_empty() {
CancelTaskRequest {
id: String::new(),
metadata: None,
tenant: None,
}
} else {
match serde_json::from_slice::<Value>(&body)
.map_err(|e| e.to_string())
.and_then(|raw| {
protojson_conv::from_value::<CancelTaskRequest>(raw).map_err(|e| e.to_string())
}) {
Ok(req) => req,
Err(e) => return rest_payload_error_response(e),
}
};
req.id = id;
req.tenant = match reconcile_tenant(tenant, req.tenant.take()) {
Ok(tenant) => tenant,
Err(response) => return *response,
};
match state.handler.cancel_task(¶ms, req).await {
Ok(task) => protojson_json_response(&task),
Err(e) => rest_error_response(e),
}
}
async fn handle_post_task_action<H: RequestHandler>(
State(state): State<RestState<H>>,
OriginalUri(original_uri): OriginalUri,
Path(TaskPath { tenant, id }): Path<TaskPath>,
headers: HeaderMap,
body: Bytes,
) -> impl IntoResponse {
let params = extract_service_params(&headers);
if let Some(task_id) = task_id_for_action(&original_uri, &id, "cancel") {
return handle_cancel_task_inner(state, params, task_id.to_string(), tenant, body).await;
}
if let Some(task_id) = task_id_for_action(&original_uri, &id, "subscribe") {
return handle_subscribe_to_task_inner(state, params, task_id.to_string(), tenant).await;
}
rest_error_response(A2AError::invalid_request("unsupported task action"))
}
async fn handle_cancel_task_legacy<H: RequestHandler>(
State(state): State<RestState<H>>,
Path(id): Path<String>,
headers: HeaderMap,
body: Bytes,
) -> impl IntoResponse {
let params = extract_service_params(&headers);
handle_cancel_task_inner(state, params, id, None, body).await
}
async fn handle_subscribe_to_task_inner<H: RequestHandler>(
state: RestState<H>,
params: ServiceParams,
id: String,
tenant: Option<String>,
) -> axum::response::Response {
let req = SubscribeToTaskRequest { id, tenant };
match state.handler.subscribe_to_task(¶ms, req).await {
Ok(stream) => rest_sse(protojson_stream(stream)),
Err(e) => rest_error_response(e),
}
}
async fn handle_subscribe_to_task_legacy<H: RequestHandler>(
State(state): State<RestState<H>>,
Path(id): Path<String>,
headers: HeaderMap,
) -> impl IntoResponse {
let params = extract_service_params(&headers);
handle_subscribe_to_task_inner(state, params, id, None).await
}
#[derive(Deserialize)]
pub struct ListPushConfigsQuery {
#[serde(default, rename = "pageSize")]
pub page_size: Option<i32>,
#[serde(default, rename = "pageToken")]
pub page_token: Option<String>,
}
async fn handle_create_push_config<H: RequestHandler>(
State(state): State<RestState<H>>,
Path(TaskPath { tenant, id }): Path<TaskPath>,
headers: HeaderMap,
body: Result<Json<Value>, JsonRejection>,
) -> impl IntoResponse {
let Json(raw_config) = match body {
Ok(body) => body,
Err(rejection) => return json_rejection_response(rejection),
};
let mut req = match parse_create_push_config_request(id, raw_config) {
Ok(req) => req,
Err(e) => return rest_payload_error_response(e),
};
req.tenant = match reconcile_tenant(tenant, req.tenant.take()) {
Ok(tenant) => tenant,
Err(response) => return *response,
};
let params = extract_service_params(&headers);
match state.handler.create_push_config(¶ms, req).await {
Ok(resp) => protojson_json_response(&resp),
Err(e) => rest_error_response(e),
}
}
async fn handle_get_push_config<H: RequestHandler>(
State(state): State<RestState<H>>,
Path(PushConfigPath {
tenant,
id,
config_id,
}): Path<PushConfigPath>,
headers: HeaderMap,
) -> impl IntoResponse {
let params = extract_service_params(&headers);
let req = GetTaskPushNotificationConfigRequest {
task_id: id,
id: config_id,
tenant,
};
match state.handler.get_push_config(¶ms, req).await {
Ok(resp) => protojson_json_response(&resp),
Err(e) => rest_error_response(e),
}
}
async fn handle_list_push_configs<H: RequestHandler>(
State(state): State<RestState<H>>,
Path(TaskPath { tenant, id }): Path<TaskPath>,
query: Result<Query<ListPushConfigsQuery>, QueryRejection>,
headers: HeaderMap,
) -> impl IntoResponse {
let Query(query) = match query {
Ok(query) => query,
Err(rejection) => return rest_payload_error_response(rejection.body_text()),
};
let params = extract_service_params(&headers);
let req = ListTaskPushNotificationConfigsRequest {
task_id: id,
page_size: query.page_size,
page_token: query.page_token,
tenant,
};
match state.handler.list_push_configs(¶ms, req).await {
Ok(resp) => protojson_json_response(&resp),
Err(e) => rest_error_response(e),
}
}
async fn handle_delete_push_config<H: RequestHandler>(
State(state): State<RestState<H>>,
Path(PushConfigPath {
tenant,
id,
config_id,
}): Path<PushConfigPath>,
headers: HeaderMap,
) -> impl IntoResponse {
let params = extract_service_params(&headers);
let req = DeleteTaskPushNotificationConfigRequest {
task_id: id,
id: config_id,
tenant,
};
match state.handler.delete_push_config(¶ms, req).await {
Ok(()) => with_content_type(
Json(Value::Object(Default::default())).into_response(),
"application/a2a+json",
),
Err(e) => rest_error_response(e),
}
}
async fn handle_get_extended_agent_card<H: RequestHandler>(
State(state): State<RestState<H>>,
tenant: Option<Path<String>>,
headers: HeaderMap,
) -> impl IntoResponse {
let tenant = tenant.map(|Path(tenant)| tenant);
let params = extract_service_params(&headers);
let req = GetExtendedAgentCardRequest { tenant };
match state.handler.get_extended_agent_card(¶ms, req).await {
Ok(card) => protojson_json_response(&card),
Err(e) => rest_error_response(e),
}
}
fn protojson_json_response<T: ProtoJsonPayload>(value: &T) -> axum::response::Response {
match protojson_conv::to_value(value) {
Ok(payload) => with_content_type(Json(payload).into_response(), "application/a2a+json"),
Err(e) => rest_error_response(crate::sanitized_internal_error(format!(
"failed to serialize ProtoJSON payload: {e}"
))),
}
}
fn with_content_type(
mut response: axum::response::Response,
content_type: &'static str,
) -> axum::response::Response {
response
.headers_mut()
.insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
response
}
fn protojson_stream<T: ProtoJsonPayload + 'static>(
stream: BoxStream<'static, Result<T, A2AError>>,
) -> BoxStream<'static, Result<Value, A2AError>> {
Box::pin(stream.map(|item| {
item.and_then(|value| {
protojson_conv::to_value(&value).map_err(|e| {
crate::sanitized_internal_error(format!(
"failed to serialize ProtoJSON stream payload: {e}"
))
})
})
}))
}
fn rest_sse(stream: BoxStream<'static, Result<Value, A2AError>>) -> axum::response::Response {
let events = stream.map(|item| item.map_err(|err| rest_error_envelope(err).1));
sse::sse_from_rest_stream(Box::pin(events)).into_response()
}
fn parse_create_push_config_request(
task_id: String,
raw_config: Value,
) -> Result<TaskPushNotificationConfig, String> {
protojson_conv::from_value::<TaskPushNotificationConfig>(raw_config)
.map_err(|e| e.to_string())
.and_then(|mut config| {
if !config.task_id.is_empty() && config.task_id != task_id {
Err(format!(
"taskId in request body ({}) did not match task id in path ({task_id})",
config.task_id
))
} else {
config.task_id = task_id;
Ok(config)
}
})
}
fn json_rejection_response(rejection: JsonRejection) -> axum::response::Response {
if rejection.status() == StatusCode::PAYLOAD_TOO_LARGE {
return rejection.into_response();
}
rest_payload_error_response(rejection.body_text())
}
fn rest_payload_error_response(error: impl std::fmt::Display) -> axum::response::Response {
rest_violation_response(FieldViolation {
field: String::new(),
description: error.to_string(),
})
}
fn protojson_error_response(error: ProtoJsonPayloadError) -> axum::response::Response {
match error {
ProtoJsonPayloadError::Invalid(violation) => rest_violation_response(violation),
error => rest_payload_error_response(error),
}
}
fn rest_violation_response(violation: FieldViolation) -> axum::response::Response {
rest_error_response(
A2AError::invalid_params("invalid request body")
.with_details(vec![TypedDetail::bad_request(vec![violation])]),
)
}
fn rest_error_response(err: A2AError) -> axum::response::Response {
let (status, body) = rest_error_envelope(err);
(status, Json(body)).into_response()
}
fn rest_error_envelope(err: A2AError) -> (StatusCode, RestErrorEnvelope) {
let status =
StatusCode::from_u16(err.http_status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
let reason = error_reason(err.code);
let grpc_status = rest_grpc_status(err.code);
let mut metadata =
HashMap::from([("timestamp".to_string(), a2a::format_timestamp(&Utc::now()))]);
let mut details = Vec::new();
if let Some(extra) = err.details {
for detail in extra {
if detail.type_url == errordetails::ERROR_INFO_TYPE {
if let Some(Value::Object(meta)) = detail.value.get("metadata") {
for (k, v) in meta {
if let Some(s) = v.as_str() {
metadata.entry(k.clone()).or_insert_with(|| s.to_string());
}
}
}
} else {
details.push(detail);
}
}
}
details.push(TypedDetail::error_info(
reason,
errordetails::PROTOCOL_DOMAIN,
Some(metadata),
));
let body = RestErrorEnvelope {
error: RestErrorStatus {
code: status.as_u16(),
status: grpc_status,
message: err.message,
details,
},
};
(status, body)
}
fn rest_grpc_status(code: i32) -> &'static str {
match code {
error_code::TASK_NOT_FOUND => "NOT_FOUND",
error_code::METHOD_NOT_FOUND => "UNIMPLEMENTED",
error_code::TASK_NOT_CANCELABLE
| error_code::EXTENDED_CARD_NOT_CONFIGURED
| error_code::EXTENSION_SUPPORT_REQUIRED
| error_code::PUSH_NOTIFICATION_NOT_SUPPORTED
| error_code::UNSUPPORTED_OPERATION
| error_code::VERSION_NOT_SUPPORTED => "FAILED_PRECONDITION",
error_code::CONTENT_TYPE_NOT_SUPPORTED
| error_code::PARSE_ERROR
| error_code::INVALID_REQUEST
| error_code::INVALID_PARAMS => "INVALID_ARGUMENT",
_ => "INTERNAL",
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::InMemoryPushConfigStore;
use crate::executor::ExecutorContext;
use crate::handler::DefaultRequestHandler;
use crate::task_store::InMemoryTaskStore;
use a2a_pb::protojson_conv;
use axum::body::Body;
use axum::http::Request;
use futures::stream::BoxStream;
use http_body_util::BodyExt;
use crate::test_util::{CapturingHandler, assert_header_captured, install_crypto_provider};
use tower::ServiceExt;
struct EchoExecutor;
impl crate::AgentExecutor for EchoExecutor {
fn execute(
&self,
ctx: ExecutorContext,
) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
let task = Task {
id: ctx.task_id.clone(),
context_id: ctx.context_id.clone(),
status: TaskStatus {
state: TaskState::Completed,
message: ctx.message,
timestamp: None,
},
artifacts: None,
history: None,
metadata: None,
};
Box::pin(futures::stream::once(async move {
Ok(StreamResponse::Task(task))
}))
}
fn cancel(
&self,
ctx: ExecutorContext,
) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
let task = Task {
id: ctx.task_id.clone(),
context_id: ctx.context_id.clone(),
status: TaskStatus {
state: TaskState::Canceled,
message: None,
timestamp: None,
},
artifacts: None,
history: None,
metadata: None,
};
Box::pin(futures::stream::once(async move {
Ok(StreamResponse::Task(task))
}))
}
}
fn make_app() -> axum::Router {
let handler = Arc::new(DefaultRequestHandler::new(
EchoExecutor,
InMemoryTaskStore::new(),
));
rest_router(handler)
}
fn make_push_app() -> axum::Router {
install_crypto_provider();
let handler = Arc::new(
DefaultRequestHandler::new(EchoExecutor, InMemoryTaskStore::new())
.with_push_config_store(InMemoryPushConfigStore::new()),
);
rest_router(handler)
}
#[tokio::test]
async fn test_client_role_validation_through_rest() {
for path in [REST_SEND_MESSAGE_PATH, REST_STREAM_MESSAGE_PATH] {
for role in ["ROLE_AGENT", "ROLE_UNSPECIFIED"] {
let body = serde_json::json!({
"message": {
"messageId": "role-validation",
"role": role,
"parts": [{"text": "hello"}]
}
});
let req = Request::builder()
.header("a2a-version", "1.0")
.uri(path)
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_string(&body).unwrap()))
.unwrap();
let response = make_app().oneshot(req).await.unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
let bytes = response.into_body().collect().await.unwrap().to_bytes();
let error: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(error["error"]["status"], "INVALID_ARGUMENT");
assert!(error["error"]["message"].as_str().unwrap().contains(role));
}
}
}
#[tokio::test]
async fn test_send_message() {
let app = make_app();
let body = serde_json::json!({
"message": {
"messageId": "m1",
"role": "ROLE_USER",
"parts": [{"text": "hello"}]
}
});
let req = Request::builder()
.header("a2a-version", "1.0")
.uri(REST_SEND_MESSAGE_PATH)
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_string(&body).unwrap()))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_send_message_rejects_a_missing_message_and_a_part_without_content() {
let cases = [
(
serde_json::json!({"message": {
"messageId": "m1",
"role": "ROLE_USER",
"parts": [{"text": "ok"}, {}]
}}),
"message.parts[1]",
"must have one of: text, raw, url, data",
),
(serde_json::json!({}), "message", "is required"),
(
serde_json::json!({"message": 5}),
"",
"ProtoJSON error: invalid type: integer `5`, expected struct lf.a2a.v1.Message",
),
];
for path in [REST_SEND_MESSAGE_PATH, REST_STREAM_MESSAGE_PATH] {
for (body, field, description) in &cases {
let req = Request::builder()
.header("a2a-version", "1.0")
.uri(path)
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_string(body).unwrap()))
.unwrap();
let resp = make_app().oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{path}");
let body = resp.into_body().collect().await.unwrap().to_bytes();
let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
let violation = &payload["error"]["details"][0]["fieldViolations"][0];
assert_eq!(violation["field"], *field, "{path}");
assert_eq!(violation["description"], *description, "{path}");
}
}
}
#[tokio::test]
async fn test_send_message_response_content_type_is_a2a_json() {
let app = make_app();
let body = serde_json::json!({
"message": {
"messageId": "m1",
"role": "ROLE_USER",
"parts": [{"text": "hello"}]
}
});
let req = Request::builder()
.header("a2a-version", "1.0")
.uri(REST_SEND_MESSAGE_PATH)
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_string(&body).unwrap()))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers()
.get("content-type")
.unwrap()
.to_str()
.unwrap(),
"application/a2a+json"
);
}
#[tokio::test]
async fn test_rest_error_response_content_type_is_json() {
let resp = rest_error_response(A2AError::task_not_found("missing"));
assert_eq!(
resp.headers()
.get("content-type")
.unwrap()
.to_str()
.unwrap(),
"application/json"
);
}
#[tokio::test]
async fn test_send_message_legacy_alias() {
let app = make_app();
let body = serde_json::json!({
"message": {
"messageId": "m1",
"role": "ROLE_USER",
"parts": [{"text": "hello"}]
}
});
let req = Request::builder()
.header("a2a-version", "1.0")
.uri(REST_SEND_MESSAGE_LEGACY_PATH)
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_string(&body).unwrap()))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_get_task_not_found() {
let app = make_app();
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/nonexistent")
.method("GET")
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn test_list_tasks_empty() {
let app = make_app();
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks")
.method("GET")
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = resp.into_body().collect().await.unwrap().to_bytes();
let list_resp =
protojson_conv::from_str::<ListTasksResponse>(std::str::from_utf8(&body).unwrap())
.unwrap();
assert!(list_resp.tasks.is_empty());
}
#[tokio::test]
async fn test_cancel_task_not_found() {
let app = make_app();
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/nonexistent:cancel")
.method("POST")
.header("content-type", "application/json")
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn test_create_push_config_not_supported() {
let app = make_app();
let body = serde_json::json!({
"url": "http://example.com/callback"
});
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/t1/pushNotificationConfigs")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_string(&body).unwrap()))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn test_create_push_config_accepts_raw_config_body() {
let app = make_push_app();
let body = serde_json::json!({
"id": "cfg1",
"url": "http://example.com/callback"
});
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/t1/pushNotificationConfigs")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_string(&body).unwrap()))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = resp.into_body().collect().await.unwrap().to_bytes();
let payload = serde_json::from_slice::<TaskPushNotificationConfig>(&body).unwrap();
assert_eq!(payload.task_id, "t1");
assert_eq!(payload.id.as_deref(), Some("cfg1"));
assert_eq!(payload.url, "http://example.com/callback");
}
#[tokio::test]
async fn test_create_push_config_accepts_flat_request_body() {
let app = make_push_app();
let body = serde_json::json!({
"taskId": "t1",
"id": "cfg1",
"url": "http://example.com/callback"
});
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/t1/pushNotificationConfigs")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_string(&body).unwrap()))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = resp.into_body().collect().await.unwrap().to_bytes();
let payload = serde_json::from_slice::<TaskPushNotificationConfig>(&body).unwrap();
assert_eq!(payload.task_id, "t1");
assert_eq!(payload.id.as_deref(), Some("cfg1"));
assert_eq!(payload.url, "http://example.com/callback");
}
#[tokio::test]
async fn test_create_push_config_rejects_mismatched_task_id_in_body() {
let app = make_push_app();
let body = serde_json::json!({
"taskId": "other-task",
"url": "http://example.com/callback"
});
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/t1/pushNotificationConfigs")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_string(&body).unwrap()))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn test_get_extended_agent_card() {
let app = make_app();
let req = Request::builder()
.header("a2a-version", "1.0")
.uri(REST_EXTENDED_AGENT_CARD_PATH)
.method("GET")
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn test_rest_error_response_status_codes() {
let resp = rest_error_response(A2AError::task_not_found("t1"));
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let body = resp.into_body().collect().await.unwrap().to_bytes();
let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(payload["error"]["code"], 404);
assert_eq!(payload["error"]["status"], "NOT_FOUND");
assert_eq!(payload["error"]["details"][0]["reason"], "TASK_NOT_FOUND");
let resp = rest_error_response(A2AError::internal("boom"));
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
let resp = rest_error_response(A2AError::content_type_not_supported());
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn test_rest_error_response_boundary_does_not_rewrite_internal_errors() {
let resp = rest_error_response(A2AError::internal("agent-reported failure detail"));
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
let body = resp.into_body().collect().await.unwrap().to_bytes();
let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(payload["error"]["message"], "agent-reported failure detail");
}
#[test]
fn test_sanitized_internal_error_hides_server_side_detail() {
let err = crate::sanitized_internal_error("serde fault at /etc/server/keys.pem");
assert_eq!(err.code, a2a::error_code::INTERNAL_ERROR);
assert_eq!(err.message, "Internal error");
assert!(!err.message.contains("/etc/server/keys.pem"));
let resp = rest_error_response(A2AError::task_not_found("t1"));
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
struct UnserializablePayload;
impl protojson_conv::ProtoJsonPayload for UnserializablePayload {
type Proto = a2a_pb::proto::Task;
type ProtoJson = a2a_pb::protojson::Task;
fn to_proto(_value: &Self) -> Self::Proto {
a2a_pb::proto::Task {
status: Some(a2a_pb::proto::TaskStatus {
state: 9999,
message: None,
timestamp: None,
}),
..Default::default()
}
}
fn try_from_proto(
_value: &Self::Proto,
) -> Result<Self, a2a_pb::protojson_conv::ProtoJsonPayloadError> {
Ok(Self)
}
}
#[test]
fn test_unserializable_payload_double_round_trips() {
let proto = <UnserializablePayload as protojson_conv::ProtoJsonPayload>::to_proto(
&UnserializablePayload,
);
assert!(
<UnserializablePayload as protojson_conv::ProtoJsonPayload>::try_from_proto(&proto)
.is_ok()
);
}
#[tokio::test]
async fn test_serialization_fault_is_sanitized_at_the_raise_site() {
let resp = protojson_json_response(&UnserializablePayload);
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
let body = resp.into_body().collect().await.unwrap().to_bytes();
let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(payload["error"]["message"], "Internal error");
}
#[tokio::test]
async fn test_stream_serialization_fault_is_sanitized_at_the_raise_site() {
let stream: BoxStream<'static, Result<UnserializablePayload, A2AError>> =
Box::pin(futures::stream::iter(vec![Ok(UnserializablePayload)]));
let mut mapped = protojson_stream(stream);
let item = mapped.next().await.expect("one item");
let err = item.expect_err("transcode must fail");
assert_eq!(err.code, a2a::error_code::INTERNAL_ERROR);
assert_eq!(err.message, "Internal error");
}
#[tokio::test]
async fn test_stream_error_event_is_a_google_rpc_status() {
let stream: BoxStream<'static, Result<Value, A2AError>> =
Box::pin(futures::stream::iter(vec![
Ok(serde_json::json!({"statusUpdate": {}})),
Err(A2AError::task_not_found("t1")),
]));
let body = rest_sse(stream)
.into_body()
.collect()
.await
.unwrap()
.to_bytes();
let body = String::from_utf8(body.to_vec()).unwrap();
let frames: Vec<Value> = body
.lines()
.filter_map(|line| line.strip_prefix("data: "))
.map(|data| serde_json::from_str(data).unwrap())
.collect();
assert_eq!(frames.len(), 2);
let error = &frames[1]["error"];
assert_eq!(error["code"], 404);
assert_eq!(error["status"], "NOT_FOUND");
assert_eq!(error["details"][0]["reason"], "TASK_NOT_FOUND");
let names: Vec<&str> = body
.lines()
.filter_map(|line| line.strip_prefix("event: "))
.collect();
assert_eq!(names, vec!["error"], "{body}");
}
#[tokio::test]
async fn test_rest_error_response_merges_error_info_metadata() {
let existing_info = TypedDetail::error_info(
"TASK_NOT_FOUND",
errordetails::PROTOCOL_DOMAIN,
Some(HashMap::from([("taskId".to_string(), "t99".to_string())])),
);
let err = A2AError::task_not_found("t99").with_details(vec![existing_info]);
let resp = rest_error_response(err);
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let body = resp.into_body().collect().await.unwrap().to_bytes();
let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
let details = payload["error"]["details"].as_array().unwrap();
assert_eq!(details.len(), 1);
assert_eq!(details[0]["@type"], errordetails::ERROR_INFO_TYPE);
assert_eq!(details[0]["reason"], "TASK_NOT_FOUND");
assert_eq!(details[0]["metadata"]["taskId"], "t99");
assert!(details[0]["metadata"]["timestamp"].is_string());
}
#[tokio::test]
async fn test_rest_error_info_timestamp_uses_the_z_designator() {
let resp = rest_error_response(A2AError::task_not_found("t1"));
let body = resp.into_body().collect().await.unwrap().to_bytes();
let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
let timestamp = payload["error"]["details"][0]["metadata"]["timestamp"]
.as_str()
.unwrap();
assert!(timestamp.ends_with('Z'), "{timestamp}");
assert!(timestamp.parse::<DateTime<Utc>>().is_ok());
}
#[tokio::test]
async fn test_rest_error_response_preserves_non_error_info_details() {
let bad_req = TypedDetail::bad_request(vec![FieldViolation {
field: "message.parts".into(),
description: "required".into(),
}]);
let err = A2AError::invalid_params("bad request").with_details(vec![bad_req]);
let resp = rest_error_response(err);
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let body = resp.into_body().collect().await.unwrap().to_bytes();
let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
let details = payload["error"]["details"].as_array().unwrap();
assert_eq!(details.len(), 2);
assert_eq!(details[0]["@type"], errordetails::BAD_REQUEST_TYPE);
assert_eq!(details[0]["fieldViolations"][0]["field"], "message.parts");
assert_eq!(details[1]["@type"], errordetails::ERROR_INFO_TYPE);
assert_eq!(details[1]["reason"], "INVALID_PARAMS");
}
#[tokio::test]
async fn test_rest_payload_error_response() {
let resp = rest_payload_error_response("missing field 'parts'");
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let body = resp.into_body().collect().await.unwrap().to_bytes();
let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(
payload["error"]["message"].as_str().unwrap(),
"invalid request body"
);
let details = payload["error"]["details"].as_array().unwrap();
assert_eq!(details.len(), 2);
assert_eq!(details[0]["@type"], errordetails::BAD_REQUEST_TYPE);
assert_eq!(
details[0]["fieldViolations"][0]["description"],
"missing field 'parts'"
);
assert_eq!(details[1]["@type"], errordetails::ERROR_INFO_TYPE);
assert_eq!(details[1]["reason"], "INVALID_PARAMS");
}
#[tokio::test]
async fn test_subscribe_to_task_not_found() {
let app = make_app();
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/nonexistent:subscribe")
.method("GET")
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert!(resp.status().is_client_error());
}
#[tokio::test]
async fn test_stream_message() {
let app = make_app();
let body = serde_json::json!({
"message": {
"messageId": "m1",
"role": "ROLE_USER",
"parts": [{"text": "hello"}]
}
});
let req = Request::builder()
.header("a2a-version", "1.0")
.uri(REST_STREAM_MESSAGE_PATH)
.method("POST")
.header("content-type", "application/json")
.header("accept", "text/event-stream")
.body(Body::from(serde_json::to_string(&body).unwrap()))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_get_push_config_not_found() {
let app = make_app();
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/t1/pushNotificationConfigs/cfg1")
.method("GET")
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert!(resp.status().is_client_error());
}
#[tokio::test]
async fn test_list_push_configs() {
let app = make_push_app();
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/t1/pushNotificationConfigs")
.method("GET")
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = resp.into_body().collect().await.unwrap().to_bytes();
let payload =
serde_json::from_slice::<ListTaskPushNotificationConfigsResponse>(&body).unwrap();
assert!(payload.configs.is_empty());
}
#[tokio::test]
async fn test_delete_push_config() {
let app = make_app();
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/t1/pushNotificationConfigs/cfg1")
.method("DELETE")
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert!(resp.status().is_client_error());
}
#[tokio::test]
async fn test_delete_push_config_with_store_returns_ok() {
let app = make_push_app();
let create_body = serde_json::json!({
"id": "cfg1",
"url": "http://example.com/callback"
});
let create_req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/t1/pushNotificationConfigs")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_string(&create_body).unwrap()))
.unwrap();
let create_resp = app.clone().oneshot(create_req).await.unwrap();
assert_eq!(create_resp.status(), StatusCode::OK);
let delete_req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/t1/pushNotificationConfigs/cfg1")
.method("DELETE")
.body(Body::empty())
.unwrap();
let delete_resp = app.clone().oneshot(delete_req).await.unwrap();
assert_eq!(delete_resp.status(), StatusCode::OK);
assert_eq!(
delete_resp.headers().get(header::CONTENT_TYPE).unwrap(),
"application/a2a+json"
);
let body = delete_resp.into_body().collect().await.unwrap().to_bytes();
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&body).unwrap(),
serde_json::json!({})
);
let list_req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/t1/pushNotificationConfigs")
.method("GET")
.body(Body::empty())
.unwrap();
let list_resp = app.oneshot(list_req).await.unwrap();
assert_eq!(list_resp.status(), StatusCode::OK);
let body = list_resp.into_body().collect().await.unwrap().to_bytes();
let payload =
serde_json::from_slice::<ListTaskPushNotificationConfigsResponse>(&body).unwrap();
assert!(payload.configs.is_empty());
}
#[tokio::test]
async fn test_list_tasks_with_query_params() {
let app = make_app();
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks?contextId=c1&pageSize=5&pageToken=0&historyLength=3&includeArtifacts=true&statusTimestampAfter=2025-01-01T00:00:00Z")
.method("GET")
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_list_tasks_status_unspecified_is_no_filter() {
let app = make_app();
let body = serde_json::json!({
"message": {"messageId": "m1", "role": "ROLE_USER", "parts": [{"text": "hello"}]}
});
let req = Request::builder()
.header("a2a-version", "1.0")
.uri(REST_SEND_MESSAGE_PATH)
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_string(&body).unwrap()))
.unwrap();
assert_eq!(
app.clone().oneshot(req).await.unwrap().status(),
StatusCode::OK
);
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks?status=TASK_STATE_UNSPECIFIED")
.method("GET")
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = resp.into_body().collect().await.unwrap().to_bytes();
let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(payload["totalSize"], 1, "{payload}");
}
#[tokio::test]
async fn test_list_tasks_invalid_status_returns_bad_request() {
let app = make_app();
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks?status=invalid")
.method("GET")
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let body = resp.into_body().collect().await.unwrap().to_bytes();
let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(payload["error"]["message"], "invalid status filter");
}
#[tokio::test]
async fn test_send_message_propagates_headers_as_service_params() {
let (handler, captured) = CapturingHandler::new();
let app = rest_router(handler);
let body = serde_json::json!({
"message": {
"messageId": "m1",
"role": "ROLE_USER",
"parts": [{"text": "hi"}]
}
});
let req = Request::builder()
.header("a2a-version", "1.0")
.uri(REST_SEND_MESSAGE_PATH)
.method("POST")
.header("content-type", "application/json")
.header("authorization", "Bearer test-token-abc")
.header("x-tenant-id", "acme")
.body(Body::from(serde_json::to_string(&body).unwrap()))
.unwrap();
let _ = app.oneshot(req).await.unwrap();
assert_header_captured(
&captured,
"send_message",
"authorization",
"Bearer test-token-abc",
);
assert_header_captured(&captured, "send_message", "x-tenant-id", "acme");
}
#[tokio::test]
async fn test_stream_message_propagates_headers_as_service_params() {
let (handler, captured) = CapturingHandler::new();
let app = rest_router(handler);
let body = serde_json::json!({
"message": {
"messageId": "m1",
"role": "ROLE_USER",
"parts": [{"text": "hi"}]
}
});
let req = Request::builder()
.header("a2a-version", "1.0")
.uri(REST_STREAM_MESSAGE_PATH)
.method("POST")
.header("content-type", "application/json")
.header("accept", "text/event-stream")
.header("authorization", "Bearer streaming-token")
.body(Body::from(serde_json::to_string(&body).unwrap()))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
let _ = resp.into_body().collect().await.unwrap().to_bytes();
assert_header_captured(
&captured,
"send_streaming_message",
"authorization",
"Bearer streaming-token",
);
}
#[tokio::test]
async fn test_get_task_propagates_headers_as_service_params() {
let (handler, captured) = CapturingHandler::new();
let app = rest_router(handler);
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/some-id")
.method("GET")
.header("authorization", "Bearer get-task-token")
.header("x-tenant-id", "acme")
.body(Body::empty())
.unwrap();
let _ = app.oneshot(req).await.unwrap();
assert_header_captured(
&captured,
"get_task",
"authorization",
"Bearer get-task-token",
);
assert_header_captured(&captured, "get_task", "x-tenant-id", "acme");
}
#[tokio::test]
async fn test_list_tasks_propagates_headers_as_service_params() {
let (handler, captured) = CapturingHandler::new();
let app = rest_router(handler);
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks")
.method("GET")
.header("authorization", "Bearer list-tasks-token")
.body(Body::empty())
.unwrap();
let _ = app.oneshot(req).await.unwrap();
assert_header_captured(
&captured,
"list_tasks",
"authorization",
"Bearer list-tasks-token",
);
}
#[tokio::test]
async fn test_cancel_task_propagates_headers_as_service_params() {
let (handler, captured) = CapturingHandler::new();
let app = rest_router(handler);
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/some-id:cancel")
.method("POST")
.header("authorization", "Bearer cancel-token")
.body(Body::empty())
.unwrap();
let _ = app.oneshot(req).await.unwrap();
assert_header_captured(
&captured,
"cancel_task",
"authorization",
"Bearer cancel-token",
);
}
#[tokio::test]
async fn test_cancel_task_legacy_propagates_headers_as_service_params() {
let (handler, captured) = CapturingHandler::new();
let app = rest_router(handler);
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/some-id/cancel")
.method("POST")
.header("authorization", "Bearer cancel-legacy-token")
.body(Body::empty())
.unwrap();
let _ = app.oneshot(req).await.unwrap();
assert_header_captured(
&captured,
"cancel_task",
"authorization",
"Bearer cancel-legacy-token",
);
}
#[tokio::test]
async fn test_create_push_config_propagates_headers_as_service_params() {
let (handler, captured) = CapturingHandler::new();
let app = rest_router(handler);
let body = serde_json::json!({
"id": "cfg1",
"url": "http://example.com/callback"
});
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/t1/pushNotificationConfigs")
.method("POST")
.header("content-type", "application/json")
.header("authorization", "Bearer push-create-token")
.body(Body::from(serde_json::to_string(&body).unwrap()))
.unwrap();
let _ = app.oneshot(req).await.unwrap();
assert_header_captured(
&captured,
"create_push_config",
"authorization",
"Bearer push-create-token",
);
}
#[tokio::test]
async fn test_list_push_configs_propagates_headers_as_service_params() {
let (handler, captured) = CapturingHandler::new();
let app = rest_router(handler);
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/t1/pushNotificationConfigs")
.method("GET")
.header("authorization", "Bearer push-list-token")
.body(Body::empty())
.unwrap();
let _ = app.oneshot(req).await.unwrap();
assert_header_captured(
&captured,
"list_push_configs",
"authorization",
"Bearer push-list-token",
);
}
#[tokio::test]
async fn test_get_push_config_propagates_headers_as_service_params() {
let (handler, captured) = CapturingHandler::new();
let app = rest_router(handler);
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/t1/pushNotificationConfigs/cfg1")
.method("GET")
.header("authorization", "Bearer push-get-token")
.body(Body::empty())
.unwrap();
let _ = app.oneshot(req).await.unwrap();
assert_header_captured(
&captured,
"get_push_config",
"authorization",
"Bearer push-get-token",
);
}
#[tokio::test]
async fn test_delete_push_config_propagates_headers_as_service_params() {
let (handler, captured) = CapturingHandler::new();
let app = rest_router(handler);
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/t1/pushNotificationConfigs/cfg1")
.method("DELETE")
.header("authorization", "Bearer push-delete-token")
.body(Body::empty())
.unwrap();
let _ = app.oneshot(req).await.unwrap();
assert_header_captured(
&captured,
"delete_push_config",
"authorization",
"Bearer push-delete-token",
);
}
#[tokio::test]
async fn test_get_extended_agent_card_propagates_headers_as_service_params() {
let (handler, captured) = CapturingHandler::new();
let app = rest_router(handler);
let req = Request::builder()
.header("a2a-version", "1.0")
.uri(REST_EXTENDED_AGENT_CARD_PATH)
.method("GET")
.header("authorization", "Bearer card-token")
.body(Body::empty())
.unwrap();
let _ = app.oneshot(req).await.unwrap();
assert_header_captured(
&captured,
"get_extended_agent_card",
"authorization",
"Bearer card-token",
);
}
#[tokio::test]
async fn test_subscribe_to_task_propagates_headers_as_service_params() {
let (handler, captured) = CapturingHandler::new();
let app = rest_router(handler);
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/some-id:subscribe")
.method("GET")
.header("authorization", "Bearer subscribe-token")
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
let _ = resp.into_body().collect().await.unwrap().to_bytes();
assert_header_captured(
&captured,
"subscribe_to_task",
"authorization",
"Bearer subscribe-token",
);
}
#[tokio::test]
async fn test_subscribe_to_task_legacy_propagates_headers_as_service_params() {
let (handler, captured) = CapturingHandler::new();
let app = rest_router(handler);
let req = Request::builder()
.header("a2a-version", "1.0")
.uri("/tasks/some-id/subscribe")
.method("GET")
.header("authorization", "Bearer subscribe-legacy-token")
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
let _ = resp.into_body().collect().await.unwrap().to_bytes();
assert_header_captured(
&captured,
"subscribe_to_task",
"authorization",
"Bearer subscribe-legacy-token",
);
}
#[tokio::test]
async fn test_get_task_with_history_length() {
let app = make_app();
let body = serde_json::json!({
"message": {
"messageId": "m1",
"role": "ROLE_USER",
"parts": [{"text": "hello"}]
}
});
let req = Request::builder()
.header("a2a-version", "1.0")
.uri(REST_SEND_MESSAGE_PATH)
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_string(&body).unwrap()))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let resp_body = resp.into_body().collect().await.unwrap().to_bytes();
let send_resp: serde_json::Value = serde_json::from_slice(&resp_body).unwrap();
let task_id = send_resp["task"]["id"].as_str().unwrap();
let app = make_app();
let req = Request::builder()
.header("a2a-version", "1.0")
.uri(format!("/tasks/{}?historyLength=5", task_id))
.method("GET")
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert!(resp.status() == StatusCode::OK || resp.status() == StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn test_request_body_over_the_limit_is_rejected() {
let app = make_app();
let oversized = Body::from("x".repeat(crate::jsonrpc::MAX_REQUEST_BODY_BYTES + 1));
let req = Request::builder()
.header("a2a-version", "1.0")
.uri(REST_SEND_MESSAGE_PATH)
.method("POST")
.header("content-type", "application/json")
.body(oversized)
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
}
async fn send_message_with_version(uri: &str, version: Option<&str>) -> Response {
let body = serde_json::json!({
"message": {"messageId": "m1", "role": "ROLE_USER", "parts": [{"text": "hi"}]}
});
let mut req = Request::builder()
.uri(uri)
.method("POST")
.header("content-type", "application/json");
if let Some(version) = version {
req = req.header("a2a-version", version);
}
let req = req.body(Body::from(body.to_string())).unwrap();
make_app().oneshot(req).await.unwrap()
}
async fn assert_version_not_supported(resp: Response) {
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let body = resp.into_body().collect().await.unwrap().to_bytes();
let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(
payload["error"]["status"], "FAILED_PRECONDITION",
"{payload}"
);
assert_eq!(
payload["error"]["details"][0]["reason"], "VERSION_NOT_SUPPORTED",
"{payload}"
);
}
#[tokio::test]
async fn test_unsupported_a2a_version_is_rejected() {
let resp = send_message_with_version(REST_SEND_MESSAGE_PATH, Some("99.0")).await;
assert_version_not_supported(resp).await;
}
#[tokio::test]
async fn test_missing_a2a_version_is_rejected() {
let resp = send_message_with_version(REST_SEND_MESSAGE_PATH, None).await;
assert_version_not_supported(resp).await;
let req = Request::builder()
.uri("/tasks/t1")
.body(Body::empty())
.unwrap();
assert_version_not_supported(make_app().oneshot(req).await.unwrap()).await;
}
#[tokio::test]
async fn test_a2a_version_query_parameter_is_accepted() {
let uri = format!("{REST_SEND_MESSAGE_PATH}?A2A-Version=1.0");
let resp = send_message_with_version(&uri, None).await;
assert_eq!(resp.status(), StatusCode::OK);
let uri = format!("{REST_SEND_MESSAGE_PATH}?A2A-Version=99.0");
assert_version_not_supported(send_message_with_version(&uri, None).await).await;
}
#[tokio::test]
async fn test_extractor_rejections_answer_google_rpc_status() {
let requests = [
Request::builder()
.uri("/tasks/t1?historyLength=abc")
.method("GET")
.header("a2a-version", "1.0")
.body(Body::empty())
.unwrap(),
Request::builder()
.uri("/tasks?pageSize=x")
.method("GET")
.header("a2a-version", "1.0")
.body(Body::empty())
.unwrap(),
Request::builder()
.uri(REST_SEND_MESSAGE_PATH)
.method("POST")
.header("a2a-version", "1.0")
.header("content-type", "application/json")
.body(Body::from("{"))
.unwrap(),
Request::builder()
.uri(REST_SEND_MESSAGE_PATH)
.method("POST")
.header("a2a-version", "1.0")
.body(Body::from("{}"))
.unwrap(),
Request::builder()
.uri(REST_STREAM_MESSAGE_PATH)
.method("POST")
.header("a2a-version", "1.0")
.header("content-type", "application/json")
.body(Body::from("{"))
.unwrap(),
Request::builder()
.uri("/tasks/t1/pushNotificationConfigs")
.method("POST")
.header("a2a-version", "1.0")
.header("content-type", "application/json")
.body(Body::from("{"))
.unwrap(),
Request::builder()
.uri("/tasks/t1/pushNotificationConfigs?pageSize=x")
.method("GET")
.header("a2a-version", "1.0")
.body(Body::empty())
.unwrap(),
];
for req in requests {
let target = req.uri().to_string();
let resp = make_app().oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{target}");
assert_eq!(
resp.headers().get("content-type").unwrap(),
"application/json",
"{target}"
);
let body = resp.into_body().collect().await.unwrap().to_bytes();
let body: Value = serde_json::from_slice(&body).unwrap();
assert_eq!(body["error"]["code"], 400, "{target}");
assert_eq!(body["error"]["status"], "INVALID_ARGUMENT", "{target}");
}
}
struct CancelMetadataExecutor(Arc<std::sync::Mutex<Option<HashMap<String, Value>>>>);
impl crate::AgentExecutor for CancelMetadataExecutor {
fn execute(
&self,
_: ExecutorContext,
) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
Box::pin(futures::stream::empty())
}
fn cancel(
&self,
ctx: ExecutorContext,
) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
*self.0.lock().unwrap() = ctx.metadata.clone();
let update = StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
task_id: ctx.task_id,
context_id: ctx.context_id,
status: TaskStatus {
state: TaskState::Canceled,
message: None,
timestamp: None,
},
metadata: None,
});
Box::pin(futures::stream::once(async move { Ok(update) }))
}
}
#[tokio::test]
async fn test_cancel_task_passes_body_metadata_to_the_executor() {
for (action, body, expected) in [
(":cancel", r#"{"metadata":{"reason":"user"}}"#, Some("user")),
(
"/cancel",
r#"{"metadata":{"reason":"legacy"}}"#,
Some("legacy"),
),
(":cancel", "", None),
] {
let seen = Arc::new(std::sync::Mutex::new(None));
let app = rest_router(Arc::new(DefaultRequestHandler::new(
CancelMetadataExecutor(seen.clone()),
InMemoryTaskStore::new(),
)));
let send = serde_json::json!({
"message": {"messageId": "m1", "role": "ROLE_USER", "parts": [{"text": "hi"}]},
"configuration": {"returnImmediately": true}
});
let req = Request::builder()
.uri(REST_SEND_MESSAGE_PATH)
.method("POST")
.header("a2a-version", "1.0")
.header("content-type", "application/json")
.body(Body::from(send.to_string()))
.unwrap();
let resp = app.clone().oneshot(req).await.unwrap();
let sent = resp.into_body().collect().await.unwrap().to_bytes();
let sent: Value = serde_json::from_slice(&sent).unwrap();
let id = sent["task"]["id"].as_str().unwrap().to_owned();
let uri = format!("/tasks/{id}{action}");
let req = Request::builder()
.uri(&uri)
.method("POST")
.header("a2a-version", "1.0")
.header("content-type", "application/json")
.body(Body::from(body))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK, "{uri} {body}");
let reason = seen
.lock()
.unwrap()
.as_ref()
.and_then(|metadata| metadata.get("reason").cloned());
assert_eq!(reason, expected.map(Value::from), "{uri} {body}");
}
}
#[tokio::test]
async fn test_cancel_task_rejects_a_body_that_is_not_a_request() {
let req = Request::builder()
.uri("/tasks/t1:cancel")
.method("POST")
.header("a2a-version", "1.0")
.header("content-type", "application/json")
.body(Body::from("{"))
.unwrap();
let resp = make_app().oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn test_every_method_is_routed_under_a_tenant() {
let (handler, _) = CapturingHandler::new();
let app = rest_router(handler.clone());
let send = r#"{"message":{"messageId":"m1","role":"ROLE_USER","parts":[{"text":"hi"}]}}"#;
let config = r#"{"url":"https://example.com/cb"}"#;
for (method, uri, body, called, tenant) in [
(
"POST",
"/acme/message:send",
send,
"send_message",
Some("acme"),
),
(
"POST",
"/acme/message:stream",
send,
"send_streaming_message",
Some("acme"),
),
("GET", "/acme/tasks/t1", "", "get_task", Some("acme")),
("GET", "/acme/tasks", "", "list_tasks", Some("acme")),
(
"POST",
"/acme/tasks/t1:cancel",
"",
"cancel_task",
Some("acme"),
),
(
"GET",
"/acme/tasks/t1:subscribe",
"",
"subscribe_to_task",
Some("acme"),
),
(
"POST",
"/acme/tasks/t1:subscribe",
"",
"subscribe_to_task",
Some("acme"),
),
(
"POST",
"/acme/tasks/t1/pushNotificationConfigs",
config,
"create_push_config",
Some("acme"),
),
(
"GET",
"/acme/tasks/t1/pushNotificationConfigs/c1",
"",
"get_push_config",
Some("acme"),
),
(
"GET",
"/acme/tasks/t1/pushNotificationConfigs",
"",
"list_push_configs",
Some("acme"),
),
(
"DELETE",
"/acme/tasks/t1/pushNotificationConfigs/c1",
"",
"delete_push_config",
Some("acme"),
),
(
"GET",
"/acme/extendedAgentCard",
"",
"get_extended_agent_card",
Some("acme"),
),
("POST", REST_SEND_MESSAGE_PATH, send, "send_message", None),
] {
let req = Request::builder()
.uri(uri)
.method(method)
.header("a2a-version", "1.0")
.header("content-type", "application/json")
.body(Body::from(body))
.unwrap();
app.clone().oneshot(req).await.unwrap();
assert_eq!(
handler.take_tenant(called),
Some(tenant.map(str::to_owned)),
"{method} {uri}"
);
}
}
#[tokio::test]
async fn test_an_undecodable_tenant_is_rejected() {
let (handler, _) = CapturingHandler::new();
let app = rest_router(handler.clone());
let send = r#"{"message":{"messageId":"m1","role":"ROLE_USER","parts":[{"text":"hi"}]}}"#;
for (method, uri, body, called) in [
("POST", "/%FF/message:send", send, "send_message"),
(
"POST",
"/%FF/message:stream",
send,
"send_streaming_message",
),
("GET", "/%FF/tasks", "", "list_tasks"),
("GET", "/%FF/tasks/t1", "", "get_task"),
(
"GET",
"/%FF/extendedAgentCard",
"",
"get_extended_agent_card",
),
] {
let req = Request::builder()
.uri(uri)
.method(method)
.header("a2a-version", "1.0")
.header("content-type", "application/json")
.body(Body::from(body))
.unwrap();
let resp = app.clone().oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{method} {uri}");
assert_eq!(handler.take_tenant(called), None, "{method} {uri}");
}
}
#[tokio::test]
async fn test_path_and_body_tenant() {
let (handler, _) = CapturingHandler::new();
let app = rest_router(handler.clone());
let send = r#"{"message":{"messageId":"m1","role":"ROLE_USER","parts":[{"text":"hi"}]}}"#;
let send_acme = r#"{"tenant":"acme","message":{"messageId":"m1","role":"ROLE_USER","parts":[{"text":"hi"}]}}"#;
let send_body = r#"{"tenant":"body","message":{"messageId":"m1","role":"ROLE_USER","parts":[{"text":"hi"}]}}"#;
let cancel_acme = r#"{"tenant":"acme"}"#;
let cancel_body = r#"{"tenant":"body"}"#;
let config_acme = r#"{"tenant":"acme","url":"https://example.com/cb"}"#;
let config_body = r#"{"tenant":"body","url":"https://example.com/cb"}"#;
for (uri, body, called, tenant) in [
("/acme/message:send", send, "send_message", Some("acme")),
(
"/acme/message:send",
send_acme,
"send_message",
Some("acme"),
),
("/acme/message:send", send_body, "send_message", None),
(
REST_SEND_MESSAGE_PATH,
send_body,
"send_message",
Some("body"),
),
(
"/acme/message:stream",
send_acme,
"send_streaming_message",
Some("acme"),
),
(
"/acme/message:stream",
send_body,
"send_streaming_message",
None,
),
(
REST_STREAM_MESSAGE_PATH,
send_body,
"send_streaming_message",
Some("body"),
),
("/acme/tasks/t1:cancel", "", "cancel_task", Some("acme")),
(
"/acme/tasks/t1:cancel",
cancel_acme,
"cancel_task",
Some("acme"),
),
("/acme/tasks/t1:cancel", cancel_body, "cancel_task", None),
("/tasks/t1:cancel", cancel_body, "cancel_task", Some("body")),
(
"/acme/tasks/t1/pushNotificationConfigs",
config_acme,
"create_push_config",
Some("acme"),
),
(
"/acme/tasks/t1/pushNotificationConfigs",
config_body,
"create_push_config",
None,
),
(
"/tasks/t1/pushNotificationConfigs",
config_body,
"create_push_config",
Some("body"),
),
] {
let req = Request::builder()
.uri(uri)
.method("POST")
.header("a2a-version", "1.0")
.header("content-type", "application/json")
.body(Body::from(body))
.unwrap();
let resp = app.clone().oneshot(req).await.unwrap();
assert_eq!(
resp.status() == StatusCode::BAD_REQUEST,
tenant.is_none(),
"POST {uri} {body}"
);
assert_eq!(
handler.take_tenant(called),
tenant.map(|tenant| Some(tenant.to_owned())),
"POST {uri} {body}"
);
}
let req = Request::builder()
.uri("/acme/tasks/t1:cancel")
.method("POST")
.header("a2a-version", "1.0")
.header("content-type", "application/json")
.body(Body::from(cancel_body))
.unwrap();
let resp = app.oneshot(req).await.unwrap();
let body = resp.into_body().collect().await.unwrap().to_bytes();
let payload: serde_json::Value = serde_json::from_slice(&body).unwrap();
let violation = &payload["error"]["details"][0]["fieldViolations"][0];
assert_eq!(violation["field"], "tenant");
assert_eq!(
violation["description"],
"tenant in the body (body) does not match the tenant in the path (acme)"
);
}
}
#[cfg(test)]
mod encoded_task_action_regression {
use super::*;
use crate::executor::ExecutorContext;
use crate::handler::DefaultRequestHandler;
use crate::task_store::InMemoryTaskStore;
use crate::test_util::CapturingHandler;
use axum::body::Body;
use axum::http::Request;
use http_body_util::BodyExt;
use tower::ServiceExt;
struct CustomTaskIdExecutor {
state: TaskState,
}
impl crate::AgentExecutor for CustomTaskIdExecutor {
fn execute(
&self,
ctx: ExecutorContext,
) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
let task = Task {
id: "foo:subscribe".into(),
context_id: ctx.context_id,
status: TaskStatus {
state: self.state.clone(),
message: None,
timestamp: None,
},
artifacts: None,
history: None,
metadata: None,
};
Box::pin(futures::stream::once(async move {
Ok(StreamResponse::Task(task))
}))
}
fn cancel(
&self,
_ctx: ExecutorContext,
) -> BoxStream<'static, Result<StreamResponse, A2AError>> {
Box::pin(futures::stream::empty())
}
}
#[tokio::test]
async fn get_task_with_encoded_colon_emitted_by_executor() {
let app = rest_router(Arc::new(DefaultRequestHandler::new(
CustomTaskIdExecutor {
state: TaskState::Completed,
},
InMemoryTaskStore::new(),
)));
let message = serde_json::json!({ "message": {
"messageId": "m1", "role": "ROLE_USER", "parts": [{"text": "hello"}]
}});
let request = Request::builder()
.method("POST")
.uri("/message:send")
.header("a2a-version", "1.0")
.header("content-type", "application/json")
.body(Body::from(message.to_string()))
.unwrap();
let response = app.clone().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body: Value =
serde_json::from_slice(&response.into_body().collect().await.unwrap().to_bytes())
.unwrap();
assert_eq!(body["task"]["id"], "foo:subscribe");
let request = Request::builder()
.uri("/tasks/foo%3Asubscribe")
.header("a2a-version", "1.0")
.body(Body::empty())
.unwrap();
let response = app.oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body: Value =
serde_json::from_slice(&response.into_body().collect().await.unwrap().to_bytes())
.unwrap();
assert_eq!(body["id"], "foo:subscribe");
}
#[tokio::test]
async fn cancel_task_with_encoded_colon_emitted_by_executor() {
use crate::task_store::TaskStore;
let store = InMemoryTaskStore::new();
store
.create(Task {
id: "foo".into(),
context_id: "unrelated".into(),
status: TaskStatus {
state: TaskState::InputRequired,
message: None,
timestamp: None,
},
artifacts: None,
history: None,
metadata: None,
})
.await
.unwrap();
let app = rest_router(Arc::new(DefaultRequestHandler::new(
CustomTaskIdExecutor {
state: TaskState::InputRequired,
},
store,
)));
let message = serde_json::json!({ "message": {
"messageId": "m-cancel", "role": "ROLE_USER", "parts": [{"text": "hello"}]
}});
let request = Request::builder()
.method("POST")
.uri("/message:send")
.header("a2a-version", "1.0")
.header("content-type", "application/json")
.body(Body::from(message.to_string()))
.unwrap();
let response = app.clone().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body: Value =
serde_json::from_slice(&response.into_body().collect().await.unwrap().to_bytes())
.unwrap();
assert_eq!(body["task"]["id"], "foo:subscribe");
let request = Request::builder()
.method("POST")
.uri("/tasks/foo%3Asubscribe:cancel")
.header("a2a-version", "1.0")
.header("content-type", "application/json")
.body(Body::from("{}"))
.unwrap();
let response = app.clone().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body: Value =
serde_json::from_slice(&response.into_body().collect().await.unwrap().to_bytes())
.unwrap();
assert_eq!(body["id"], "foo:subscribe");
assert_eq!(body["status"]["state"], "TASK_STATE_CANCELED");
for (uri, id, state) in [
(
"/tasks/foo%3Asubscribe",
"foo:subscribe",
"TASK_STATE_CANCELED",
),
("/tasks/foo", "foo", "TASK_STATE_INPUT_REQUIRED"),
] {
let request = Request::builder()
.uri(uri)
.header("a2a-version", "1.0")
.body(Body::empty())
.unwrap();
let response = app.clone().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body: Value =
serde_json::from_slice(&response.into_body().collect().await.unwrap().to_bytes())
.unwrap();
assert_eq!(body["id"], id);
assert_eq!(body["status"]["state"], state);
}
}
#[tokio::test]
async fn encoded_action_suffix_is_part_of_id() {
for (uri, id) in [
("/tasks/foo%3Asubscribe", "foo:subscribe"),
("/tasks/foo%3As%75bscribe", "foo:subscribe"),
("/tasks/foo%3asubscribe?historyLength=1", "foo:subscribe"),
("/tasks/foo%253Asubscribe", "foo%3Asubscribe"),
] {
let (handler, _) = CapturingHandler::new();
let req = Request::builder()
.uri(uri)
.header("a2a-version", "1.0")
.body(Body::empty())
.unwrap();
let _ = rest_router(handler.clone()).oneshot(req).await.unwrap();
assert!(
handler.take_tenant("get_task").is_some(),
"{uri}: not dispatched to get_task"
);
assert_eq!(handler.take_id("get_task").as_deref(), Some(id));
assert!(
handler.take_tenant("subscribe_to_task").is_none(),
"{uri}: dispatched to subscribe"
);
}
}
#[tokio::test]
async fn unencoded_action_suffix_subscribes() {
for (uri, id) in [
("/tasks/foo:subscribe", "foo"),
("/tasks/foo:s%75bscribe", "foo"),
("/tasks/foo%3Asubscribe:s%75bscribe", "foo:subscribe"),
("/tasks/foo%3Asubscribe:subscribe", "foo:subscribe"),
(
"/tenant/tasks/foo%3Asubscribe:subscribe?x=y",
"foo:subscribe",
),
] {
let (handler, _) = CapturingHandler::new();
let req = Request::builder()
.uri(uri)
.header("a2a-version", "1.0")
.body(Body::empty())
.unwrap();
let _ = rest_router(handler.clone()).oneshot(req).await.unwrap();
assert!(
handler.take_tenant("subscribe_to_task").is_some(),
"{uri}: not dispatched to subscribe"
);
assert_eq!(handler.take_id("subscribe_to_task").as_deref(), Some(id));
}
}
#[tokio::test]
async fn post_encoded_action_suffix_does_not_cancel_other_task() {
for uri in [
"/tasks/foo%3Acancel",
"/tasks/foo%3Ac%61ncel",
"/tenant/tasks/foo%3acancel?x=y",
"/tasks/foo%253Acancel",
] {
let (handler, _) = CapturingHandler::new();
let req = Request::builder()
.method("POST")
.uri(uri)
.header("a2a-version", "1.0")
.header("content-type", "application/json")
.body(Body::from("{}"))
.unwrap();
let _ = rest_router(handler.clone()).oneshot(req).await.unwrap();
assert!(
handler.take_tenant("cancel_task").is_none(),
"{uri}: incorrectly cancelled a different task"
);
}
}
#[tokio::test]
async fn post_literal_action_suffix_cancels() {
for (uri, id) in [
("/tasks/foo:cancel", "foo"),
("/tasks/foo:c%61ncel", "foo"),
("/tenant/tasks/foo%3Acancel:c%61ncel?x=y", "foo:cancel"),
("/tenant/tasks/foo%3Acancel:cancel?x=y", "foo:cancel"),
] {
let (handler, _) = CapturingHandler::new();
let req = Request::builder()
.method("POST")
.uri(uri)
.header("a2a-version", "1.0")
.header("content-type", "application/json")
.body(Body::from("{}"))
.unwrap();
let _ = rest_router(handler.clone()).oneshot(req).await.unwrap();
assert!(
handler.take_tenant("cancel_task").is_some(),
"{uri}: not dispatched to cancel"
);
assert_eq!(handler.take_id("cancel_task").as_deref(), Some(id));
}
}
#[tokio::test]
async fn post_subscribe_requires_literal_suffix_and_preserves_id() {
for (uri, expected) in [
("/tasks/foo%3Asubscribe", None),
("/tasks/foo%253Asubscribe", None),
("/tasks/foo:s%75bscribe", Some("foo")),
(
"/tasks/foo%3Asubscribe:subscribe?x=y",
Some("foo:subscribe"),
),
] {
let (handler, _) = CapturingHandler::new();
let req = Request::builder()
.method("POST")
.uri(uri)
.header("a2a-version", "1.0")
.header("content-type", "application/json")
.body(Body::from("{}"))
.unwrap();
let _ = rest_router(handler.clone()).oneshot(req).await.unwrap();
assert_eq!(
handler.take_id("subscribe_to_task").as_deref(),
expected,
"{uri}"
);
}
}
#[tokio::test]
async fn routing_works_under_nested_base_path() {
for (uri, method, id) in [
(
"/a2a/tasks/foo%3Asubscribe?x=:subscribe",
"get_task",
"foo:subscribe",
),
(
"/a2a/tasks/foo%3Asubscribe:subscribe",
"subscribe_to_task",
"foo:subscribe",
),
] {
let (handler, _) = CapturingHandler::new();
let app = axum::Router::new().nest("/a2a", rest_router(handler.clone()));
let req = Request::builder()
.uri(uri)
.header("a2a-version", "1.0")
.body(Body::empty())
.unwrap();
let _ = app.oneshot(req).await.unwrap();
assert_eq!(handler.take_id(method).as_deref(), Some(id), "{uri}");
}
}
}