fix(logging): stamp scrubbed records with a private sentinel a caller cannot supply

A record stamped litellm_redacted=True skips the secret filter and both
formatters, and extra={"litellm_redacted": True} on any log call put that
stamp on a fresh record before the filter ran. The stamp is now a private
object compared by identity, so only the filter's own pass marks a record
scrubbed.
This commit is contained in:
mateo-berri 2026-09-16 17:30:49 -07:00
parent c340046de2
commit 55cf4c43ed
2 changed files with 20 additions and 2 deletions

View file

@ -80,11 +80,12 @@ def _redact_structured_value(key: str | None, value: str) -> str:
_REDACTED_RECORD_ATTR: Final = "litellm_redacted"
_REDACTED_STAMP: Final = object()
_UNREDACTED_SCALAR_TYPES: Final = (bool, int, float, type(None))
def _is_redacted(record: logging.LogRecord) -> bool:
return getattr(record, _REDACTED_RECORD_ATTR, False) is True
return getattr(record, _REDACTED_RECORD_ATTR, None) is _REDACTED_STAMP
def _scrubbing_changed_nothing(scrubbed: object, original: object) -> bool:
@ -193,7 +194,7 @@ class SecretRedactionFilter(logging.Filter):
elif not isinstance(value, _UNREDACTED_SCALAR_TYPES):
setattr(record, key, _redact_extra_value(key, value))
setattr(record, _REDACTED_RECORD_ATTR, True)
setattr(record, _REDACTED_RECORD_ATTR, _REDACTED_STAMP)
return True

View file

@ -1015,6 +1015,23 @@ def test_stamped_record_is_not_scanned_again(monkeypatch):
assert counting.calls == 1
def test_caller_supplied_stamp_never_skips_the_scrub(monkeypatch):
"""The stamp is a private sentinel, so a caller passing extra={"litellm_redacted": True}
still gets the full scrub, and only the filter's own stamp lets a later pass skip it."""
counting = _CountingPattern(secret_redaction._SECRET_RE)
monkeypatch.setattr(secret_redaction, "_SECRET_RE", counting)
monkeypatch.setattr("litellm._logging._ENABLE_SECRET_REDACTION", True)
record = _make_record(logging.DEBUG, "api_key=sk-1234567890abcdefghij")
record.litellm_redacted = True
assert SecretRedactionFilter().filter(record) is True
assert "sk-1234567890abcdefghij" not in record.getMessage()
assert counting.calls == 1
assert SecretRedactionFilter().filter(record) is True
assert counting.calls == 1
def test_stack_info_is_scrubbed_before_the_plain_formatter(monkeypatch):
monkeypatch.setattr("litellm._logging._ENABLE_SECRET_REDACTION", True)
record = _make_record(logging.INFO, "call failed")