Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/dudamel/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -255,6 +279,8 @@ def cmd_run(args: argparse.Namespace) -> int:
format=_LOG_FORMAT,
datefmt=_LOG_DATEFMT,
)
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)
Expand Down
14 changes: 14 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import contextlib
import importlib
import logging
import os
from datetime import datetime
from typing import Any
Expand All @@ -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.
Expand Down
58 changes: 58 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,64 @@ async def fake_serve(orchestrator, settings, **kwargs):
assert captured["level"] == logging.DEBUG


@pytest.mark.parametrize("argv", [["run"], ["run", "--debug"]])
def test_run_does_not_log_secrets_carried_in_urls(
argv: list[str],
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
) -> None:
"""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)
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):
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 = [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:
Expand Down
Loading