Skip to content

Commit f22943c

Browse files
committed
fix: validate content type and protocol version in REST routes
- Removing consumes from route annotations and adding explicit ContentTypeNotSupportedError validation in sendMessage/sendMessageStreaming - Moving VersionNotSupportedError HTTP status from 501 -> 400 - Adding unit and integration tests for both scenarios fix: HTTP+JSON error mapping is incorrect for ContentTypeNotSupportedError & VersionNotSupportedError Signed-off-by: Emmanuel Hugonnet <ehugonne@redhat.com>
1 parent fd1e40a commit f22943c

7 files changed

Lines changed: 131 additions & 10 deletions

File tree

‎reference/rest/src/main/java/io/a2a/server/rest/quarkus/A2AServerRoutes.java‎

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
import io.a2a.server.extensions.A2AExtensions;
3232
import io.a2a.server.util.async.Internal;
3333
import io.a2a.spec.A2AError;
34+
import io.a2a.spec.ContentTypeNotSupportedError;
3435
import io.a2a.spec.InternalError;
3536
import io.a2a.spec.InvalidParamsError;
3637
import io.a2a.spec.MethodNotFoundError;
@@ -165,8 +166,11 @@ public class A2AServerRoutes {
165166
* @param body the JSON request body
166167
* @param rc the Vert.x routing context
167168
*/
168-
@Route(regex = "^\\/(?<tenant>[^\\/]*\\/?)message:send$", order = 1, methods = {Route.HttpMethod.POST}, consumes = {APPLICATION_JSON}, type = Route.HandlerType.BLOCKING)
169+
@Route(regex = "^\\/(?<tenant>[^\\/]*\\/?)message:send$", order = 1, methods = {Route.HttpMethod.POST}, type = Route.HandlerType.BLOCKING)
169170
public void sendMessage(@Body String body, RoutingContext rc) {
171+
if(!validateContentType(rc)) {
172+
return;
173+
}
170174
ServerCallContext context = createCallContext(rc, SEND_MESSAGE_METHOD);
171175
HTTPRestResponse response = null;
172176
try {
@@ -198,8 +202,11 @@ public void sendMessage(@Body String body, RoutingContext rc) {
198202
* @param body the JSON request body
199203
* @param rc the Vert.x routing context
200204
*/
201-
@Route(regex = "^\\/(?<tenant>[^\\/]*\\/?)message:stream$", order = 1, methods = {Route.HttpMethod.POST}, consumes = {APPLICATION_JSON}, type = Route.HandlerType.BLOCKING)
205+
@Route(regex = "^\\/(?<tenant>[^\\/]*\\/?)message:stream$", order = 1, methods = {Route.HttpMethod.POST}, type = Route.HandlerType.BLOCKING)
202206
public void sendMessageStreaming(@Body String body, RoutingContext rc) {
207+
if(!validateContentType(rc)) {
208+
return;
209+
}
203210
ServerCallContext context = createCallContext(rc, SEND_STREAMING_MESSAGE_METHOD);
204211
HTTPRestStreamingResponse streamingResponse = null;
205212
HTTPRestResponse error = null;
@@ -339,6 +346,9 @@ public void getTask(RoutingContext rc) {
339346
*/
340347
@Route(regex = "^\\/(?<tenant>[^\\/]*\\/?)tasks\\/(?<taskId>[^/]+):cancel$", order = 1, methods = {Route.HttpMethod.POST}, type = Route.HandlerType.BLOCKING)
341348
public void cancelTask(@Body String body, RoutingContext rc) {
349+
if (!validateContentType(rc)) {
350+
return;
351+
}
342352
String taskId = rc.pathParam("taskId");
343353
ServerCallContext context = createCallContext(rc, CANCEL_TASK_METHOD);
344354
HTTPRestResponse response = null;
@@ -443,8 +453,11 @@ public void subscribeToTask(RoutingContext rc) {
443453
* @param body the JSON request body with notification configuration
444454
* @param rc the Vert.x routing context (taskId extracted from path)
445455
*/
446-
@Route(regex = "^\\/(?<tenant>[^\\/]*\\/?)tasks\\/(?<taskId>[^/]+)\\/pushNotificationConfigs$", order = 1, methods = {Route.HttpMethod.POST}, consumes = {APPLICATION_JSON}, type = Route.HandlerType.BLOCKING)
447-
public void CreateTaskPushNotificationConfiguration(@Body String body, RoutingContext rc) {
456+
@Route(regex = "^\\/(?<tenant>[^\\/]*\\/?)tasks\\/(?<taskId>[^/]+)\\/pushNotificationConfigs$", order = 1, methods = {Route.HttpMethod.POST}, type = Route.HandlerType.BLOCKING)
457+
public void createTaskPushNotificationConfiguration(@Body String body, RoutingContext rc) {
458+
if(!validateContentType(rc)) {
459+
return;
460+
}
448461
String taskId = rc.pathParam("taskId");
449462
ServerCallContext context = createCallContext(rc, SET_TASK_PUSH_NOTIFICATION_CONFIG_METHOD);
450463
HTTPRestResponse response = null;
@@ -597,6 +610,20 @@ private String extractTenant(RoutingContext rc) {
597610
return tenantPath;
598611
}
599612

613+
/**
614+
* Check if the request content type is application/json.
615+
* @param rc
616+
* @return true if the content type is application/json - false otherwise.
617+
*/
618+
private boolean validateContentType(RoutingContext rc) {
619+
String contentType = rc.request().getHeader(CONTENT_TYPE);
620+
if (contentType == null || !contentType.trim().startsWith(APPLICATION_JSON)) {
621+
sendResponse(rc, jsonRestHandler.createErrorResponse(new ContentTypeNotSupportedError(null, null, null)));
622+
return false;
623+
}
624+
return true;
625+
}
626+
600627
/**
601628
* Retrieves the public agent card for agent discovery.
602629
*

‎reference/rest/src/test/java/io/a2a/server/rest/quarkus/A2AServerRoutesTest.java‎

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import static org.mockito.ArgumentMatchers.anyString;
1919
import static org.mockito.ArgumentMatchers.eq;
2020
import static org.mockito.Mockito.mock;
21+
import static org.mockito.Mockito.never;
2122
import static org.mockito.Mockito.verify;
2223
import static org.mockito.Mockito.when;
2324

@@ -26,6 +27,7 @@
2627
import jakarta.enterprise.inject.Instance;
2728

2829
import io.a2a.server.ServerCallContext;
30+
import io.a2a.spec.ContentTypeNotSupportedError;
2931
import io.a2a.transport.rest.handler.RestHandler;
3032
import io.a2a.transport.rest.handler.RestHandler.HTTPRestResponse;
3133
import io.vertx.core.Future;
@@ -80,6 +82,7 @@ public void setUp() {
8082
when(mockRoutingContext.user()).thenReturn(null);
8183
when(mockRequest.headers()).thenReturn(mockHeaders);
8284
when(mockRequest.params()).thenReturn(mockParams);
85+
when(mockRequest.getHeader(any(CharSequence.class))).thenReturn("application/json");
8386
when(mockRoutingContext.body()).thenReturn(mockRequestBody);
8487
when(mockRequestBody.asString()).thenReturn("{}");
8588
when(mockResponse.setStatusCode(any(Integer.class))).thenReturn(mockResponse);
@@ -358,7 +361,7 @@ public void testCreateTaskPushNotificationConfiguration_MethodNameSetInContext()
358361
ArgumentCaptor<ServerCallContext> contextCaptor = ArgumentCaptor.forClass(ServerCallContext.class);
359362

360363
// Act
361-
routes.CreateTaskPushNotificationConfiguration("{}", mockRoutingContext);
364+
routes.createTaskPushNotificationConfiguration("{}", mockRoutingContext);
362365

363366
// Assert
364367
verify(mockRestHandler).createTaskPushNotificationConfiguration(contextCaptor.capture(), anyString(), eq("{}"), eq("task123"));
@@ -438,6 +441,61 @@ public void testDeleteTaskPushNotificationConfiguration_MethodNameSetInContext()
438441
assertEquals(DELETE_TASK_PUSH_NOTIFICATION_CONFIG_METHOD, capturedContext.getState().get(METHOD_NAME_KEY));
439442
}
440443

444+
@Test
445+
public void testSendMessage_UnsupportedContentType_ReturnsContentTypeNotSupportedError() {
446+
// Arrange
447+
HTTPRestResponse mockErrorResponse = mock(HTTPRestResponse.class);
448+
when(mockErrorResponse.getStatusCode()).thenReturn(415);
449+
when(mockErrorResponse.getContentType()).thenReturn("application/problem+json");
450+
when(mockErrorResponse.getBody()).thenReturn("{\"type\":\"https://a2a-protocol.org/errors/content-type-not-supported\"}");
451+
when(mockRestHandler.createErrorResponse(any(ContentTypeNotSupportedError.class))).thenReturn(mockErrorResponse);
452+
when(mockRequest.getHeader(any(CharSequence.class))).thenReturn("text/plain");
453+
454+
// Act
455+
routes.sendMessage("{}", mockRoutingContext);
456+
457+
// Assert: createErrorResponse called with ContentTypeNotSupportedError, sendMessage NOT called
458+
verify(mockRestHandler).createErrorResponse(any(ContentTypeNotSupportedError.class));
459+
verify(mockRestHandler, never()).sendMessage(any(ServerCallContext.class), anyString(), anyString());
460+
}
461+
462+
@Test
463+
public void testSendMessageStreaming_UnsupportedContentType_ReturnsContentTypeNotSupportedError() {
464+
// Arrange
465+
HTTPRestResponse mockErrorResponse = mock(HTTPRestResponse.class);
466+
when(mockErrorResponse.getStatusCode()).thenReturn(415);
467+
when(mockErrorResponse.getContentType()).thenReturn("application/problem+json");
468+
when(mockErrorResponse.getBody()).thenReturn("{\"type\":\"https://a2a-protocol.org/errors/content-type-not-supported\"}");
469+
when(mockRestHandler.createErrorResponse(any(ContentTypeNotSupportedError.class))).thenReturn(mockErrorResponse);
470+
when(mockRequest.getHeader(any(CharSequence.class))).thenReturn("text/plain");
471+
472+
// Act
473+
routes.sendMessageStreaming("{}", mockRoutingContext);
474+
475+
// Assert: createErrorResponse called with ContentTypeNotSupportedError, sendStreamingMessage NOT called
476+
verify(mockRestHandler).createErrorResponse(any(ContentTypeNotSupportedError.class));
477+
verify(mockRestHandler, never()).sendStreamingMessage(any(ServerCallContext.class), anyString(), anyString());
478+
}
479+
480+
@Test
481+
public void testSendMessage_UnsupportedProtocolVersion_ReturnsVersionNotSupportedError() {
482+
// Arrange: content type is OK, but RestHandler returns a VersionNotSupportedError response
483+
HTTPRestResponse mockErrorResponse = mock(HTTPRestResponse.class);
484+
when(mockErrorResponse.getStatusCode()).thenReturn(400);
485+
when(mockErrorResponse.getContentType()).thenReturn("application/problem+json");
486+
when(mockErrorResponse.getBody()).thenReturn("{\"type\":\"https://a2a-protocol.org/errors/version-not-supported\"}");
487+
when(mockRequest.getHeader(any(CharSequence.class))).thenReturn("application/json");
488+
when(mockRestHandler.sendMessage(any(ServerCallContext.class), anyString(), anyString()))
489+
.thenReturn(mockErrorResponse);
490+
491+
// Act
492+
routes.sendMessage("{}", mockRoutingContext);
493+
494+
// Assert: sendMessage was called and error response forwarded
495+
verify(mockRestHandler).sendMessage(any(ServerCallContext.class), anyString(), eq("{}"));
496+
verify(mockResponse).setStatusCode(400);
497+
}
498+
441499
/**
442500
* Helper method to set a field via reflection for testing purposes.
443501
*/

‎reference/rest/src/test/java/io/a2a/server/rest/quarkus/QuarkusA2ARestTest.java‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,39 @@ protected String getTransportUrl() {
3030
@Override
3131
protected abstract void configureTransport(ClientBuilder builder);
3232

33+
@Test
34+
public void testSendMessageWithUnsupportedContentType() throws Exception {
35+
HttpClient client = HttpClient.newBuilder()
36+
.version(HttpClient.Version.HTTP_2)
37+
.build();
38+
HttpRequest request = HttpRequest.newBuilder()
39+
.uri(URI.create("http://localhost:" + serverPort + "/message:send"))
40+
.POST(HttpRequest.BodyPublishers.ofString("test body"))
41+
.header("Content-Type", "text/plain")
42+
.build();
43+
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
44+
Assertions.assertEquals(415, response.statusCode());
45+
Assertions.assertTrue(response.body().contains("content-type-not-supported"),
46+
"Expected content-type-not-supported in response body: " + response.body());
47+
}
48+
49+
@Test
50+
public void testSendMessageWithUnsupportedProtocolVersion() throws Exception {
51+
HttpClient client = HttpClient.newBuilder()
52+
.version(HttpClient.Version.HTTP_2)
53+
.build();
54+
HttpRequest request = HttpRequest.newBuilder()
55+
.uri(URI.create("http://localhost:" + serverPort + "/message:send"))
56+
.POST(HttpRequest.BodyPublishers.ofString("{}"))
57+
.header("Content-Type", APPLICATION_JSON)
58+
.header("A2A-Version", "0.4.0")
59+
.build();
60+
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
61+
Assertions.assertEquals(400, response.statusCode());
62+
Assertions.assertTrue(response.body().contains("version-not-supported"),
63+
"Expected version-not-supported in response body: " + response.body());
64+
}
65+
3366
@Test
3467
public void testMethodNotFound() throws Exception {
3568
// Create the client

‎spec/src/main/java/io/a2a/spec/ContentTypeNotSupportedError.java‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,9 @@
4040
*/
4141
public class ContentTypeNotSupportedError extends A2AProtocolError {
4242

43+
public ContentTypeNotSupportedError() {
44+
this(null, null, null);
45+
}
4346
/**
4447
* Constructs a content type not supported error.
4548
*

‎transport/rest/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,7 @@ All error responses use [RFC 7807 Problem Details](https://tools.ietf.org/html/r
323323
| `https://a2a-protocol.org/errors/content-type-not-supported` | 415 | The requested content type is not supported. |
324324
| `https://a2a-protocol.org/errors/push-notification-not-supported` | 501 | Push notifications are not configured for this agent. |
325325
| `https://a2a-protocol.org/errors/unsupported-operation` | 501 | The operation is not implemented or not applicable (e.g., subscribing to a finalized task). |
326-
| `https://a2a-protocol.org/errors/version-not-supported` | 501 | The requested protocol version is not supported. |
326+
| `https://a2a-protocol.org/errors/version-not-supported` | 400 | The requested protocol version is not supported. |
327327
| `https://a2a-protocol.org/errors/invalid-agent-response` | 502 | The agent produced an invalid response. |
328328
| `https://a2a-protocol.org/errors/extended-agent-card-not-configured` | 400 | The agent does not have an extended agent card configured. |
329329
| `https://a2a-protocol.org/errors/internal-error` | 500 | An unexpected server-side error occurred. |

‎transport/rest/src/main/java/io/a2a/transport/rest/handler/RestHandler.java‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -770,8 +770,7 @@ private static int mapErrorToHttpStatus(A2AError error) {
770770
return 409;
771771
}
772772
if (error instanceof PushNotificationNotSupportedError
773-
|| error instanceof UnsupportedOperationError
774-
|| error instanceof VersionNotSupportedError) {
773+
|| error instanceof UnsupportedOperationError) {
775774
return 501;
776775
}
777776
if (error instanceof ContentTypeNotSupportedError) {
@@ -781,7 +780,8 @@ private static int mapErrorToHttpStatus(A2AError error) {
781780
return 502;
782781
}
783782
if (error instanceof ExtendedAgentCardNotConfiguredError
784-
|| error instanceof ExtensionSupportRequiredError) {
783+
|| error instanceof ExtensionSupportRequiredError
784+
|| error instanceof VersionNotSupportedError) {
785785
return 400;
786786
}
787787
if (error instanceof InternalError) {

‎transport/rest/src/test/java/io/a2a/transport/rest/handler/RestHandlerTest.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -777,7 +777,7 @@ public void testVersionNotSupportedErrorOnSendMessage() {
777777

778778
RestHandler.HTTPRestResponse response = handler.sendMessage(contextWithVersion, "", requestBody);
779779

780-
assertProblemDetail(response, 501,
780+
assertProblemDetail(response, 400,
781781
"https://a2a-protocol.org/errors/version-not-supported",
782782
"Protocol version '2.0' is not supported. Supported versions: [1.0]");
783783
}

0 commit comments

Comments
 (0)