~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
harden: redact credentials in the log file sink (#5768)
LearningCircuitd18c05decbfa
diff --git a/changelog.d/5768.security.md b/changelog.d/5768.security.mdnew file mode 100644index 0000000000..44c74f8578--- /dev/null+++ b/changelog.d/5768.security.md@@ -0,0 +1 @@+Credentials are now redacted from every log record before it reaches any sink (stderr, the `<LDR_DATA_DIR>/logs/*.log` file, the per-user database and the browser progress stream): the message, bound/structured `extra` fields, and exception text (value, notes, chained and grouped exceptions) are scrubbed for credential shapes and sensitive `name=value` assignments, and values bound under a sensitive key name are masked whole. To keep that scan bounded, any single logged string longer than 32 KiB (32,768 characters) is now truncated in **every** sink, including the server log file and stderr: the text is cut at the last whitespace before the limit (a newline, tab, other control character or line/paragraph separator does not count) and the rest replaced by ` [... N characters omitted from log output]`, so a string with no such whitespace in its first 32 KiB is replaced by the marker alone. The database and browser caps now say that server logs keep up to 32 KiB and report the length before truncation. An exception whose text is redacted or truncated is logged as a rebuilt copy -- its builtin type, or `RuntimeError("<TypeName>: ...")` for an application exception class -- with the original traceback; the live exception is not modified.diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.pyindex 84b5b119f8..94f55f05a3 100644--- a/src/local_deep_research/config/llm_config.py+++ b/src/local_deep_research/config/llm_config.py@@ -341,9 +341,10 @@ def get_llm(} | {"none"}if provider not in valid_providers:# ``provider`` is a user-settable value (``llm.provider``) reaching a- # log sink. The process-wide ``sanitize_log_record`` patcher already- # strips control characters (\x00-\x1f, \x7f) from every loguru- # record's message, so ``sanitize_for_log`` isn't newline/ANSI+ # log sink. The process-wide loguru patcher (``_sanitize_record`` in+ # utilities/log_utils.py, via ``redact_log_record``) already strips+ # control characters (\x00-\x1f, \x7f) from every record's message+ # and redacts credentials, so ``sanitize_for_log`` isn't newline/ANSI# defence here -- it adds the length cap plus the ``None`` guard# below. The exception text is a different audience (it never# reaches a client -- boundaries answer withdiff --git a/src/local_deep_research/mcp/server.py b/src/local_deep_research/mcp/server.pyindex c741daa7b3..fc7fc85475 100644--- a/src/local_deep_research/mcp/server.py+++ b/src/local_deep_research/mcp/server.py@@ -1020,13 +1020,20 @@ def get_configuration() -> Dict[str, Any]:def configure_mcp_logging(sink=None):- """Send this process's logs to stderr, with control characters stripped.+ """Send this process's logs to stderr, with credentials redacted from+ log messages and bound ``extra`` fields and control characters stripped.++ Exception values attached to a record (``logger.exception``,+ ``opt(exception=...)``) are NOT scrubbed here and render to stderr as+ before, unredacted: the rendered exception-value scrub+ (``log_utils._redact_exception_value``) is only installed by the web+ process's ``config_logger``.MCP uses stdout for JSON-RPC, so logging goes to stderr. This runs in aseparate subprocess (ldr-mcp), so logger.remove() only affects this MCPprocess, not the main LDR application."""- from ..security.log_sanitizer import sanitize_log_record+ from ..security.log_sanitizer import redact_log_recordlogger.remove()# local_deep_research/__init__.py disables the package's own namespace, so@@ -1034,12 +1041,19 @@ def configure_mcp_logging(sink=None):# only third-party records get here. config_logger does the same on the# web path.logger.enable("local_deep_research")- # The same patcher config_logger installs. Without it a query containing a- # newline splits one WARNING into two stderr lines, and queries reach the- # log verbatim (query[:80] in the citation-handler warnings). loguru holds- # one patcher per process, so this has to be set here rather than- # inherited.- logger.configure(patcher=sanitize_log_record)+ # The same redaction chokepoint config_logger's _sanitize_record layers+ # over sanitize_log_record for the web process's sinks: control+ # characters stripped (a query containing a newline used to split one+ # WARNING into two stderr lines) AND credentials redacted (a bare+ # api_key=/token= in a message, or a secret bound via logger.bind(),+ # reaching this process's stderr without going through scrub_error+ # first). loguru holds one patcher per process, so this has to be set+ # here rather than inherited. redact_log_record lives in+ # security/log_sanitizer.py rather than utilities/log_utils.py (which+ # would pull in the web stack) precisely so the MCP subprocess can share+ # it. Not extended here: log_utils._redact_exception_value's+ # rendered-exception-value scrub, which stays web-process-only.+ logger.configure(patcher=redact_log_record)# diagnose=False: loguru's default is True, which renders repr() of every# local in every traceback frame on exception. The many logger.exception()# call sites in this file run with frame locals that hold credentialsdiff --git a/src/local_deep_research/security/log_sanitizer.py b/src/local_deep_research/security/log_sanitizer.pyindex c54fa1a06e..812f503137 100644--- a/src/local_deep_research/security/log_sanitizer.py+++ b/src/local_deep_research/security/log_sanitizer.py@@ -20,6 +20,8 @@ import dataclassesimport refrom typing import Any, Optional, Union+from .data_sanitizer import DataSanitizer, REDACTION_TEXT+# Strip C0/C1 control characters and dangerous Unicode format characters,# but preserve visible Unicode (accented, CJK, emoji, etc.)@@ -258,15 +260,31 @@ _CREDENTIAL_PATTERNS: list[tuple[re.Pattern[str], str]] = [# ID that every real Slack token carries (gitleaks expects ``[0-9]{10,13}``# segments). This keeps real tokens redacted while leaving prose such as# ``xapp-release-notes-2026`` intact.+ #+ # Linear-time form (these patterns run on every log record through+ # redact_log_message): the naive ``\bxox[baeprs]-(?=[A-Za-z0-9-]*...)``+ # lets EVERY ``xoxb-`` inside one ``[A-Za-z0-9-]`` run start an attempt+ # whose lookahead rescans the rest of the run, so ``"xoxb-" * n`` is+ # O(n^2) (measured: 10 KB 0.3 s, 20 KB 1.2 s). Every start inside the+ # same run sees a suffix of what the run's leftmost ``\bxox`` start sees+ # (same run end, same later digits, fewer characters), so if any start+ # in a run matches, the leftmost one does. Attempts therefore begin only+ # at a run start (the lookbehind) and commit, atomically, to the first+ # ``\bxox*-`` in the run; the run prefix before it is captured and kept.+ # Same matches as the naive form, one scan per run.(re.compile(- r"\bxox[baeprs]-(?=[A-Za-z0-9-]*[0-9]{9,})[A-Za-z0-9-]{10,}\b"+ r"(?<![A-Za-z0-9-])(?>([A-Za-z0-9-]*?)\bxox[baeprs]-)"+ r"(?=[A-Za-z0-9-]*[0-9]{9,})[A-Za-z0-9-]{10,}\b"),- "[REDACTED_KEY]",+ r"\1[REDACTED_KEY]",),(- re.compile(r"\bxapp-(?=[A-Za-z0-9-]*[0-9]{9,})[A-Za-z0-9-]{10,}\b"),- "[REDACTED_KEY]",+ re.compile(+ r"(?<![A-Za-z0-9-])(?>([A-Za-z0-9-]*?)\bxapp-)"+ r"(?=[A-Za-z0-9-]*[0-9]{9,})[A-Za-z0-9-]{10,}\b"+ ),+ r"\1[REDACTED_KEY]",),# Google OAuth access tokens (ya29...).(re.compile(r"\bya29\.[A-Za-z0-9_\-]{20,}"), "[REDACTED_KEY]"),@@ -277,11 +295,21 @@ _CREDENTIAL_PATTERNS: list[tuple[re.Pattern[str], str]] = [# redacted — over-redaction, not a leak. ``/`` is intentionally omitted# (RFC 7515 JWTs are base64url); ``Bearer``/``Authorization`` paths# already catch standard-base64 JWTs.+ #+ # Linear-time form, for the reason given on the Slack patterns above:+ # ``.`` is outside the segment class, so a segment always runs to the end+ # of its ``[A-Za-z0-9_+-]`` run, and the naive ``\beyJ...`` retried (and+ # rescanned) at every ``eyJ`` inside one run — ``"eyJ-" * n`` was O(n^2)+ # (320 KB: ~60 s). Only the run's leftmost ``\beyJ`` can matter (it+ # has the longest first segment and the same run end), so attempts+ # start at run starts and commit to it; the segments are possessive+ # because backtracking inside a run can never reach a ``.``.(re.compile(- r"\beyJ[A-Za-z0-9_+\-]{8,}\.[A-Za-z0-9_+\-]{8,}\.[A-Za-z0-9_+\-]+"+ r"(?<![A-Za-z0-9_+\-])(?>([A-Za-z0-9_+\-]*?)\beyJ)"+ r"[A-Za-z0-9_+\-]{8,}+\.[A-Za-z0-9_+\-]{8,}+\.[A-Za-z0-9_+\-]+"),- "[REDACTED_KEY]",+ r"\1[REDACTED_KEY]",),]@@ -580,3 +608,370 @@ def sanitize_error_details(value: Any) -> Any:if isinstance(value, str):return sanitize_error_message(value)return value+++# ---------------------------------------------------------------------------+# Log-sink credential redaction (the backstop applied by the loguru patcher)+# ---------------------------------------------------------------------------+#+# ``utilities/log_utils.py`` installs :func:`redact_log_message` /+# :func:`redact_log_extra` as a global loguru *patcher* so every record is+# scrubbed once, before it reaches ANY sink — stderr, the encrypted per-user+# DB, the browser progress stream, and (when enabled) the persistent,+# unencrypted ``<LDR_DATA_DIR>/logs/*.log`` file.+#+# The sanctioned per-call-site pattern is ``logger.error(scrub_error(msg,+# secret))`` (see :func:`scrub_error`). This sink-level pass is the BACKSTOP+# for the recurring class of bug where a call site forgets it: a credential+# that rides the message as a bare ``field=value`` pair, or that is bound as+# a structured ``extra`` value under a key the name-based checks miss. Both+# the message string and the structured extras are scrubbed here.++# Settings redaction's default secret names, plus credentials that appear only+# in logs. Routing fields remain explicitly exempt below. This is a set of+# exact names; message text is matched against these names only. Structured+# ``extra`` KEYS additionally get settings redaction's underscore-suffix rule+# (``openai_api_key``, ``db_password``; see ``_is_sensitive_log_key``), but+# a prefixed name in message text (``db_password=...``) is not recognised by+# name -- only by the credential shapes ``sanitize_error_message`` knows.+LOG_SENSITIVE_KEYS: frozenset = frozenset(+ DataSanitizer.DEFAULT_SENSITIVE_KEYS+) | frozenset(+ {+ "passwd",+ "pwd",+ "user_password",+ "encryption_key",+ "sqlcipher_key",+ "derived_key",+ "salt",+ "authorization",+ "id_token",+ "subscription_key",+ }+)++# ``extra`` keys the log sinks read for routing / behaviour. They are never+# redacted, or the DB sink loses per-user attribution+# (``database_sink``/``_get_research_id`` read ``username``/``research_id``)+# and the frontend filter loses its ``policy_audit`` guard. None of these+# hold a secret.+_LOG_STRUCTURAL_EXTRA_KEYS: frozenset = frozenset(+ {+ "research_id",+ "username",+ "policy_audit",+ }+)++# Keep query and bare-assignment credential names in agreement, but retain+# their distinct value boundaries so harmless query parameters survive.+_LOG_SENSITIVE_NAME_PATTERN = "|".join(+ re.escape(name).replace("_", r"[_-]?")+ for name in sorted(LOG_SENSITIVE_KEYS, key=lambda name: (-len(name), name))+)+_SENSITIVE_QUERY_RE = re.compile(+ r"(?i)([?&](?:" + _LOG_SENSITIVE_NAME_PATTERN + r")=)([^&\s#]+)"+)++# Quoted values may contain spaces and escaped quotes. An unfinished quote+# consumes the remaining message. Unquoted values end at whitespace, not at+# punctuation that may be part of a password. Prose using ':' is unchanged.+_SENSITIVE_ASSIGNMENT_RE = re.compile(+ r"(?i)(?<![\w.?&-])(" + _LOG_SENSITIVE_NAME_PATTERN + r")"+ r"(\s*=\s*)"+ r"(?:\"(?:\\.|[^\"\\])*(?:\"|\\?$)|'(?:\\.|[^'\\])*(?:'|\\?$)|[^\s]+)"+)+++def redact_sensitive_assignments(message: str) -> str:+ """Redact known credential assignments with quoted or unquoted values.++ Complements :func:`sanitize_error_message` (which only redacts a+ ``field=value`` when it sits in a URL query string, i.e. preceded by+ ``?``/``&``). The field name (``api_key=``, ``password=``, ``token=``,+ ...) is preserved; only its value is replaced. Returns *message*+ unchanged when it is falsy or contains no sensitive assignment.+ """+ if not message:+ return message+ return _SENSITIVE_ASSIGNMENT_RE.sub(r"\1\2" + REDACTION_TEXT, message)+++# Upper bound on how much of ONE string the log-path redaction scans. The+# patcher runs synchronously in the logging thread on every record (message,+# every ``extra`` string leaf, every rendered exception field), so its cost+# must not grow with whatever a call site hands it -- fetched page text, a+# response body, a long traceback string. Text past the bound is NOT passed+# through unscanned (that would ship any secret in it); it is dropped and+# replaced by a marker giving the omitted length, in every sink (stderr,+# file, DB, frontend). 32 KiB keeps a fetched page (the fetch tool logs up+# to 10,000 characters) intact. On adversarial 32 KiB input (a run of+# spaces, or of ``https://a:b@ ``) the two passes of :func:`_redact_log_text`+# measured up to ~80 ms together, the same for a 1 MB or a 10 MB string; the+# cut itself is one scan of at most 32 KiB (under 0.3 ms).+_LOG_REDACTION_MAX_CHARS = 32_768+# The run at the end of a truncated head, matched reversed: non-whitespace+# plus every character ``strip_control_chars`` removes (``\n``, ``\t``,+# ``\x1c``, U+0085, U+2028, ...). ``_redact_log_text`` strips those between+# its passes, which rejoins a token they split, so they are not a boundary.+# Built from ``_UNSAFE_CHAR_RE`` itself so the two cannot drift apart.+_LOG_TRAILING_RUN_RE = re.compile(r"(?:\S|" + _UNSAFE_CHAR_RE.pattern + r")*")+# Digits bounded (ASCII, at most 19) so a forged marker cannot make+# ``int()`` exceed its digit limit; the real count is far below that.+_LOG_OMISSION_MARKER_RE = re.compile(+ r" \[\.\.\. ([0-9]{1,19}) characters omitted from log output\]\Z"+)+++def _truncate_for_log_redaction(message: str) -> tuple[str, str]:+ """Split *message* into the part to scan and a marker for the rest.++ The cut only lands at a boundary: a whitespace character that+ :func:`strip_control_chars` keeps (a space, U+00A0, U+3000, ...). A+ control or separator whitespace character (``\n``, ``\t``, ``\x1c``,+ U+0085, U+2028, ...) is not one, because :func:`_redact_log_text`+ strips it between its passes and so joins the text on either side.+ Unless the character at the bound is a boundary, the cut moves back to+ just after the last boundary before the bound, dropping the whole run+ the bound falls in -- however long, so a string with no boundary in its+ first ``_LOG_REDACTION_MAX_CHARS`` characters keeps nothing but the+ marker. A partial run could be a credential fragment its shape pattern+ no longer recognises (a key cut below its minimum length, URL userinfo+ cut before its ``@``, a password cut at a ``&``). A credential token+ contains no boundary character -- one split by a stripped control+ character is a single run here, as it is to the second pass -- so the+ head keeps at most a label that the passes redact or that holds no+ secret (``password = ``, ``Authorization: Basic ``, or an unterminated+ quote, which the assignment pass redacts to the end of the head, so a+ quoted value with spaces in it is covered too).+ """+ if len(message) <= _LOG_REDACTION_MAX_CHARS:+ return message, ""+ cut = _LOG_REDACTION_MAX_CHARS+ at_bound = message[cut]+ if not at_bound.isspace() or _UNSAFE_CHAR_RE.match(at_bound):+ # ``\S`` is exactly ``not str.isspace()``; matching the reversed head+ # measures the trailing run in one linear scan.+ run = _LOG_TRAILING_RUN_RE.match(message[cut - 1 :: -1])+ cut -= run.end()+ omitted = len(message) - cut+ return message[:cut], f" [... {omitted} characters omitted from log output]"+++def log_length_before_truncation(message: str) -> int:+ """Length *message* had before the log-path length bound cut it.++ For a string ending in the marker :func:`redact_log_message` appends,+ the kept text plus the omitted count; otherwise ``len(message)``. Both+ are measured after redaction, which may change the length. Never+ raises: a marker the pattern does not accept (logged text can forge+ one) yields ``len(message)``.+ """+ marker = _LOG_OMISSION_MARKER_RE.search(message)+ if marker is None:+ return len(message)+ try:+ return marker.start() + int(marker.group(1))+ except ValueError:+ return len(message)+++def redact_log_message(message: str) -> str:+ """Full credential scrub for a log *message* string.++ Composes the credential-*shape* pass (:func:`sanitize_error_message`:+ URL userinfo, ``?param=`` credentials, ``Bearer``/``x-api-key`` headers,+ well-known key prefixes, JWTs) with the bare ``field=value`` pass+ (:func:`redact_sensitive_assignments`). This is the same redaction the+ sanctioned :func:`scrub_error` applies for credential shapes, run as a+ backstop on every record. Non-sensitive text up to+ ``_LOG_REDACTION_MAX_CHARS`` characters is returned unchanged; a longer+ string is cut there (see :func:`_truncate_for_log_redaction`) and the+ remainder replaced by an omitted-length marker, so the cost per string+ is bounded.+ """+ if not message:+ return message+ head, marker = _truncate_for_log_redaction(message)+ return _redact_bounded_log_text(head) + marker+++def _redact_bounded_log_text(text: str) -> str:+ """:func:`redact_log_message`'s passes, on text already within the bound."""+ shaped = sanitize_error_message(text)+ queried = _SENSITIVE_QUERY_RE.sub(r"\1" + REDACTION_TEXT, shaped)+ return redact_sensitive_assignments(queried)+++def _redact_log_text(value: str) -> str:+ """Redact, strip control characters, then redact again.++ The first pass sees the original separators, so ``failure\ntoken=x`` does+ not glue into an unrecognisable ``failuretoken=x``; the second catches a+ name that only becomes recognisable once invisible characters are gone+ (``api_<U+200B>key=x``). Used for the message and every ``extra`` string.+ The length bound is applied once, up front, so the second pass never+ re-truncates the first pass's output.+ """+ if not value:+ return value+ head, marker = _truncate_for_log_redaction(value)+ first = _redact_bounded_log_text(head)+ return _redact_bounded_log_text(strip_control_chars(first)) + marker+++def _is_sensitive_log_key(key: Any) -> bool:+ """True when *key* names a secret under settings redaction's rules.++ Delegates to ``DataSanitizer.is_sensitive_setting`` with+ :data:`LOG_SENSITIVE_KEYS`: the last dotted segment matches a name exactly+ or as an underscore-delimited suffix (``openai_api_key``,+ ``db_password``), after invisible characters are removed from it. Keys+ only -- message text uses the exact names.+ """+ if not isinstance(key, str):+ return False+ return DataSanitizer.is_sensitive_setting(+ key, sensitive_keys=LOG_SENSITIVE_KEYS+ )+++def _is_empty_log_value(value: Any) -> bool:+ """``None`` or an empty str/list/dict (left readable, like DataSanitizer).++ Type-checked rather than ``value in (None, "", [], {})`` so an object with+ a raising ``__eq__`` cannot abort the redaction of the whole record.+ """+ if value is None:+ return True+ return isinstance(value, (str, list, dict)) and len(value) == 0+++# Nesting bound for ``extra`` values: a container at this depth or deeper+# (a value bound directly in ``extra`` is depth 1) becomes a placeholder.+_LOG_EXTRA_MAX_DEPTH = 32+++def _scrub_log_leaf(value: Any, _depth: int = 0, _active: Any = None) -> Any:+ """Recursively scrub credential shapes from an ``extra`` value.++ Redacts by key *name* (a value under a sensitive key is masked whole)+ AND by value *shape* (a credential embedded in a string leaf under any+ key is scrubbed) — the two halves that a name-only or shape-only check+ would each miss. Non-string, non-container leaves pass through.++ A container that contains itself (directly or further down) is rendered+ as ``"<cycle>"`` and a container at depth :data:`_LOG_EXTRA_MAX_DEPTH`+ or deeper as ``"<nested too deep>"``, so neither raises+ ``RecursionError`` and trips :func:`redact_log_record`'s fail-closed+ fallback for the whole record.+ """+ if isinstance(value, str):+ return _redact_log_text(value)+ if not isinstance(value, (dict, list, tuple)):+ return value+ if _depth >= _LOG_EXTRA_MAX_DEPTH:+ return "<nested too deep>"+ if _active is None:+ _active = set()+ marker = id(value)+ if marker in _active:+ return "<cycle>"+ _active.add(marker)+ try:+ if isinstance(value, dict):+ return {+ k: (+ REDACTION_TEXT+ if _is_sensitive_log_key(k) and not _is_empty_log_value(v)+ else _scrub_log_leaf(v, _depth + 1, _active)+ )+ for k, v in value.items()+ }+ return [_scrub_log_leaf(v, _depth + 1, _active) for v in value]+ finally:+ _active.discard(marker)+++def redact_log_extra(extra: Any) -> Any:+ """Redact secrets from a loguru record's structured ``extra`` mapping.++ * Keys the sinks depend on for routing (``research_id``, ``username``,+ ``policy_audit``) pass through untouched.+ * A value under a sensitive key name (:data:`LOG_SENSITIVE_KEYS`, exact+ or as an ``_``-delimited suffix such as ``openai_api_key``) is masked+ whole (empty values are left readable, mirroring ``DataSanitizer``).+ * Every other value is recursively scrubbed for credential *shapes*, so+ a token/URL/query bound under an innocuous key (the family of bug the+ name-based checks miss) is still caught. String values get the same+ control-character strip as the message, between two redaction passes.++ Returns a new dict; the input is not mutated. A non-dict ``extra`` is+ returned unchanged.+ """+ if not isinstance(extra, dict):+ return extra+ out: dict = {}+ # ``extra`` itself counts as an enclosing container, so a value that+ # refers back to the mapping is reported as a cycle at the first level.+ active = {id(extra)}+ for key, value in extra.items():+ if key in _LOG_STRUCTURAL_EXTRA_KEYS:+ out[key] = value+ elif _is_sensitive_log_key(key) and not _is_empty_log_value(value):+ out[key] = REDACTION_TEXT+ else:+ out[key] = _scrub_log_leaf(value, 1, active)+ return out+++def redact_log_record(record) -> None:+ """loguru patcher: control-char strip + message/extra credential redaction.++ Layers :func:`redact_log_message` and :func:`redact_log_extra` on top of+ :func:`sanitize_log_record`'s control-character strip -- the same+ composition ``utilities.log_utils._sanitize_record`` uses for the web+ process's sinks, minus that function's additional rendered-exception-value+ scrub (:func:`utilities.log_utils._redact_exception_value`), which stays+ in ``log_utils`` since it is only reachable through that module's patcher.+ Kept here, rather than in ``log_utils``, because that module imports the+ web stack at module scope and the MCP subprocess (``mcp/server.py``'s+ ``configure_mcp_logging``) must not pull that in -- so this is the shared+ chokepoint both processes' patchers install, catching a credential that+ reaches a record (bare ``field=value`` in the message, or a secret bound+ via ``logger.bind()``) without having gone through ``scrub_error`` first.++ Fail-closed per field, mirroring ``log_utils._sanitize_record``: a field+ that fails to redact is replaced rather than passed through as-is, since+ doing so could ship the very secret the redactor choked on. For ``extra``+ the routing keys (:data:`_LOG_STRUCTURAL_EXTRA_KEYS`) are kept on that+ path -- they pass through unredacted on the normal path too -- so a+ record whose other extras fail to redact still reaches the right user's+ DB log and keeps its ``policy_audit`` frontend guard.+ """+ try:+ # Preserve credential boundaries that control stripping may remove,+ # then catch names that become recognizable after normalization.+ record["message"] = _redact_log_text(record["message"])+ except Exception:+ record["message"] = "<log message redacted: sanitization error>"++ extra = record.get("extra")+ if extra:+ try:+ record["extra"] = redact_log_extra(extra)+ except Exception:+ record["extra"] = _structural_extra_only(extra)+++def _structural_extra_only(extra: Any) -> dict:+ """The routing keys of *extra* alone; ``{}`` if even that fails."""+ try:+ return {+ key: extra[key]+ for key in _LOG_STRUCTURAL_EXTRA_KEYS+ if key in extra+ }+ except Exception:+ return {}diff --git a/src/local_deep_research/utilities/log_utils.py b/src/local_deep_research/utilities/log_utils.pyindex 8c69c96c44..ab9a46d770 100644--- a/src/local_deep_research/utilities/log_utils.py+++ b/src/local_deep_research/utilities/log_utils.py@@ -6,6 +6,7 @@ Utilities for logging.from __future__ import annotationsimport asyncio+import builtinsimport inspect# import logging - needed for InterceptHandler compatibility@@ -87,18 +88,21 @@ Default log directory to use.# (model outputs, long tracebacks, extracted text) — many KB per call — which# is useless in the UI (a single massive blob fills the viewport) and inflates both# wire traffic and client-side state. Container-log/stderr, file, and DB-# sinks remain unchanged, so full diagnostics are preserved for grep/DB-# queries. The cap bounds the *prefix* preserved from the original message;-# the wire payload is the prefix plus a short truncation indicator (~100-# bytes), so it can exceed this value by that fixed overhead.+# sinks do not apply this cap, so longer text stays available for grep/DB+# queries -- up to the 32 KiB per-string bound the redaction patcher+# (``_sanitize_record``) applies to every sink. The cap bounds the+# *prefix* preserved from the original message; the wire payload is the+# prefix plus a short truncation indicator (~100 bytes), so it can exceed+# this value by that fixed overhead.FRONTEND_MESSAGE_MAX_LENGTH = 2000# Cap the size of messages persisted to ResearchLog. The DB column is# unbounded TEXT, so a long langgraph run can accumulate thousands of# 10 KB rows — paginated reads (PR #4037) hide the symptom but don't# stop the storage growth. Same prefix-plus-indicator semantics as-# FRONTEND_MESSAGE_MAX_LENGTH; container-log/stderr/file sinks remain-# unchanged so full diagnostics are still preserved out-of-band.+# FRONTEND_MESSAGE_MAX_LENGTH; container-log/stderr/file sinks do not+# apply this cap, so text up to the patcher's 32 KiB per-string bound is+# still available out-of-band.DATABASE_MESSAGE_MAX_LENGTH = 5000@@ -569,16 +573,34 @@ def _truncate_for_database(message: str) -> str:``DATABASE_MESSAGE_MAX_LENGTH`` is the preserved-prefix length;the stored string is at most that plus a ~100-char suffix that- reports the original length so debug context is not lost. Full- messages remain available in container-log/stderr/file sinks.+ reports the original length so debug context is not lost. The+ container-log/stderr/file sinks keep up to the patcher's 32 KiB+ per-string bound."""if len(message) <= DATABASE_MESSAGE_MAX_LENGTH:return message- suffix = (- f"… (truncated; full message in server logs; "- f"original length: {len(message)} chars)"+ return message[:DATABASE_MESSAGE_MAX_LENGTH] + _truncation_suffix(message)+++def _truncation_suffix(message: str) -> str:+ """Indicator appended by the DB and frontend caps.++ The reported length counts what the patcher's 32 KiB bound already+ dropped (its omission marker records the count), so it is the length+ before any truncation; the server logs hold at most the first+ ``_LOG_REDACTION_MAX_CHARS`` characters.+ """+ # Deferred import to avoid potential circular imports during module initialization+ from ..security.log_sanitizer import (+ _LOG_REDACTION_MAX_CHARS,+ log_length_before_truncation,+ )++ return (+ f"… (truncated; server logs keep up to {_LOG_REDACTION_MAX_CHARS} "+ f"chars; original length: {log_length_before_truncation(message)} "+ f"chars)")- return message[:DATABASE_MESSAGE_MAX_LENGTH] + suffixdef _exception_context(record) -> str:@@ -635,20 +657,16 @@ def _truncate_for_frontend(message: str) -> str:``FRONTEND_MESSAGE_MAX_LENGTH`` caps the *preserved prefix* of theoriginal message. When truncation kicks in, a short indicator isappended that names the original length and points the user at the- server-side logs for the full text, so the returned string is+ server-side logs, which keep up to 32 KiB of it, so the returned string is``FRONTEND_MESSAGE_MAX_LENGTH`` plus the fixed indicator overhead(~100 bytes). Verbose diagnostic / agent logs (model outputs, longtracebacks, extracted text) are useless in the UI when displayed infull and inflate socket payloads + client-side memory;- container-log/stderr, file, and DB sinks remain unchanged.+ container-log/stderr, file, and DB sinks do not apply this cap."""if len(message) <= FRONTEND_MESSAGE_MAX_LENGTH:return message- suffix = (- f"… (truncated; full message in server logs; "- f"original length: {len(message)} chars)"- )- return message[:FRONTEND_MESSAGE_MAX_LENGTH] + suffix+ return message[:FRONTEND_MESSAGE_MAX_LENGTH] + _truncation_suffix(message)def frontend_progress_sink(message: loguru.Message) -> None:@@ -786,6 +804,202 @@ def stop_log_queue_processor(timeout: float = 2.0) -> None:_queue_processor_thread = None+def _sanitize_record(record) -> None:+ """Global loguru patcher: scrub every record before it reaches a sink.++ Runs once per record, ahead of ALL sinks (stderr, the encrypted per-user+ DB, the browser progress stream, and the persistent, unencrypted+ ``<LDR_DATA_DIR>/logs/*.log`` file), so it is the single chokepoint that+ protects every sink regardless of per-call-site logging discipline:++ * Control / format characters are stripped from the message (prevents log+ forging via CR/LF, RLO, zero-width, etc.).+ * Credential *shapes* and bare ``field=value`` secrets are redacted from+ the message — the sink-level backstop for any call site that logged a+ credential without going through ``scrub_error`` first.+ * Structured ``extra`` / ``logger.bind(...)`` values are redacted by+ sensitive key name AND by embedded credential shape, catching the+ recurring family bug of a secret carried as a bound structured value+ (a token/URL nested under a key the name-based checks miss).+ * The *rendered* exception value is scrubbed too (see+ :func:`_redact_exception_value`), so a credential embedded in an+ exception's string does not render verbatim to the default-format+ stderr / file sinks — the message scrub alone never reaches it.++ Fail-closed: this patcher runs synchronously, ahead of every sink, on+ every single log call app-wide, so a redactor that *raised* would break+ ALL logging. Each redaction step is therefore individually guarded --+ if a redactor errors, the field it was scrubbing is never passed+ through unredacted (that could leak the very secret it failed to+ catch); instead it is dropped / replaced with a safe placeholder.++ The security helpers are imported lazily (never at this module's import+ time): importing ``..security`` runs ``install_audit_hook()``, and+ ``log_utils`` must stay importable before the security layer is wired.+ """+ from ..security.log_sanitizer import redact_log_record++ # Control-character strip + message/extra credential redaction. Shared+ # with the MCP subprocess's own patcher (mcp/server.py's+ # configure_mcp_logging installs the same function), so a credential+ # reaching a record without going through scrub_error first is caught+ # regardless of which process logged it. Only the rendered-exception+ # scrub below is web-process-only (see _redact_exception_value).+ redact_log_record(record)++ try:+ _redact_exception_value(record)+ except Exception:+ # `_redact_exception_value` is written to never raise, but if it+ # somehow does, do not let the (possibly unredacted) exception+ # reach any sink -- drop it rather than fail open.+ record["exception"] = None+++def _redact_exception_value(record) -> None:+ """Give sinks a scrubbed exception graph without changing live exceptions.++ Loguru renders exception values, notes and group messages independently+ of record["message"]. Rebuild changed nodes using builtin exceptions only;+ custom constructors, copy hooks and group derive methods are never called.+ Custom non-group types retain their name in a RuntimeError message; group+ subclasses become builtin groups. Application-specific attributes are not+ copied to log output. Sensitive SyntaxError source details are omitted.+ Tracebacks and safe notes are retained. Cycles and traversal limits become+ explicit placeholders instead of links back to unsanitized objects.+ """+ exc = record.get("exception") if record else None+ if not exc:+ return+ value = getattr(exc, "value", None)+ if value is None and isinstance(exc, tuple) and len(exc) >= 2:+ value = exc[1]+ if value is None:+ return+ from ..security.log_sanitizer import redact_log_message++ new_value = _build_redacted_exception(+ value, redact_log_message, memo={}, in_progress=set(), budget=[200]+ )+ if new_value is value:+ return+ if hasattr(exc, "_replace"):+ record["exception"] = exc._replace(value=new_value)+ elif isinstance(exc, tuple) and len(exc) >= 3:+ record["exception"] = (exc[0], new_value, exc[2])+ else:+ record["exception"] = None+++def _build_redacted_exception(+ node,+ redact_log_message: Callable[[str], str],+ memo: dict,+ in_progress: set,+ budget: list,+):+ """Return an independent rendering graph when any visible field changes.++ Unchanged nodes retain identity. Changed nodes never invoke application+ copying/derivation hooks. The budget bounds both depth and group width;+ omitted branches contain a safe diagnostic placeholder.+ """+ if node is None:+ return None+ if budget[0] <= 0:+ return RuntimeError("<exception traversal limit reached>")+ # Cached children still consume work and space in a group's output.+ budget[0] -= 1+ key = id(node)+ if key in memo:+ return memo[key]+ if key in in_progress:+ return RuntimeError("<exception cycle omitted>")+ in_progress.add(key)+ try:+ cause = node.__cause__+ new_cause = _build_redacted_exception(+ cause, redact_log_message, memo, in_progress, budget+ )+ suppress_context = node.__suppress_context__+ context = (+ node.__context__ if cause is None and not suppress_context else None+ )+ new_context = _build_redacted_exception(+ context, redact_log_message, memo, in_progress, budget+ )++ is_group = isinstance(node, BaseExceptionGroup)+ subs = node.exceptions if is_group else ()+ new_subs = []+ for child in subs:+ if budget[0] <= 0:+ new_subs.append(RuntimeError("<remaining exceptions omitted>"))+ break+ new_subs.append(+ _build_redacted_exception(+ child, redact_log_message, memo, in_progress, budget+ )+ )+ subs_changed = len(new_subs) != len(subs) or any(+ new is not old for new, old in zip(new_subs, subs)+ )++ message = node.message if is_group else str(node)+ safe_message = redact_log_message(message)+ rendered_message = str(node)+ rendered_changed = (+ redact_log_message(rendered_message) != rendered_message+ )+ # SyntaxError has additional fields rendered outside str(exception).+ # Reconstructing it from its safe message omits sensitive source text.+ syntax_changed = isinstance(node, SyntaxError) and any(+ isinstance(value, str) and redact_log_message(value) != value+ for value in (node.text, node.filename, node.msg)+ )+ notes = getattr(node, "__notes__", ())+ if not isinstance(notes, (list, tuple)):+ notes = (str(notes),)+ note_texts = [str(note) for note in notes]+ safe_notes = [redact_log_message(note) for note in note_texts]+ changed = (+ safe_message != message+ or rendered_changed+ or syntax_changed+ or safe_notes != note_texts+ or new_cause is not cause+ or new_context is not context+ or subs_changed+ )+ if not changed:+ memo[key] = node+ return node++ if is_group:+ # The builtin constructor rebuilds the read-only message and+ # members, without trusting a subclass's derive implementation.+ new_node = BaseExceptionGroup(safe_message, new_subs)+ else:+ kind = type(node)+ if getattr(builtins, kind.__name__, None) is kind:+ try:+ new_node = kind(safe_message)+ except Exception:+ new_node = RuntimeError(f"{kind.__name__}: {safe_message}")+ else:+ new_node = RuntimeError(f"{kind.__name__}: {safe_message}")+ new_node.__traceback__ = node.__traceback__+ new_node.__cause__ = new_cause+ new_node.__context__ = new_context+ new_node.__suppress_context__ = suppress_context+ if safe_notes:+ new_node.__notes__ = safe_notes+ memo[key] = new_node+ return new_node+ finally:+ in_progress.discard(key)++def config_logger(name: str, debug: bool = False) -> None:"""Configures the default logger.@@ -795,9 +1009,7 @@ def config_logger(name: str, debug: bool = False) -> None:debug: Whether to enable unsafe debug logging."""- from ..security.log_sanitizer import sanitize_log_record-- logger.configure(patcher=sanitize_log_record)+ logger.configure(patcher=_sanitize_record)logger.enable("local_deep_research")logger.remove()diff --git a/tests/mcp/test_stderr_control_chars.py b/tests/mcp/test_stderr_control_chars.pyindex ba98263feb..3d0f15f0d6 100644--- a/tests/mcp/test_stderr_control_chars.py+++ b/tests/mcp/test_stderr_control_chars.py@@ -12,8 +12,6 @@ to enable it or it sees nothing the package logs."""import io-import sys-from contextlib import contextmanagerimport pytestfrom loguru import logger@@ -23,41 +21,18 @@ from local_deep_research.utilities.url_utils import (is_safe_custom_llm_endpoint,)--@contextmanager-def _restored_logger():- """Undo what ``configure_mcp_logging`` does to the process-wide logger.-- ``logger.configure(patcher=None)`` does not clear a patcher: None means- "leave unchanged", so the patcher would leak into the rest of the pytest- worker. The namespace activation and the handlers are process-wide for the- same reason, so all three are snapshotted off ``logger._core`` and put back.- """- core = logger._core- saved = (- core.patcher,- core.enabled.copy(),- list(core.activation_list),- core.activation_none,- )- try:- yield- finally:- logger.remove()- (- core.patcher,- core.enabled,- core.activation_list,- core.activation_none,- ) = saved- # configure_mcp_logging removed loguru's default stderr handler.- logger.add(sys.stderr)+from tests.test_utils import restored_loguru_state@pytest.fixturedef emit():"""Emit through a real MCP sink and return what it wrote."""- with _restored_logger():+ # configure_mcp_logging's patcher/namespace-activation/handler changes are+ # process-wide (loguru holds one of each per process); restored_loguru_state+ # snapshots and restores them so they don't leak into later tests. See its+ # docstring in tests/test_utils.py for why logger.configure(patcher=None)+ # can't be used for this instead.+ with restored_loguru_state():sink = io.StringIO()configure_mcp_logging(sink=sink)@@ -108,3 +83,31 @@ def test_a_log_call_inside_the_package_reaches_the_sink(emit):assert "rejected non-string custom_endpoint" in outassert "local_deep_research.utilities.url_utils" in out+++def test_credential_in_message_is_redacted(emit):+ out = emit(+ lambda: logger.warning("auth failed api_key=plainvalue1234567890ab")+ )+ # The value is replaced, the field name kept, so the line stays useful.+ assert "plainvalue1234567890ab" not in out+ assert "api_key=" in out+++def test_bound_secret_is_redacted(emit):+ records = []++ def _bound_warning():+ logger.add(+ lambda m: records.append(m.record), level="INFO", diagnose=False+ )+ logger.bind(user_password="BoundSecretPw999").warning("connecting")++ out = emit(_bound_warning)+ # The stderr format renders only {message}, so a bound secret never+ # shows in the formatted line on its own -- it rides on the record+ # every sink formats from. The second sink above captures that record+ # under the same process-wide patcher, like the sink tests in+ # tests/security/test_log_sink_redaction.py.+ assert "BoundSecretPw999" not in out+ assert records[-1]["extra"].get("user_password") == "[REDACTED]"diff --git a/tests/research_library/test_download_service_contracts.py b/tests/research_library/test_download_service_contracts.pyindex 7b2de80594..c2a9ff08ed 100644--- a/tests/research_library/test_download_service_contracts.py+++ b/tests/research_library/test_download_service_contracts.py@@ -60,9 +60,9 @@ Covered:the skip reasons that ``GenericDownloader`` emits, withthe producer and the classifier wired together so drift in eitherhalf fails;- * an exception message surfaced to the client is credential-scrubbed- (holds), while the same URL is written to the log verbatim (DEFECT- -- xfail).+ * an exception message surfaced to the client is credential-scrubbed,+ and configured application logging scrubs the same URL before sinks+ receive it (holds)."""import hashlib@@ -389,32 +389,35 @@ def make_service(store, downloader, *, storage_mode="database", max_mb=3072):@pytest.fixture-def log_sink():- """Capture everything the package logs, message AND bound extras.+def log_sink(monkeypatch):+ """Capture messages and extras after real application logger setup.- A dedicated loguru sink rather than ``caplog``: the package calls- ``logger.disable("local_deep_research")`` at import time, and the- structured ``logger.bind(...)`` payloads never appear in a- ``{message}``-only rendering. Restores the disabled state afterwards.+ Configure the production patcher explicitly so this contract does not+ depend on another test having started the application first. Restore+ process-wide state so this fixture cannot affect later tests either."""+ from local_deep_research.utilities.log_utils import config_logger+ from tests.test_utils import restored_loguru_state+captured = []def _sink(message):captured.append(f"{message}{message.record['extra']!r}")- logger.enable("local_deep_research")- sink_id = logger.add(- _sink,- level="TRACE",- format="{level} | {name}:{function} | {message}",- diagnose=False,- backtrace=True,- )- try:+ monkeypatch.setenv("LDR_ENABLE_FILE_LOGGING", "false")+ with restored_loguru_state():+ config_logger("download_contract")+ # Exercise the installed production patcher with an isolated sink;+ # this service-level contract needs no DB or frontend log delivery.+ logger.remove()+ logger.add(+ _sink,+ level="TRACE",+ format="{level} | {name}:{function} | {message}",+ diagnose=False,+ backtrace=True,+ )yield captured- finally:- logger.remove(sink_id)- logger.disable("local_deep_research")@pytest.fixture@@ -1212,20 +1215,6 @@ def test_error_returned_to_the_client_is_credential_scrubbed(db, store, seeded):assert SECRET_KEY not in (attempt.error_message or "")- strict=True,- reason=(- "DEFECT: _download_pdf logs the raw resource URL at INFO, both "- 'when selecting a downloader ("Using {downloader} for {url}") and '- 'on its own success path ("Successfully stored PDF in database: '- '{resource.url}"). The global loguru patcher only '- "strips control characters, so URL userinfo credentials and "- "query-string API keys are written verbatim to the console sink, "- "the log database and the Socket.IO frontend sink. "- "redact_url_for_log exists and is used on the egress-denial path "- "but not here."- ),-)def test_download_logs_do_not_leak_url_credentials(db, store, seeded, log_sink):"""CONTRACT: a credential-bearing URL never reaches a log sink."""fixture = seeded(SECRET_URL)diff --git a/tests/security/test_log_sink_redaction.py b/tests/security/test_log_sink_redaction.pynew file mode 100644index 0000000000..78b4fe82cd--- /dev/null+++ b/tests/security/test_log_sink_redaction.py@@ -0,0 +1,878 @@+"""Regression tests for the log-sink credential redaction backstop.++The loguru patcher installed by ``utilities/log_utils.config_logger``+(:func:`local_deep_research.utilities.log_utils._sanitize_record`) is the+single chokepoint every sink shares — stderr, the encrypted per-user DB, the+browser progress stream, and the persistent, unencrypted+``<LDR_DATA_DIR>/logs/*.log`` file. These tests pin the invariant that a+credential which reaches a record without going through ``scrub_error`` first+is still scrubbed before any sink sees it:++* a secret carried in the message string is absent from the sink output,+* a secret carried as a bound/structured ``extra`` value is absent too, and+* an ordinary, non-sensitive message passes through unchanged.++They also cover the pure helpers in ``security/log_sanitizer`` directly, so a+future refactor of the patcher wiring can't silently drop the redaction.+"""++import pytest+from loguru import logger++from local_deep_research.security.log_sanitizer import (+ redact_log_extra,+ redact_log_message,+ redact_sensitive_assignments,+)+from tests.test_utils import restored_loguru_state+++class TestRedactSensitiveAssignments:+ """Bare ``field=value`` credential assignments in a plain string."""++ @pytest.mark.parametrize(+ "field",+ ["api_key", "password", "secret", "token", "user_password"],+ )+ def test_value_redacted_field_name_preserved(self, field):+ secret = "plaintext-secret-value-12345678"+ redacted = redact_sensitive_assignments(f"{field}={secret}")+ assert f"{field}=" in redacted+ assert secret not in redacted++ def test_compound_name_kept_whole(self):+ assert (+ redact_sensitive_assignments("client_secret=abcdef123456")+ == "client_secret=[REDACTED]"+ )++ def test_does_not_match_mid_identifier(self):+ # ``token`` inside ``mytoken`` must not trigger redaction.+ assert (+ redact_sensitive_assignments("mytoken=keepme") == "mytoken=keepme"+ )++ @pytest.mark.parametrize(+ "message",+ [+ "Starting research run 42",+ "the secret to success is hard work",+ "monkey=banana count=5 ratio=0.9",+ "Fetched 10 results from engine",+ ],+ )+ def test_ordinary_text_unchanged(self, message):+ assert redact_sensitive_assignments(message) == message+++class TestRedactLogMessage:+ """Full message scrub: credential shapes + bare assignments."""++ def test_all_shapes_and_fields_scrubbed(self):+ message = (+ "provider failed "+ "https://user:[email protected]/v1"+ "?api_key=example-api-key-val00&token=tok-abcdefghij1234 "+ "sk-live-abcdefghijklmnopqrst and password=RawFieldSecret9999"+ )+ out = redact_log_message(message)+ for leak in (+ "hunter2secret",+ "example-api-key-val00",+ "tok-abcdefghij1234",+ "sk-live-abcdefghijklmnopqrst",+ "RawFieldSecret9999",+ ):+ assert leak not in out, leak+ assert "provider failed" in out++ def test_normal_message_unchanged(self):+ assert redact_log_message("Starting research run 42") == (+ "Starting research run 42"+ )+++class TestRedactLogExtra:+ """Structured ``extra`` / bound values."""++ def test_sensitive_key_masked_structural_preserved(self):+ extra = {+ "research_id": "abc-123",+ "username": "alice",+ "user_password": "SuperSecretPw",+ "api_key": "AIzaSyABCDEFGHIJKLMNOPQRSTUV1234567890",+ "note": "harmless text",+ }+ out = redact_log_extra(extra)+ # Routing keys the sinks depend on survive unchanged.+ assert out["research_id"] == "abc-123"+ assert out["username"] == "alice"+ # Secrets are masked.+ assert out["user_password"] == "[REDACTED]"+ assert out["api_key"] == "[REDACTED]"+ # Innocuous values pass through.+ assert out["note"] == "harmless text"++ def test_credential_shape_under_innocuous_key(self):+ # The family bug: a secret bound under a non-sensitive key name that a+ # name-only check would miss is still scrubbed by value shape.+ extra = {+ "url": "https://u:p@host/path?token=leak-tok-1234567890abcdef",+ }+ out = redact_log_extra(extra)+ assert "leak-tok-1234567890abcdef" not in out["url"]+ assert "u:p@host" not in out["url"]++ def test_nested_and_empty_values(self):+ extra = {+ "nested": {"password": "nestedpw123", "ok": "fine"},+ "password": "", # empty stays readable ("configured" vs "not")+ "count": 5,+ }+ out = redact_log_extra(extra)+ assert out["nested"]["password"] == "[REDACTED]"+ assert out["nested"]["ok"] == "fine"+ assert out["password"] == ""+ assert out["count"] == 5+++def captured_records():+ """Route loguru through the real patcher into an in-memory sink.++ Uses ``restored_loguru_state`` (tests/test_utils.py) to snapshot and+ restore loguru's process-wide patcher/handlers afterwards, so the global+ loguru state is left usable for other tests. ``logger.configure(patcher=+ None)`` does NOT do this -- loguru's ``configure()`` treats ``None`` as+ "leave unchanged", not "clear" -- so a fixture that relied on it would+ leak ``_sanitize_record`` into every later test in the same pytest+ worker.+ """+ from local_deep_research.utilities.log_utils import _sanitize_record++ records = []+ with restored_loguru_state():+ logger.remove()+ logger.configure(patcher=_sanitize_record)+ logger.add(+ lambda m: records.append(m.record), level="DEBUG", diagnose=False+ )+ yield records+++class TestPatcherThroughSink:+ """End-to-end: the patcher scrubs before any sink observes the record."""++ def test_secret_in_message_absent_from_sink(self, captured_records):+ logger.info("provider auth failed password=SinkMessageSecret123")+ assert captured_records, "sink captured nothing"+ message = captured_records[-1]["message"]+ assert "password=" in message+ assert "SinkMessageSecret123" not in message++ def test_bound_secret_absent_from_sink(self, captured_records):+ logger.bind(user_password="BoundSecretPw999").info("connecting")+ extra = captured_records[-1]["extra"]+ assert extra.get("user_password") == "[REDACTED]"++ def test_bound_credential_shape_absent_from_sink(self, captured_records):+ logger.bind(detail="token=leak-bound-abcdef1234567890").info(+ "calling service"+ )+ extra = captured_records[-1]["extra"]+ assert "leak-bound-abcdef1234567890" not in extra["detail"]++ def test_normal_message_unchanged_through_sink(self, captured_records):+ logger.info("Starting research run 42")+ assert captured_records[-1]["message"] == "Starting research run 42"++ def test_control_characters_still_stripped(self, captured_records):+ logger.info("before\x00\x1b[31m\u202evisible")+ message = captured_records[-1]["message"]+ assert "visible" in message+ assert "\x00" not in message+ assert "\x1b" not in message+ assert "\u202e" not in message+++def rendered_sink():+ """Route loguru through the real patcher into a default-format stream sink.++ Unlike ``captured_records`` (which inspects the raw record dict), this+ sink RENDERS each record — including ``record["exception"]`` via loguru's+ own exception formatter — into an in-memory text stream, so the test can+ assert on what actually reaches a default-format stderr/file sink.++ Uses ``restored_loguru_state`` (tests/test_utils.py) to snapshot and+ restore loguru's process-wide patcher/handlers afterwards -- see+ ``captured_records`` above for why ``logger.configure(patcher=None)``+ can't be used for that instead.+ """+ import io++ from local_deep_research.utilities.log_utils import _sanitize_record++ stream = io.StringIO()+ with restored_loguru_state():+ logger.remove()+ logger.configure(patcher=_sanitize_record)+ logger.add(+ stream,+ level="DEBUG",+ diagnose=False,+ backtrace=False,+ colorize=False,+ )+ yield stream+++class TestExceptionValueRedactedInRenderedSink:+ """A secret inside an exception value must not render to a text sink.++ Loguru renders ``record["exception"]`` through its own formatter, which+ the message scrub never touches; ``_redact_exception_value`` closes that+ gap by building a redacted COPY of the exception (and its+ ``__cause__``/``__context__`` chain) for the sinks to render, leaving+ traceback structure intact -- and leaving the original, live exception+ instance completely unmutated (see ``TestExceptionInstanceNotMutated``+ below).+ """++ def test_credential_in_exception_value_absent_but_traceback_kept(+ self, rendered_sink+ ):+ secret = "SuperSecretPw12345"+ dsn = f"postgresql://admin:{secret}@db.internal:5432/app"+ try:+ raise ConnectionError(f"could not connect to {dsn}")+ except ConnectionError:+ logger.opt(exception=True).error("db connection failed")++ rendered = rendered_sink.getvalue()+ # Traceback STRUCTURE is preserved: type name and the rendered+ # exception line both survive.+ assert "ConnectionError" in rendered+ assert "Traceback" in rendered+ # ...but the credential embedded in the exception value is gone.+ assert secret not in rendered++ def test_credential_in_chained_cause_absent(self, rendered_sink):+ secret = "ChainedCauseSecret987"+ try:+ try:+ raise ValueError(f"token={secret}")+ except ValueError as inner:+ raise RuntimeError("wrapping failure") from inner+ except RuntimeError:+ logger.opt(exception=True).error("wrapped failure")++ rendered = rendered_sink.getvalue()+ assert "RuntimeError" in rendered+ assert secret not in rendered+++class TestExceptionInstanceNotMutated:+ """`_redact_exception_value` must copy, never mutate, the live exception.++ The exception instance logged here is the SAME object the surrounding+ ``except`` block holds, and may still inspect it, re-raise it, or hand+ it to other error handling after the logging call returns. Redacting a+ credential from the rendered output must never rewrite that instance's+ ``.args`` (or any other attribute) in place -- it must instead build a+ separate, redacted copy for the sink to render.+ """++ def test_original_args_unchanged_after_logging(self, captured_records):+ secret = "example-api-key-val00" # noqa: S105 - fake, not a real credential shape+ exc = ValueError(f"token={secret}")+ original_args = exc.args+ try:+ raise exc+ except ValueError as caught:+ assert caught is exc+ logger.opt(exception=True).error("boom")++ # The live exception instance was NOT mutated by logging it.+ assert exc.args == original_args+ assert secret in exc.args[0]++ # ...while the copy handed to the sink IS redacted.+ redacted_value = captured_records[-1]["exception"].value+ assert redacted_value is not exc+ assert secret not in redacted_value.args[0]++ def test_original_cause_chain_unchanged_after_logging(+ self, captured_records+ ):+ secret = "example-chained-secret02" # noqa: S105 - fake credential+ inner = ValueError(f"token={secret}")+ outer = RuntimeError("wrapping failure")+ try:+ try:+ raise inner+ except ValueError:+ raise outer from inner+ except RuntimeError:+ logger.opt(exception=True).error("wrapped failure")++ # Neither exception in the chain was mutated.+ assert inner.args == (f"token={secret}",)+ assert outer.__cause__ is inner++ redacted_outer = captured_records[-1]["exception"].value+ assert redacted_outer is not outer+ redacted_cause = redacted_outer.__cause__+ assert redacted_cause is not inner+ assert secret not in redacted_cause.args[0]+++ "value",+ [+ '"QuotedMarker987 and another word"',+ "'QuotedMarker987 and another word'",+ r'"prefix\"QuotedMarker987"',+ "prefix,QuotedMarker987",+ "prefix#QuotedMarker987",+ "prefix&QuotedMarker987",+ ],+)+def test_complete_assignment_value_is_redacted(value):+ """Punctuation and quoting must not leave a credential suffix behind."""+ assert redact_sensitive_assignments(f"password={value} count=3") == (+ "password=[REDACTED] count=3"+ )++[email protected]("quote", ['"', "'"])+def test_unfinished_quoted_assignment_redacts_remaining_text(quote):+ assert (+ redact_sensitive_assignments(+ f"token={quote}UnfinishedMarker987 with spaces\\"+ )+ == "token=[REDACTED]"+ )++[email protected]("name", ["api_token", "service_url"])+def test_known_credential_names_in_messages_and_nested_extras(name):+ """These application credential names are not generic value shapes."""+ value = "discord://12345/InventoryMarker987"+ assert redact_log_message(f"{name}={value}") == f"{name}=[REDACTED]"+ assert redact_log_extra({"nested": {f"notifications.{name}": value}}) == {+ "nested": {f"notifications.{name}": "[REDACTED]"}+ }+++def test_exception_notes_are_scrubbed_without_mutating_original(rendered_sink):+ exc = ValueError("ordinary failure")+ exc.add_note("token=NoteMarker987")+ exc.add_note("useful diagnostic note")+ original_notes = list(exc.__notes__)+ logger.opt(exception=exc).error("operation failed")+ rendered = rendered_sink.getvalue()+ assert "ValueError: ordinary failure" in rendered+ assert "useful diagnostic note" in rendered+ assert "NoteMarker987" not in rendered+ assert exc.__notes__ == original_notes+++def test_group_message_and_notes_are_scrubbed(rendered_sink):+ records = []+ sink = logger.add(+ lambda message: records.append(message.record), diagnose=False+ )+ exc = ExceptionGroup("token=GroupMarker987", [ValueError("normal child")])+ exc.add_note("useful group note")+ try:+ logger.opt(exception=exc).error("group failed")+ finally:+ logger.remove(sink)+ rendered = rendered_sink.getvalue()+ assert "ExceptionGroup" in rendered and "normal child" in rendered+ assert "useful group note" in rendered+ assert "GroupMarker987" not in rendered+ assert exc.message == "token=GroupMarker987"+ from local_deep_research.utilities.log_utils import _exception_context++ assert records, "expected a group exception record"+ prefix = _exception_context(records[-1])+ assert "ExceptionGroup" in prefix+ assert "GroupMarker987" not in prefix+++def test_group_keeps_benign_notes_when_only_child_changes(rendered_sink):+ exc = ExceptionGroup("ordinary group", [ValueError("token=ChildMarker987")])+ exc.add_note("preserve this diagnostic")+ logger.opt(exception=exc).error("group failed")+ rendered = rendered_sink.getvalue()+ assert "preserve this diagnostic" in rendered+ assert "ChildMarker987" not in rendered+ assert exc.exceptions[0].args == ("token=ChildMarker987",)++[email protected]("count", [200, 201])+def test_exception_traversal_boundary_does_not_restore_raw_nodes(+ rendered_sink, count+):+ exc = ValueError("token=BoundaryMarker987")+ for _ in range(count - 1):+ parent = RuntimeError("ordinary wrapper")+ parent.__cause__ = exc+ exc = parent+ logger.opt(exception=exc).error("chain failed")+ rendered = rendered_sink.getvalue()+ assert "ordinary wrapper" in rendered+ assert "BoundaryMarker987" not in rendered+ if count == 201:+ assert "exception traversal limit reached" in rendered+++def test_exception_cycle_uses_safe_placeholder(rendered_sink):+ outer = RuntimeError("token=CycleMarker987")+ inner = ValueError("ordinary child")+ outer.__cause__ = inner+ inner.__cause__ = outer+ logger.opt(exception=outer).error("cycle failed")+ rendered = rendered_sink.getvalue()+ assert "exception cycle omitted" in rendered+ assert "CycleMarker987" not in rendered+ assert inner.__cause__ is outer+ assert outer.args == ("token=CycleMarker987",)++[email protected]("behavior", ["self", "alias", "raise"])+def test_custom_copy_hooks_are_never_called(rendered_sink, behavior):+ calls = []++ class CustomError(ValueError):+ def __copy__(self):+ calls.append(behavior)+ if behavior == "raise":+ raise TypeError("copy unavailable")+ return self if behavior == "self" else self.__context__++ exc = CustomError("token=CopyMarker987")+ exc.__context__ = ValueError("ordinary context")+ logger.opt(exception=exc).error("custom failure")+ rendered = rendered_sink.getvalue()+ assert "CustomError" in rendered+ assert "CopyMarker987" not in rendered+ assert calls == []+ assert exc.args == ("token=CopyMarker987",)+ assert exc.__context__.args == ("ordinary context",)+++def test_nonstandard_constructor_preserves_safe_cause(rendered_sink):+ from types import SimpleNamespace++ from local_deep_research.security.egress.policy import PolicyDeniedError++ exc = PolicyDeniedError(SimpleNamespace(reason="synthetic denial"))+ cause = ValueError("token=PolicyCauseMarker987")+ exc.__cause__ = cause+ logger.opt(exception=exc).error("policy failure")+ rendered = rendered_sink.getvalue()+ assert "PolicyDeniedError" in rendered and "synthetic denial" in rendered+ assert "PolicyCauseMarker987" not in rendered+ assert exc.__cause__ is cause+ assert cause.args == ("token=PolicyCauseMarker987",)+++def test_nested_logger_context_restores_existing_sink(captured_records):+ logger.info("before isolated context")+ with restored_loguru_state():+ logger.add(lambda message: None, diagnose=False)+ logger.info("inside isolated context")+ logger.info("after isolated context")+ assert [record["message"] for record in captured_records] == [+ "before isolated context",+ "after isolated context",+ ]++[email protected]("field", ["text", "filename", "msg"])+def test_syntax_error_details_are_scrubbed(rendered_sink, field):+ exc = SyntaxError("invalid syntax", ("synthetic.py", 1, 1, "normal text"))+ setattr(exc, field, "token=SyntaxDetailMarker987")+ logger.opt(exception=exc).error("syntax failure")+ rendered = rendered_sink.getvalue()+ assert "SyntaxError" in rendered+ assert "SyntaxDetailMarker987" not in rendered+ assert getattr(exc, field) == "token=SyntaxDetailMarker987"++[email protected]("separator", ["\n", "\r\n", "\t", "\u2028"])+def test_redaction_preserves_control_character_boundaries(+ captured_records, separator+):+ """Removing a separator must not hide an otherwise recognized name."""+ logger.info(f"failure{separator}token=BoundaryCredential739 count=3")+ assert captured_records, "sink captured nothing"+ assert captured_records[-1]["message"] == (+ "failuretoken=[REDACTED] count=3"+ )+++def test_normalized_credential_name_is_also_redacted(captured_records):+ """Redacting only before normalization misses an invisible name split."""+ logger.info("api_\u200bkey=NormalizedCredential739 count=3")+ assert captured_records, "sink captured nothing"+ assert captured_records[-1]["message"] == "api_key=[REDACTED] count=3"++[email protected]("name", ["api_token", "service_url", "user_password"])[email protected]("prefix", ["?", "?page=3&"])+def test_known_query_names_preserve_other_parameters(+ captured_records, name, prefix+):+ """Bare and query assignments share names, but not value delimiters."""+ url = f"https://example.invalid/{prefix}{name}=QueryCredential739&sort=new#top"+ expected = f"https://example.invalid/{prefix}{name}=[REDACTED]&sort=new#top"+ assert redact_log_message(url) == expected+ logger.bind(detail=url).info(url)+ assert captured_records, "sink captured nothing"+ assert captured_records[-1]["message"] == expected+ assert captured_records[-1]["extra"]["detail"] == expected+++def test_repeated_exception_children_respect_traversal_limit(captured_records):+ """Memoized children must not bypass the rendered group width limit."""+ child = ValueError("token=RepeatedCredential739")+ original = ExceptionGroup("ordinary group", [child] * 3000)+ logger.opt(exception=original).error("group failed")+ assert captured_records, "sink captured nothing"+ rendered = captured_records[-1]["exception"].value+ assert isinstance(rendered, ExceptionGroup)+ assert rendered is not original+ assert len(rendered.exceptions) == 200+ assert rendered.exceptions[0] is rendered.exceptions[1]+ assert str(rendered.exceptions[-1]) == "<remaining exceptions omitted>"+ assert all(+ "RepeatedCredential739" not in str(e) for e in rendered.exceptions+ )+ assert len(original.exceptions) == 3000+ assert all(e is child for e in original.exceptions)+ assert child.args == ("token=RepeatedCredential739",)+++# The adversarial shapes below made the Slack/JWT patterns quadratic: every+# ``xoxb-``/``eyJ`` inside one character run started an attempt that rescanned+# the rest of the run. At these sizes the quadratic patterns took ~9-10 s per+# pass (measured); the linear ones take tens of milliseconds, so a 1 s budget+# has a wide margin on both sides.+_QUADRATIC_BUDGET_SECONDS = 1.0+++ ("fragment", "size"),+ [("xoxb-", 80_000), ("xapp-", 80_000), ("eyJ-", 200_000)],+)+def test_credential_shape_patterns_are_linear_on_repeated_prefixes(+ fragment, size+):+ """sanitize_error_message (not length-capped) stays fast on a long run."""+ import time++ from local_deep_research.security.log_sanitizer import (+ sanitize_error_message,+ )++ message = fragment * (size // len(fragment))+ started = time.perf_counter()+ sanitize_error_message(message)+ elapsed = time.perf_counter() - started+ assert elapsed < _QUADRATIC_BUDGET_SECONDS, elapsed+++# Explicit ids: without them pytest uses each string value verbatim as the+# test id, so the node ids here were 0.2-1 MB each. Every such id is written+# into the ``-v`` progress lines, the xdist reports and the JUnit XML, and in+# CI those four lines stalled the job's log for over an hour.+ "message",+ ["a" * 1_000_000, "xoxb-" * 40_000, "eyJ-" * 80_000, "token=x " * 100_000],+ ids=["a-1M", "xoxb-200K", "eyJ-320K", "token-assignment-800K"],+)+def test_log_path_redaction_cost_is_bounded(captured_records, message):+ """The patcher scans a bounded prefix and marks the omitted remainder."""+ import time++ started = time.perf_counter()+ logger.bind(detail=message).info(message)+ elapsed = time.perf_counter() - started+ assert elapsed < _QUADRATIC_BUDGET_SECONDS, elapsed+ record = captured_records[-1]+ for value in (record["message"], record["extra"]["detail"]):+ assert value.endswith("characters omitted from log output]")+ assert len(value) < 100_000+++def test_truncation_does_not_split_a_credential():+ """A secret straddling the length bound is dropped, not half-emitted."""+ from local_deep_research.security.log_sanitizer import (+ _LOG_REDACTION_MAX_CHARS,+ )++ # A hard cut at the bound would keep "sk-Stradd", too short for the+ # ``sk-`` shape pattern to recognise, so it would reach the sink.+ prefix = "w" * (_LOG_REDACTION_MAX_CHARS - 11) + " "+ message = prefix + "sk-StraddlingKey0123456789abcdef tail " * 50+ out = redact_log_message(message)+ assert "sk-Stradd" not in out+ assert out.startswith(prefix)+ assert out[len(prefix) :].startswith(" [... ")+ assert out.endswith("characters omitted from log output]")+ assert redact_log_message("short message") == "short message"+++def test_truncation_at_userinfo_at_sign_drops_the_whole_url():+ """A cut landing on the ``@`` must not keep ``user:password``.++ Without its ``@`` the URL-userinfo pattern cannot match, so a cut just+ before it would ship the password; the whole URL run is dropped instead.+ """+ from local_deep_research.security.log_sanitizer import (+ _LOG_REDACTION_MAX_CHARS,+ _redact_log_text,+ )++ url = "postgresql://admin:S3cretPassw0rd"+ pad_len = _LOG_REDACTION_MAX_CHARS - len(url)+ pad = "x " * (pad_len // 2) + "x" * (pad_len % 2)+ message = pad + url + "@db.internal:5432/app tail"+ assert message[_LOG_REDACTION_MAX_CHARS] == "@"+ for redact in (redact_log_message, _redact_log_text):+ out = redact(message)+ assert "S3cr" not in out+ assert "admin:" not in out+ assert out.endswith("characters omitted from log output]")+++ "secret",+ [+ "sk-" + "A" * 22,+ "ghp_Ab3dEf6hIj9kLm2oPq5sTu8wXy1zAb4cD5eF6",+ "AKIAIOSFODNN7EXAMPLE",+ "admin:Tr0ub4dor&3xyzQ@db",+ ],+)+def test_truncation_without_whitespace_drops_the_whole_run(secret):+ """No whitespace before the bound: nothing of the run is kept.++ A hard cut (or a back-off to punctuation inside the run) would keep a+ key prefix too short for its shape pattern, or a password up to a ``&``.+ """+ from local_deep_research.security.log_sanitizer import (+ _LOG_REDACTION_MAX_CHARS,+ _redact_log_text,+ )++ for offset in (-12, -6, -3):+ head = "a/" * ((_LOG_REDACTION_MAX_CHARS + offset) // 2)+ message = head + secret + "9" * 20_000+ marker = f" [... {len(message)} characters omitted from log output]"+ for redact in (redact_log_message, _redact_log_text):+ out = redact(message)+ assert secret[:4] not in out+ assert out == marker++[email protected]("separator", ["\n", "\t", "\x1c", "\u2028", "\x85"])+def test_truncation_does_not_cut_at_a_stripped_control_character(+ captured_records, separator+):+ """A control character inside a credential is not a cut boundary.++ ``_redact_log_text`` strips control characters between its passes,+ which rejoins ``S3cret`` and ``Passw0rd@db...`` into one URL the+ userinfo pattern redacts whole. Cutting at the control character and+ keeping ``postgresql://admin:S3cret`` would ship the password's first+ half: without its ``@`` the pattern cannot match.+ """+ from local_deep_research.security.log_sanitizer import (+ _LOG_REDACTION_MAX_CHARS,+ _redact_log_text,+ )++ url = f"postgresql://admin:S3cret{separator}[email protected]/app"+ assert "S3cr" not in _redact_log_text("pad " + url + " end")+ # The bound on the separator itself, and with "Pa" between the two.+ for gap in (0, 3):+ pad_len = _LOG_REDACTION_MAX_CHARS - (url.index(separator) + gap)+ pad = "x " * (pad_len // 2) + "x" * (pad_len % 2)+ message = pad[:-1] + " " + url + " " + "y" * 40_000+ assert message[_LOG_REDACTION_MAX_CHARS - gap] == separator+ logger.info(message)+ outputs = [+ _redact_log_text(message),+ redact_log_message(message),+ captured_records[-1]["message"],+ ]+ for out in outputs:+ assert "S3cr" not in out+ assert "admin" not in out+ assert "Pass" not in out+ assert out.endswith("characters omitted from log output]")+++def test_log_length_before_truncation_reads_a_genuine_marker():+ """The patcher's marker yields the pre-cut length; others ``len()``."""+ from local_deep_research.security.log_sanitizer import (+ _LOG_REDACTION_MAX_CHARS,+ log_length_before_truncation,+ )++ message = "word " * (_LOG_REDACTION_MAX_CHARS // 2)+ out = redact_log_message(message)+ assert out.endswith("characters omitted from log output]")+ assert len(out) < len(message)+ assert log_length_before_truncation(out) == len(message)+ assert log_length_before_truncation("no marker") == len("no marker")+++ "digits",+ ["9" * 4_300, "9" * 4_301, "9" * 20, "\u0663" * 5, "\uff19" * 5],+ ids=[+ "4300-digits",+ "4301-digits",+ "20-digits",+ "arabic-indic",+ "fullwidth",+ ],+)+def test_log_length_before_truncation_never_raises_on_a_forged_marker(+ digits,+):+ """Logged text can end in a forged marker; its count is not trusted.++ An unbounded digit group let ``int()`` raise past Python's digit limit,+ and the DB and frontend sinks, which report this length, then dropped+ the record.+ """+ from local_deep_research.security.log_sanitizer import (+ log_length_before_truncation,+ )++ message = (+ "x" * 6_000 + f" [... {digits} characters omitted from log output]"+ )+ assert log_length_before_truncation(message) == len(message)+++def test_self_referential_extra_keeps_record_and_routing(captured_records):+ """A cycle is rendered as a placeholder instead of dropping all extras."""+ blob = {"note": "token=CycleCredential739"}+ blob["self"] = blob+ blob["items"] = [blob]+ logger.bind(username="alice", research_id="r-1", blob=blob).info("cyc")+ extra = captured_records[-1]["extra"]+ assert extra["username"] == "alice"+ assert extra["research_id"] == "r-1"+ assert extra["blob"]["note"] == "token=[REDACTED]"+ assert extra["blob"]["self"] == "<cycle>"+ assert extra["blob"]["items"] == ["<cycle>"]+ assert blob["note"] == "token=CycleCredential739"+++def test_deeply_nested_extra_is_bounded(captured_records):+ deep = "token=DeepCredential739"+ for _ in range(5000):+ deep = [deep]+ logger.bind(username="alice", deep=deep).info("deep")+ extra = captured_records[-1]["extra"]+ assert extra["username"] == "alice"+ assert "DeepCredential739" not in repr(extra)+ assert "<nested too deep>" in repr(extra)+++class _RaisingEq:+ def __eq__(self, other):+ raise RuntimeError("comparison refused")++ __hash__ = object.__hash__+++def test_raising_eq_value_under_sensitive_key_is_masked():+ out = redact_log_extra(+ {"username": "alice", "api_key": _RaisingEq(), "note": "fine"}+ )+ assert out == {"username": "alice", "api_key": "[REDACTED]", "note": "fine"}+++class _RaisingItems(dict):+ def items(self):+ raise RuntimeError("items refused")+++def test_fail_closed_extra_keeps_routing_keys():+ """When extra cannot be redacted, only the routing keys survive."""+ from local_deep_research.security.log_sanitizer import redact_log_record++ record = {+ "message": "m",+ "extra": {+ "username": "alice",+ "research_id": "r-1",+ "policy_audit": True,+ "api_key": "FailClosedCredential739",+ "blob": _RaisingItems(secret="FailClosedCredential739"),+ },+ }+ redact_log_record(record)+ assert record["extra"] == {+ "username": "alice",+ "research_id": "r-1",+ "policy_audit": True,+ }+++def test_extra_strings_are_normalized_like_messages(captured_records):+ """An invisible character cannot hide a credential name in an extra."""+ logger.bind(+ detail="api_key=ExtraZeroWidth739 count=3",+ lines="failure\ntoken=ExtraNewline739 count=3",+ ).info("x")+ extra = captured_records[-1]["extra"]+ assert extra["detail"] == "api_key=[REDACTED] count=3"+ assert extra["lines"] == "failuretoken=[REDACTED] count=3"+++def test_prefixed_sensitive_extra_keys_are_masked():+ """Extra keys use settings redaction's underscore-suffix rule."""+ out = redact_log_extra(+ {+ "openai_api_key": "PrefixedCredential739",+ "db_password": "PrefixedCredential739",+ "api_key": "PrefixedCredential739",+ "nested": {"llm.openai.api_key": "PrefixedCredential739"},+ "requires_api_key": True,+ "max_tokens": 512,+ }+ )+ assert "PrefixedCredential739" not in repr(out)+ assert out["openai_api_key"] == "[REDACTED]"+ assert out["db_password"] == "[REDACTED]"+ assert out["nested"]["llm.openai.api_key"] == "[REDACTED]"+ assert out["requires_api_key"] is True+ assert out["max_tokens"] == 512+++# Longest node id the parametrized tests in this module may produce. The+# adversarial inputs above are hundreds of KB; they belong in the test body,+# never in the id pytest prints for every test.+_MAX_NODE_ID_LENGTH = 300+++def test_parametrized_node_ids_stay_short(request):+ """No test in this module gets a multi-KB id from a parametrize value."""+ module_path = request.node.path+ long_ids = [+ (item.nodeid[:120], len(item.nodeid))+ for item in request.session.items+ if item.path == module_path and len(item.nodeid) > _MAX_NODE_ID_LENGTH+ ]+ assert not long_ids, long_idsdiff --git a/tests/test_utils.py b/tests/test_utils.pyindex 1395df7f0a..45d0ace162 100644--- a/tests/test_utils.py+++ b/tests/test_utils.py@@ -7,10 +7,13 @@ This module provides common utilities for tests.import jsonimport sys+from contextlib import contextmanagerfrom pathlib import Pathfrom typing import Any, Dict, List, Optionalfrom unittest.mock import Mock+from loguru import logger+def add_src_to_path():"""Add the src directory to Python path for imports."""@@ -182,6 +185,41 @@ def assert_progress_callback_called()+@contextmanager+def restored_loguru_state():+ """Isolate patcher, namespace activation and handlers, then restore them.++ Detach the original handlers without stopping them: logger.remove() in+ the wrapped block must only close that block's sinks. Handler IDs remain+ monotonic so an existing ID cannot be reused by an isolated sink.+ """+ core = logger._core+ with core.lock:+ saved = (+ core.patcher,+ core.enabled.copy(),+ list(core.activation_list),+ core.activation_none,+ core.handlers,+ core.min_level,+ )+ core.handlers = {}+ core.min_level = float("inf")+ try:+ yield+ finally:+ logger.remove()+ with core.lock:+ (+ core.patcher,+ core.enabled,+ core.activation_list,+ core.activation_none,+ core.handlers,+ core.min_level,+ ) = saved++class MockCache:"""Mock cache implementation for testing."""diff --git a/tests/utilities/test_log_utils.py b/tests/utilities/test_log_utils.pyindex bbcd1faa50..296d8a650a 100644--- a/tests/utilities/test_log_utils.py+++ b/tests/utilities/test_log_utils.py@@ -523,6 +523,33 @@ class TestTruncateForDatabase:# Indicator overhead is bounded (~100 chars), well under the cap.assert len(out) < DATABASE_MESSAGE_MAX_LENGTH + 200+ def test_forged_omission_marker_does_not_break_the_caps(self):+ """A message ending in a forged marker with a huge count is capped.++ Parsing a 4,301-digit count raised ``ValueError`` (Python's int+ digit limit), so both caps raised and their sinks lost the record.+ """+ from local_deep_research.utilities.log_utils import (+ DATABASE_MESSAGE_MAX_LENGTH,+ FRONTEND_MESSAGE_MAX_LENGTH,+ _truncate_for_database,+ _truncate_for_frontend,+ )++ message = (+ "q " * 3_000+ + " [... "+ + "9" * 4_301+ + " characters omitted from log output]"+ )+ suffix = f"original length: {len(message)} chars)"+ out = _truncate_for_database(message)+ assert out.startswith(message[:DATABASE_MESSAGE_MAX_LENGTH])+ assert out.endswith(suffix)+ out = _truncate_for_frontend(message)+ assert out.startswith(message[:FRONTEND_MESSAGE_MAX_LENGTH])+ assert out.endswith(suffix)+def test_database_sink_queues_truncated_message(self):"""database_sink must apply the cap BEFORE queueing so the 10 KBblob never sits in _log_queue (bounded to 1000 entries; without the@@ -950,8 +977,9 @@ class TestFrontendProgressSink:def test_long_messages_truncated_with_indicator(self):"""Messages exceeding the cap must be truncated and carry a clear- indicator that points the user at the server logs for the full- text. Other log levels / sinks are unaffected by this sink."""+ indicator that points the user at the server logs (which keep up+ to 32 KiB of the text). Other log levels / sinks are unaffected by+ this sink."""from local_deep_research.utilities.log_utils import (FRONTEND_MESSAGE_MAX_LENGTH,frontend_progress_sink,