From a67bcf33e5a6f4237daa15167b482d76ddc7d6f5 Mon Sep 17 00:00:00 2001 From: Maciej Lisiewski Date: Sat, 14 Nov 2026 12:10:53 +0100 Subject: [PATCH] fix(mcp): mask URL credentials in echoed rejection bodies and body-cap errors The rejection recorder masked the request URL but kept a body that echoes it (`?sig=` survived into ConnectionError and `hermes mcp test`); the two wire-body-cap ReadErrors interpolated the raw URL. Adds a test pinning the NonMcpEndpointError masking. Refs #133713 Co-authored-by: BearHuddleston <196404565+BearHuddleston@users.noreply.github.com> --- tests/tools/test_mcp_http_body_cap.py | 21 ++++++++++++++++++ .../tools/test_mcp_preflight_content_type.py | 11 ++++++++++ tests/tools/test_mcp_sse_fallback.py | 22 +++++++++++++++++++ tools/mcp_tool_errors.py | 17 +++++++++----- 4 files changed, 66 insertions(+), 5 deletions(-) diff --git a/tests/tools/test_mcp_http_body_cap.py b/tests/tools/test_mcp_http_body_cap.py index 8846366365..6ac0162c53 100644 --- a/tests/tools/test_mcp_http_body_cap.py +++ b/tests/tools/test_mcp_http_body_cap.py @@ -40,6 +40,27 @@ async def test_oversized_body_rejected_via_content_length(): await client.get("http://mcp.test/rpc") +@pytest.mark.asyncio +@pytest.mark.parametrize("declare_length", [True, False]) +async def test_cap_error_masks_url_query_credentials(declare_length): + """The ReadError text reaches the model and ``hermes mcp test`` (#133713).""" + secret = "s1g" + "Value" + "0123456789" + + class _Stream(httpx.AsyncByteStream): + async def __aiter__(self): + yield b"y" * (LIMIT + 1) + + async def handler(request): + if declare_length: + return httpx.Response(200, content=b"x" * (LIMIT + 1)) + return httpx.Response(200, stream=_Stream()) + async with _client_for(handler) as client: + with pytest.raises(httpx.ReadError) as exc: + await client.get(f"http://mcp.test/rpc?sig={secret}&v=1") + assert secret not in str(exc.value) + assert "/rpc?sig=***&v=1" in str(exc.value) + + @pytest.mark.asyncio async def test_oversized_streamed_body_rejected_without_content_length(): # A streaming body with no Content-Length must still trip the cap. diff --git a/tests/tools/test_mcp_preflight_content_type.py b/tests/tools/test_mcp_preflight_content_type.py index 1b6a8273dd..5a6d84daae 100644 --- a/tests/tools/test_mcp_preflight_content_type.py +++ b/tests/tools/test_mcp_preflight_content_type.py @@ -132,6 +132,17 @@ def test_non_mcp_content_type_raises(content_type): assert "bad_srv" in msg +def test_non_mcp_content_type_error_masks_url_query_credentials(): + """The error text reaches the model and ``hermes mcp test``: a ``?token=`` key must not ride along (#133713).""" + secret = "s3cr3t" + "Value" + "0123456789" + with _serve(_handler(status=200, content_type="text/html")) as base: + with pytest.raises(NonMcpEndpointError) as exc_info: + asyncio.run(_make_task("bad_srv")._preflight_content_type(f"{base}/mcp?token={secret}&v=1", timeout=5.0)) + msg = str(exc_info.value) + assert secret not in msg + assert "/mcp?token=***&v=1" in msg + + # --------------------------------------------------------------------------- # Pass-through: valid MCP content types, ambiguous, and error responses # --------------------------------------------------------------------------- diff --git a/tests/tools/test_mcp_sse_fallback.py b/tests/tools/test_mcp_sse_fallback.py index 434d172088..ac7d379371 100644 --- a/tests/tools/test_mcp_sse_fallback.py +++ b/tests/tools/test_mcp_sse_fallback.py @@ -163,3 +163,25 @@ def test_rejection_recorder_masks_url_query_credentials(): recorded = asyncio.run(_roundtrip()) assert recorded["status"] == 504 assert recorded["url"] == "http://127.0.0.1:1/mcp?token=***®ion=eu" + + +def test_rejection_recorder_masks_url_credentials_echoed_in_body(): + """A proxy that echoes the request URL in its error body must not leak ``sig=`` (#133713).""" + from tools.mcp_tool import sdk_httpx + from tools.mcp_tool_errors import _make_http_rejection_recorder + + httpx2 = sdk_httpx() + secret = "opaque" + "Sig" + "0123456789" + + async def _roundtrip(): + sink: dict = {} + transport = httpx2.MockTransport(lambda req: httpx2.Response( + 403, text=f"denied: https://mcp.example/mcp?sig={secret}&v=1")) + async with httpx2.AsyncClient(transport=transport, event_hooks={ + "response": [_make_http_rejection_recorder(sink)]}) as client: + await client.post("http://127.0.0.1:1/mcp", json={}) + return sink + + recorded = asyncio.run(_roundtrip()) + assert secret not in recorded["body"] + assert recorded["body"] == "denied: https://mcp.example/mcp?sig=***&v=1" diff --git a/tools/mcp_tool_errors.py b/tools/mcp_tool_errors.py index 9613c74534..59d3c44285 100644 --- a/tools/mcp_tool_errors.py +++ b/tools/mcp_tool_errors.py @@ -111,11 +111,12 @@ def _make_http_rejection_recorder(sink: dict): body = " ".join(raw[:_HTTP_REJECTION_BODY_CHARS * 4].decode("utf-8", "replace").split()) except Exception: # the failure itself is still reported, just without the body body = "" - # The URL lands in WARNING / ConnectionError text: a ``?token=`` credential must not ride along. + # URL and body land in WARNING / ConnectionError text: a ``?token=`` credential must not ride + # along, including one a server or proxy echoes back in its error body. from agent.redact import redact_sensitive_text sink.update(status=response.status_code, method=response.request.method, - url=redact_sensitive_text(str(response.request.url), redact_url_credentials=True), - body=body[:_HTTP_REJECTION_BODY_CHARS]) + url=_shown_url(str(response.request.url)), + body=redact_sensitive_text(body[:_HTTP_REJECTION_BODY_CHARS], redact_url_credentials=True)) return _record @@ -343,6 +344,12 @@ _SSE_BOUNDARY_RE = re.compile(rb"(?:\r\n|\r(?!\n)|\n){2}") _SSE_BOUNDARY_CARRY = 3 # longest boundary ("\r\n\r\n") minus one byte +def _shown_url(url: str) -> str: + """*url* for error text that reaches the model and ``hermes mcp test``: credential params masked.""" + from agent.redact import redact_sensitive_text + return redact_sensitive_text(url, redact_url_credentials=True) + + def _make_mcp_body_cap_transport(httpx_mod, inner_transport, limit: int = _MCP_HTTP_MAX_BODY_BYTES): """Wrap ``inner_transport`` so every response body is size-capped. ``httpx_mod`` must be the SDK's own httpx module (``sdk_httpx()``): the transport is handed to that SDK's ``AsyncClient``.""" @@ -352,7 +359,7 @@ def _make_mcp_body_cap_transport(httpx_mod, inner_transport, limit: int = _MCP_H self._inner, self._is_sse, self._url = inner, is_sse, url def _reject(self, kind: str): - return httpx_mod.ReadError(f"MCP {kind} exceeds {limit} bytes (from {self._url})") + return httpx_mod.ReadError(f"MCP {kind} exceeds {limit} bytes (from {_shown_url(self._url)})") async def __aiter__(self): counted = 0 @@ -394,7 +401,7 @@ def _make_mcp_body_cap_transport(httpx_mod, inner_transport, limit: int = _MCP_H if declared is not None and int(declared) > limit: await response.aclose() raise httpx_mod.ReadError(f"MCP HTTP response declares Content-Length {declared} > {limit} " - f"bytes cap (from {request.url})") + f"bytes cap (from {_shown_url(str(request.url))})") is_sse = "text/event-stream" in response.headers.get("content-type", "").lower() response.stream = _CappedStream(response.stream, is_sse, str(request.url)) return response