fix(redact): mask credential-bearing URL query params and userinfo on the log path
A remote MCP server configured the documented token-auth way (`https://mcp.example.com/mcp?token=…`) landed its API key verbatim on every log line mentioning the URL (#133713). Two independent gaps: - RedactingFormatter only ran redact_sensitive_text, which deliberately passes web-URL query params / userinfo through for OAuth callbacks and magic links. Log files are a persistence boundary, not a live tool flow, so the formatter now also runs redact_log_urls(): a thin opt-in over the existing strict URL redactor that masks credential-named query values (token=***) and URL userinfo (//***:***@) while keys, separators, public params, hosts and paths survive byte-for-byte. Lines without "://" are returned untouched. - _NOISY_LOGGERS listed "httpx" but mcp SDK >= 2.0 rides on "httpx2" (tools/mcp_tool.py already documents this), so its INFO request lines — which interpolate the full URL — were never quieted. Add "httpx2".
This commit is contained in:
committed by
Maciej Lisiewski
parent
50b33d1513
commit
4c7af743b1
@@ -1206,6 +1206,21 @@ def _redact_strict_url_credentials(text: str) -> str:
|
||||
return _STRICT_URL_USERINFO_RE.sub("//***:***@", text)
|
||||
|
||||
|
||||
def redact_log_urls(text: str) -> str:
|
||||
"""Mask credential-named query params and URL userinfo in log-bound text.
|
||||
|
||||
A log file is a persistence boundary, not a live tool flow: magic-link /
|
||||
OAuth-callback URLs only need their non-secret parts to survive on disk, so
|
||||
the log path opts into the strict URL redactors that
|
||||
``redact_sensitive_text`` deliberately leaves off for live flows. Without
|
||||
it, a remote MCP server configured as ``https://mcp.example.com/mcp?token=…``
|
||||
lands its API key on every log line that mentions the URL (issue #133713).
|
||||
"""
|
||||
if not text or "://" not in text:
|
||||
return text
|
||||
return _redact_strict_url_credentials(text)
|
||||
|
||||
|
||||
def redact_cdp_url(value: object) -> str:
|
||||
"""Mask secrets in a CDP/browser endpoint URL before it is logged.
|
||||
|
||||
@@ -1921,11 +1936,12 @@ class RedactingFormatter(logging.Formatter):
|
||||
safe_record = copy.copy(record)
|
||||
safe_record.msg = _LOG_UNSAFE_CHARS.sub(" ", redact_sensitive_text(record.getMessage()))
|
||||
safe_record.args = None
|
||||
formatted = redact_sensitive_text(super().format(safe_record))
|
||||
formatted = redact_log_urls(redact_sensitive_text(super().format(safe_record)))
|
||||
# aiohttp's access line carries the raw request target, and webhook platforms that cannot
|
||||
# send headers authenticate in the query string (BlueBubbles ``?password=``). An adapter's
|
||||
# own ``access_log=None`` does not reach the shared listener that serves multiplexed
|
||||
# profiles (#143550), so credential params are masked on every Hermes log handler.
|
||||
# profiles (#143550), so credential params are masked on every Hermes log handler. Its target
|
||||
# is relative (no ``://``), which redact_log_urls above skips.
|
||||
if record.name == "aiohttp.access":
|
||||
formatted = _redact_strict_url_credentials(formatted)
|
||||
first, *rest = _EXC_UNSAFE_CHARS.sub(" ", formatted).split("\n")
|
||||
|
||||
@@ -238,9 +238,9 @@ def _is_unavailable_log_stream(exc: BaseException | None) -> bool:
|
||||
|
||||
# Third-party loggers that are noisy at DEBUG/INFO level.
|
||||
_NOISY_LOGGERS = (
|
||||
"openai", "openai._base_client", "httpx", "httpcore", "asyncio", "hpack", "hpack.hpack",
|
||||
"grpc", "modal", "urllib3", "urllib3.connectionpool", "websockets", "charset_normalizer",
|
||||
"markdown_it",
|
||||
"openai", "openai._base_client", "httpx", "httpx2", "httpcore", "asyncio", "hpack",
|
||||
"hpack.hpack", "grpc", "modal", "urllib3", "urllib3.connectionpool", "websockets",
|
||||
"charset_normalizer", "markdown_it",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -630,6 +630,40 @@ class TestRedactingFormatter:
|
||||
assert "abc123def456" not in result
|
||||
assert "sk-pro" in result
|
||||
|
||||
@staticmethod
|
||||
def _record(message: str) -> logging.LogRecord:
|
||||
return logging.LogRecord(
|
||||
name="test", level=logging.INFO, pathname="", lineno=0,
|
||||
msg=message, args=(), exc_info=None,
|
||||
)
|
||||
|
||||
def test_log_path_masks_sensitive_url_query_params(self):
|
||||
# issue #133713: a remote MCP URL with token auth must not reach disk verbatim
|
||||
formatter = RedactingFormatter("%(message)s")
|
||||
result = formatter.format(
|
||||
self._record(
|
||||
'HTTP Request: POST https://mcp.example.com/mcp?token=SECRETVALUE "HTTP/1.1 200 OK"'
|
||||
)
|
||||
)
|
||||
assert "SECRETVALUE" not in result
|
||||
assert "token=***" in result
|
||||
assert "https://mcp.example.com/mcp" in result
|
||||
|
||||
def test_log_path_masks_url_userinfo(self):
|
||||
formatter = RedactingFormatter("%(message)s")
|
||||
result = formatter.format(
|
||||
self._record("connect failed: https://user:hunter2@mcp.example.com/mcp")
|
||||
)
|
||||
assert "hunter2" not in result
|
||||
assert "//***:***@mcp.example.com" in result
|
||||
|
||||
def test_log_path_keeps_public_query_params_and_url_free_lines(self):
|
||||
formatter = RedactingFormatter("%(message)s")
|
||||
url_line = "GET https://example.com/list?page=2&sort=name done"
|
||||
assert formatter.format(self._record(url_line)) == url_line
|
||||
plain = "state codes like A=1;B=2 survive when no URL is present"
|
||||
assert formatter.format(self._record(plain)) == plain
|
||||
|
||||
|
||||
class TestPrintenvSimulation:
|
||||
"""Simulate what happens when the agent runs `env` or `printenv`."""
|
||||
|
||||
@@ -1183,6 +1183,14 @@ def test_router_never_builds_a_child_handler_under_a_lock_logging_shutdown_takes
|
||||
"lock while the router built a child handler (which needs logging._lock)")
|
||||
|
||||
|
||||
def test_quiet_noisy_loggers_covers_httpx2():
|
||||
"""mcp SDK >= 2.0 rides on ``httpx2``, whose INFO request lines interpolate the
|
||||
full URL (query credentials included) — it must be pinned at WARNING like httpx
|
||||
(issue #133713)."""
|
||||
hermes_logging._quiet_noisy_loggers()
|
||||
assert logging.getLogger("httpx2").level == logging.WARNING
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_aiohttp_access_line_never_writes_a_query_credential_to_disk(hermes_home):
|
||||
"""The listener serving multiplexed profiles logs every request target with aiohttp's default
|
||||
@@ -1205,14 +1213,13 @@ async def test_aiohttp_access_line_never_writes_a_query_credential_to_disk(herme
|
||||
assert secret not in log
|
||||
|
||||
|
||||
def test_strict_url_pass_stays_off_ordinary_log_lines():
|
||||
"""Only aiohttp's access line gets the strict pass: magic-link / OAuth URLs in other lines are
|
||||
meant to survive (the redactor's documented web-URL policy)."""
|
||||
def test_strict_url_pass_covers_absolute_urls_on_every_log_line():
|
||||
"""A log file is a persistence sink (#133713): an absolute URL's credential params are masked on
|
||||
every logger, not only aiohttp's access line (whose relative request target keeps its own pass)."""
|
||||
from agent.redact import RedactingFormatter
|
||||
|
||||
fmt = RedactingFormatter("%(message)s")
|
||||
line = "open https://example.com/magic?token=abcdef123456 to continue"
|
||||
formatted = {name: fmt.format(logging.LogRecord(name, logging.INFO, __file__, 1, line, None, None))
|
||||
for name in ("aiohttp.access", "gateway.run")}
|
||||
assert "magic?token=***" in formatted["aiohttp.access"]
|
||||
assert "magic?token=abcdef123456" in formatted["gateway.run"]
|
||||
for name in ("aiohttp.access", "gateway.run"):
|
||||
formatted = fmt.format(logging.LogRecord(name, logging.INFO, __file__, 1, line, None, None))
|
||||
assert formatted == "open https://example.com/magic?token=*** to continue", name
|
||||
|
||||
Reference in New Issue
Block a user