diff --git a/docs/handler-authoring.md b/docs/handler-authoring.md index 4bf77d808..e36de66f2 100644 --- a/docs/handler-authoring.md +++ b/docs/handler-authoring.md @@ -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( @@ -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 diff --git a/src/adcp/server/__init__.py b/src/adcp/server/__init__.py index 681340e27..2b88d4946 100644 --- a/src/adcp/server/__init__.py +++ b/src/adcp/server/__init__.py @@ -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 @@ -293,6 +294,7 @@ async def get_products(params, context=None): "ADCPAgentExecutor", "MessageParser", "PublicUrlResolver", + "HostValidator", "ASGIMiddlewareEntry", "SkillMiddleware", "create_a2a_server", diff --git a/src/adcp/server/a2a_server.py b/src/adcp/server/a2a_server.py index c6e4d8c71..d07377f80 100644 --- a/src/adcp/server/a2a_server.py +++ b/src/adcp/server/a2a_server.py @@ -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 @@ -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, @@ -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 diff --git a/src/adcp/server/http_policy.py b/src/adcp/server/http_policy.py index 7816abba2..1a03e8b2c 100644 --- a/src/adcp/server/http_policy.py +++ b/src/adcp/server/http_policy.py @@ -2,13 +2,34 @@ from __future__ import annotations -from collections.abc import Sequence +import inspect +import ipaddress +import logging +import re +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from typing import Any from mcp.server.transport_security import TransportSecurityMiddleware, TransportSecuritySettings +from pydantic import Field from starlette.requests import Request from starlette.responses import Response from starlette.types import ASGIApp, Receive, Scope, Send +logger = logging.getLogger(__name__) + +HostValidator = Callable[[str], bool] +"""Callable Host policy: receives the normalized request hostname, returns allow. + +The argument is the lowercased hostname without the port, after the SDK has +rejected malformed values (userinfo, paths, whitespace, non-ASCII, empty +labels). Bracketed IPv6 literals keep their brackets (``"[::1]"``). The +callable runs synchronously on the event loop for every request whose Host +matched no ``allowed_hosts`` entry, so it must be fast and must not block; +``async def`` validators are refused at configuration. Only a return value of +``True`` admits the Host; anything else, or raising, rejects it. +""" + _PUBLIC_DISCOVERY_PATHS = frozenset( { "/.well-known/agent-card.json", @@ -17,31 +38,350 @@ } ) +LOOPBACK_ALLOWED_HOSTS: tuple[str, ...] = ("127.0.0.1:*", "localhost:*", "[::1]:*") + +# One DNS label in LDH form (RFC 1123), which also covers A-labels (``xn--``). +_LABEL = re.compile(r"^(?!-)[a-z0-9_-]{1,63}(?{}|^` \t\r\n\x00") + class HTTPTransportSecuritySettings(TransportSecuritySettings): """Retain explicit Origin enforcement when Host validation is disabled.""" explicit_origins: bool = False + host_validator: HostValidator | None = Field(default=None, exclude=True) + + +def _split_host_port(value: str) -> tuple[str, str | None] | None: + """Split ``host[:port]`` honouring bracketed IPv6; ``None`` when malformed.""" + if value.startswith("["): + end = value.find("]") + if end == -1: + return None + host, rest = value[: end + 1], value[end + 1 :] + if not rest: + return host, None + if not rest.startswith(":"): + return None + return host, rest[1:] + if value.count(":") > 1: + return None + host, sep, port = value.partition(":") + return host, (port if sep else None) + + +def _strip_root_dot(hostname: str) -> str: + """Drop one trailing dot: ``example.com.`` and ``example.com`` name one host.""" + return hostname[:-1] if hostname.endswith(".") else hostname + + +def _valid_labels(labels: Sequence[str]) -> bool: + return bool(labels) and all(_LABEL.match(label) for label in labels) + + +def normalize_request_host(raw: str | None) -> tuple[str, str | None] | None: + """Parse a request ``Host`` header into ``(hostname, port)``. + + Returns ``None`` for anything that is not a plain ``host[:port]`` value: + userinfo, path or query characters, whitespace, non-ASCII bytes (raw IDN + must arrive as punycode), empty labels, an empty or non-numeric port, or + unbracketed IPv6. The hostname is lowercased and one trailing dot (the + absolute FQDN form, ``example.com.``) is removed, as it is from entries. + """ + if not raw or not raw.isascii() or any(ch in _FORBIDDEN_HOST_CHARS for ch in raw): + return None + parts = _split_host_port(raw.lower()) + if parts is None: + return None + hostname, port = parts + if port is not None and not (_PORT.match(port) and 0 < int(port) <= 65535): + return None + if hostname.startswith("["): + try: + ipaddress.IPv6Address(hostname[1:-1]) + except ValueError: + return None + return hostname, port + hostname = _strip_root_dot(hostname) + if not _valid_labels(hostname.split(".")): + return None + return hostname, port + + +@dataclass(frozen=True) +class _HostPattern: + hostname: str + """Exact hostname, or the suffix (``agents.example.com``) for a wildcard.""" + wildcard: str | None + """``None`` (exact), ``"*"`` (exactly one label) or ``"**"`` (one or more).""" + port: str | None + """``None`` (no port), ``"*"`` (any port present) or a literal port.""" + + def matches(self, hostname: str, port: str | None) -> bool: + if self.port is None: + port_ok = port is None + elif self.port == "*": + port_ok = port is not None + else: + port_ok = port == self.port + if not port_ok: + return False + if self.wildcard is None: + return hostname == self.hostname + suffix = "." + self.hostname + if not hostname.endswith(suffix): + return False + prefix = hostname[: -len(suffix)] + labels = prefix.split(".") + if not _valid_labels(labels): + return False + return self.wildcard == "**" or len(labels) == 1 + + +def _compile_host_pattern(entry: str) -> _HostPattern | None: + """Compile one ``allowed_hosts`` entry. + + Raises ``ValueError`` for a malformed wildcard so a typo fails at startup + instead of silently admitting nothing (or too much). Malformed entries + without ``*`` in the host part return ``None``; they keep matching only + their literal value, as before wildcard support. + """ + parts = _split_host_port(entry.strip()) + if parts is None: + if "*" in entry.rpartition(":")[0]: + raise ValueError(f"Invalid allowed_hosts wildcard pattern: {entry!r}") + return None + hostname, port = parts + if port is not None and port != "*" and not _PORT.match(port): + if "*" in hostname: + raise ValueError(f"Invalid port in allowed_hosts pattern: {entry!r}") + return None + if hostname.startswith("["): + return _HostPattern(hostname.lower(), None, port) + wildcard: str | None = None + for marker in ("**.", "*."): + if hostname.startswith(marker): + wildcard, hostname = marker[:-1], hostname[len(marker) :] + break + if "*" in hostname: + raise ValueError( + f"Invalid allowed_hosts wildcard pattern: {entry!r}. Only a whole leftmost " + "label is supported: '*.example.com' (exactly one label) or " + "'**.example.com' (one or more labels)." + ) + if not hostname.isascii(): + raise ValueError( + f"allowed_hosts entry {entry!r} is not ASCII. Clients send internationalized " + "names as punycode; list the A-label form (xn--...) instead." + ) + hostname = _strip_root_dot(hostname.lower()) + if not _valid_labels(hostname.split(".")): + if wildcard is not None: + raise ValueError(f"Invalid allowed_hosts wildcard pattern: {entry!r}") + return None + if wildcard is not None and not _is_dev_hostname(hostname): + from adcp.signing.etld import registrable_domain + + if registrable_domain(hostname) is None: + raise ValueError( + f"allowed_hosts wildcard {entry!r} covers a public suffix ({hostname!r}), " + "so it would admit domains other parties register. Put the wildcard under " + "a domain you control, such as '*.agents.example.com'." + ) + return _HostPattern(hostname, wildcard, port) + + +class HostMatcher: + """Case-insensitive Host policy: exact, ``:*`` port, wildcard and callable. + + ``*.agents.example.com`` matches exactly one additional label + (``acme.agents.example.com``, like a TLS wildcard certificate); + ``**.agents.example.com`` matches one or more. Neither matches the apex + ``agents.example.com``, which must be listed on its own. A pattern without + a port matches only a Host without a port; ``serve`` and the factories + add a ``:*`` sibling for every port-less entry, so configured entries + accept any port unless they name one. + """ + + def __init__( + self, allowed_hosts: Sequence[str], validator: HostValidator | None = None + ) -> None: + patterns: list[_HostPattern] = [] + literals: set[str] = set() + for entry in allowed_hosts: + pattern = _compile_host_pattern(entry) + if pattern is None: + literals.add(entry.lower()) + else: + patterns.append(pattern) + self._patterns = tuple(patterns) + # Entries the parser cannot structure (e.g. a raw "::1") keep their + # pre-wildcard behaviour: an exact, now case-insensitive, match. + self._literal = frozenset(literals) + self._validator = validator + + def __call__(self, raw: str | None) -> bool: + parsed = normalize_request_host(raw) + if parsed is None: + return raw is not None and raw.lower() in self._literal + hostname, port = parsed + if any(pattern.matches(hostname, port) for pattern in self._patterns): + return True + if self._validator is None: + return False + try: + # Typed ``object``: adopters can return anything, including a coroutine. + result: object = self._validator(hostname) + except Exception: + logger.exception("host_validator raised for Host %r; rejecting", hostname) + return False + if inspect.isawaitable(result): + close = getattr(result, "close", None) + if callable(close): + close() + logger.error("host_validator returned an awaitable; it must be synchronous. Rejecting.") + return False + return result is True + + +def _is_dev_hostname(hostname: str) -> bool: + if hostname in {"localhost", "0.0.0.0"} or hostname.endswith(".localhost"): # nosec B104 + return True + if hostname.rsplit(".", 1)[-1] in {"test", "example", "invalid"}: + return True + try: + address = ipaddress.ip_address(hostname.strip("[]")) + except ValueError: + return False + return address.is_loopback or address.is_unspecified + + +def only_dev_hosts(allowed_hosts: Sequence[str]) -> bool: + """True when every ``allowed_hosts`` entry names a loopback or dev host. + + Dev hosts are ``localhost`` and ``*.localhost``, loopback and unspecified + IP literals, and the RFC 2606 reserved ``.test``, ``.example`` and + ``.invalid`` names. + """ + for entry in allowed_hosts: + parts = _split_host_port(entry.strip().lower()) + hostname = parts[0] if parts is not None else entry.strip().lower() + hostname = _strip_root_dot(hostname.removeprefix("**.").removeprefix("*.")) + if not _is_dev_hostname(hostname): + return False + return True + + +def _listener_may_be_public(bind_host: str | None) -> bool: + """Whether a listener on ``bind_host`` can receive non-loopback traffic. + + ``None`` means the address is unknown (an app the adopter serves itself), + which may be public. A non-loopback IP literal, including ``0.0.0.0`` and + ``::``, is public. A hostname is the operator's explicit choice of + interface, so it is not second-guessed. + """ + if bind_host is None: + return True + try: + return not ipaddress.ip_address(bind_host.strip().strip("[]")).is_loopback + except ValueError: + return False + + +def warn_if_host_policy_admits_only_dev_hosts( + settings: TransportSecuritySettings | None, *, bind_host: str | None +) -> bool: + """Log a WARNING when a possibly public listener will 421 every public Host. + + Fires when DNS-rebinding protection is on, no ``host_validator`` is set, + every ``allowed_hosts`` entry is a loopback/dev host, and ``bind_host`` is + unknown (``None``) or a non-loopback IP literal. Returns whether it warned. + """ + if settings is None or not settings.enable_dns_rebinding_protection: + return False + if getattr(settings, "host_validator", None) is not None: + return False + if not only_dev_hosts(settings.allowed_hosts): + return False + if not _listener_may_be_public(bind_host): + return False + where = ( + f"the server listens on {bind_host}" + if bind_host is not None + else "this app may be served on a public interface" + ) + logger.warning( + "DNS-rebinding protection is on and allowed_hosts admits only loopback/dev " + "hosts (%s), but %s. Requests addressed to any public hostname will get 421 " + "Misdirected Request on MCP, A2A and agent-card discovery. Pass " + "allowed_hosts=[...] (wildcards such as '*.agents.example.com' are supported) " + "or host_validator=..., or set enable_dns_rebinding_protection=False when " + "another layer validates Host.", + ", ".join(settings.allowed_hosts), + where, + ) + return True + + +#: Policies already judged in this process. The first judgement wins, so +#: ``serve()`` (which knows the listener) decides before the factories it +#: calls, and one policy warns at most once. +_HOST_POLICY_DECISIONS: dict[tuple[Any, ...], bool] = {} + + +def check_host_policy_once( + settings: TransportSecuritySettings | None, *, bind_host: str | None, http: bool = True +) -> bool: + """Apply :func:`warn_if_host_policy_admits_only_dev_hosts` once per policy. + + ``http=False`` (stdio) records the policy as judged without warning. + """ + if settings is None: + return False + validator = getattr(settings, "host_validator", None) + key = ( + settings.enable_dns_rebinding_protection, + tuple(settings.allowed_hosts), + None if validator is None else id(validator), + ) + if key in _HOST_POLICY_DECISIONS: + return False + warned = http and warn_if_host_policy_admits_only_dev_hosts(settings, bind_host=bind_host) + _HOST_POLICY_DECISIONS[key] = warned + return warned def transport_security_settings( allowed_hosts: Sequence[str] | None = None, allowed_origins: Sequence[str] | None = None, enable_dns_rebinding_protection: bool | None = None, + host_validator: HostValidator | None = None, ) -> HTTPTransportSecuritySettings: # Preserve the SDK's additive loopback defaults and bare-host expansion. from adcp.server.serve import _expand_allowed_hosts + if host_validator is not None: + if not callable(host_validator): + raise TypeError(f"host_validator must be callable, got {type(host_validator).__name__}") + if inspect.iscoroutinefunction(host_validator) or inspect.iscoroutinefunction( + getattr(host_validator, "__call__", None) + ): + raise TypeError( + "host_validator must be a synchronous callable returning bool; it runs on " + "every request before routing. Look tenants up from an in-memory cache." + ) + hosts = [*LOOPBACK_ALLOWED_HOSTS, *_expand_allowed_hosts(allowed_hosts or ())] + # Compile now so a malformed wildcard fails at configuration time. + HostMatcher(hosts) return HTTPTransportSecuritySettings( enable_dns_rebinding_protection=( True if enable_dns_rebinding_protection is None else enable_dns_rebinding_protection ), - allowed_hosts=[ - "127.0.0.1:*", - "localhost:*", - "[::1]:*", - *_expand_allowed_hosts(allowed_hosts or ()), - ], + allowed_hosts=hosts, allowed_origins=[ "http://127.0.0.1:*", "http://localhost:*", @@ -49,6 +389,7 @@ def transport_security_settings( *(allowed_origins or ()), ], explicit_origins=allowed_origins is not None, + host_validator=host_validator, ) @@ -58,8 +399,11 @@ class HostOriginMiddleware: Missing Origin is valid for native clients, including AgentCard discovery. Public discovery GET/HEAD requests bypass Origin checks; Host checks still apply. Protocol requests and operational endpoints retain Origin checks. - Matching follows MCP's exact-value and trailing ``:*`` port semantics; a - bare configured Host also accepts any port. Domain wildcards are not globbed. + Host matching is case-insensitive and follows :class:`HostMatcher`: exact + values, trailing ``:*`` port patterns, leftmost-label wildcards + (``*.example.com`` / ``**.example.com``) and an optional + ``host_validator`` callable. A bare configured Host also accepts any port. + Origins keep MCP's exact-value and ``:*`` port semantics. Inner instances skip a policy already checked by the assembled outer app. MCP's own Host/Origin check is disabled, retaining its content-type check. """ @@ -68,6 +412,8 @@ def __init__(self, app: ASGIApp, *, settings: TransportSecuritySettings | None) self.app = app self.settings = settings or TransportSecuritySettings(enable_dns_rebinding_protection=False) self.validator = TransportSecurityMiddleware(self.settings) + self.host_validator: HostValidator | None = getattr(self.settings, "host_validator", None) + self.host_matcher = HostMatcher(self.settings.allowed_hosts, self.host_validator) async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] != "http": @@ -79,11 +425,12 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: ) if scope.get("method") in {"GET", "HEAD"} and scope.get("path") in _PUBLIC_DISCOVERY_PATHS: check_origin = False - policy = ( + policy: tuple[Any, ...] = ( check_host, check_origin, tuple(self.settings.allowed_hosts), tuple(self.settings.allowed_origins), + self.host_validator, ) if scope.get("adcp.http_policy") != policy: request = Request(scope) @@ -91,7 +438,8 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: # protocol handlers to choose different effective values. hosts = request.headers.getlist("host") origins = request.headers.getlist("origin") - if check_host and (len(hosts) != 1 or not self.validator._validate_host(hosts[0])): + if check_host and (len(hosts) != 1 or not self.host_matcher(hosts[0])): + logger.warning("Rejected Host header %r with 421", hosts[:2]) await Response("Invalid Host header", status_code=421)(scope, receive, send) return if check_origin and ( diff --git a/src/adcp/server/serve.py b/src/adcp/server/serve.py index 4c57b3ccf..8cbc8726c 100644 --- a/src/adcp/server/serve.py +++ b/src/adcp/server/serve.py @@ -40,7 +40,12 @@ async def get_adcp_capabilities(self, params, context=None): from adcp.server._hooks import PreValidationHooks from adcp.server.base import ADCPHandler, ToolContext from adcp.server.helpers import ResponseEnhancer -from adcp.server.http_policy import HostOriginMiddleware, transport_security_settings +from adcp.server.http_policy import ( + HostOriginMiddleware, + HostValidator, + check_host_policy_once, + transport_security_settings, +) from adcp.server.implementation import ( ImplementationReport, ImplementationReporter, @@ -326,6 +331,8 @@ class ServeConfig: allowed_hosts: Sequence[str] | None = None allowed_origins: Sequence[str] | None = None enable_dns_rebinding_protection: bool | None = None + # Called with the normalized hostname when no allowed_hosts entry matches. + host_validator: HostValidator | None = None # --- Operational endpoints --- unauthenticated_routes: Sequence[Route | Mount] | None = None @@ -1048,6 +1055,7 @@ def serve( 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, request_signature_verification: RequestSignatureVerification | None = None, public_url: str | PublicUrlResolver | None = None, @@ -1414,6 +1422,7 @@ async def force_account_status(self, account_id, status): allowed_hosts = config.allowed_hosts allowed_origins = config.allowed_origins enable_dns_rebinding_protection = config.enable_dns_rebinding_protection + host_validator = config.host_validator mcp_result_text = config.mcp_result_text test_controller = config.test_controller context_factory = config.context_factory @@ -1533,6 +1542,20 @@ async def force_account_status(self, account_id, status): "Single-transport support is tracked as a follow-up to #709." ) + _warn_on_host_policy_misconfiguration( + allowed_hosts=allowed_hosts, + allowed_origins=allowed_origins, + enable_dns_rebinding_protection=enable_dns_rebinding_protection, + host_validator=host_validator, + # A2A always binds every interface; MCP paths honour host/ADCP_HOST. + bind_host=( + "0.0.0.0" # nosec B104 + if transport == "a2a" + else host or os.environ.get("ADCP_HOST") or "0.0.0.0" # nosec B104 + ), + http=transport != "stdio", + ) + if transport == "a2a": _serve_a2a( handler, @@ -1561,6 +1584,7 @@ async def force_account_status(self, account_id, status): allowed_hosts=allowed_hosts, allowed_origins=allowed_origins, enable_dns_rebinding_protection=enable_dns_rebinding_protection, + host_validator=host_validator, auth=auth, request_signature_verification=request_signature_verification, public_url=public_url, @@ -1598,6 +1622,7 @@ async def force_account_status(self, account_id, status): allowed_hosts=allowed_hosts, allowed_origins=allowed_origins, enable_dns_rebinding_protection=enable_dns_rebinding_protection, + host_validator=host_validator, auth=auth, request_signature_verification=request_signature_verification, ) @@ -1638,6 +1663,7 @@ async def force_account_status(self, account_id, status): allowed_hosts=allowed_hosts, allowed_origins=allowed_origins, enable_dns_rebinding_protection=enable_dns_rebinding_protection, + host_validator=host_validator, auth=auth, request_signature_verification=request_signature_verification, public_url=public_url, @@ -1649,6 +1675,30 @@ async def force_account_status(self, account_id, status): raise ValueError(f"Unknown transport {transport!r}. Valid: {valid}") +def _warn_on_host_policy_misconfiguration( + *, + allowed_hosts: Sequence[str] | None, + allowed_origins: Sequence[str] | None, + enable_dns_rebinding_protection: bool | None, + host_validator: HostValidator | None, + bind_host: str, + http: bool, +) -> None: + """Judge the Host policy with the real listener before the factories do.""" + if host_validator is not None and enable_dns_rebinding_protection is False: + logger.warning( + "host_validator is ignored because enable_dns_rebinding_protection=False " + "disables Host validation." + ) + check_host_policy_once( + transport_security_settings( + allowed_hosts, allowed_origins, enable_dns_rebinding_protection, host_validator + ), + bind_host=bind_host, + http=http, + ) + + def _prepend_debug_endpoint( asgi_middleware: Sequence[ASGIMiddlewareEntry] | None, *, @@ -2057,6 +2107,7 @@ def _serve_mcp( 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, request_signature_verification: RequestSignatureVerification | None = None, ) -> None: @@ -2085,6 +2136,7 @@ def _serve_mcp( allowed_hosts=allowed_hosts, allowed_origins=allowed_origins, enable_dns_rebinding_protection=enable_dns_rebinding_protection, + host_validator=host_validator, ) if test_controller is not None: @@ -2248,6 +2300,7 @@ def _build_a2a_app( 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, request_signature_verification: RequestSignatureVerification | None = None, public_url: str | PublicUrlResolver | None = None, @@ -2281,6 +2334,7 @@ def _build_a2a_app( allowed_hosts=allowed_hosts, allowed_origins=allowed_origins, enable_dns_rebinding_protection=enable_dns_rebinding_protection, + host_validator=host_validator, auth=auth, public_url=public_url, ) @@ -2311,7 +2365,7 @@ def _build_a2a_app( app = HostOriginMiddleware( app, settings=transport_security_settings( - allowed_hosts, allowed_origins, enable_dns_rebinding_protection + allowed_hosts, allowed_origins, enable_dns_rebinding_protection, host_validator ), ) return _apply_asgi_middleware(app, asgi_middleware) @@ -2345,6 +2399,7 @@ def _serve_a2a( 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, request_signature_verification: RequestSignatureVerification | None = None, public_url: str | PublicUrlResolver | None = None, @@ -2380,6 +2435,7 @@ def _serve_a2a( allowed_hosts=allowed_hosts, allowed_origins=allowed_origins, enable_dns_rebinding_protection=enable_dns_rebinding_protection, + host_validator=host_validator, auth=auth, request_signature_verification=request_signature_verification, public_url=public_url, @@ -2439,6 +2495,7 @@ def _build_mcp_and_a2a_app( 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, request_signature_verification: RequestSignatureVerification | None = None, public_url: str | PublicUrlResolver | None = None, @@ -2490,6 +2547,7 @@ def _build_mcp_and_a2a_app( allowed_hosts=allowed_hosts, allowed_origins=allowed_origins, enable_dns_rebinding_protection=enable_dns_rebinding_protection, + host_validator=host_validator, ) if test_controller is not None: from adcp.server.test_controller import register_test_controller @@ -2551,6 +2609,7 @@ def _build_mcp_and_a2a_app( allowed_hosts=allowed_hosts, allowed_origins=allowed_origins, enable_dns_rebinding_protection=enable_dns_rebinding_protection, + host_validator=host_validator, auth=auth, public_url=public_url, ) @@ -2676,6 +2735,7 @@ def _serve_mcp_and_a2a( 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, request_signature_verification: RequestSignatureVerification | None = None, public_url: str | PublicUrlResolver | None = None, @@ -2746,6 +2806,7 @@ def _serve_mcp_and_a2a( allowed_hosts=allowed_hosts, allowed_origins=allowed_origins, enable_dns_rebinding_protection=enable_dns_rebinding_protection, + host_validator=host_validator, auth=auth, request_signature_verification=request_signature_verification, public_url=public_url, @@ -2861,6 +2922,7 @@ def create_mcp_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, ) -> Any: """Create a FastMCP server from an ADCP handler without starting it. @@ -3060,13 +3122,11 @@ def create_mcp_server( else: object.__setattr__(mcp.settings, "json_response", False) object.__setattr__(mcp.settings, "stateless_http", stateless_http) - object.__setattr__( - mcp.settings, - "transport_security", - transport_security_settings( - allowed_hosts, allowed_origins, enable_dns_rebinding_protection - ), + security_settings = transport_security_settings( + allowed_hosts, allowed_origins, enable_dns_rebinding_protection, host_validator ) + check_host_policy_once(security_settings, bind_host=resolved_host) + object.__setattr__(mcp.settings, "transport_security", security_settings) object.__setattr__(mcp.settings, "session_idle_timeout", session_idle_timeout) object.__setattr__(mcp.settings, "max_active_sessions", max_active_sessions) object.__setattr__(mcp.settings, "retry_interval", None) diff --git a/src/adcp/testing/decisioning.py b/src/adcp/testing/decisioning.py index 7ff22c489..a90a38741 100644 --- a/src/adcp/testing/decisioning.py +++ b/src/adcp/testing/decisioning.py @@ -50,6 +50,7 @@ ) from adcp.server.auth import BearerTokenAuth from adcp.server.helpers import ResponseEnhancer + from adcp.server.http_policy import HostValidator from adcp.server.serve import ( ASGIMiddlewareEntry, ContextFactory, @@ -160,6 +161,7 @@ def build_asgi_app( session_idle_timeout: float | None = 1800.0, max_active_sessions: int | None = None, enable_dns_rebinding_protection: bool | None = None, + host_validator: HostValidator | None = None, max_request_size: int | None = None, validation: ValidationHookConfig | None = DEFAULT_VALIDATION, discovery_base_url: str | None = None, @@ -218,7 +220,8 @@ def build_asgi_app( (``localhost``, ``127.0.0.1``, ``[::1]``). Pass the hostname embedded in your ``base_url`` when using a non-loopback test address (e.g. ``["test"]`` for ``base_url="http://test"``). - :func:`build_test_client` sets this automatically. + :func:`build_test_client` sets this automatically. Entries may + be leftmost-label wildcards (``"*.agents.example"``). :param allowed_origins: CORS origin allowlist forwarded to :func:`create_mcp_server`. ``None`` → FastMCP default (no CORS). :param auth: Optional :class:`~adcp.server.auth.BearerTokenAuth` @@ -247,6 +250,8 @@ def build_asgi_app( ``"a2a"``. :param enable_dns_rebinding_protection: Forwarded to :func:`create_mcp_server`. ``None`` → FastMCP default. + :param host_validator: Optional ``(hostname) -> bool`` callable + consulted when the Host matches no ``allowed_hosts`` entry. :param max_request_size: Request body size cap in bytes. ``None`` → the framework default (10 MB). ``0`` → disabled. :param validation: Schema validation config forwarded to @@ -309,6 +314,7 @@ def build_asgi_app( ) from adcp.decisioning.serve import create_adcp_server_from_platform + from adcp.server.http_policy import check_host_policy_once, transport_security_settings from adcp.server.serve import ( _apply_asgi_middleware, _build_a2a_app, @@ -319,6 +325,14 @@ def build_asgi_app( create_mcp_server, ) + # The caller serves the returned app, so the listener is unknown. Judge the + # Host policy before the transports below, whose bind defaults are placeholders. + check_host_policy_once( + transport_security_settings( + allowed_hosts, allowed_origins, enable_dns_rebinding_protection, host_validator + ), + bind_host=None, + ) handler, _executor, _registry = create_adcp_server_from_platform( platform, advertise_all=advertise_all, @@ -354,6 +368,7 @@ def build_asgi_app( allowed_hosts=allowed_hosts, allowed_origins=allowed_origins, enable_dns_rebinding_protection=enable_dns_rebinding_protection, + host_validator=host_validator, unauthenticated_routes=unauthenticated_routes, auth=auth, on_startup=on_startup, @@ -382,6 +397,7 @@ def build_asgi_app( allowed_hosts=allowed_hosts, allowed_origins=allowed_origins, enable_dns_rebinding_protection=enable_dns_rebinding_protection, + host_validator=host_validator, unauthenticated_routes=unauthenticated_routes, auth=auth, include_discovery=discovery_base_url is not None, @@ -399,6 +415,7 @@ def build_asgi_app( session_idle_timeout=session_idle_timeout, max_active_sessions=max_active_sessions, enable_dns_rebinding_protection=enable_dns_rebinding_protection, + host_validator=host_validator, validation=validation, pre_validation_hooks=pre_validation_hooks, response_enhancer=response_enhancer, diff --git a/tests/test_host_policy_wildcards.py b/tests/test_host_policy_wildcards.py new file mode 100644 index 000000000..906172c9f --- /dev/null +++ b/tests/test_host_policy_wildcards.py @@ -0,0 +1,569 @@ +"""Wildcard and callable Host policy, plus the loopback-only startup warning (#2010).""" + +from __future__ import annotations + +import importlib +import logging +from typing import Any +from unittest.mock import patch + +import pytest +from starlette.testclient import TestClient + +from adcp.server import ADCPHandler, ServeConfig, create_a2a_server, create_mcp_server, http_policy +from adcp.server.http_policy import ( + HostMatcher, + check_host_policy_once, + normalize_request_host, + only_dev_hosts, + transport_security_settings, + warn_if_host_policy_admits_only_dev_hosts, +) +from adcp.server.serve import _build_a2a_app, _build_mcp_and_a2a_app + +_serve_mod = importlib.import_module("adcp.server.serve") +POLICY_LOGGER = "adcp.server.http_policy" + + +def matcher(*hosts: str, validator: Any = None) -> HostMatcher: + """Build the matcher exactly as the transports do (loopback + bare-host expansion).""" + settings = transport_security_settings(list(hosts), host_validator=validator) + return HostMatcher(settings.allowed_hosts, settings.host_validator) + + +# --------------------------------------------------------------------------- +# Wildcard matching +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "host,allowed", + [ + ("acme.agents.example.com", True), + ("acme.agents.example.com:8443", True), + ("ACME.Agents.Example.COM", True), + ("Acme.AGENTS.example.com:443", True), + ("xn--bcher-kva.agents.example.com", True), # punycode label + ("t-1.agents.example.com", True), + # The apex is never implied by the wildcard. + ("agents.example.com", False), + ("agents.example.com:8443", False), + # '*' covers exactly one label. + ("a.b.agents.example.com", False), + # Suffix confusion. + ("evilagents.example.com", False), + ("acme.agents.example.com.evil.com", False), + ("acme.agents.example.co", False), + ("agents.example.com.acme", False), + # One trailing dot (the absolute FQDN form) names the same host. + ("acme.agents.example.com.", True), + ("acme.agents.example.com.:8443", True), + ("acme.agents.example.com..", False), + ("agents.example.com.", False), + # Empty and malformed labels. + (".agents.example.com", False), + ("..agents.example.com", False), + ("-acme.agents.example.com", False), + ("acme-.agents.example.com", False), + ("a" * 64 + ".agents.example.com", False), + # Userinfo, paths and other smuggling. + ("user@acme.agents.example.com", False), + ("acme.agents.example.com@evil.com", False), + ("evil.com@acme.agents.example.com", False), + ("acme.agents.example.com/evil", False), + ("evil.com/.agents.example.com", False), + ("evil.com?.agents.example.com", False), + ("evil.com#.agents.example.com", False), + ("evil.com\\.agents.example.com", False), + ("acme.agents.example.com evil", False), + ("acme.agents.example.com%2f", False), + ("*.agents.example.com", False), + # Raw (non-punycode) IDN never reaches the pattern. + ("bücher.agents.example.com", False), + # Ports must be a valid decimal port. + ("acme.agents.example.com:", False), + ("acme.agents.example.com:abc", False), + ("acme.agents.example.com:0", False), + ("acme.agents.example.com:65536", False), + ("acme.agents.example.com:80:80", False), + ("", False), + ], +) +def test_single_label_wildcard(host: str, allowed: bool) -> None: + assert matcher("*.agents.example.com")(host) is allowed + + +def test_apex_matches_only_when_listed() -> None: + m = matcher("*.agents.example.com", "agents.example.com") + assert m("agents.example.com") + assert m("agents.example.com:443") + assert m("acme.agents.example.com") + + +@pytest.mark.parametrize( + "host,allowed", + [ + ("acme.agents.example.com", True), + ("a.b.agents.example.com", True), + ("A.B.C.agents.example.com:8443", True), + ("agents.example.com", False), + ("a..b.agents.example.com", False), + ("a.b.agents.example.com.", True), + ("a.b.agents.example.com..", False), + ("x.evilagents.example.com", False), + ], +) +def test_multi_label_wildcard(host: str, allowed: bool) -> None: + assert matcher("**.agents.example.com")(host) is allowed + + +@pytest.mark.parametrize( + "pattern,host,allowed", + [ + ("*.agents.example.com:8443", "acme.agents.example.com:8443", True), + ("*.agents.example.com:8443", "acme.agents.example.com:9443", False), + ("*.agents.example.com:8443", "acme.agents.example.com", False), + ("*.agents.example.com:*", "acme.agents.example.com:1", True), + # ':*' requires a port; the bare form is only added for bare entries. + ("*.agents.example.com:*", "acme.agents.example.com", False), + ], +) +def test_wildcard_ports(pattern: str, host: str, allowed: bool) -> None: + assert matcher(pattern)(host) is allowed + + +def test_punycode_pattern_matches_and_unicode_entries_are_refused() -> None: + m = matcher("*.xn--bcher-kva.example") + assert m("shop.xn--bcher-kva.example") + assert not m("shop.bücher.example") + # IDNA 2003 would map "faß" to "fass", a different domain: refuse instead. + for entry in ("*.bücher.example", "faß.example.de", "*.faß.example.de"): + with pytest.raises(ValueError, match="punycode"): + transport_security_settings([entry]) + + +@pytest.mark.parametrize("pattern", ["*.com", "**.com", "*.co.uk", "**.github.io", "*.fly.dev"]) +def test_wildcards_over_a_public_suffix_are_refused(pattern: str) -> None: + with pytest.raises(ValueError, match="public suffix"): + transport_security_settings([pattern]) + + +@pytest.mark.parametrize( + "pattern,host", + [ + ("*.localhost", "acme.localhost:3000"), + ("*.test", "acme.test"), + ("*.example", "acme.example"), + ("*.example.co.uk", "acme.example.co.uk"), + ("*.acme.github.io", "eu.acme.github.io"), + ], +) +def test_wildcards_under_a_registrable_or_dev_domain_compile(pattern: str, host: str) -> None: + assert matcher(pattern)(host) + + +def test_exact_hosts_are_case_insensitive_and_strict() -> None: + m = matcher("Seller.Example") + assert m("seller.example") + assert m("SELLER.EXAMPLE:443") + assert m("seller.example.") + assert m("seller.example.:8443") + assert not m("seller.example..") + assert not m("www.seller.example") + assert not m("seller.example:443@evil.example") + + +@pytest.mark.parametrize("entry", ["example.com.", "example.com"]) +@pytest.mark.parametrize( + "host", ["example.com", "example.com.", "example.com:8080", "example.com.:8080"] +) +def test_trailing_dot_is_stripped_from_entries_and_hosts(entry: str, host: str) -> None: + # MCP's literal matcher accepted "example.com.:8080" for an "example.com." entry. + assert matcher(entry)(host) + + +def test_trailing_dot_wildcard_entry() -> None: + m = matcher("*.agents.example.com.") + assert m("acme.agents.example.com") + assert m("acme.agents.example.com.:443") + assert not m("agents.example.com.") + + +def test_loopback_defaults_remain() -> None: + m = matcher() + for host in ("localhost:3001", "127.0.0.1:8000", "[::1]:8000", "LOCALHOST:1"): + assert m(host), host + # Unchanged from MCP's defaults: the loopback entries are ':*' patterns. + assert not m("localhost") + assert not m("evil.example") + assert not m("localhost.evil.example") + assert not m("[::2]:8000") + + +@pytest.mark.parametrize( + "pattern", + [ + "*", + "**", + "*.", + "*:*", + "foo*.example.com", + "*foo.example.com", + "a.*.example.com", + "*.*.example.com", + "***.example.com", + "*.example.com:abc", + "*.-bad.example.com", + "*.example..com", + ], +) +def test_malformed_wildcards_fail_at_configuration(pattern: str) -> None: + with pytest.raises(ValueError): + transport_security_settings([pattern]) + with pytest.raises(ValueError): + create_mcp_server(Seller(), allowed_hosts=[pattern]) + + +def test_normalize_request_host() -> None: + assert normalize_request_host("Acme.Example:8443") == ("acme.example", "8443") + assert normalize_request_host("[::1]:80") == ("[::1]", "80") + assert normalize_request_host("[::1]") == ("[::1]", None) + assert normalize_request_host("[not-ipv6]:80") is None + assert normalize_request_host("::1") is None + assert normalize_request_host(None) is None + + +# --------------------------------------------------------------------------- +# host_validator callable +# --------------------------------------------------------------------------- + + +def test_validator_receives_normalized_hostname_and_is_fallback_only() -> None: + seen: list[str] = [] + + def validator(host: str) -> bool: + seen.append(host) + return host.endswith(".tenants.example.net") + + m = matcher("seller.example", validator=validator) + assert m("seller.example") # list match, validator not consulted + assert seen == [] + assert m("Acme.Tenants.Example.NET:8443") + assert seen == ["acme.tenants.example.net"] + assert not m("acme.other.example") + # Malformed values never reach the callable. + seen.clear() + for bad in ("u@acme.tenants.example.net", "acme.tenants.example.net..", "a/b", ""): + assert not m(bad) + assert seen == [] + assert m("acme.tenants.example.net.") + assert seen == ["acme.tenants.example.net"] + + +def test_validator_exception_rejects(caplog: pytest.LogCaptureFixture) -> None: + def validator(host: str) -> bool: + raise RuntimeError("tenant lookup down") + + with caplog.at_level(logging.ERROR, logger=POLICY_LOGGER): + assert not matcher(validator=validator)("acme.example") + assert "host_validator raised" in caplog.text + + +def test_validator_must_be_callable() -> None: + with pytest.raises(TypeError): + transport_security_settings(host_validator="acme.example") # type: ignore[arg-type] + + +def test_async_validators_are_refused_at_configuration() -> None: + async def lookup(host: str) -> bool: + return True + + class AsyncLookup: + async def __call__(self, host: str) -> bool: + return True + + for validator in (lookup, AsyncLookup()): + with pytest.raises(TypeError, match="synchronous"): + transport_security_settings(host_validator=validator) # type: ignore[arg-type] + with pytest.raises(TypeError, match="synchronous"): + create_mcp_server(Seller(), host_validator=validator) # type: ignore[arg-type] + + +@pytest.mark.parametrize("result", ["yes", 1, ["acme"], object(), None, False]) +def test_only_true_admits(result: Any) -> None: + assert not matcher(validator=lambda host: result)("acme.example") + + +def test_awaitable_result_is_rejected_and_closed(caplog: pytest.LogCaptureFixture) -> None: + async def lookup() -> bool: + return True + + created: list[Any] = [] + + def sneaky(host: str) -> Any: + coro = lookup() + created.append(coro) + return coro + + with caplog.at_level(logging.ERROR, logger=POLICY_LOGGER): + assert not matcher(validator=sneaky)("acme.example") + assert "must be synchronous" in caplog.text + assert created[0].cr_frame is None # closed, so no "never awaited" warning + + +# --------------------------------------------------------------------------- +# End-to-end through every transport +# --------------------------------------------------------------------------- + + +class Seller(ADCPHandler): + advertised_tools = {"get_products"} + + async def get_products(self, params, context=None): + return {"products": []} + + +HEADERS = {"accept": "application/json, text/event-stream"} +INIT = { + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "policy-test", "version": "1"}, + }, +} + + +def build(transport: str, **policy: Any) -> Any: + seller = Seller() + if transport == "mcp": + return create_mcp_server(seller, validation=None, **policy).streamable_http_app() + if transport == "direct-a2a": + return create_a2a_server(seller, validation=None, **policy) + if transport == "a2a": + return _build_a2a_app( + seller, name="test", port=3001, test_controller=None, validation=None, **policy + ) + return _build_mcp_and_a2a_app( + seller, + name="test", + port=3001, + host="127.0.0.1", + instructions=None, + test_controller=None, + validation=None, + **policy, + ) + + +def probe(client: TestClient, transport: str, host: str) -> int: + if transport == "mcp": + return client.post("/mcp", json=INIT, headers={**HEADERS, "host": host}).status_code + return client.get("/.well-known/agent-card.json", headers={"host": host}).status_code + + +@pytest.mark.parametrize("transport", ["mcp", "a2a", "both", "direct-a2a"]) +def test_wildcard_and_validator_through_transports(transport: str) -> None: + app = build( + transport, + allowed_hosts=["*.agents.example.com"], + host_validator=lambda host: host == "partner.example.net", + ) + with TestClient(app, base_url="http://localhost:3001") as client: + assert probe(client, transport, "acme.agents.example.com") == 200 + assert probe(client, transport, "ACME.agents.example.com:8443") == 200 + assert probe(client, transport, "partner.example.net") == 200 + assert probe(client, transport, "agents.example.com") == 421 + assert probe(client, transport, "a.b.agents.example.com") == 421 + assert probe(client, transport, "acme.agents.example.com.") == 200 + assert probe(client, transport, "acme.agents.example.com..") == 421 + assert probe(client, transport, "evil.example") == 421 + + +def test_validator_is_inert_when_protection_disabled() -> None: + calls: list[str] = [] + app = build( + "both", + enable_dns_rebinding_protection=False, + host_validator=lambda host: calls.append(host) or False, + ) + with TestClient(app, base_url="http://localhost:3001") as client: + assert probe(client, "both", "anything.example") == 200 + assert calls == [] + + +def test_serve_config_carries_host_validator() -> None: + def validator(host: str) -> bool: + return True + + cfg = ServeConfig(transport="streamable-http", host_validator=validator) + with patch.object(_serve_mod, "_serve_mcp") as mock_mcp: + _serve_mod.serve(Seller(), config=cfg) + assert mock_mcp.call_args.kwargs["host_validator"] is validator + + +# --------------------------------------------------------------------------- +# Startup warning +# --------------------------------------------------------------------------- + +WARNING_TEXT = "admits only loopback/dev hosts" + + +@pytest.fixture(autouse=True) +def _fresh_policy_decisions(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(http_policy, "_HOST_POLICY_DECISIONS", {}) + monkeypatch.delenv("ADCP_HOST", raising=False) + + +@pytest.mark.parametrize( + "hosts,expected", + [ + ([], True), + (["127.0.0.1:*", "localhost:*", "[::1]:*"], True), + (["acme.localhost", "*.localhost", "0.0.0.0", "127.0.0.2:8000", "x.localhost."], True), + (["seller.test", "seller.example", "x.invalid"], True), + (["seller.example.com"], False), + (["*.agents.example.com"], False), + (["localhost", "seller.example.com"], False), + ], +) +def test_only_dev_hosts(hosts: list[str], expected: bool) -> None: + assert only_dev_hosts(hosts) is expected + + +@pytest.mark.parametrize( + "kwargs,bind,warns", + [ + ({}, "0.0.0.0", True), + ({}, "::", True), + ({}, "[::]", True), + ({}, "10.0.0.5", True), + ({}, None, True), # unknown listener: an app the adopter serves itself + ({"allowed_hosts": ["acme.localhost"]}, "0.0.0.0", True), + ({}, "127.0.0.1", False), + ({}, "::1", False), + # A hostname is the operator's explicit interface choice. + ({}, "localhost", False), + ({}, "my-laptop", False), + ({}, "seller.internal", False), + ({"allowed_hosts": ["seller.example.com"]}, "0.0.0.0", False), + ({"allowed_hosts": ["*.agents.example.com"]}, None, False), + ({"host_validator": lambda host: True}, "0.0.0.0", False), + ({"enable_dns_rebinding_protection": False}, "0.0.0.0", False), + ], +) +def test_loopback_only_warning( + kwargs: dict[str, Any], bind: str | None, warns: bool, caplog: pytest.LogCaptureFixture +) -> None: + with caplog.at_level(logging.WARNING, logger=POLICY_LOGGER): + result = warn_if_host_policy_admits_only_dev_hosts( + transport_security_settings(**kwargs), bind_host=bind + ) + assert result is warns + assert ("421 Misdirected Request" in caplog.text) is warns + + +def test_warning_fires_once_per_policy(caplog: pytest.LogCaptureFixture) -> None: + settings = transport_security_settings() + with caplog.at_level(logging.WARNING, logger=POLICY_LOGGER): + assert check_host_policy_once(settings, bind_host="0.0.0.0") + assert not check_host_policy_once(settings, bind_host="0.0.0.0") + assert not check_host_policy_once(transport_security_settings(), bind_host=None) + assert caplog.text.count(WARNING_TEXT) == 1 + + +def _warned(caplog: pytest.LogCaptureFixture) -> bool: + return WARNING_TEXT in caplog.text + + +def test_create_mcp_server_warns_for_a_public_bind(caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.WARNING, logger=POLICY_LOGGER): + create_mcp_server(Seller(), validation=None) + assert _warned(caplog) + assert "listens on 0.0.0.0" in caplog.text + + +def test_create_mcp_server_quiet_for_loopback_or_hostname_bind( + caplog: pytest.LogCaptureFixture, +) -> None: + with caplog.at_level(logging.WARNING, logger=POLICY_LOGGER): + create_mcp_server(Seller(), validation=None, host="127.0.0.1") + create_mcp_server(Seller(), validation=None, host="my-laptop", allowed_hosts=["x.test"]) + create_mcp_server(Seller(), validation=None, allowed_hosts=["seller.example.com"]) + assert not _warned(caplog) + + +def test_create_a2a_server_warns(caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.WARNING, logger=POLICY_LOGGER): + create_a2a_server(Seller(), validation=None) + assert _warned(caplog) + assert "may be served on a public interface" in caplog.text + + +@pytest.mark.parametrize("transport", ["mcp", "a2a", "both"]) +def test_build_asgi_app_warns(transport: str, caplog: pytest.LogCaptureFixture) -> None: + from adcp.testing import build_asgi_app + from tests.test_testing_decisioning import _SalesPlatformWithMethods + + with caplog.at_level(logging.WARNING, logger=POLICY_LOGGER): + build_asgi_app(_SalesPlatformWithMethods(), transport=transport) # type: ignore[arg-type] + assert _warned(caplog) + + +@pytest.mark.parametrize( + "transport,target", + [ + ("streamable-http", "_serve_mcp"), + ("sse", "_serve_mcp"), + ("a2a", "_serve_a2a"), + ("both", "_serve_mcp_and_a2a"), + ], +) +def test_serve_logs_startup_warning( + transport: str, target: str, caplog: pytest.LogCaptureFixture +) -> None: + with caplog.at_level(logging.WARNING, logger=POLICY_LOGGER): + with patch.object(_serve_mod, target): + _serve_mod.serve(Seller(), transport=transport) + assert "listens on 0.0.0.0" in caplog.text + + +def test_serve_decides_before_its_factories(caplog: pytest.LogCaptureFixture) -> None: + """A loopback serve() is not contradicted by the A2A factory's unknown listener.""" + with caplog.at_level(logging.WARNING, logger=POLICY_LOGGER): + with patch.object(_serve_mod, "_serve_mcp_and_a2a"): + _serve_mod.serve(Seller(), transport="both", host="127.0.0.1") + build("both") + assert not _warned(caplog) + + +def test_serve_skips_warning_for_loopback_bind_and_stdio( + caplog: pytest.LogCaptureFixture, +) -> None: + with caplog.at_level(logging.WARNING, logger=POLICY_LOGGER): + with patch.object(_serve_mod, "_serve_mcp"): + _serve_mod.serve(Seller(), transport="stdio") + # stdio judged the policy: its own MCP factory stays quiet. + create_mcp_server(Seller(), validation=None) + assert not _warned(caplog) + http_policy._HOST_POLICY_DECISIONS.clear() + with caplog.at_level(logging.WARNING, logger=POLICY_LOGGER): + with patch.object(_serve_mod, "_serve_mcp"): + _serve_mod.serve(Seller(), transport="streamable-http", host="127.0.0.1") + assert not _warned(caplog) + + +def test_serve_warns_validator_ignored_without_protection( + caplog: pytest.LogCaptureFixture, +) -> None: + with caplog.at_level(logging.WARNING, logger="adcp.server"): + with patch.object(_serve_mod, "_serve_mcp"): + _serve_mod.serve( + Seller(), + transport="streamable-http", + enable_dns_rebinding_protection=False, + host_validator=lambda host: True, + ) + assert "host_validator is ignored" in caplog.text