Skip to content

Commit 257626b

Browse files
ShivamSharma43claudeIwaniukooo11
authored
fix: reject decoded values that are not objects in parse_lenient (a2aproject#1431)
## Problem `parse_lenient` calls `ParseDict(..., ignore_unknown_fields=True)`. `ParseDict` iterates the decoded value as if it were an object's keys. So when a decoded value is not a `dict`: - `[]` parses as an empty message - `None`, a number or a boolean raises a bare `TypeError` (`'NoneType' object is not iterable`) The REST and JSON-RPC client transports pass decoded response JSON to `parse_lenient`. Here is `RestTransport.get_task` against a server that answers `200` with each body, on main: ``` client get_task, 200 []: returned Task(id='') client get_task, 200 null: TypeError: 'NoneType' object is not iterable ``` The caller gets an empty `Task` with no error. The JSON-RPC transport does the same with a `"result"` of `[]` or `null`. ## Fix `parse_lenient` raises `ParseError` when a decoded value is not a `dict`. Raw text and bytes still go straight to `Parse`, unchanged. With the fix: ``` client get_task, 200 []: ParseError: Expected a JSON object for Task, got list. client get_task, 200 null: ParseError: Expected a JSON object for Task, got NoneType. ``` This matches `test_malformed_known_field_still_raises` from a2aproject#1354: unknown fields are ignored, but a malformed payload raises `ParseError`. ## Tests - `tests/utils/test_proto_utils.py`: decoded values `[]`, `None`, `0`, `True` raise `ParseError`. A separate test checks that a `str` goes to the raw-text branch (`'id'` fails JSON decoding there, not the object check). - `tests/client/transports/test_rest_client.py`: `get_task` with a body of `[]` or `null`. - `tests/client/transports/test_jsonrpc_client.py`: `get_task` with a `result` of `[]` or `null`. The 8 new `ParseError` cases fail on main. Two existing REST tests, `test_send_message_with_timeout_context` and `test_send_message_with_default_extensions`, never set a response body. The mocked `json()` returned a `MagicMock`, which only parsed because of this bug, so they now return `{}`. - `bash scripts/lint.sh`: success. The 3 ruff diagnostics it prints are in `client_factory.py` and `transports/__init__.py`, which this change does not touch. - `uv run pytest` on Windows, Python 3.10, skipping `tests/integration/cross_version` and `tests/integration/push_notifications`, which do not run on Windows (`os.killpg`, spawn-mode multiprocessing): 2557 passed, 207 skipped, 4 xfailed, 1 xpassed 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Mateusz Iwaniuk <45974414+Iwaniukooo11@users.noreply.github.com>
1 parent 2ba8e7b commit 257626b

4 files changed

Lines changed: 71 additions & 1 deletion

File tree

‎src/a2a/utils/proto_utils.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def parse_lenient(
7070
7171
Raises:
7272
ParseError: If the data is not valid ProtoJSON, including bytes that
73-
are not valid UTF-8.
73+
are not valid UTF-8 and decoded values that are not objects.
7474
"""
7575
if isinstance(data, bytes):
7676
try:
@@ -79,6 +79,14 @@ def parse_lenient(
7979
raise ParseError(f'Failed to load JSON: {e}.') from e
8080
if isinstance(data, str):
8181
return Parse(data, message, ignore_unknown_fields=True)
82+
# A message is a JSON object. With ignore_unknown_fields, ParseDict reads
83+
# an empty list as an empty message (it iterates the value as if it were
84+
# the object's keys), and raises TypeError for null or a number.
85+
if not isinstance(data, dict):
86+
raise ParseError(
87+
f'Expected a JSON object for {message.DESCRIPTOR.name}, '
88+
f'got {type(data).__name__}.'
89+
)
8290
return ParseDict(data, message, ignore_unknown_fields=True)
8391

8492

‎tests/client/transports/test_jsonrpc_client.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -829,6 +829,24 @@ async def test_send_message_streaming_ignores_unrecognized_fields(
829829
assert events[0].message.message_id == 'r1'
830830
assert events[0].message.parts[0].text == 'hello'
831831

832+
@pytest.mark.asyncio
833+
@pytest.mark.parametrize('result', [[], None])
834+
async def test_get_task_rejects_result_that_is_not_an_object(
835+
self, transport, mock_httpx_client, result
836+
):
837+
"""A non-object result is not read as an empty Task."""
838+
mock_response = MagicMock()
839+
mock_response.json.return_value = {
840+
'jsonrpc': '2.0',
841+
'id': '1',
842+
'result': result,
843+
}
844+
mock_response.raise_for_status = MagicMock()
845+
mock_httpx_client.send.return_value = mock_response
846+
847+
with pytest.raises(json_format.ParseError, match='JSON object'):
848+
await transport.get_task(GetTaskRequest(id='task-1'))
849+
832850

833851
# A JSON-RPC error object with a member beyond code, message and data.
834852
_ERROR_WITH_EXTRA_MEMBER = {

‎tests/client/transports/test_rest_client.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,7 @@ async def test_send_message_with_timeout_context(
232232

233233
mock_response = AsyncMock(spec=httpx.Response)
234234
mock_response.status_code = 200
235+
mock_response.json = MagicMock(return_value={})
235236
mock_httpx_client.send.return_value = mock_response
236237

237238
await client.send_message(request=params, context=context)
@@ -305,6 +306,7 @@ async def test_send_message_with_default_extensions(
305306
# Mock the send method
306307
mock_response = AsyncMock(spec=httpx.Response)
307308
mock_response.status_code = 200
309+
mock_response.json = MagicMock(return_value={})
308310
mock_httpx_client.send.return_value = mock_response
309311

310312
context = ClientCallContext(
@@ -918,3 +920,28 @@ async def test_send_message_streaming_ignores_unrecognized_fields(
918920
assert len(events) == 1
919921
assert events[0].message.message_id == 'r1'
920922
assert events[0].message.parts[0].text == 'hello'
923+
924+
@pytest.mark.asyncio
925+
@pytest.mark.parametrize('body', [[], None])
926+
async def test_get_task_rejects_body_that_is_not_an_object(
927+
self,
928+
mock_httpx_client: AsyncMock,
929+
mock_agent_card: MagicMock,
930+
body: object,
931+
):
932+
"""A 200 body that is not an object is not read as an empty Task."""
933+
client = RestTransport(
934+
httpx_client=mock_httpx_client,
935+
agent_card=mock_agent_card,
936+
url='http://agent.example.com/api',
937+
)
938+
mock_httpx_client.build_request = MagicMock(
939+
return_value=AsyncMock(spec=httpx.Request)
940+
)
941+
mock_response = AsyncMock(spec=httpx.Response)
942+
mock_response.raise_for_status = MagicMock()
943+
mock_response.json = MagicMock(return_value=body)
944+
mock_httpx_client.send.return_value = mock_response
945+
946+
with pytest.raises(json_format.ParseError, match='JSON object'):
947+
await client.get_task(GetTaskRequest(id='task-1'))

‎tests/utils/test_proto_utils.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -482,3 +482,20 @@ def test_invalid_utf8_bytes_raise_parse_error(self) -> None:
482482
"""Bytes that are not UTF-8 are malformed JSON, not an internal error."""
483483
with pytest.raises(ParseError):
484484
proto_utils.parse_lenient(b'{"messageId": "\xff"}', Message())
485+
486+
@pytest.mark.parametrize(
487+
'data',
488+
[[], None, 0, True],
489+
ids=['empty-list', 'none', 'int', 'bool'],
490+
)
491+
def test_decoded_value_that_is_not_an_object_raises(
492+
self, data: Any
493+
) -> None:
494+
"""A decoded value that is not a dict is not read as an empty message."""
495+
with pytest.raises(ParseError, match='Expected a JSON object'):
496+
proto_utils.parse_lenient(data, Task())
497+
498+
def test_str_is_parsed_as_text_not_as_decoded_value(self) -> None:
499+
"""A str is raw ProtoJSON text, so it never reaches the object check."""
500+
with pytest.raises(ParseError, match='Failed to load JSON'):
501+
proto_utils.parse_lenient('id', Task())

0 commit comments

Comments
 (0)