Skip to content

fix(client): percent-encode ids in REST transport paths - #1436

Merged
Iwaniukooo11 merged 4 commits into
a2aproject:mainfrom
Sonica-B:fix/rest-client-encode-path-ids
Nov 12, 2026
Merged

Iwaniukooo11 merged 4 commits into
a2aproject:mainfrom
Sonica-B:fix/rest-client-encode-path-ids

Conversation

@Sonica-B

@Sonica-B Sonica-B commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

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
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'"]
Loading

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.

  • Follow the CONTRIBUTING Guide.

  • Make your Pull Request title in the https://www.conventionalcommits.org/ specification.

  • Ensure the tests and linter pass (Run bash scripts/format.sh from the repository root to format)

  • Appropriate docs were updated (if necessary)

RestTransport put task ids and push notification config ids into URL
paths as raw text. An id that contains '#', '?' or '%' then reaches a
different resource: '#' and '?' cut the path short, and the server
decodes '%xx'. For example, deleting the push config 'alerts#ops'
deleted the config 'alerts', and get_task('t1?x') returned task 't1'.
JSON-RPC and gRPC send the same ids in the body and are not affected.

Encode each id with urllib.parse.quote(safe='') so it stays one path
segment. The server's router decodes it back to the original id.
@Sonica-B
Sonica-B requested a review from a team as a code owner November 8, 2026 00:51
@github-actions

github-actions Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

🧪 Code Coverage (vs main)

⬇️ Download Full Report

Base PR Delta
src/a2a/client/transports/rest.py 86.43% 89.05% 🟢 +2.62%
Total 93.55% 93.60% 🟢 +0.05%

Generated by coverage-comment.yml

Replace the assertions on the URL passed to a mocked build_request with
tests that run a DefaultRequestHandler behind create_rest_routes through
httpx.ASGITransport: deleting the push config 'alerts#ops' must leave
'alerts', and get_task('t1?x') must raise TaskNotFoundError instead of
returning task 't1'. Both fail with rest.py from main.

Drop the 'a/b%2F' and 'task 1' cases: the first is a 404 with and without
the change, and httpx already encodes the space on main.

@Iwaniukooo11 Iwaniukooo11 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Iwaniukooo11
Iwaniukooo11 merged commit 1bbe69c into a2aproject:main Nov 12, 2026
17 checks passed
Iwaniukooo11 added a commit that referenced this pull request Nov 13, 2026
# 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`. #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 #1457 🦕

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Mateusz Iwaniuk <[email protected]>
mykytanetipa added a commit that referenced this pull request Nov 13, 2026
…onfig (#1445)

# Description

`RestTransport.delete_task_push_notification_config` goes through
`_execute_request`, which always calls `response.json()`. The spec
leaves the result to the server
([3.1.10](https://a2a-protocol.org/latest/specification/#3110-delete-push-notification-config):
"Confirmation of deletion (implementation-specific)"), and the SDKs
answer differently:

- this SDK's server answers 200 with `{}`;
- a2a-js answers 204 No Content
([`rest_handler.ts`](https://github.com/a2aproject/a2a-js/blob/3d3ca8291e1f6b1f53293f61c12ba46c36670000/src/server/express/rest_handler.ts#L548-L559));
- a2a-go answers 200 with no body
([`handleDeleteTaskPushConfig`](https://github.com/a2aproject/a2a-go/blob/ea739de3859f0574175bc9876eda39b7120da8e3/a2asrv/rest.go#L536-L557)).

Against a2a-js or a2a-go servers, the config is deleted, but the Python
client then raises `A2AClientError: JSON Decode Error`. A caller that
retries or reports the failure is acting on a delete that succeeded.

The delete now sends its request, checks the status, and does not read
the body. Error responses still go through `_handle_http_error`, so a
404 with `TASK_NOT_FOUND` still raises `TaskNotFoundError`.
`send_http_request` and the JSON-RPC transport are unchanged.

The repro at the end of this description answers the delete the way each
server does. On main (2cc1dd5):

```
a2a-python 200 b'{}' -> ok
a2a-js     204 b''   -> A2AClientError: JSON Decode Error: Expecting value: line 1 column 1 (char 0)
a2a-go     200 b''   -> A2AClientError: JSON Decode Error: Expecting value: line 1 column 1 (char 0)
```

On this branch, all three print `ok`.

```
$ pytest tests/client/transports/test_rest_client.py   # src change reverted
FAILED ...::TestTaskCallback::test_delete_task_push_notification_config_ignores_body[no_content]
FAILED ...::TestTaskCallback::test_delete_task_push_notification_config_ignores_body[empty_200]
2 failed, 44 passed
$ pytest --ignore=tests/integration/cross_version   # this branch, Python 3.10, locked deps
2560 passed, 207 skipped, 4 xfailed, 1 xpassed
$ pytest --cov=src
src/a2a/client/transports/rest.py   87%   (the new lines are covered)
TOTAL   94%
```

The new tests also cover a mapped error and a closed client on this
path. I left the cross-version tests out because their servers don't
start within the 3 s timeout on my machine; the same happens on main.
`ruff check`, `ruff format` and `ty check` pass. `ty` prints only the
three existing unused `type: ignore` warnings.

#1439 touches `send_http_request` and the transport type hints. This
change stays inside `delete_task_push_notification_config` to keep out
of its way, apart from one added import. #1436 percent-encodes the ids
in this method's path, so whichever of the two lands second has a
one-line conflict there; I'll rebase this one if #1436 goes first.

- [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)

No issue exists, since the new tests reproduce it.

<details><summary>Repro script</summary>

```python
import asyncio

import httpx

from a2a.client.transports.rest import RestTransport
from a2a.types.a2a_pb2 import AgentCard, DeleteTaskPushNotificationConfigRequest

# How each SDK's server confirms DELETE /tasks/{id}/pushNotificationConfigs/{configId}.
SERVERS = {'a2a-python': (200, b'{}'), 'a2a-js': (204, b''), 'a2a-go': (200, b'')}


async def main() -> None:
    for name, (status, body) in SERVERS.items():
        transport = httpx.MockTransport(lambda r, s=status, b=body: httpx.Response(s, content=b))
        async with httpx.AsyncClient(transport=transport) as http:
            client = RestTransport(http, AgentCard(), 'http://agent.example')
            try:
                await client.delete_task_push_notification_config(
                    DeleteTaskPushNotificationConfigRequest(task_id='t1', id='cfg1')
                )
                print(f'{name:10} {status} {body!r:5} -> ok')
            except Exception as e:
                print(f'{name:10} {status} {body!r:5} -> {type(e).__name__}: {e}')


asyncio.run(main())
```

</details>

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: mykytanetipa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants