Skip to content

Commit 1ff86d5

Browse files
1AbdullahButtclaudeIwaniukooo11
authored
fix(compat): percent-encode ids in v0.3 REST transport paths (a2aproject#1458)
# Description `CompatRestTransport` (the v0.3 REST client) put task ids and push notification config ids into URL paths as raw text. An id containing `#`, `?` or `%` then reached a different resource: getting the push config `alerts#ops` returned the config `alerts`, and `get_task('t1?x')` returned task `t1`. a2aproject#1436 fixed this for `RestTransport`; the v0.3 client was not covered. This PR encodes each id with `urllib.parse.quote(value, safe='')`, the same helper `RestTransport` uses, at the six path sites (`get_task`, `cancel_task`, `subscribe`, and push config create, get and list). Ids without reserved characters produce the same URL as before. Tests: `TestCompatRestTransportPathEncoding` in `tests/compat/v0_3/test_rest_transport.py` runs a real `DefaultRequestHandler` behind `create_rest_routes(..., enable_v0_3_compat=True)` through `httpx.ASGITransport`. One test creates `alerts` and `alerts#ops` and checks that getting `alerts#ops` returns that config. The other checks that `get_task('t1?x')` does not return task `t1`. ``` $ pytest tests/compat/v0_3/test_rest_transport.py -k PathEncoding # rest_transport.py from main 2 failed, 35 deselected $ pytest tests/compat/v0_3/test_rest_transport.py -k PathEncoding # this branch 2 passed, 35 deselected $ pytest tests/compat tests/client 595 passed ``` `ruff check`, `ruff format` and `ty check` pass on the changed files. This change was written with Claude Code. - [x] Follow the [`CONTRIBUTING` Guide](https://github.com/a2aproject/a2a-python/blob/main/CONTRIBUTING.md). - [x] Make your Pull Request title in the <https://www.conventionalcommits.org/> specification. - [x] Ensure the tests and linter pass (Run `bash scripts/format.sh` from the repository root to format) - [x] Appropriate docs were updated (if necessary) Fixes a2aproject#1457 🦕 🤖 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 2399993 commit 1ff86d5

2 files changed

Lines changed: 92 additions & 6 deletions

File tree

‎src/a2a/compat/v0_3/rest_transport.py‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from collections.abc import AsyncGenerator
66
from typing import Any, NoReturn
7+
from urllib.parse import quote
78

89
import httpx
910

@@ -58,6 +59,11 @@
5859
}
5960

6061

62+
def _quote_id(value: str) -> str:
63+
"""Percent-encodes an id so it stays a single URL path segment."""
64+
return quote(value, safe='')
65+
66+
6167
@trace_class(kind=SpanKind.CLIENT)
6268
class CompatRestTransport(ClientTransport):
6369
"""A backward compatible REST transport for A2A v0.3."""
@@ -163,7 +169,7 @@ async def get_task(
163169

164170
response_data = await self._execute_request(
165171
'GET',
166-
f'/v1/tasks/{request.id}',
172+
f'/v1/tasks/{_quote_id(request.id)}',
167173
context=context,
168174
params=params,
169175
)
@@ -192,7 +198,7 @@ async def cancel_task(
192198
"""Requests the agent to cancel a specific task."""
193199
response_data = await self._execute_request(
194200
'POST',
195-
f'/v1/tasks/{request.id}:cancel',
201+
f'/v1/tasks/{_quote_id(request.id)}:cancel',
196202
context=context,
197203
)
198204
resp_proto = ParseDict(
@@ -221,7 +227,7 @@ async def create_task_push_notification_config(
221227
)
222228
response_data = await self._execute_request(
223229
'POST',
224-
f'/v1/tasks/{request.task_id}/pushNotificationConfigs',
230+
f'/v1/tasks/{_quote_id(request.task_id)}/pushNotificationConfigs',
225231
context=context,
226232
json=MessageToDict(req_proto),
227233
)
@@ -243,7 +249,8 @@ async def get_task_push_notification_config(
243249
"""Retrieves the push notification configuration for a specific task."""
244250
response_data = await self._execute_request(
245251
'GET',
246-
f'/v1/tasks/{request.task_id}/pushNotificationConfigs/{request.id}',
252+
f'/v1/tasks/{_quote_id(request.task_id)}'
253+
f'/pushNotificationConfigs/{_quote_id(request.id)}',
247254
context=context,
248255
)
249256
resp_proto = ParseDict(
@@ -264,7 +271,7 @@ async def list_task_push_notification_configs(
264271
"""Lists push notification configurations for a specific task."""
265272
response_data = await self._execute_request(
266273
'GET',
267-
f'/v1/tasks/{request.task_id}/pushNotificationConfigs',
274+
f'/v1/tasks/{_quote_id(request.task_id)}/pushNotificationConfigs',
268275
context=context,
269276
)
270277
resp_proto = ParseDict(
@@ -310,7 +317,7 @@ async def subscribe(
310317
try:
311318
async for event in self._send_stream_request(
312319
subscribe_method,
313-
f'/v1/tasks/{request.id}:subscribe',
320+
f'/v1/tasks/{_quote_id(request.id)}:subscribe',
314321
context=context,
315322
):
316323
yield event

‎tests/compat/v0_3/test_rest_transport.py‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,22 @@
11
import json
22

3+
from collections.abc import AsyncGenerator
34
from unittest.mock import AsyncMock, MagicMock, patch
45

56
import httpx
67
import pytest
8+
import pytest_asyncio
79

810
from a2a.client.errors import A2AClientError
911
from a2a.compat.v0_3 import types as types_v03
1012
from a2a.compat.v0_3.rest_transport import CompatRestTransport
13+
from a2a.server.context import ServerCallContext
14+
from a2a.server.request_handlers import DefaultRequestHandler
15+
from a2a.server.routes import create_rest_routes
16+
from a2a.server.tasks import (
17+
InMemoryPushNotificationConfigStore,
18+
InMemoryTaskStore,
19+
)
1120
from a2a.types.a2a_pb2 import (
1221
AgentCapabilities,
1322
AgentCard,
@@ -27,9 +36,11 @@
2736
SubscribeToTaskRequest,
2837
Task,
2938
TaskPushNotificationConfig,
39+
TaskState,
3040
TaskStatus,
3141
)
3242
from a2a.utils.errors import InvalidParamsError, MethodNotFoundError
43+
from starlette.applications import Starlette
3344

3445

3546
@pytest.fixture
@@ -906,3 +917,71 @@ async def test_compat_rest_transport_execute_request(
906917
mock_send_http_request.assert_called_once_with(
907918
transport.httpx_client, mock_request, transport._handle_http_error
908919
)
920+
921+
922+
class TestCompatRestTransportPathEncoding:
923+
"""Ids with reserved URL characters reach their own resource.
924+
925+
Runs a real request handler behind the v0.3 REST routes, so a wrong path
926+
reads the wrong resource.
927+
"""
928+
929+
@pytest_asyncio.fixture
930+
async def transport(self) -> AsyncGenerator[CompatRestTransport, None]:
931+
task_store = InMemoryTaskStore()
932+
await task_store.save(
933+
Task(
934+
id='t1',
935+
context_id='c1',
936+
status=TaskStatus(state=TaskState.TASK_STATE_WORKING),
937+
),
938+
ServerCallContext(),
939+
)
940+
agent_card = AgentCard(
941+
capabilities=AgentCapabilities(push_notifications=True)
942+
)
943+
request_handler = DefaultRequestHandler(
944+
None,
945+
task_store,
946+
agent_card,
947+
push_config_store=InMemoryPushNotificationConfigStore(),
948+
)
949+
app = Starlette(
950+
routes=create_rest_routes(
951+
request_handler=request_handler, enable_v0_3_compat=True
952+
)
953+
)
954+
httpx_client = httpx.AsyncClient(transport=httpx.ASGITransport(app=app))
955+
transport = CompatRestTransport(
956+
httpx_client, agent_card, 'http://agent'
957+
)
958+
yield transport
959+
await transport.close()
960+
961+
@pytest.mark.asyncio
962+
async def test_get_push_config_does_not_return_config_named_by_prefix(
963+
self, transport: CompatRestTransport
964+
):
965+
for config_id, url in (
966+
('alerts', 'https://hooks.example.com/alerts'),
967+
('alerts#ops', 'https://hooks.example.com/ops'),
968+
):
969+
await transport.create_task_push_notification_config(
970+
TaskPushNotificationConfig(task_id='t1', id=config_id, url=url)
971+
)
972+
973+
config = await transport.get_task_push_notification_config(
974+
GetTaskPushNotificationConfigRequest(task_id='t1', id='alerts#ops')
975+
)
976+
977+
assert config.id == 'alerts#ops'
978+
assert config.url == 'https://hooks.example.com/ops'
979+
980+
@pytest.mark.asyncio
981+
async def test_get_task_does_not_return_task_named_by_id_prefix(
982+
self, transport: CompatRestTransport
983+
):
984+
# The v0.3 client maps the server's 404 for an unknown task to
985+
# MethodNotFoundError.
986+
with pytest.raises(MethodNotFoundError):
987+
await transport.get_task(GetTaskRequest(id='t1?x'))

0 commit comments

Comments
 (0)