Skip to content

Commit 1bbe69c

Browse files
fix(client): percent-encode ids in REST transport paths (a2aproject#1436)
# Description A REST client that names its push notification configs, or talks to a server whose task ids are not plain UUIDs, can read or delete the wrong resource. `RestTransport` puts task ids and push config ids into the URL path as raw text, so an id with `#`, `?` or `%` changes the URL: `delete_task_push_notification_config(id='alerts#ops')` sends `DELETE .../pushNotificationConfigs/alerts` and deletes the config `alerts`. The same ids work over JSON-RPC and gRPC, which send them in the request body. This PR encodes each id with `urllib.parse.quote(value, safe='')` at the 7 path sites (`get_task`, `cancel_task`, `subscribe` and the four push config methods). The server's router decodes the segment back, so ids with `#`, `?`, `%`, spaces, unicode or `:` now reach their own resource. Ids without reserved characters produce the same URL as before. Reproducer: a real `DefaultRequestHandler` behind `create_rest_routes`, served through `httpx.ASGITransport` to a real `RestTransport`. The client creates the configs `alerts` and `alerts#ops` on one task, deletes `alerts#ops`, then calls `get_task('t1?x')`. ``` # main (28f8a62) configs before: ['alerts', 'alerts#ops'] delete('alerts#ops') -> configs after: ['alerts#ops'] get_task('t1?x') -> returned task 't1' # this branch configs before: ['alerts', 'alerts#ops'] delete('alerts#ops') -> configs after: ['alerts'] get_task('t1?x') -> TaskNotFoundError ``` ```mermaid flowchart LR I["id = 'alerts#ops'"] --> P{RestTransport path} P -->|main| R1["f'.../pushNotificationConfigs/{id}'"] R1 --> H1["httpx: '#ops' is a fragment"] H1 --> S1["DELETE .../alerts: wrong config deleted"] P -->|this PR| R2["_quote_id(id) = 'alerts%23ops'"] R2 --> H2["DELETE .../alerts%23ops"] H2 --> S2["router decodes push_id = 'alerts#ops'"] ``` The tests in `tests/client/transports/test_rest_client.py` (`TestRestTransportPathEncoding`) run the reproducer above: a real `DefaultRequestHandler` behind `create_rest_routes`, called through `httpx.ASGITransport`. One deletes `alerts#ops` and asserts that `alerts` is left. The other asserts that `get_task('t1?x')` raises `TaskNotFoundError`. ``` $ pytest tests/client/transports/test_rest_client.py -k PathEncoding # rest.py from main 2 failed, 41 deselected $ pytest tests/client/transports/test_rest_client.py -k PathEncoding # this branch 2 passed, 41 deselected ``` Run on Windows 11, Python 3.10, on b2a6aa3: `ruff check` and `ruff format --check` pass on the changed files; `pytest --ignore=tests/integration/cross_version --ignore=tests/integration/test_scenarios.py` gives 2431 passed, 207 skipped, 4 xfailed. The 4 push notification e2e tests error at setup on Windows (spawn pickling) on `main` as well. Out of scope, noted for review: - An id containing `/` is encoded as `%2F`, which Starlette decodes before routing, so it now gets a 404 instead of reaching another route. Supporting `/` in ids would need a server change. - Ids that are exactly `.` or `..` are still collapsed by httpx dot-segment handling. - The tenant prefix in `_get_path` is left as is: it is configured by the operator and is not an id. - `src/a2a/compat/v0_3/rest_transport.py` builds paths the same way; happy to follow up there. - [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) - [ ] Appropriate docs were updated (if necessary) --------- Co-authored-by: Mateusz Iwaniuk <45974414+Iwaniukooo11@users.noreply.github.com>
1 parent 01483cb commit 1bbe69c

2 files changed

Lines changed: 106 additions & 9 deletions

File tree

‎src/a2a/client/transports/rest.py‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from collections.abc import AsyncGenerator
55
from typing import Any, NoReturn
6+
from urllib.parse import quote
67

78
import httpx
89

@@ -89,6 +90,11 @@ def _parse_rest_error(
8990
return None
9091

9192

93+
def _quote_id(value: str) -> str:
94+
"""Percent-encodes an id so it stays a single URL path segment."""
95+
return quote(value, safe='')
96+
97+
9298
@trace_class(kind=SpanKind.CLIENT)
9399
class RestTransport(ClientTransport):
94100
"""A REST transport for the A2A client."""
@@ -158,7 +164,7 @@ async def get_task(
158164

159165
response_data = await self._execute_request(
160166
'GET',
161-
f'/tasks/{request.id}',
167+
f'/tasks/{_quote_id(request.id)}',
162168
request.tenant,
163169
context=context,
164170
params=params,
@@ -198,7 +204,7 @@ async def cancel_task(
198204
"""Requests the agent to cancel a specific task."""
199205
response_data = await self._execute_request(
200206
'POST',
201-
f'/tasks/{request.id}:cancel',
207+
f'/tasks/{_quote_id(request.id)}:cancel',
202208
request.tenant,
203209
context=context,
204210
json=MessageToDict(request),
@@ -215,7 +221,7 @@ async def create_task_push_notification_config(
215221
"""Sets or updates the push notification configuration for a specific task."""
216222
response_data = await self._execute_request(
217223
'POST',
218-
f'/tasks/{request.task_id}/pushNotificationConfigs',
224+
f'/tasks/{_quote_id(request.task_id)}/pushNotificationConfigs',
219225
request.tenant,
220226
context=context,
221227
json=MessageToDict(request),
@@ -242,7 +248,8 @@ async def get_task_push_notification_config(
242248

243249
response_data = await self._execute_request(
244250
'GET',
245-
f'/tasks/{request.task_id}/pushNotificationConfigs/{request.id}',
251+
f'/tasks/{_quote_id(request.task_id)}'
252+
f'/pushNotificationConfigs/{_quote_id(request.id)}',
246253
request.tenant,
247254
context=context,
248255
params=params,
@@ -267,7 +274,7 @@ async def list_task_push_notification_configs(
267274

268275
response_data = await self._execute_request(
269276
'GET',
270-
f'/tasks/{request.task_id}/pushNotificationConfigs',
277+
f'/tasks/{_quote_id(request.task_id)}/pushNotificationConfigs',
271278
request.tenant,
272279
context=context,
273280
params=params,
@@ -294,7 +301,8 @@ async def delete_task_push_notification_config(
294301

295302
await self._execute_request(
296303
'DELETE',
297-
f'/tasks/{request.task_id}/pushNotificationConfigs/{request.id}',
304+
f'/tasks/{_quote_id(request.task_id)}'
305+
f'/pushNotificationConfigs/{_quote_id(request.id)}',
298306
request.tenant,
299307
context=context,
300308
params=params,
@@ -309,7 +317,7 @@ async def subscribe(
309317
"""Reconnects to get task updates."""
310318
async for event in self._send_stream_request(
311319
'POST',
312-
f'/tasks/{request.id}:subscribe',
320+
f'/tasks/{_quote_id(request.id)}:subscribe',
313321
request.tenant,
314322
context=context,
315323
):

‎tests/client/transports/test_rest_client.py‎

Lines changed: 91 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,20 @@
55

66
import httpx
77
import pytest
8+
import pytest_asyncio
89

910
from a2a.client.client import ClientCallContext
1011
from a2a.client.errors import A2AClientError
1112
from a2a.client.transports.rest import RestTransport
1213
from a2a.extensions.common import HTTP_EXTENSION_HEADER
1314
from a2a.helpers.proto_helpers import new_text_message
15+
from a2a.server.context import ServerCallContext
16+
from a2a.server.request_handlers import DefaultRequestHandler
17+
from a2a.server.routes import create_rest_routes
18+
from a2a.server.tasks import (
19+
InMemoryPushNotificationConfigStore,
20+
InMemoryTaskStore,
21+
)
1422
from a2a.types.a2a_pb2 import (
1523
AgentCapabilities,
1624
AgentCard,
@@ -24,13 +32,24 @@
2432
ListTasksRequest,
2533
SendMessageRequest,
2634
SubscribeToTaskRequest,
35+
Task,
2736
TaskPushNotificationConfig,
2837
TaskState,
38+
TaskStatus,
39+
)
40+
from a2a.utils.constants import (
41+
PROTOCOL_VERSION_CURRENT,
42+
VERSION_HEADER,
43+
TransportProtocol,
44+
)
45+
from a2a.utils.errors import (
46+
A2A_ERROR_MAPPING,
47+
MethodNotFoundError,
48+
TaskNotFoundError,
2949
)
30-
from a2a.utils.constants import TransportProtocol
31-
from a2a.utils.errors import A2A_ERROR_MAPPING, MethodNotFoundError
3250
from google.protobuf import json_format
3351
from google.protobuf.timestamp_pb2 import Timestamp
52+
from starlette.applications import Starlette
3453

3554

3655
@pytest.fixture
@@ -752,6 +771,76 @@ async def test_rest_streaming_methods_prepend_tenant( # noqa: PLR0913
752771
assert args[2] == f'http://agent.example.com/api{expected_path}'
753772

754773

774+
class TestRestTransportPathEncoding:
775+
"""Ids with reserved URL characters reach their own resource.
776+
777+
Runs a real request handler behind the REST routes, so a wrong path
778+
reads or deletes the wrong resource.
779+
"""
780+
781+
@pytest_asyncio.fixture
782+
async def transport(self) -> AsyncGenerator[RestTransport, None]:
783+
task_store = InMemoryTaskStore()
784+
await task_store.save(
785+
Task(
786+
id='t1',
787+
context_id='c1',
788+
status=TaskStatus(state=TaskState.TASK_STATE_WORKING),
789+
),
790+
ServerCallContext(),
791+
)
792+
agent_card = AgentCard(
793+
capabilities=AgentCapabilities(push_notifications=True)
794+
)
795+
request_handler = DefaultRequestHandler(
796+
None,
797+
task_store,
798+
agent_card,
799+
push_config_store=InMemoryPushNotificationConfigStore(),
800+
)
801+
app = Starlette(
802+
routes=create_rest_routes(request_handler=request_handler)
803+
)
804+
httpx_client = httpx.AsyncClient(
805+
transport=httpx.ASGITransport(app=app),
806+
headers={VERSION_HEADER: PROTOCOL_VERSION_CURRENT},
807+
)
808+
transport = RestTransport(httpx_client, agent_card, 'http://agent')
809+
yield transport
810+
await transport.close()
811+
812+
@pytest.mark.asyncio
813+
async def test_delete_push_config_keeps_config_with_shared_prefix(
814+
self, transport: RestTransport
815+
):
816+
for config_id in ('alerts', 'alerts#ops'):
817+
await transport.create_task_push_notification_config(
818+
TaskPushNotificationConfig(
819+
task_id='t1',
820+
id=config_id,
821+
url='https://hooks.example.com/hook',
822+
)
823+
)
824+
825+
await transport.delete_task_push_notification_config(
826+
DeleteTaskPushNotificationConfigRequest(
827+
task_id='t1', id='alerts#ops'
828+
)
829+
)
830+
831+
response = await transport.list_task_push_notification_configs(
832+
ListTaskPushNotificationConfigsRequest(task_id='t1')
833+
)
834+
assert [config.id for config in response.configs] == ['alerts']
835+
836+
@pytest.mark.asyncio
837+
async def test_get_task_does_not_return_task_named_by_id_prefix(
838+
self, transport: RestTransport
839+
):
840+
with pytest.raises(TaskNotFoundError):
841+
await transport.get_task(GetTaskRequest(id='t1?x'))
842+
843+
755844
class TestRestUnrecognizedResponseFields:
756845
"""Spec 5.7: unrecognized response fields are ignored (issue #1341)."""
757846

0 commit comments

Comments
 (0)