Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 91 additions & 14 deletions a2a-client/src/jsonrpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,22 @@ fn parse_jsonrpc_error(err: JsonRpcError) -> A2AError {
crate::a2a_error_from_details(err.code, err.message, details)
}

/// Parses a JSON-RPC envelope. A body that is not one, sent with a non-success
/// status (an authenticating proxy's 401, a gateway's 429 or 502), is reported
/// with that status, as the REST transport reports it.
fn parse_jsonrpc_response(
status: reqwest::StatusCode,
body: &str,
) -> Result<JsonRpcResponse, A2AError> {
serde_json::from_str(body).map_err(|e| {
if status.is_success() {
A2AError::internal(format!("failed to parse JSON-RPC response: {e}"))
} else {
A2AError::internal(format!("HTTP {status}: {body}"))
}
})
}

/// JSON-RPC transport implementation.
///
/// Sends all requests as JSON-RPC 2.0 POSTs to a single endpoint.
Expand Down Expand Up @@ -67,15 +83,15 @@ impl JsonRpcTransport {
}

let response = wire::send(&self.client, builder.json(&rpc_request)).await?;
let status = response.status();

// Read the body as text first so the raw bytes can be logged before
// they become a typed value; one error message still covers both a
// transport failure and a parse failure, as `json()` did.
let body = wire::response_text(response)
.await
.map_err(|e| A2AError::internal(format!("failed to parse JSON-RPC response: {e}")))?;
let rpc_response: JsonRpcResponse = serde_json::from_str(&body)
.map_err(|e| A2AError::internal(format!("failed to parse JSON-RPC response: {e}")))?;
let rpc_response = parse_jsonrpc_response(status, &body)?;

if let Some(err) = rpc_response.error {
return Err(parse_jsonrpc_error(err));
Expand Down Expand Up @@ -150,14 +166,16 @@ impl JsonRpcTransport {
// in the envelope rather than via status code. Detect that case by
// content type before handing the body to the SSE parser, which
// would otherwise find no `data:` frames and yield an empty stream.
// A response with no content type is still treated as a stream:
// A success with no content type is still treated as a stream:
// reading it to inspect it would hang on a stream that has not sent
// anything yet.
let is_event_stream = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.map(|v| v.as_bytes().starts_with(b"text/event-stream"))
.unwrap_or(true);
// anything yet. A non-success status is never a stream.
let status = response.status();
let is_event_stream = status.is_success()
&& response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.map(|v| v.as_bytes().starts_with(b"text/event-stream"))
.unwrap_or(true);

if is_event_stream {
let stream = response.bytes_stream();
Expand All @@ -166,9 +184,7 @@ impl JsonRpcTransport {
let body = wire::response_text(response).await.map_err(|e| {
A2AError::internal(format!("failed to parse JSON-RPC response: {e}"))
})?;
let rpc_response: JsonRpcResponse = serde_json::from_str(&body).map_err(|e| {
A2AError::internal(format!("failed to parse JSON-RPC response: {e}"))
})?;
let rpc_response = parse_jsonrpc_response(status, &body)?;

match rpc_response.error {
Some(err) => Err(parse_jsonrpc_error(err)),
Expand Down Expand Up @@ -525,12 +541,12 @@ impl Transport for JsonRpcTransport {
}

let response = wire::send(&self.client, builder.json(&rpc_request)).await?;
let status = response.status();

let body = wire::response_text(response)
.await
.map_err(|e| A2AError::internal(format!("failed to parse JSON-RPC response: {e}")))?;
let rpc_response: JsonRpcResponse = serde_json::from_str(&body)
.map_err(|e| A2AError::internal(format!("failed to parse JSON-RPC response: {e}")))?;
let rpc_response = parse_jsonrpc_response(status, &body)?;

if let Some(err) = rpc_response.error {
return Err(parse_jsonrpc_error(err));
Expand Down Expand Up @@ -657,6 +673,25 @@ mod tests {
format!("http://{addr}")
}

/// Answers one request with `status` and a body that is not JSON-RPC, as an
/// authenticating proxy or a gateway in front of the agent does.
async fn spawn_http_error_server(status: &'static str, body: &'static str) -> String {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();

tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
let _request = read_http_request(&mut socket).await;
let response = format!(
"HTTP/1.1 {status}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len(),
);
socket.write_all(response.as_bytes()).await.unwrap();
});

format!("http://{addr}")
}

async fn read_http_request(socket: &mut TcpStream) -> String {
let mut buffer = Vec::new();
let mut chunk = [0_u8; 1024];
Expand Down Expand Up @@ -1502,6 +1537,48 @@ mod tests {
assert!(error.message.contains("failed to parse JSON-RPC response"));
}

#[tokio::test]
async fn test_http_error_without_jsonrpc_body_reports_the_status() {
let endpoint = spawn_http_error_server("429 Too Many Requests", "budget exceeded").await;
let transport =
JsonRpcTransport::new(crate::default_reqwest_client(None).unwrap(), endpoint);

let error = transport
.get_task(
&ServiceParams::new(),
&GetTaskRequest {
id: "task-1".into(),
history_length: None,
tenant: None,
},
)
.await
.unwrap_err();

assert_eq!(error.code, error_code::INTERNAL_ERROR);
assert_eq!(error.message, "HTTP 429 Too Many Requests: budget exceeded");
}

#[tokio::test]
async fn test_streaming_http_error_reports_the_status_not_an_empty_stream() {
// No content type, so the status is the only thing marking it as no stream.
let endpoint = spawn_http_error_server("401 Unauthorized", "").await;
let transport =
JsonRpcTransport::new(crate::default_reqwest_client(None).unwrap(), endpoint);

let req = SubscribeToTaskRequest {
id: "task-1".into(),
tenant: None,
};
let error = transport
.subscribe_to_task(&ServiceParams::new(), &req)
.await
.err()
.expect("expected error, got a stream");

assert_eq!(error.message, "HTTP 401 Unauthorized: ");
}

#[tokio::test]
async fn test_create_push_config_rejects_missing_result() {
let response = json!({
Expand Down
20 changes: 20 additions & 0 deletions a2a-grpc/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,15 @@ fn extract_service_params(
params
}

/// §3.6.2 for every gRPC method, on the `A2A-Version` read from metadata
/// (§10.2) -- the same check the HTTP bindings apply.
#[allow(clippy::result_large_err)]
fn validate_protocol_version(
params: &a2a_server::middleware::ServiceParams,
) -> Result<(), tonic::Status> {
a2a_server::middleware::check_a2a_version(params).map_err(|error| a2a_error_to_status(&error))
}

#[allow(clippy::result_large_err)]
fn map_proto_stream_item(
item: Result<StreamResponse, A2AError>,
Expand All @@ -69,6 +78,7 @@ impl<H: RequestHandler> A2aService for GrpcHandler<H> {
request: tonic::Request<proto::SendMessageRequest>,
) -> Result<tonic::Response<proto::SendMessageResponse>, tonic::Status> {
let params = extract_service_params(request.metadata());
validate_protocol_version(&params)?;
let native_req = pbconv::from_proto_send_message_request(request.get_ref());
let result = self
.handler
Expand All @@ -87,6 +97,7 @@ impl<H: RequestHandler> A2aService for GrpcHandler<H> {
request: tonic::Request<proto::SendMessageRequest>,
) -> Result<tonic::Response<Self::SendStreamingMessageStream>, tonic::Status> {
let params = extract_service_params(request.metadata());
validate_protocol_version(&params)?;
let native_req = pbconv::from_proto_send_message_request(request.get_ref());
let stream = self
.handler
Expand All @@ -102,6 +113,7 @@ impl<H: RequestHandler> A2aService for GrpcHandler<H> {
request: tonic::Request<proto::GetTaskRequest>,
) -> Result<tonic::Response<proto::Task>, tonic::Status> {
let params = extract_service_params(request.metadata());
validate_protocol_version(&params)?;
let native_req = pbconv::from_proto_get_task_request(request.get_ref());
let result = self
.handler
Expand All @@ -116,6 +128,7 @@ impl<H: RequestHandler> A2aService for GrpcHandler<H> {
request: tonic::Request<proto::ListTasksRequest>,
) -> Result<tonic::Response<proto::ListTasksResponse>, tonic::Status> {
let params = extract_service_params(request.metadata());
validate_protocol_version(&params)?;
let native_req = pbconv::from_proto_list_tasks_request(request.get_ref());
let result = self
.handler
Expand All @@ -132,6 +145,7 @@ impl<H: RequestHandler> A2aService for GrpcHandler<H> {
request: tonic::Request<proto::CancelTaskRequest>,
) -> Result<tonic::Response<proto::Task>, tonic::Status> {
let params = extract_service_params(request.metadata());
validate_protocol_version(&params)?;
let native_req = pbconv::from_proto_cancel_task_request(request.get_ref());
let result = self
.handler
Expand All @@ -148,6 +162,7 @@ impl<H: RequestHandler> A2aService for GrpcHandler<H> {
request: tonic::Request<proto::SubscribeToTaskRequest>,
) -> Result<tonic::Response<Self::SubscribeToTaskStream>, tonic::Status> {
let params = extract_service_params(request.metadata());
validate_protocol_version(&params)?;
let native_req = pbconv::from_proto_subscribe_to_task_request(request.get_ref());
let stream = self
.handler
Expand All @@ -163,6 +178,7 @@ impl<H: RequestHandler> A2aService for GrpcHandler<H> {
request: tonic::Request<proto::TaskPushNotificationConfig>,
) -> Result<tonic::Response<proto::TaskPushNotificationConfig>, tonic::Status> {
let params = extract_service_params(request.metadata());
validate_protocol_version(&params)?;
let native_req =
pbconv::from_proto_create_task_push_notification_config_request(request.get_ref());
let result = self
Expand All @@ -180,6 +196,7 @@ impl<H: RequestHandler> A2aService for GrpcHandler<H> {
request: tonic::Request<proto::GetTaskPushNotificationConfigRequest>,
) -> Result<tonic::Response<proto::TaskPushNotificationConfig>, tonic::Status> {
let params = extract_service_params(request.metadata());
validate_protocol_version(&params)?;
let native_req =
pbconv::from_proto_get_task_push_notification_config_request(request.get_ref());
let result = self
Expand All @@ -198,6 +215,7 @@ impl<H: RequestHandler> A2aService for GrpcHandler<H> {
) -> Result<tonic::Response<proto::ListTaskPushNotificationConfigsResponse>, tonic::Status>
{
let params = extract_service_params(request.metadata());
validate_protocol_version(&params)?;
let native_req =
pbconv::from_proto_list_task_push_notification_configs_request(request.get_ref());
let result = self
Expand All @@ -215,6 +233,7 @@ impl<H: RequestHandler> A2aService for GrpcHandler<H> {
request: tonic::Request<proto::GetExtendedAgentCardRequest>,
) -> Result<tonic::Response<proto::AgentCard>, tonic::Status> {
let params = extract_service_params(request.metadata());
validate_protocol_version(&params)?;
let native_req = pbconv::from_proto_get_extended_agent_card_request(request.get_ref());
let result = self
.handler
Expand All @@ -229,6 +248,7 @@ impl<H: RequestHandler> A2aService for GrpcHandler<H> {
request: tonic::Request<proto::DeleteTaskPushNotificationConfigRequest>,
) -> Result<tonic::Response<()>, tonic::Status> {
let params = extract_service_params(request.metadata());
validate_protocol_version(&params)?;
let native_req =
pbconv::from_proto_delete_task_push_notification_config_request(request.get_ref());
self.handler
Expand Down
Loading
Loading