From 307e5105c3fb8155f73a7e5d96d70cb96464e99b Mon Sep 17 00:00:00 2001 From: ggapp1 <19319387+ggapp1@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:34:24 -0300 Subject: [PATCH 1/2] fix(cli): hold httpx and httpcore logging at WARNING, so request URLs (the Telegram bot token among them) stop reaching the log --- src/dudamel/cli.py | 8 ++++++++ tests/test_cli.py | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/src/dudamel/cli.py b/src/dudamel/cli.py index a35fff0..04e2066 100644 --- a/src/dudamel/cli.py +++ b/src/dudamel/cli.py @@ -255,6 +255,14 @@ def cmd_run(args: argparse.Namespace) -> int: format=_LOG_FORMAT, datefmt=_LOG_DATEFMT, ) + # httpx logs every request's full URL at INFO, and a URL can be a + # credential: python-telegram-bot puts the bot token in the path of every + # Bot API call, so at the level above the token reached the terminal or + # journal on every poll. Held at WARNING even under --debug -- request + # tracing is not worth printing a secret for. httpcore is the transport + # underneath and is held for the same reason. + for name in ("httpx", "httpcore"): + logging.getLogger(name).setLevel(logging.WARNING) project_dir = Path.cwd() _load_dotenv_into_environ(project_dir) settings = Settings.load(project_dir) diff --git a/tests/test_cli.py b/tests/test_cli.py index dfab5fa..a0105dd 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -408,6 +408,52 @@ async def fake_serve(orchestrator, settings, **kwargs): assert captured["level"] == logging.DEBUG +@pytest.fixture +def _restore_http_loggers(): + """`dudamel run` sets levels on the httpx/httpcore loggers, which are + process-global; put them back so the rest of the suite is unaffected.""" + saved = {name: logging.getLogger(name).level for name in ("httpx", "httpcore")} + yield + for name, level in saved.items(): + logging.getLogger(name).setLevel(level) + + +@pytest.mark.parametrize("argv", [["run"], ["run", "--debug"]]) +def test_run_does_not_log_request_urls( + argv: list[str], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + _restore_http_loggers, +) -> None: + """httpx logs every request's full URL at INFO, and a URL can be a + credential: python-telegram-bot puts the bot token in the path of every + Bot API call, and a private calendar link is its own secret. Under the + logging `run` installs -- with or without --debug -- no such line may + reach a handler. + + Captured at DEBUG on the root logger: at caplog's default level an INFO + record is never collected, so the assertion below would pass with the + leak live.""" + import httpx + + target = scaffold(tmp_path) + monkeypatch.chdir(target) + monkeypatch.setattr(cli.logging, "basicConfig", lambda **kw: None) + caplog.set_level(logging.DEBUG) + secret = "123456:SECRET-BOT-TOKEN" + + async def fake_serve(orchestrator, settings, **kwargs): + transport = httpx.MockTransport(lambda request: httpx.Response(200)) + async with httpx.AsyncClient(transport=transport) as client: + await client.post(f"https://api.telegram.org/bot{secret}/getUpdates") + + monkeypatch.setattr(cli, "serve", fake_serve) + assert cli.main(argv) == 0 + leaked = [r.getMessage() for r in caplog.records if secret in r.getMessage()] + assert leaked == [] + + def test_run_wires_orchestrator_and_settings_into_serve( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: From a06cdb4618fda4d79fd5f0b95f856002d2c78d83 Mon Sep 17 00:00:00 2001 From: ggapp1 <19319387+ggapp1@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:40:56 -0300 Subject: [PATCH 2/2] fix(cli): also quiet the MCP SDK's httpx2/httpcore2, telegram.Bot's token-bearing debug lines and the MCP session-id line; restore logger levels after every test --- src/dudamel/cli.py | 34 ++++++++++++++++++++++++-------- tests/conftest.py | 14 ++++++++++++++ tests/test_cli.py | 48 +++++++++++++++++++++++++++++----------------- 3 files changed, 70 insertions(+), 26 deletions(-) diff --git a/src/dudamel/cli.py b/src/dudamel/cli.py index 04e2066..bf05373 100644 --- a/src/dudamel/cli.py +++ b/src/dudamel/cli.py @@ -243,6 +243,30 @@ def cmd_new(args: argparse.Namespace) -> int: _LOG_DATEFMT = "%H:%M:%S" +# Third-party loggers that print secrets at the levels `run` configures, each +# held at the lowest level that no longer does. Applied even under --debug: +# request tracing is not worth printing a credential for. +# +# - httpx logs every request's full URL at INFO. python-telegram-bot puts the +# bot token in the path of every Bot API call, so the token reached the +# terminal or journal on every poll. httpcore is the transport underneath. +# - httpx2/httpcore2 are the same pair as shipped inside the MCP SDK, logging +# under their own names -- an MCP server URL can carry a token in its query +# string or userinfo. +# - telegram.Bot logs the Bot API base URL, token included, at DEBUG when the +# bot is constructed. +# - mcp.client.streamable_http logs the server-issued session id at INFO, and a +# session id is a bearer credential for that session. +QUIET_LOGGERS: dict[str, int] = { + "httpx": logging.WARNING, + "httpcore": logging.WARNING, + "httpx2": logging.WARNING, + "httpcore2": logging.WARNING, + "telegram.Bot": logging.INFO, + "mcp.client.streamable_http": logging.WARNING, +} + + def cmd_run(args: argparse.Namespace) -> int: # A real `dudamel run` invocation is a fresh interpreter with nothing # else configuring logging, so INFO-and-up (DEBUG with --debug) reaching @@ -255,14 +279,8 @@ def cmd_run(args: argparse.Namespace) -> int: format=_LOG_FORMAT, datefmt=_LOG_DATEFMT, ) - # httpx logs every request's full URL at INFO, and a URL can be a - # credential: python-telegram-bot puts the bot token in the path of every - # Bot API call, so at the level above the token reached the terminal or - # journal on every poll. Held at WARNING even under --debug -- request - # tracing is not worth printing a secret for. httpcore is the transport - # underneath and is held for the same reason. - for name in ("httpx", "httpcore"): - logging.getLogger(name).setLevel(logging.WARNING) + for name, level in QUIET_LOGGERS.items(): + logging.getLogger(name).setLevel(level) project_dir = Path.cwd() _load_dotenv_into_environ(project_dir) settings = Settings.load(project_dir) diff --git a/tests/conftest.py b/tests/conftest.py index 0d12764..15b8d14 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -16,6 +16,7 @@ import contextlib import importlib +import logging import os from datetime import datetime from typing import Any @@ -27,6 +28,19 @@ from dudamel.db import Database +@pytest.fixture(autouse=True) +def _restore_quiet_loggers(): + """`dudamel run` sets levels on a few third-party loggers, and logger levels + are process-global. Every test that drives `run` would otherwise leave them + changed for the rest of the session.""" + from dudamel.cli import QUIET_LOGGERS + + saved = {name: logging.getLogger(name).level for name in QUIET_LOGGERS} + yield + for name, level in saved.items(): + logging.getLogger(name).setLevel(level) + + @pytest.fixture(autouse=True) def _restore_environ(): """Give every test the process environment it started with, whatever it wrote. diff --git a/tests/test_cli.py b/tests/test_cli.py index a0105dd..d1de2a5 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -408,34 +408,25 @@ async def fake_serve(orchestrator, settings, **kwargs): assert captured["level"] == logging.DEBUG -@pytest.fixture -def _restore_http_loggers(): - """`dudamel run` sets levels on the httpx/httpcore loggers, which are - process-global; put them back so the rest of the suite is unaffected.""" - saved = {name: logging.getLogger(name).level for name in ("httpx", "httpcore")} - yield - for name, level in saved.items(): - logging.getLogger(name).setLevel(level) - - @pytest.mark.parametrize("argv", [["run"], ["run", "--debug"]]) -def test_run_does_not_log_request_urls( +def test_run_does_not_log_secrets_carried_in_urls( argv: list[str], tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, - _restore_http_loggers, ) -> None: - """httpx logs every request's full URL at INFO, and a URL can be a - credential: python-telegram-bot puts the bot token in the path of every - Bot API call, and a private calendar link is its own secret. Under the - logging `run` installs -- with or without --debug -- no such line may - reach a handler. + """A URL can be a credential: python-telegram-bot puts the bot token in the + path of every Bot API call, and an MCP server URL can carry a token in its + query string. Under the logging `run` installs -- with or without --debug -- + no such URL may reach a handler, through either HTTP client in the + dependency tree or through the bot's own construction-time logging. Captured at DEBUG on the root logger: at caplog's default level an INFO record is never collected, so the assertion below would pass with the leak live.""" import httpx + import httpx2 + import telegram target = scaffold(tmp_path) monkeypatch.chdir(target) @@ -444,16 +435,37 @@ def test_run_does_not_log_request_urls( secret = "123456:SECRET-BOT-TOKEN" async def fake_serve(orchestrator, settings, **kwargs): + telegram.Bot(secret) transport = httpx.MockTransport(lambda request: httpx.Response(200)) async with httpx.AsyncClient(transport=transport) as client: await client.post(f"https://api.telegram.org/bot{secret}/getUpdates") + transport2 = httpx2.MockTransport(lambda request: httpx2.Response(200)) + async with httpx2.AsyncClient(transport=transport2) as client2: + await client2.post(f"https://mcp.example/mcp?token={secret}") monkeypatch.setattr(cli, "serve", fake_serve) assert cli.main(argv) == 0 - leaked = [r.getMessage() for r in caplog.records if secret in r.getMessage()] + leaked = [f"{r.name}: {r.getMessage()}" for r in caplog.records if secret in r.getMessage()] assert leaked == [] +def test_run_holds_every_quiet_logger(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Each entry in QUIET_LOGGERS is applied. The behavioural test above drives + the three it can reach without a live server; this covers the rest (the MCP + session-id line needs a real streamable-HTTP exchange).""" + target = scaffold(tmp_path) + monkeypatch.chdir(target) + monkeypatch.setattr(cli.logging, "basicConfig", lambda **kw: None) + + async def fake_serve(orchestrator, settings, **kwargs): + pass + + monkeypatch.setattr(cli, "serve", fake_serve) + assert cli.main(["run", "--debug"]) == 0 + for name, level in cli.QUIET_LOGGERS.items(): + assert logging.getLogger(name).level == level, name + + def test_run_wires_orchestrator_and_settings_into_serve( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: