Redact through the log record factory, not a logger filter

Adding a filter at interpreter startup created Red-Lavalink's logger before
Red set its logger class, so the logger lacked trace() and verbose() and
Audio could not connect. Wrapping the record factory touches no logger; a
test checks that importing the module creates none.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GUebqhE8dK19vyn4Ct5g1L
This commit is contained in:
ziadarafatandClaude Opus 5.5 committed 2026-11-04 19:53:11 -07:00
1 parent 81f211c687
commit fb1a15b97d
2 files changed
+63 -29

No files matched your search

+32 -19
View File
@@ -2,16 +2,24 @@
Red-Lavalink logs its connection headers, password included, every time
Audio connects. The image imports this module at interpreter startup (through
a ``.pth`` file), before Red configures logging, and adds a filter that
redacts the header.
a ``.pth`` file), before Red configures logging.
It wraps the log record factory instead of adding a filter to Red-Lavalink's
logger: creating that logger this early would make it a plain
``logging.Logger`` instead of Red's logger class, which has the ``trace`` and
``verbose`` methods Red-Lavalink calls.
"""
import logging
from collections.abc import Mapping
from collections.abc import Callable, Mapping
from typing import Any
LOGGER = "red.Audio.WS.LLNode"
SECRET_HEADERS = ("Authorization",)
# Factories this module installed, so installing again is a no-op
_installed: set[Callable[..., logging.LogRecord]] = set()
def redact(value: object) -> object:
"""Return ``value`` with secret headers replaced, if it's a mapping."""
@@ -25,25 +33,30 @@ def redact(value: object) -> object:
return value
class RedactHeaders(logging.Filter):
"""Redact secret headers in a log record's arguments."""
def filter(self, record: logging.LogRecord) -> bool:
"""Rewrite the record's arguments; never drop the record."""
if isinstance(record.args, tuple):
record.args = tuple(redact(a) for a in record.args)
elif isinstance(record.args, Mapping):
record.args = {
k: redact(v) for k, v in record.args.items()
}
return True
def redact_record(record: logging.LogRecord) -> None:
"""Redact secret headers in ``record``'s arguments, in place."""
if isinstance(record.args, tuple):
record.args = tuple(redact(a) for a in record.args)
elif isinstance(record.args, Mapping):
record.args = {k: redact(v) for k, v in record.args.items()}
def install() -> None:
"""Add the filter to Red-Lavalink's logger (safe to call twice)."""
logger = logging.getLogger(LOGGER)
if not any(isinstance(f, RedactHeaders) for f in logger.filters):
logger.addFilter(RedactHeaders())
"""Redact Red-Lavalink's records as they are created (idempotent)."""
previous: Callable[..., logging.LogRecord] = (
logging.getLogRecordFactory()
)
if previous in _installed:
return
def factory(*args: Any, **kwargs: Any) -> logging.LogRecord: # noqa: ANN401
record = previous(*args, **kwargs)
if record.name == LOGGER:
redact_record(record)
return record
_installed.add(factory)
logging.setLogRecordFactory(factory)
install()
+31 -10
View File
@@ -1,6 +1,8 @@
"""The Lavalink password never reaches the logs."""
import logging
import subprocess
import sys
import pytest
@@ -13,24 +15,43 @@ def test_password_is_redacted(caplog: pytest.LogCaptureFixture) -> None:
logger = logging.getLogger(logfilter.LOGGER)
headers = {"Authorization": "hunter2", "User-Id": "42"}
with caplog.at_level(logging.INFO, logger=logfilter.LOGGER):
logger.info(
"connecting to %s with headers %s", "ws://x", headers
)
logger.info("connect %s headers %s", "ws://x", headers)
assert "hunter2" not in caplog.text
assert "<redacted>" in caplog.text
assert "'User-Id': '42'" in caplog.text
assert headers["Authorization"] == "hunter2"
def test_other_loggers_are_untouched(caplog: pytest.LogCaptureFixture) -> None:
"""Only Red-Lavalink's records are rewritten."""
logfilter.install()
with caplog.at_level(logging.INFO, logger="other"):
logging.getLogger("other").info("%s", {"Authorization": "x"})
assert "'Authorization': 'x'" in caplog.text
def test_install_is_idempotent() -> None:
"""Importing and installing again adds only one filter."""
"""Installing twice wraps the factory only once."""
logfilter.install()
factory = logging.getLogRecordFactory()
logfilter.install()
filters = logging.getLogger(logfilter.LOGGER).filters
assert sum(isinstance(f, logfilter.RedactHeaders) for f in filters) == 1
assert logging.getLogRecordFactory() is factory
def test_other_arguments_are_untouched() -> None:
"""Non-mapping arguments pass through as they are."""
assert logfilter.redact("text") == "text"
assert logfilter.redact({"a": 1}) == {"a": 1}
def test_import_creates_no_logger() -> None:
"""Importing it early must not create Red-Lavalink's logger.
Red sets its own logger class later; a logger created before that
lacks the trace() and verbose() methods Red-Lavalink calls.
"""
code = (
"import logging, dogebot.logfilter as f; "
"print(f.LOGGER in logging.Logger.manager.loggerDict)"
)
out = subprocess.run( # noqa: S603
[sys.executable, "-c", code],
capture_output=True,
text=True,
check=True,
)
assert out.stdout.strip() == "False"