Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.
* <p>
Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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= """
Expand Down
Loading