Skip to content

The agent that grows with you

fix(a2a): refuse a non-loopback Host in no-token mode

John Paul Soliva38466417654c
diff --git a/plugins/platforms/a2a/README.md b/plugins/platforms/a2a/README.md
index ab6b1b535b3..5b89d391a76 100644
--- a/plugins/platforms/a2a/README.md
+++ b/plugins/platforms/a2a/README.md
@@ -77,7 +77,7 @@ via `tasks/get`.
|---|---|---|
| `A2A_PEER_TOKENS` | _(unset)_ | Per-peer credentials `name:token,…` (preferred). |
| `A2A_BEARER_TOKEN` | _(unset)_ | Shared token; identity falls back to caller IP. |
-| `A2A_HOST` | `127.0.0.1` | Bind host. Only widens with a token set. |
+| `A2A_HOST` | `127.0.0.1` | Bind host. Only widens with a token set. Without a token, requests must name `localhost`, `127.0.0.1` or `[::1]` in `Host`. |
| `A2A_PORT` | `9900` | Inbound port. |
| `A2A_AGENT_NAME` | hostname-derived | Name on the Agent Card. |
| `A2A_PUBLIC_URL` | _(unset)_ | Routable URL advertised on the card (reverse proxies). |
diff --git a/plugins/platforms/a2a/adapter.py b/plugins/platforms/a2a/adapter.py
index cf560d59013..6821e4f13ef 100644
--- a/plugins/platforms/a2a/adapter.py
+++ b/plugins/platforms/a2a/adapter.py
@@ -157,6 +157,17 @@ class A2ARequestHandler(BaseHTTPRequestHandler):
def adapter(self) -> A2AAdapter:
return self.server.adapter # type: ignore[attr-defined]
+ def parse_request(self) -> bool:
+ """Without a token, refuse any request whose ``Host`` is not a loopback name, before a route
+ runs: a page on a hostname re-resolved to 127.0.0.1 (DNS rebinding) is same-origin to this
+ listener and could otherwise read its served-agent list and Agent Card."""
+ if not super().parse_request():
+ return False
+ if self.adapter._security_context.localhost_only() and not security.is_loopback_host_header(self.headers.get("Host")):
+ self._error(403, None, protocol.ERR_UNAUTHORIZED, "Host must be localhost, 127.0.0.1 or [::1] (no A2A token configured)")
+ return False
+ return True
+
def log_message(self, format, *args):
logger.debug("A2A http: " + format, *args) # silence the default stderr access log
diff --git a/plugins/platforms/a2a/security.py b/plugins/platforms/a2a/security.py
index a8e07b7aeb9..03257d39697 100644
--- a/plugins/platforms/a2a/security.py
+++ b/plugins/platforms/a2a/security.py
@@ -204,6 +204,22 @@ _BLOCKED_PREFIXES = ("169.254.", "127.", "10.", *(f"172.{i}." for i in range(16,
"0.0.0.0", "::1", "fe80:", "fc00:", "fd00:")
+_LOOPBACK_HOST_NAMES = frozenset({"localhost", "127.0.0.1", "::1"})
+
+
+def is_loopback_host_header(host_header: Optional[str]) -> bool:
+ """True when an HTTP ``Host`` value names a loopback address (any port); malformed fails closed."""
+ value = (host_header or "").strip()
+ if not value or any(c in value for c in "@/\\?# \t"):
+ return False
+ try:
+ parts = urllib.parse.urlsplit("//" + value)
+ parts.port # noqa: B018 -- raises ValueError on a malformed port
+ except ValueError:
+ return False
+ return (parts.hostname or "").lower() in _LOOPBACK_HOST_NAMES
+
+
def is_safe_callback_url(url: str, *, localhost_mode: Optional[bool] = None) -> bool:
"""True when a push callback URL is http(s) and not internal/private/loopback."""
if localhost_mode is None:
diff --git a/tests/plugins/test_a2a_plugin.py b/tests/plugins/test_a2a_plugin.py
index 96af420947d..16a98259bb2 100644
--- a/tests/plugins/test_a2a_plugin.py
+++ b/tests/plugins/test_a2a_plugin.py
@@ -1328,6 +1328,41 @@ class TestInboundRoundTrip:
set_multiplex_active(False)
[email protected]("host,served", [
+ (None, True), # urllib's own Host: 127.0.0.1:<port>
+ ("localhost", True),
+ ("[::1]", True),
+ ("rebound.example", False), # a page's hostname re-resolved to 127.0.0.1
+])
+def test_no_token_listener_serves_only_loopback_host_names(monkeypatch, host, served):
+ """Without a token the listener trusts the loopback socket; a page on a hostname re-resolved to
+ 127.0.0.1 is same-origin to it, so every route refuses a non-loopback Host before it runs."""
+ monkeypatch.delenv("A2A_BEARER_TOKEN", raising=False)
+ monkeypatch.delenv("A2A_PEER_TOKENS", raising=False)
+ seen: list = []
+ adapter, base = _make_live_adapter(monkeypatch, reply_fn=lambda event: seen.append(event) or "ok")
+ headers = {"Host": f"{host}:{base.rsplit(':', 1)[1]}"} if host else {}
+
+ def status(fn, *args):
+ try:
+ fn(*args)
+ return 200
+ except urllib.error.HTTPError as exc:
+ return exc.code
+
+ async def run():
+ assert await adapter.connect() is True
+ try:
+ return [await asyncio.to_thread(status, _get_json, base + "/health", headers),
+ await asyncio.to_thread(status, _get_json, base + "/.well-known/agent-card.json", headers),
+ await asyncio.to_thread(status, _post_json, base + "/", _send_body("hi"), headers)]
+ finally:
+ await adapter.disconnect()
+
+ assert asyncio.run(run()) == [200 if served else 403] * 3
+ assert bool(seen) is served
+
+
# --------------------------------------------------------------------------
# Push notifications end-to-end (inline config in message/send)
# --------------------------------------------------------------------------
diff --git a/website/docs/user-guide/messaging/a2a.md b/website/docs/user-guide/messaging/a2a.md
index 53d727d7544..e745879fae9 100644
--- a/website/docs/user-guide/messaging/a2a.md
+++ b/website/docs/user-guide/messaging/a2a.md
@@ -156,4 +156,5 @@ curl -X POST http://your-host:9900/ \
- **Peers can't reach the card URL** — the card was advertising your bind address; set `A2A_PUBLIC_URL` to the externally routable URL.
- **`401 Unauthorized`** — token mismatch; check `A2A_PEER_TOKENS`/`A2A_BEARER_TOKEN` on the server and the peer's `auth:` block.
- **Server won't bind non-localhost** — by design: set a bearer token first, then `A2A_HOST=0.0.0.0`.
+- **`403` "Host must be localhost…" with no token** — without a token the server answers only requests addressed to `localhost`, `127.0.0.1` or `[::1]`, so a web page on another hostname that resolves to your machine cannot read the card or the served-agent list. Call it by one of those names, or configure a token.
- **Replies time out on long tasks** — raise `A2A_REPLY_TIMEOUT` (the orphan sweep follows it, so a late reply is stored, not discarded), or have the caller register a push-notification config and poll `GetTask`.