Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(security): redact non-dict settings in log_settings' debug level (#6693)

LearningCircuit18ea1149f235
diff --git a/changelog.d/+settings-log-nondict-redaction.security.md b/changelog.d/+settings-log-nondict-redaction.security.md
new file mode 100644
index 0000000000..8c03f085d7
--- /dev/null
+++ b/changelog.d/+settings-log-nondict-redaction.security.md
@@ -0,0 +1 @@
+`log_settings`' debug level now redacts non-dict settings objects the same way it has always redacted dicts: the object is coerced to a mapping (mapping, pydantic `model_dump()`, or instance attributes) and run through the same `redact_sensitive_keys` pass; shapes that cannot be coerced log only their type name. Previously any non-dict was logged as a raw `repr()` with no redaction — a latent gap, since every current caller passes a snapshot dict, but one future caller away from shipping plaintext API keys into server logs while the documented contract promised redaction.
diff --git a/src/local_deep_research/settings/logger.py b/src/local_deep_research/settings/logger.py
index e2bce460ea..8fbd2cd5a0 100644
--- a/src/local_deep_research/settings/logger.py
+++ b/src/local_deep_research/settings/logger.py
@@ -10,6 +10,7 @@ Environment variable LDR_LOG_SETTINGS controls the verbosity:
"""
import os
+from collections.abc import Mapping
from typing import Any, Dict, Optional
from loguru import logger
@@ -85,7 +86,42 @@ def log_settings(
safe_settings = redact_sensitive_keys(settings)
logger.debug(f"{message} (redacted): {safe_settings}")
else:
- logger.debug(f"{message}: {settings}")
+ # Non-dict settings get the same redaction: coerce to a dict
+ # (mapping, pydantic model_dump, or instance attrs) so
+ # redact_sensitive_keys can mask secret-bearing keys. An
+ # unredactable shape logs the type name ONLY — never a raw
+ # repr, which would bypass the redaction this level promises
+ # for both shapes (see the docstring above).
+ def _unredactable_shape_message() -> str:
+ return (
+ f"{message}: <{type(settings).__name__} not logged — "
+ f"unredactable shape>"
+ )
+
+ # The whole coercion (including Mapping iteration, model_dump(),
+ # and vars()/__dict__ access) AND the redaction/formatting run
+ # inside one try: any of these can raise on an adversarial or
+ # malformed object (e.g. a Mapping with a raising __iter__, a
+ # __dict__ property that raises, or a coerced dict with
+ # non-string keys that break is_sensitive_setting_key()). On any
+ # exception we fall back to the type name only — never a raw
+ # repr or partially-redacted value.
+ try:
+ coerced = None
+ if isinstance(settings, Mapping):
+ coerced = dict(settings)
+ elif hasattr(settings, "model_dump"):
+ coerced = dict(settings.model_dump())
+ elif hasattr(settings, "__dict__"):
+ coerced = dict(vars(settings))
+ if coerced is not None:
+ logger.debug(
+ f"{message} (redacted): {redact_sensitive_keys(coerced)}"
+ )
+ else:
+ logger.debug(_unredactable_shape_message())
+ except Exception:
+ logger.debug(_unredactable_shape_message())
_SENSITIVE_KEY_PATTERNS = (
diff --git a/tests/security/test_settings_logger_non_dict_redaction.py b/tests/security/test_settings_logger_non_dict_redaction.py
new file mode 100644
index 0000000000..078c6ca353
--- /dev/null
+++ b/tests/security/test_settings_logger_non_dict_redaction.py
@@ -0,0 +1,194 @@
+"""``log_settings`` must redact non-dict settings the same way it redacts dicts.
+
+``settings/logger.py`` documents the ``debug`` level as "Log full settings
+at DEBUG level with sensitive keys redacted", but the implementation only
+redacts when ``settings`` is a dict — any other object is logged with a raw
+``f"{message}: {settings}"``, i.e. its full ``repr()``, with no redaction at
+all. Every current caller passes a snapshot dict, so the branch is latent —
+but one future caller passing a settings object (dataclass, pydantic model,
+plain instance with ``openai_api_key``-style attributes) ships plaintext
+secrets into server logs while the docstring still promises redaction.
+
+These tests also cover the defensive fallback: coercing an arbitrary object
+to a dict (Mapping iteration, ``model_dump()``, ``vars()``) and then
+redacting it can itself raise (non-string keys, a Mapping whose ``__iter__``
+raises, a ``__dict__`` property that raises). In every such case the log
+must fall back to the type name only — never a partially-formed value and
+never an escaping exception.
+"""
+
+from types import MappingProxyType
+
+import pytest
+
+from local_deep_research.settings.logger import log_settings
+
+_SECRET = "sk-supersecret-7f3a"
+
+
+class _FauxSettings:
+ """A non-dict settings object whose repr carries a secret value."""
+
+ def __init__(self):
+ self.openai_api_key = _SECRET
+ self.model = "some-model"
+
+ def __repr__(self) -> str:
+ return (
+ f"_FauxSettings(openai_api_key={self.openai_api_key!r}, "
+ f"model={self.model!r})"
+ )
+
+
+def test_debug_level_redacts_non_dict_settings(loguru_caplog):
+ """A non-dict settings object must never leak secret attribute values.
+ RED on main: the else-branch logs the raw repr unredacted."""
+ with loguru_caplog.at_level("DEBUG"):
+ log_settings(_FauxSettings(), "probe message", force_level="debug")
+
+ text = loguru_caplog.text
+ assert _SECRET not in text, (
+ "log_settings debug level logged a non-dict settings object's raw "
+ "repr, including the plaintext api key"
+ )
+ # The redaction must actually happen (not just "drop everything"): the
+ # sensitive key is replaced with the marker, and a non-secret sibling
+ # value is still visible so the log stays useful.
+ assert "***REDACTED***" in text
+ assert "some-model" in text
+
+
+def test_debug_level_still_redacts_dict_settings(loguru_caplog):
+ """The existing dict path keeps redacting (guard against over-fixing)."""
+ with loguru_caplog.at_level("DEBUG"):
+ log_settings(
+ {"openai_api_key": _SECRET, "model": "some-model"},
+ "probe message",
+ force_level="debug",
+ )
+
+ assert _SECRET not in loguru_caplog.text
+ assert "***REDACTED***" in loguru_caplog.text
+
+
+def test_debug_level_still_names_the_object(loguru_caplog):
+ """The diagnostic itself survives: the message and the coerced,
+ redacted content (identifying the settings shape) still appear — just
+ never the raw secret value."""
+ with loguru_caplog.at_level("DEBUG"):
+ log_settings(_FauxSettings(), "probe message", force_level="debug")
+
+ text = loguru_caplog.text
+ assert "probe message" in text
+ # _FauxSettings is coercible via vars(), so the diagnostic is the
+ # redacted coerced dict, not just a type name — the non-secret "model"
+ # value is what lets a reader identify which settings this was.
+ assert "some-model" in text
+
+
+def test_debug_level_redacts_mapping_proxy_with_non_string_key(loguru_caplog):
+ """A MappingProxyType with a non-string key breaks the redaction step
+ itself (``key.lower()`` on an int raises inside
+ ``is_sensitive_setting_key``). The whole coercion+redaction must be
+ guarded so this falls back to the type name only, never a raw dump
+ of the secret value."""
+ settings = MappingProxyType({1: _SECRET})
+
+ with loguru_caplog.at_level("DEBUG"):
+ log_settings(settings, "probe message", force_level="debug")
+
+ text = loguru_caplog.text
+ assert _SECRET not in text
+ assert "mappingproxy" in text
+ assert "unredactable shape" in text
+
+
+def test_debug_level_redacts_pydantic_model(loguru_caplog):
+ """A pydantic settings object (project dependency) is coerced via
+ ``model_dump()`` and redacted like a dict. Uses a nested submodel so
+ this actually exercises ``model_dump()`` rather than the ``__dict__``
+ fallback: ``model_dump()`` recursively serializes the nested model into
+ a plain dict, which ``redact_sensitive_keys`` then redacts one level
+ in; ``vars()`` would instead leave the nested field as a live pydantic
+ instance whose own repr carries the secret unredacted."""
+ pydantic = pytest.importorskip("pydantic")
+
+ class _Inner(pydantic.BaseModel):
+ api_key: str = _SECRET
+
+ class _PydanticSettings(pydantic.BaseModel):
+ inner: _Inner = _Inner()
+ model: str = "some-model"
+
+ with loguru_caplog.at_level("DEBUG"):
+ log_settings(_PydanticSettings(), "probe message", force_level="debug")
+
+ text = loguru_caplog.text
+ assert _SECRET not in text
+ assert "***REDACTED***" in text
+ assert "some-model" in text
+
+
+def test_debug_level_type_name_only_for_slotted_object(loguru_caplog):
+ """An object with ``__slots__`` (no ``__dict__``, not a Mapping, no
+ ``model_dump``) is unredactable — it must log the type name only, never
+ its repr (which would carry the secret via the custom ``__repr__``)."""
+
+ class _SlottedSecret:
+ __slots__ = ("api_key",)
+
+ def __init__(self):
+ self.api_key = _SECRET
+
+ def __repr__(self):
+ return f"_SlottedSecret(api_key={self.api_key!r})"
+
+ with loguru_caplog.at_level("DEBUG"):
+ log_settings(_SlottedSecret(), "probe message", force_level="debug")
+
+ text = loguru_caplog.text
+ assert _SECRET not in text
+ assert "_SlottedSecret" in text
+ assert "unredactable shape" in text
+
+
+def test_debug_level_type_name_only_for_primitive(loguru_caplog):
+ """A bare primitive (no Mapping/model_dump/__dict__ shape) also falls
+ back to the type name only, not a raw repr of its value."""
+ with loguru_caplog.at_level("DEBUG"):
+ log_settings(_SECRET, "probe message", force_level="debug")
+
+ text = loguru_caplog.text
+ assert _SECRET not in text
+ assert "str" in text
+ assert "unredactable shape" in text
+
+
+def test_debug_level_falls_back_on_raising_mapping(loguru_caplog):
+ """A Mapping whose ``__iter__`` raises must not let the exception
+ escape ``log_settings`` — it must fall back to the type name only,
+ and must never leak a secret held in the object's other attributes."""
+ from collections.abc import Mapping
+
+ class _BoobyTrappedMapping(Mapping):
+ def __init__(self):
+ self._hidden_api_key = _SECRET
+
+ def __getitem__(self, key):
+ return self._hidden_api_key
+
+ def __iter__(self):
+ raise RuntimeError("boom")
+
+ def __len__(self):
+ return 1
+
+ with loguru_caplog.at_level("DEBUG"):
+ log_settings(
+ _BoobyTrappedMapping(), "probe message", force_level="debug"
+ )
+
+ text = loguru_caplog.text
+ assert _SECRET not in text
+ assert "_BoobyTrappedMapping" in text
+ assert "unredactable shape" in text