-
Notifications
You must be signed in to change notification settings - Fork 74
fix(mcp): validate Host and Origin headers on the HTTP transport #1120
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Pablo (pablo-airbyte)
wants to merge
6
commits into
main
Choose a base branch
from
devin/1787620448-mcp-host-origin-guard
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
c272d49
fix: guard MCP HTTP host and origin headers
pablo-airbyte aca0a85
test: assert host/origin guard wraps the HTTP app
pablo-airbyte bc59c43
test: drop unreachable return in lifespan test app
pablo-airbyte 8654bfd
fix: avoid CodeQL URL substring alert
pablo-airbyte 2c64f45
fix: reject duplicate MCP Host headers
pablo-airbyte e6f4a5f
docs(mcp): clarify allowed hosts ignore ports
pablo-airbyte File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| # Copyright (c) 2025 Airbyte, Inc., all rights reserved. | ||
| """ASGI transport security for the HTTP MCP server.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import fnmatch | ||
| import ipaddress | ||
| import os | ||
| from typing import TYPE_CHECKING | ||
| from urllib.parse import urlparse | ||
|
|
||
| from starlette.responses import Response | ||
|
|
||
|
|
||
| if TYPE_CHECKING: | ||
| from collections.abc import Sequence | ||
|
|
||
| from starlette.types import ASGIApp, Receive, Scope, Send | ||
|
|
||
|
|
||
| ALLOWED_HOSTS_ENV = "AIRBYTE_MCP_ALLOWED_HOSTS" | ||
| HTTP_HOST_ENV = "AIRBYTE_MCP_HTTP_HOST" | ||
|
|
||
| _DEFAULT_ALLOWED_HOSTS = ("127.0.0.1", "localhost", "::1") | ||
|
|
||
|
|
||
| def _strip_host_port(value: str) -> str: | ||
| """Normalize a host or host pattern for comparison.""" | ||
| normalized = value.strip().lower() | ||
| if normalized.startswith("["): | ||
| closing_bracket = normalized.find("]") | ||
| if closing_bracket != -1: | ||
| return normalized[1:closing_bracket] | ||
| if normalized.count(":") == 1: | ||
| return normalized.rsplit(":", 1)[0] | ||
| return normalized | ||
|
|
||
|
|
||
| def _is_unspecified_address(hostname: str) -> bool: | ||
| try: | ||
| return ipaddress.ip_address(hostname).is_unspecified | ||
| except ValueError: | ||
| return False | ||
|
|
||
|
|
||
| def resolve_allowed_hosts(server_url: str) -> tuple[str, ...]: | ||
| """Resolve allowed hostnames from defaults, the server URL, and the environment.""" | ||
| resolved: list[str] = [] | ||
| seen: set[str] = set() | ||
|
|
||
| def add(host: str) -> None: | ||
| cleaned = host.strip() | ||
| if not cleaned: | ||
| return | ||
| key = _strip_host_port(cleaned) | ||
| if key and key not in seen: | ||
| resolved.append(cleaned) | ||
| seen.add(key) | ||
|
|
||
| for host in _DEFAULT_ALLOWED_HOSTS: | ||
| add(host) | ||
|
|
||
| hostname = urlparse(server_url).hostname | ||
| if hostname and not _is_unspecified_address(hostname): | ||
| add(hostname) | ||
|
|
||
| for host in os.getenv(ALLOWED_HOSTS_ENV, "").split(","): | ||
| add(host) | ||
|
|
||
| return tuple(resolved) | ||
|
|
||
|
|
||
| def _request_host(scope: Scope) -> str | None: | ||
| hosts = [ | ||
| value.decode("latin-1") | ||
| for name, value in scope.get("headers", []) | ||
| if name.lower() == b"host" | ||
| ] | ||
| if len(hosts) != 1: | ||
| return None | ||
| return _strip_host_port(hosts[0]) or None | ||
|
|
||
|
|
||
| def _origin_hosts(scope: Scope) -> tuple[str | None, ...]: | ||
| origins: list[str | None] = [] | ||
| for name, value in scope.get("headers", []): | ||
| if name.lower() == b"origin": | ||
| origin = value.decode("latin-1").strip() | ||
| try: | ||
| hostname = urlparse(origin).hostname | ||
| except ValueError: | ||
| origins.append(None) | ||
| else: | ||
| origins.append(_strip_host_port(hostname) if hostname else None) | ||
| return tuple(origins) | ||
|
|
||
|
|
||
| class HostOriginGuardMiddleware: | ||
| """Reject HTTP requests whose host or origin is outside the allowlist.""" | ||
|
|
||
| def __init__(self, app: ASGIApp, allowed_hosts: Sequence[str]) -> None: | ||
| self.app = app | ||
| self.allowed_hosts = tuple( | ||
| normalized | ||
| for normalized in (_strip_host_port(host) for host in allowed_hosts) | ||
| if normalized | ||
| ) | ||
|
|
||
| def _is_allowed(self, hostname: str | None) -> bool: | ||
| return hostname is not None and any( | ||
| fnmatch.fnmatchcase(hostname, allowed_host) for allowed_host in self.allowed_hosts | ||
| ) | ||
|
|
||
| async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: | ||
| if scope["type"] != "http": | ||
| await self.app(scope, receive, send) | ||
| return | ||
|
|
||
| if not self._is_allowed(_request_host(scope)): | ||
| await Response("Misdirected Request", status_code=421)(scope, receive, send) | ||
| return | ||
|
|
||
| origin_hosts = _origin_hosts(scope) | ||
| # Both headers are attacker-controlled; do not fall back to request Host. | ||
| if any(not self._is_allowed(origin_host) for origin_host in origin_hosts): | ||
| await Response("Forbidden Origin", status_code=403)(scope, receive, send) | ||
| return | ||
|
|
||
| await self.app(scope, receive, send) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,124 @@ | ||
| # Copyright (c) 2025 Airbyte, Inc., all rights reserved. | ||
| """Unit tests for HTTP MCP host and origin validation.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
|
|
||
| import pytest | ||
| from starlette.responses import PlainTextResponse | ||
| from starlette.testclient import TestClient | ||
| from starlette.types import Receive, Scope, Send | ||
|
|
||
| from airbyte.mcp._transport_security import ( | ||
| ALLOWED_HOSTS_ENV, | ||
| HostOriginGuardMiddleware, | ||
| resolve_allowed_hosts, | ||
| ) | ||
|
|
||
|
|
||
| async def _app(scope: Scope, receive: Receive, send: Send) -> None: | ||
| if scope["type"] == "lifespan": | ||
| while True: | ||
| message = await receive() | ||
| if message["type"] == "lifespan.startup": | ||
| await send({"type": "lifespan.startup.complete"}) | ||
| elif message["type"] == "lifespan.shutdown": | ||
| await send({"type": "lifespan.shutdown.complete"}) | ||
| return | ||
| await PlainTextResponse("ok")(scope, receive, send) | ||
|
|
||
|
|
||
| def _client(allowed_hosts: tuple[str, ...]) -> TestClient: | ||
| return TestClient(HostOriginGuardMiddleware(_app, allowed_hosts)) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("host", ["localhost", "127.0.0.1"]) | ||
| def test_allowed_loopback_hosts_pass_through(host: str) -> None: | ||
| with _client(("localhost", "127.0.0.1")) as client: | ||
| response = client.get("/", headers={"host": host}) | ||
|
|
||
| assert response.status_code == 200 | ||
| assert response.text == "ok" | ||
|
|
||
|
|
||
| def test_unallowed_host_is_rejected() -> None: | ||
| with _client(("localhost",)) as client: | ||
| response = client.get("/", headers={"host": "attacker.example:8080"}) | ||
|
|
||
| assert response.status_code == 421 | ||
| assert response.text == "Misdirected Request" | ||
|
|
||
|
|
||
| def test_unallowed_origin_is_rejected_even_with_allowed_host() -> None: | ||
| with _client(("localhost",)) as client: | ||
| response = client.get( | ||
| "/", | ||
| headers={ | ||
| "host": "localhost", | ||
| "origin": "http://attacker.example:8080", | ||
| }, | ||
| ) | ||
|
|
||
| assert response.status_code == 403 | ||
| assert response.text == "Forbidden Origin" | ||
|
|
||
|
|
||
| def test_missing_origin_is_allowed() -> None: | ||
| with _client(("localhost",)) as client: | ||
| response = client.get("/", headers={"host": "localhost"}) | ||
|
|
||
| assert response.status_code == 200 | ||
|
|
||
|
|
||
| def test_missing_host_is_rejected() -> None: | ||
| with _client(("localhost",)) as client: | ||
| response = client.get("/", headers={"host": ""}) | ||
|
|
||
| assert response.status_code == 421 | ||
|
|
||
|
|
||
| def test_duplicate_hosts_are_rejected() -> None: | ||
| messages: list[dict[str, object]] = [] | ||
|
|
||
| async def receive() -> dict[str, object]: | ||
| return {"type": "http.request", "body": b""} | ||
|
|
||
| async def send(message: dict[str, object]) -> None: | ||
| messages.append(message) | ||
|
|
||
| scope: Scope = { | ||
| "type": "http", | ||
| "method": "GET", | ||
| "path": "/", | ||
| "raw_path": b"/", | ||
| "query_string": b"", | ||
| "headers": [ | ||
| (b"host", b"localhost"), | ||
| (b"host", b"attacker.example"), | ||
| ], | ||
| } | ||
|
|
||
| async def call_middleware() -> None: | ||
| await HostOriginGuardMiddleware(_app, ("localhost",))(scope, receive, send) | ||
|
|
||
| asyncio.run(call_middleware()) | ||
|
|
||
| assert messages[0]["status"] == 421 | ||
|
|
||
|
|
||
| def test_configured_hosts_are_allowed(monkeypatch: pytest.MonkeyPatch) -> None: | ||
| monkeypatch.setenv(ALLOWED_HOSTS_ENV, "custom.example:8443,*.run.app") | ||
|
|
||
| with _client(resolve_allowed_hosts("")) as client: | ||
| custom_response = client.get("/", headers={"host": "custom.example"}) | ||
| pattern_response = client.get("/", headers={"host": "service.run.app"}) | ||
|
|
||
| assert custom_response.status_code == 200 | ||
| assert pattern_response.status_code == 200 | ||
|
|
||
|
|
||
| def test_server_url_hostname_is_allowed() -> None: | ||
| allowed_hosts = resolve_allowed_hosts("https://mcp.example.com:443/mcp") | ||
|
|
||
| assert allowed_hosts[-1:] == ("mcp.example.com",) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🙋 Human Input Needed: the behavior is real, but I don't think it's a bypass of what this guard is for, and narrowing it would break hosted deployments. Asking before changing it.
Why it isn't a bypass of the intended protection: this guard defends the browser-driven rebinding path, where the malicious page cannot choose the
Hostheader (the browser sets it to the rebound attacker hostname), so the allowlist stops it. A non-browser attacker who can already open a TCP connection to the port can of course sendHost: localhost, but that attacker never needed aHosttrick in the first place; the control for network reachability is the bind address, which this PR makes configurable viaAIRBYTE_MCP_HTTP_HOST, plus the auth layer for hosted deployments.Why the narrowing has a cost: dropping loopback when
MCP_SERVER_URLis a public URL would 421 anything that legitimately dials the container over loopback or an IP literal, which in practice is health probes and sidecars. That's the same class of breakage already called out for probes sending an IP-literalHost.Aaron ("AJ") Steers (@aaronsteers), if you'd rather have the stricter behavior, the shape I'd pick is an opt-out (
AIRBYTE_MCP_ALLOWED_HOSTS=explicitly empty means "no loopback defaults") rather than making it conditional onMCP_SERVER_URL, so the hosted rollout can turn it on once probes are confirmed. Happy to add that here or as a follow-up. Leaving as-is unless you want it.Devin session