The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(mcp): enforce strict_redirect_headers on redirects and the preflight probe (#115155)
beardtheliona8afb3b56730
diff --git a/tests/tools/test_mcp_preflight_content_type.py b/tests/tools/test_mcp_preflight_content_type.pyindex b34d0b19091..b22bb1afa3d 100644--- a/tests/tools/test_mcp_preflight_content_type.py+++ b/tests/tools/test_mcp_preflight_content_type.py@@ -25,7 +25,7 @@ import asyncioimport http.serverimport socketserverimport threading-from contextlib import contextmanager+from contextlib import asynccontextmanager, contextmanagerimport pytest@@ -269,6 +269,37 @@ def test_run_skips_preflight_when_skip_preflight_set(monkeypatch):)+def test_run_forwards_strict_redirect_headers_to_preflight(monkeypatch):+ """``strict_redirect_headers`` in server config must reach the probe — the+ boundary it promises is meaningless if the preflight leaks the configured+ headers on a redirect before the SDK client ever runs."""+ import tools.mcp_tool as _mcp+ from tools import mcp_tool_errors as _mcp_errors++ seen_kwargs: list[dict] = []++ async def _inner():+ async def _fake_preflight(self, url, **kwargs):+ seen_kwargs.append(kwargs)++ async def _fake_run_http(self, config):+ raise asyncio.CancelledError()++ monkeypatch.setattr(_mcp_errors, "_validate_remote_mcp_url", lambda n, u: None)+ monkeypatch.setattr(_mcp.MCPServerTask, "_preflight_content_type", _fake_preflight)+ monkeypatch.setattr(_mcp.MCPServerTask, "_run_http", _fake_run_http)++ task = _mcp.MCPServerTask("strict-preflight-test")+ with pytest.raises(asyncio.CancelledError):+ await task.run({+ "url": "https://mcp.example.com/mcp",+ "strict_redirect_headers": True,+ })++ asyncio.run(_inner())+ assert seen_kwargs and seen_kwargs[0].get("strict_redirect_headers") is True++# ---------------------------------------------------------------------------# POST probe fallback for POST-only MCP servers# ---------------------------------------------------------------------------@@ -287,3 +318,184 @@ def test_post_probe_not_attempted_for_valid_head():asyncio.run(task._preflight_content_type(f"{base}/mcp", timeout=5.0))assert record == ["HEAD"]assert "POST" not in record+++# ---------------------------------------------------------------------------+# Redirect header scoping: credentials must not leave the configured origin+# ---------------------------------------------------------------------------+++def _redirect_handler(target_base: str, record=None):+ """HEAD/GET/POST all 302 to ``target_base/mcp``."""++ class _H(http.server.BaseHTTPRequestHandler):+ def _redir(self):+ if record is not None:+ record.append(dict(self.headers))+ self.send_response(302)+ self.send_header("Location", f"{target_base}/mcp")+ self.end_headers()++ do_HEAD = do_GET = do_POST = _redir++ def log_message(self, format, *args): # noqa: A002+ pass++ return _H+++def _recording_mcp_handler(seen: dict):+ """200 application/json; captures request headers into ``seen``."""++ class _H(http.server.BaseHTTPRequestHandler):+ def _write_ok(self):+ seen.update({k.lower(): v for k, v in self.headers.items()})+ payload = b"{}"+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(payload)))+ self.end_headers()+ if self.command != "HEAD":+ self.wfile.write(payload)++ do_HEAD = do_GET = do_POST = _write_ok++ def log_message(self, format, *args): # noqa: A002+ pass++ return _H+++def test_preflight_strips_credential_headers_on_cross_origin_redirect():+ """A configured ``Authorization``/``X-API-Key`` header must not reach a+ redirect target on another origin — the probe client previously followed+ redirects with no hook, forwarding every configured header verbatim."""+ task = _make_task()+ seen: dict = {}+ with _serve(_recording_mcp_handler(seen)) as target, \+ _serve(_redirect_handler(target)) as origin:+ asyncio.run(task._preflight_content_type(+ f"{origin}/mcp",+ headers={"Authorization": "Bearer s3cr3t", "X-API-Key": "k3y"},+ strict_redirect_headers=True,+ timeout=5.0,+ ))+ assert "s3cr3t" not in seen.values() and "k3y" not in seen.values()+ assert "authorization" not in seen and "x-api-key" not in seen+++def test_preflight_keeps_headers_on_same_origin_redirect():+ """Relative redirects stay on the configured origin — headers must arrive."""+ task = _make_task()+ seen: dict = {}+ origin_hits: list = []++ class _Origin(http.server.BaseHTTPRequestHandler):+ def do_HEAD(self):+ if self.path == "/mcp":+ seen.update({k.lower(): v for k, v in self.headers.items()})+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", "2")+ self.end_headers()+ else:+ origin_hits.append(dict(self.headers))+ self.send_response(302)+ self.send_header("Location", "/mcp")+ self.end_headers()++ def log_message(self, format, *args): # noqa: A002+ pass++ with _serve(_Origin) as origin:+ asyncio.run(task._preflight_content_type(+ f"{origin}/old",+ headers={"Authorization": "Bearer s3cr3t"},+ timeout=5.0,+ ))+ assert seen.get("authorization") == "Bearer s3cr3t"+++def test_preflight_non_strict_forwards_configured_headers():+ """Non-strict is the documented compat contract: configured headers follow+ redirects (gateways that bounce to a same-service regional host). Only+ ``Authorization`` is withheld — matching the transport client's policy."""+ task = _make_task()+ seen: dict = {}+ with _serve(_recording_mcp_handler(seen)) as target, \+ _serve(_redirect_handler(target)) as origin:+ asyncio.run(task._preflight_content_type(+ f"{origin}/mcp",+ headers={"Authorization": "Bearer s3cr3t", "X-API-Key": "k3y"},+ strict_redirect_headers=False,+ timeout=5.0,+ ))+ assert seen.get("x-api-key") == "k3y" # configured headers forward+ assert "authorization" not in seen # bearer never leaves origin+++def test_preflight_multi_hop_redirect_stays_stripped():+ """origin -> B -> C: once headers are stripped at the first cross-origin hop+ they must not reappear on a later hop (and are not restored if a redirect+ chains back toward the configured origin)."""+ task = _make_task()+ seen_b: dict = {}+ seen_c: dict = {}+ with _serve(_recording_mcp_handler(seen_c)) as c_base:+ class _B(http.server.BaseHTTPRequestHandler):+ def do_HEAD(self):+ seen_b.update({k.lower(): v for k, v in self.headers.items()})+ self.send_response(302)+ self.send_header("Location", f"{c_base}/mcp")+ self.end_headers()+ def log_message(self, format, *args): # noqa: A002+ pass++ with _serve(_B) as b_base, _serve(_redirect_handler(b_base)) as origin:+ asyncio.run(task._preflight_content_type(+ f"{origin}/mcp",+ headers={"Authorization": "Bearer s3cr3t", "X-API-Key": "k3y"},+ strict_redirect_headers=True,+ timeout=5.0,+ ))+ assert "authorization" not in seen_b and "x-api-key" not in seen_b+ assert "authorization" not in seen_c and "x-api-key" not in seen_c+++# ---------------------------------------------------------------------------+# Streamable HTTP transport client: same boundary on the real connection+# ---------------------------------------------------------------------------+++def test_streamable_http_client_strips_credentials_on_redirect(monkeypatch):+ """Drive the REAL ``_streamable_http_transport`` construction: the client the+ SDK receives must be the stripping subclass — proven against a live redirect+ pair. Only the SDK's streams context manager is faked (a full MCP handshake+ is out of scope); the httpx client, its kwargs and the strip are all real."""+ import tools.mcp_tool as _mcp++ task = _make_task()+ seen: dict = {}+ captured: dict = {}++ @asynccontextmanager+ async def _fake_streams(url, http_client=None, **kwargs):+ captured["client"] = http_client+ yield (None, None, None)++ monkeypatch.setattr(_mcp, "streamable_http_client", _fake_streams)++ with _serve(_recording_mcp_handler(seen)) as target, \+ _serve(_redirect_handler(target)) as origin:+ async def _drive():+ cm = task._streamable_http_transport(+ f"{origin}/mcp",+ {"Authorization": "Bearer s3cr3t", "X-API-Key": "k3y"},+ connect_timeout=5.0, ssl_verify=True, client_cert=None,+ oauth_auth=None, strict_cfg_headers=True,+ configured_header_names={"x-api-key"})+ async with cm:+ await captured["client"].get(f"{origin}/mcp")++ asyncio.run(_drive())+ assert "authorization" not in seen and "x-api-key" not in seendiff --git a/tests/tools/test_mcp_tool.py b/tests/tools/test_mcp_tool.pyindex 6a2abaf5bb8..94206e6fc83 100644--- a/tests/tools/test_mcp_tool.py+++ b/tests/tools/test_mcp_tool.py@@ -3293,49 +3293,41 @@ class TestMCPDiscoveryCrossProcessLock:class TestRedirectHeaderStripper:- """Cross-origin redirect header boundary (portable Agent Plugins v1)."""+ """Cross-origin redirect header boundary (portable Agent Plugins v1).- def _make_response(self, next_headers):- import httpx+ The stripper is an ``AsyncClient`` subclass overriding ``_build_redirect_request`` — the only+ seam that sees the actual redirect follow-up (``response.next_request`` is unset when response+ hooks fire) without also touching non-redirect traffic (a request hook would strip the OAuth+ auth flow's token/registration calls to a different-origin authorization server)."""- next_request = httpx.Request(- "GET", "https://other.example.test/mcp", headers=next_headers- )- response = SimpleNamespace(- is_redirect=True,- next_request=next_request,- )- return response, next_request+ def _build_redirect(self, httpx, *, strict=False, configured=frozenset(),+ headers, location):+ from tools.mcp_tool_errors import _make_redirect_header_stripper++ client_cls = _make_redirect_header_stripper(+ httpx, httpx.URL("https://origin.example.test/mcp"),+ strict=strict, configured_header_names=configured)+ client = client_cls()+ request = httpx.Request("GET", "https://origin.example.test/mcp", headers=headers)+ response = httpx.Response(302, headers={"location": location}, request=request)+ return client._build_redirect_request(request, response)def test_default_strips_only_authorization(self):import httpx- from tools.mcp_tool_errors import _make_redirect_header_stripper-- hook = _make_redirect_header_stripper(- httpx.URL("https://origin.example.test/mcp")- )- response, next_request = self._make_response(- {"Authorization": "Bearer x", "X-Tenant": "t"}- )- asyncio.run(hook(response))+ next_request = self._build_redirect(+ httpx, headers={"Authorization": "Bearer x", "X-Tenant": "t"},+ location="https://other.example.test/mcp")assert "authorization" not in next_request.headersassert next_request.headers["x-tenant"] == "t"def test_strict_strips_configured_headers_cross_origin(self):import httpx- from tools.mcp_tool_errors import _make_redirect_header_stripper-- hook = _make_redirect_header_stripper(- httpx.URL("https://origin.example.test/mcp"),- strict=True,- configured_header_names={"x-tenant"},- )- response, next_request = self._make_response(- {"Authorization": "Bearer x", "X-Tenant": "t", "Accept": "a"}- )- asyncio.run(hook(response))+ next_request = self._build_redirect(+ httpx, strict=True, configured={"x-tenant"},+ headers={"Authorization": "Bearer x", "X-Tenant": "t", "Accept": "a"},+ location="https://other.example.test/mcp")assert "authorization" not in next_request.headersassert "x-tenant" not in next_request.headers# Client-generated headers unrelated to package config survive.@@ -3344,19 +3336,9 @@ class TestRedirectHeaderStripper:def test_same_origin_redirect_keeps_headers(self):import httpx- from tools.mcp_tool_errors import _make_redirect_header_stripper-- hook = _make_redirect_header_stripper(- httpx.URL("https://origin.example.test/mcp"),- strict=True,- configured_header_names={"x-tenant"},- )- next_request = httpx.Request(- "GET",- "https://origin.example.test/other",+ next_request = self._build_redirect(+ httpx, strict=True, configured={"x-tenant"},headers={"Authorization": "Bearer x", "X-Tenant": "t"},- )- response = SimpleNamespace(is_redirect=True, next_request=next_request)- asyncio.run(hook(response))+ location="https://origin.example.test/other")assert next_request.headers["authorization"] == "Bearer x"assert next_request.headers["x-tenant"] == "t"diff --git a/tools/mcp_tool_errors.py b/tools/mcp_tool_errors.pyindex 2227ea8d917..0ab2a74a1fe 100644--- a/tools/mcp_tool_errors.py+++ b/tools/mcp_tool_errors.py@@ -262,24 +262,34 @@ def _apply_identity_header(server_name: str, config: dict, headers: dict) -> dicreturn headers-def _make_redirect_header_stripper(original_url, *, strict: bool = False,+def _make_redirect_header_stripper(httpx_mod, original_url, *, strict: bool = False,configured_header_names: "set[str] | frozenset[str]" = frozenset()):- """httpx response hook: strips ``Authorization`` when a redirect leaves the original origin;- with *strict* (Agent Plugins v1 ``strict_redirect_headers``) every configured header (lowercase- names in *configured_header_names*) is stripped too — v1 forbids forwarding them cross-origin."""+ """AsyncClient subclass enforcing the redirect credential boundary: on a cross-origin redirect+ follow-up it strips ``Authorization``; with *strict* (Agent Plugins v1 ``strict_redirect_headers``)+ every configured header (lowercase names in *configured_header_names*) is stripped too — v1 forbids+ forwarding them cross-origin.++ This MUST live on ``_build_redirect_request``: ``response.next_request`` is unset when response+ event hooks fire (httpx populates it later in the redirect loop), so a response hook can never+ mutate the follow-up; and a *request* hook would fire on non-redirect traffic too — the OAuth+ auth flow yields token/metadata/registration requests through the same client, often to a+ different-origin authorization server whose own credentials must NOT be stripped."""origin = (original_url.scheme, original_url.host, original_url.port)- async def _strip_on_cross_origin_redirect(response):- target = response.next_request.url if response.is_redirect and response.next_request else None- if target is None or (target.scheme, target.host, target.port) == origin:- return- headers = response.next_request.headers- headers.pop("authorization", None)- headers.pop("Authorization", None)- for _name in configured_header_names if strict else ():- while _name in headers:- del headers[_name]- return _strip_on_cross_origin_redirect+ class _Client(httpx_mod.AsyncClient):+ def _build_redirect_request(self, request, response):+ next_request = super()._build_redirect_request(request, response)+ target = next_request.url+ if (target.scheme, target.host, target.port) != origin:+ headers = next_request.headers+ headers.pop("authorization", None)+ headers.pop("Authorization", None)+ for _name in configured_header_names if strict else ():+ while _name in headers:+ del headers[_name]+ return next_request++ return _Client# Wire-body cap, applied at the httpx transport before the SDK buffers/JSON-parses a response. Adiff --git a/tools/mcp_tool_server_run.py b/tools/mcp_tool_server_run.pyindex 5d999e85899..2e1af5aa119 100644--- a/tools/mcp_tool_server_run.py+++ b/tools/mcp_tool_server_run.py@@ -289,7 +289,8 @@ class MCPServerRunMixin:await self._preflight_content_type(config["url"], headers=dict(config.get("headers") or {}),ssl_verify=config.get("ssl_verify", True),- client_cert=_errors._resolve_client_cert(self.name, config))+ client_cert=_errors._resolve_client_cert(self.name, config),+ strict_redirect_headers=bool(config.get("strict_redirect_headers")))except (_errors.InvalidMcpUrlError, _errors.NonMcpEndpointError) as exc:logger.warning("%s", exc)self._publish_error(exc) # fail fast and non-retryablydiff --git a/tools/mcp_tool_transport.py b/tools/mcp_tool_transport.pyindex b042ebad0a8..663f61f83f4 100644--- a/tools/mcp_tool_transport.py+++ b/tools/mcp_tool_transport.py@@ -340,7 +340,8 @@ class MCPServerTransportMixin:# ------------------------------------------------------------------- HTTPasync def _preflight_content_type(self, url: str, *, headers: Optional[dict] = None,- ssl_verify: bool = True, client_cert=None, timeout: float = 5.0) -> None:+ ssl_verify: bool = True, client_cert=None, timeout: float = 5.0,+ strict_redirect_headers: bool = False) -> None:"""Probe *url* before the SDK connects: a plain web page would make the SDK sit out the full``connect_timeout`` before an opaque ``CancelledError``; this raises NonMcpEndpointError within``timeout``. Allow-list based: only a 2xx with a definite non-MCP content type is rejected, and@@ -359,9 +360,15 @@ class MCPServerTransportMixin:probe_headers = dict(headers) if headers else {}# Same route as the SDK client: TLS on an explicit transport (which also turns off httpx's own# env proxy auto-detection) plus the repo's proxy mounts, so the probe and the handshake agree.+ # Same redirect boundary as the transport client too: httpx strips Authorization on a+ # cross-origin hop natively, but forwards every other configured header verbatim — under+ # strict_redirect_headers those must not leave the configured origin on the probe either.probe_transport = _httpx.AsyncHTTPTransport(verify=ssl_verify, **_present(cert=client_cert))+ _client_cls = _make_redirect_header_stripper(+ _httpx, _httpx.URL(url), strict=strict_redirect_headers,+ configured_header_names={key.lower() for key in probe_headers})try:- async with _httpx.AsyncClient(+ async with _client_cls(follow_redirects=True, timeout=_httpx.Timeout(timeout), transport=probe_transport,**_present(mounts=_mcp_proxy_mounts(_httpx, url, ssl_verify, client_cert, self.name))) as client:resp = await client.head(url, headers=probe_headers) # cheapest; GET on 405/501@@ -470,22 +477,21 @@ class MCPServerTransportMixin:# Explicit AsyncClient matching the SDK's create_mcp_http_client defaults; MUST come from the# SDK's httpx (httpx2 on mcp >= 2.0) since the SDK sends its own Requests through it.httpx = _core.sdk_httpx()- _strip_auth_on_cross_origin_redirect = _make_redirect_header_stripper(- httpx.URL(url), strict=strict_cfg_headers, configured_header_names=configured_header_names)+ _client_cls = _make_redirect_header_stripper(+ httpx, httpx.URL(url), strict=strict_cfg_headers, configured_header_names=configured_header_names)# verify/cert live on the inner transport: a custom transport= makes client-level TLS kwargs# inert — and suppresses httpx's own proxy auto-detection, hence the explicit mounts=.inner_transport = httpx.AsyncHTTPTransport(verify=ssl_verify, **_present(cert=client_cert))client_kwargs: dict = {"follow_redirects": True, "timeout": httpx.Timeout(float(connect_timeout), read=300.0),**({"headers": headers} if headers else {}),- "event_hooks": {"response": [_strip_auth_on_cross_origin_redirect,- _make_http_rejection_recorder(self._http_rejection)]},+ "event_hooks": {"response": [_make_http_rejection_recorder(self._http_rejection)]},"transport": _make_mcp_body_cap_transport(httpx, inner_transport),**_present(mounts=_mcp_proxy_mounts(httpx, url, ssl_verify, client_cert, self.name),auth=oauth_auth)}@asynccontextmanagerasync def _owned_client_streams(): # the SDK skips cleanup when http_client is provided- async with httpx.AsyncClient(**client_kwargs) as http_client:+ async with _client_cls(**client_kwargs) as http_client:async with _core.streamable_http_client(url, http_client=http_client) as streams:yield streamsreturn _owned_client_streams()