From b3bb4bd69a0ea7e4eebf59fd8b85e3678e611317 Mon Sep 17 00:00:00 2001 From: Emmanuel Hugonnet Date: Fri, 20 Nov 2026 15:40:01 +0100 Subject: [PATCH] fix(spec-grpc): clarify invalid enum errors Identify the field containing an invalid enum value in JSON-RPC requests and omit protobuf enum type names from the error. Fall back to reporting the value when the field cannot be identified. Cover invalid values and supported JSON field conversions in parsing tests. Signed-off-by: Emmanuel Hugonnet --- .../sdk/grpc/utils/JSONRPCUtils.java | 71 +++++++++++- .../sdk/grpc/utils/JSONRPCUtilsTest.java | 101 ++++++++++++++++++ 2 files changed, 171 insertions(+), 1 deletion(-) diff --git a/spec-grpc/src/main/java/org/a2aproject/sdk/grpc/utils/JSONRPCUtils.java b/spec-grpc/src/main/java/org/a2aproject/sdk/grpc/utils/JSONRPCUtils.java index e42535c90..34a4a01b5 100644 --- a/spec-grpc/src/main/java/org/a2aproject/sdk/grpc/utils/JSONRPCUtils.java +++ b/spec-grpc/src/main/java/org/a2aproject/sdk/grpc/utils/JSONRPCUtils.java @@ -24,9 +24,12 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSyntaxException; import com.google.gson.Strictness; import com.google.gson.stream.JsonWriter; import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.util.JsonFormat; import org.a2aproject.sdk.grpc.StreamResponse; import org.a2aproject.sdk.jsonrpc.common.json.IdJsonMappingException; @@ -486,10 +489,67 @@ public static void parseJsonString(String body, com.google.protobuf.Message.Buil } catch (InvalidProtocolBufferException e) { LOGGER.log(Level.FINE, "Protocol buffer parsing failed for JSON: {0}", body); LOGGER.log(Level.FINE, "Proto parsing error details", e); + String message = e.getMessage(); + if (message != null && message.startsWith("Invalid enum value:") && message.contains(" for enum type: ")) { + int typeIndex = message.lastIndexOf(" for enum type: "); + String enumType = message.substring(typeIndex + " for enum type: ".length()); + String value = message.substring("Invalid enum value:".length(), typeIndex).trim(); + try { + String field = findEnumField(JsonParser.parseString(body), builder.getDescriptorForType(), enumType, value); + if (field != null) { + throw new InvalidParamsJsonMappingException(ERROR_MESSAGE.formatted("Invalid value for field " + field), id); + } + } catch (JsonSyntaxException ignored) { + // Fall through to generic conversion. + } + } throw convertProtoBufExceptionToJsonProcessingException(e, id); } } + private static @Nullable String findEnumField(JsonElement json, Descriptor descriptor, String enumType, String value) { + if (json.isJsonArray()) { + for (JsonElement element : json.getAsJsonArray()) { + String field = findEnumField(element, descriptor, enumType, value); + if (field != null) { + return field; + } + } + } else if (json.isJsonObject()) { + for (FieldDescriptor field : descriptor.getFields()) { + JsonObject object = json.getAsJsonObject(); + String name = object.has(field.getJsonName()) ? field.getJsonName() : field.getName(); + JsonElement element = object.get(name); + if (element == null || element.isJsonNull()) { + continue; + } + if (field.getJavaType() == FieldDescriptor.JavaType.ENUM + && field.getEnumType().getFullName().equals(enumType) && containsEnumValue(element, value)) { + return name; + } + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + String nested = findEnumField(element, field.getMessageType(), enumType, value); + if (nested != null) { + return nested; + } + } + } + } + return null; + } + + private static boolean containsEnumValue(JsonElement element, String value) { + if (element.isJsonArray()) { + for (JsonElement item : element.getAsJsonArray()) { + if (containsEnumValue(item, value)) { + return true; + } + } + return false; + } + return element.isJsonPrimitive() && element.getAsString().equals(value); + } + /** * Extracts a user-friendly error message from Protocol Buffer parsing exceptions. *

@@ -524,8 +584,17 @@ private static JsonProcessingException convertProtoBufExceptionToJsonProcessingE return new JsonProcessingException(ERROR_MESSAGE.formatted("unknown parsing error")); } + if (message.startsWith("Invalid enum value:")) { + String value = message.substring("Invalid enum value:".length()); + int typeIndex = value.lastIndexOf(" for enum type:"); + if (typeIndex >= 0) { + value = value.substring(0, typeIndex); + } + return new InvalidParamsJsonMappingException(ERROR_MESSAGE.formatted("Invalid enum value: " + value.trim()), id); + } + // Extract field name if present in error message - check common prefixes - String[] prefixes = {"Cannot find field: ", "Invalid value for", "Invalid enum value:", "Failed to parse"}; + String[] prefixes = {"Cannot find field: ", "Invalid value for", "Failed to parse"}; for (String prefix : prefixes) { if (message.contains(prefix)) { return new InvalidParamsJsonMappingException(ERROR_MESSAGE.formatted(message.substring(message.indexOf(prefix) + prefix.length())), id); diff --git a/spec-grpc/src/test/java/org/a2aproject/sdk/grpc/utils/JSONRPCUtilsTest.java b/spec-grpc/src/test/java/org/a2aproject/sdk/grpc/utils/JSONRPCUtilsTest.java index 530d4412c..43d264268 100644 --- a/spec-grpc/src/test/java/org/a2aproject/sdk/grpc/utils/JSONRPCUtilsTest.java +++ b/spec-grpc/src/test/java/org/a2aproject/sdk/grpc/utils/JSONRPCUtilsTest.java @@ -31,6 +31,7 @@ import com.google.protobuf.Struct; import com.google.protobuf.Value; import com.google.protobuf.util.JsonFormat; +import java.util.List; import org.a2aproject.sdk.grpc.SendMessageResponse; import org.a2aproject.sdk.grpc.StreamResponse; import org.a2aproject.sdk.jsonrpc.common.json.InvalidParamsJsonMappingException; @@ -458,6 +459,106 @@ public void testParseNumericalTimestampThrowsInvalidParamsJsonMappingException() assertEquals("2", exception.getId()); } + @Test + public void testInvalidRoleDoesNotExposeProtoEnumType() { + String request = """ + {"jsonrpc":"2.0","id":"1","method":"SendMessage","params":{ + "message":{"role":"system_user","parts":[{"text":"hi"}],"metadata":{}}}} + """; + InvalidParamsJsonMappingException exception = assertThrows(InvalidParamsJsonMappingException.class, + () -> JSONRPCUtils.parseRequestBody(request, null)); + assertEquals("1", exception.getId()); + assertEquals(ERROR_MESSAGE.formatted("Invalid value for field role"), exception.getMessage()); + } + + @Test + public void testInvalidTaskStatusIdentifiesField() { + String request = """ + {"jsonrpc":"2.0","id":"2","method":"ListTasks","params":{"status":"wrong"}} + """; + InvalidParamsJsonMappingException exception = assertThrows(InvalidParamsJsonMappingException.class, + () -> JSONRPCUtils.parseRequestBody(request, null)); + assertEquals("2", exception.getId()); + assertEquals(ERROR_MESSAGE.formatted("Invalid value for field status"), exception.getMessage()); + } + + @Test + public void testInvalidEnumWithTrailingJsonFallsBackToGenericError() { + InvalidParamsJsonMappingException exception = assertThrows(InvalidParamsJsonMappingException.class, + () -> JSONRPCUtils.parseJsonString("{\"status\":\"wrong\"} trailing", + org.a2aproject.sdk.grpc.ListTasksRequest.newBuilder(), "2")); + assertEquals("2", exception.getId()); + assertEquals(ERROR_MESSAGE.formatted("Invalid enum value: wrong"), exception.getMessage()); + } + + @Test + public void testInvalidNumericAndBooleanValues() { + for (String params : List.of("\"pageSize\":\"bad\"", "\"includeArtifacts\":\"bad\"", + "\"includeArtifacts\":123")) { + String request = """ + {"jsonrpc":"2.0","id":"type-error","method":"ListTasks","params":{%s}} + """.formatted(params); + JsonProcessingException exception = assertThrows(JsonProcessingException.class, + () -> JSONRPCUtils.parseRequestBody(request, null), params); + assertTrue(exception.getMessage().contains("Invalid request content"), exception.getMessage()); + assertFalse(exception.getMessage().contains("lf.a2a.v1."), exception.getMessage()); + assertFalse(exception.getMessage().contains("google.protobuf."), exception.getMessage()); + } + } + + @Test + public void testNumericStringIsAcceptedForIntegerField() throws JsonProcessingException { + String request = """ + {"jsonrpc":"2.0","id":"numeric-string","method":"ListTasks","params":{"pageSize":"12"}} + """; + ListTasksRequest parsed = assertInstanceOf(ListTasksRequest.class, JSONRPCUtils.parseRequestBody(request, null)); + assertEquals(12, parsed.getParams().pageSize()); + } + + @Test + public void testBooleanValuesAreAccepted() throws JsonProcessingException { + for (boolean value : new boolean[] {true, false}) { + String request = """ + {"jsonrpc":"2.0","id":"boolean","method":"ListTasks","params":{"includeArtifacts":%s}} + """.formatted(value); + ListTasksRequest parsed = assertInstanceOf(ListTasksRequest.class, JSONRPCUtils.parseRequestBody(request, null)); + assertEquals(value, parsed.getParams().shouldIncludeArtifacts()); + if (!value) { + assertNull(parsed.getParams().includeArtifacts()); + } + } + } + + @Test + public void testNumericValueForStringField() throws JsonProcessingException { + String request = """ + {"jsonrpc":"2.0","id":"number","method":"ListTasks","params":{"contextId":123}} + """; + ListTasksRequest parsed = assertInstanceOf(ListTasksRequest.class, JSONRPCUtils.parseRequestBody(request, null)); + assertEquals("123", parsed.getParams().contextId()); + } + + @Test + public void testTimestampValues() throws JsonProcessingException { + String valid = """ + {"jsonrpc":"2.0","id":"timestamp","method":"ListTasks", + "params":{"statusTimestampAfter":"2023-10-27T10:00:00Z"}} + """; + ListTasksRequest parsed = assertInstanceOf(ListTasksRequest.class, JSONRPCUtils.parseRequestBody(valid, null)); + assertEquals(java.time.Instant.parse("2023-10-27T10:00:00Z"), parsed.getParams().statusTimestampAfter()); + + for (String value : List.of("\"not-a-timestamp\"", "123")) { + String invalid = """ + {"jsonrpc":"2.0","id":"timestamp","method":"ListTasks", + "params":{"statusTimestampAfter":%s}} + """.formatted(value); + JsonProcessingException exception = assertThrows(JsonProcessingException.class, + () -> JSONRPCUtils.parseRequestBody(invalid, null), value); + assertFalse(exception.getMessage().contains("lf.a2a.v1."), exception.getMessage()); + assertFalse(exception.getMessage().contains("google.protobuf."), exception.getMessage()); + } + } + @Test public void testParseMissingField_ThrowsInvalidParamsError() throws JsonMappingException { String missingRoleMessage= """