Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 77 additions & 12 deletions docs/handler-authoring.md
Original file line number Diff line number Diff line change
Expand Up @@ -2157,11 +2157,11 @@ rejects an explicit SDK selection rather than advertising unenforced versions.
### HTTP Host and Origin policy

`serve`, `ServeConfig`, `create_mcp_server`, `create_a2a_server` and
`build_asgi_app` accept `allowed_hosts`, `allowed_origins` and
`enable_dns_rebinding_protection`. The policy covers MCP, A2A, AgentCard and
ADCP discovery, and operational paths. All HTTP transports use the SDK's
loopback allowlist by default; configure public hosts when deploying A2A.
Configured entries extend the loopback defaults.
`build_asgi_app` accept `allowed_hosts`, `allowed_origins`,
`enable_dns_rebinding_protection` and `host_validator`. The policy covers MCP,
A2A, AgentCard and ADCP discovery, and operational paths. All HTTP transports
use the SDK's loopback allowlist by default; configure public hosts when
deploying. Configured entries extend the loopback defaults.

```python
serve(
Expand All @@ -2172,14 +2172,79 @@ serve(
)
```

A bare Host entry accepts that host with or without a port. An explicit port
accepts only that value; `:*` accepts a port suffix. Origins use exact matching
or an explicit `:*` port suffix. Domain wildcards such as `*.example` are not
expanded. Missing Origin is valid for native clients. A supplied Origin is
checked on protocol and operational requests. Public GET/HEAD reads of
Host matching is case-insensitive, and one trailing dot (`example.com.`) is
removed from entries and request Hosts alike. A bare Host entry accepts that
host with or without a port. An explicit port accepts only that value; `:*` accepts any
port suffix. Disallowed Hosts return 421 on every path, including discovery.

#### Proxied and multi-tenant hostnames

Sellers behind a reverse proxy or serving one hostname per tenant can use a
leftmost-label wildcard instead of listing every Host:

```python
serve(
handler,
transport="both",
allowed_hosts=["*.agents.example.com", "agents.example.com"],
)
```

- `*.agents.example.com` matches exactly one extra label
(`acme.agents.example.com`), the same rule as a TLS wildcard certificate.
- `**.agents.example.com` matches one or more labels
(`eu.acme.agents.example.com`).
- Neither matches the apex `agents.example.com`; list it separately.
- Wildcard entries follow the same port rules as other entries.
- Requests whose Host has userinfo (`@`), a path, whitespace, an empty label,
a non-numeric port or raw non-ASCII are rejected before matching. Internationalized names arrive as punycode, so list the A-label
form (`*.xn--bcher-kva.example`); a non-ASCII entry raises `ValueError`.
- Only a whole leftmost label may be a wildcard. `tenant-*.example.com`,
`a.*.example.com` and a bare `*` raise `ValueError` when the server is built.
- A wildcard must sit under a domain someone can register, checked against
the SDK's bundled Public Suffix List (both sections). `*.com`, `*.co.uk` and
`*.github.io` raise `ValueError`; `*.acme.github.io` is accepted. Dev names
(`*.localhost`, `*.test`, `*.example`, `*.invalid`) are always accepted.

When tenancy lives in a database, pass a callable:

```python
def host_validator(hostname: str) -> bool:
return tenant_cache.contains(hostname)

serve(handler, transport="both", host_validator=host_validator)
```

The callable runs only when no `allowed_hosts` entry (including the loopback
defaults) matches. It receives the lowercased hostname without the port, after
malformed values have been rejected. It runs synchronously on the event loop
for each such request, so keep it fast and non-blocking: answer from an
in-memory cache you refresh elsewhere. An `async def` validator raises
`TypeError` when the server is built. Only a return value of `True` admits the
Host; any other value, or an exception, rejects it.
`host_validator` has no effect when `enable_dns_rebinding_protection=False`.

The SDK logs a WARNING, once per policy per process, when protection is on,
no `host_validator` is set, every `allowed_hosts` entry is a loopback or dev
host (`localhost`, `*.localhost`, loopback or unspecified IPs, `.test`,
`.example`, `.invalid`), and the listener may be public. That configuration
answers 421 to any request addressed to a public hostname. `serve` judges it
against the address it binds and stays quiet on a loopback IP or for stdio.
`create_mcp_server` uses its `host`; `create_a2a_server` and `build_asgi_app`
do not know where you will serve the app, so they warn whenever the policy is
loopback-only. A bind address given as a hostname is taken as deliberate and
never warned about.

#### Origin

Origins use exact matching or an explicit `:*` port suffix; wildcards are not
expanded for Origins. Missing Origin is valid for native clients. The Origin
check applies to protocol requests (MCP and A2A POSTs) and operational
endpoints. It does not apply to public discovery: GET/HEAD reads of
`/.well-known/agent-card.json`, `/.well-known/agent.json` and
`/.well-known/adcp-agents.json` accept any Origin. Host checks still apply to
every path. Disallowed Hosts return 421 and disallowed Origins return 403.
`/.well-known/adcp-agents.json` accept any Origin, so a directory crawler or
browser can fetch the AgentCard from anywhere. A disallowed Origin on a
protocol request returns 403.

Origin policy does not install CORS response headers. If browser clients need
to read public discovery, configure `CORSMiddleware` separately, for example
Expand Down
2 changes: 2 additions & 0 deletions src/adcp/server/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ async def get_products(params, context=None):
resolve_account_into_context,
valid_actions_for_status,
)
from adcp.server.http_policy import HostValidator
from adcp.server.idempotency import IdempotencyStore, MemoryBackend
from adcp.server.implementation import ImplementationReport, adcp_sdk_entry
from adcp.server.mcp_sessions import MCPSessionStats, get_mcp_session_stats
Expand Down Expand Up @@ -293,6 +294,7 @@ async def get_products(params, context=None):
"ADCPAgentExecutor",
"MessageParser",
"PublicUrlResolver",
"HostValidator",
"ASGIMiddlewareEntry",
"SkillMiddleware",
"create_a2a_server",
Expand Down
18 changes: 12 additions & 6 deletions src/adcp/server/a2a_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
from starlette.routing import Mount, Route

from adcp.server.auth import BearerTokenAuth
from adcp.server.http_policy import HostValidator
from adcp.server.serve import ContextFactory, SkillMiddleware

from collections.abc import AsyncGenerator, Awaitable, Callable # noqa: E402
Expand Down Expand Up @@ -1772,6 +1773,7 @@ def create_a2a_server(
allowed_hosts: Sequence[str] | None = None,
allowed_origins: Sequence[str] | None = None,
enable_dns_rebinding_protection: bool | None = None,
host_validator: HostValidator | None = None,
auth: BearerTokenAuth | None = None,
public_url: str | PublicUrlResolver | None = None,
response_enhancer: ResponseEnhancer | None = None,
Expand Down Expand Up @@ -2152,14 +2154,18 @@ def agent_card_url(request: Request) -> str:
if operational_routes is not None:
app.state.adcp_operational_routes = operational_routes
app.add_middleware(OperationalRoutesMiddleware, routes=operational_routes)
from adcp.server.http_policy import HostOriginMiddleware, transport_security_settings

app.add_middleware(
from adcp.server.http_policy import (
HostOriginMiddleware,
settings=transport_security_settings(
allowed_hosts, allowed_origins, enable_dns_rebinding_protection
),
check_host_policy_once,
transport_security_settings,
)

security_settings = transport_security_settings(
allowed_hosts, allowed_origins, enable_dns_rebinding_protection, host_validator
)
# The listener is unknown here: the adopter (or serve()) runs the app.
check_host_policy_once(security_settings, bind_host=None)
app.add_middleware(HostOriginMiddleware, settings=security_settings)
return app


Expand Down
Loading