Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(mcp): parse the Host header before trusting it for the OAuth origin
krisztian-gajdar604449a4a435
diff --git a/packages/sie_mcp/src/sie_mcp/auth.py b/packages/sie_mcp/src/sie_mcp/auth.pyindex 5d671ef3c..322884d05 100644--- a/packages/sie_mcp/src/sie_mcp/auth.py+++ b/packages/sie_mcp/src/sie_mcp/auth.py@@ -9,6 +9,7 @@ Implemented as pure ASGI (not ``BaseHTTPMiddleware``) so it does not buffer thestreaming MCP responses."""+import refrom typing import Anyfrom starlette.datastructures import Headers@@ -35,19 +36,48 @@ _EXEMPT_PATHS = frozenset(_LOOPBACK_HOSTNAMES = frozenset({"localhost", "127.0.0.1", "[::1]"})+_MAX_PORT = 65535++# RFC 9110 s7.2: a Host header is "uri-host [ ':' port ]" and carries no userinfo,+# path, query, or fragment.+_HOST_RE = re.compile(+ r"""+ \A+ (?:+ \[(?P<ipv6>[0-9a-f:.]+)\]+ | (?P<regname>[0-9a-z._~!$&'()*+,;=%-]+)+ )+ (?::(?P<port>[0-9]{1,5}))?+ \Z+ """,+ re.VERBOSE,+)-def _hostname(host: str) -> str:- if host.startswith("["):- return host[: host.find("]") + 1]- return host.rsplit(":", 1)[0]++def _split_host_port(host: str) -> tuple[str, str | None] | None:+ """Split a lowercased ``Host`` into ``(hostname, port)``, or ``None`` if malformed."""+ match = _HOST_RE.fullmatch(host)+ if match is None:+ return None+ port = match["port"]+ if port is not None and not 1 <= int(port) <= _MAX_PORT:+ return None+ ipv6 = match["ipv6"]+ return (f"[{ipv6}]" if ipv6 is not None else match["regname"]), portdef _host_trusted(config: MCPConfig, host: str) -> bool:host = host.lower()- if _hostname(host) in _LOOPBACK_HOSTNAMES:+ parsed = _split_host_port(host)+ if parsed is None:+ return False+ hostname, port = parsed+ if hostname in _LOOPBACK_HOSTNAMES:return Truefor allowed in (entry.lower() for entry in config.allowed_hosts):- if host == allowed or (allowed.endswith(":*") and host.startswith(allowed[:-1])):+ if host == allowed:+ return True+ if allowed.endswith(":*") and port is not None and hostname == allowed[:-2]:return Truereturn Falsediff --git a/packages/sie_mcp/tests/test_auth.py b/packages/sie_mcp/tests/test_auth.pyindex 6f4809361..d38c256f6 100644--- a/packages/sie_mcp/tests/test_auth.py+++ b/packages/sie_mcp/tests/test_auth.py@@ -1,4 +1,5 @@from typing import Any+from urllib.parse import urlsplitimport pytestfrom sie_mcp.auth import ConnectorSecretAuthMiddleware, authenticate, base_url, bearer_token@@ -139,6 +140,63 @@ def test_base_url_refuses_untrusted_host(host: str) -> None:assert base_url(cfg, scheme="https", headers=Headers({"host": host})) is None+ "host",+ [+ # Extra authority after the port.+ "edge.example.com:[email protected]",+ "edge.example.com:8443/evil",+ # Not ports.+ "edge.example.com:99999",+ "edge.example.com:0",+ "edge.example.com:abc",+ "edge.example.com:",+ ],+)+def test_base_url_refuses_wildcard_host_without_a_valid_port(host: str) -> None:+ cfg = _cfg(public_base_url=None, allowed_hosts=["edge.example.com:*"])+ assert base_url(cfg, scheme="https", headers=Headers({"host": host})) is None+++ "host",+ [+ # Loopback is trusted without configuration, so a Host that merely starts+ # with a loopback name must not inherit that trust.+ "localhost:[email protected]",+ "127.0.0.1:[email protected]",+ "[::1]@evil.attacker.example",+ "[::1]:[email protected]",+ "[::1].evil.attacker.example",+ "localhost:8088/evil",+ "localhost:99999",+ ],+)+def test_base_url_refuses_loopback_lookalike_hosts(host: str) -> None:+ cfg = _cfg(public_base_url=None, allowed_hosts=[])+ assert base_url(cfg, scheme="https", headers=Headers({"host": host})) is None+++ "host",+ [+ "edge.example.com:8443",+ "edge.example.com:[email protected]",+ "edge.example.com:8443/evil",+ "evil.attacker.example",+ ],+)+def test_advertised_origin_never_resolves_to_an_unconfigured_host(host: str) -> None:+ """Whatever is advertised must parse back to a host the operator configured."""+ cfg = _cfg(public_base_url=None, allowed_hosts=["edge.example.com:*"])+ origin = base_url(cfg, scheme="https", headers=Headers({"host": host}))+ if origin is None:+ return+ metadata = f"{origin}/.well-known/oauth-protected-resource"+ assert urlsplit(metadata).hostname == "edge.example.com"+ assert urlsplit(metadata).path == "/.well-known/oauth-protected-resource"++@pytest.mark.parametrize(("host", "expected"),[