~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
fix(logging): integrate v2 redaction and downloader URL safety (#7156)
LearningCircuit25b2d297e3db
diff --git a/changelog.d/+v2-log-redaction-integration.security.md b/changelog.d/+v2-log-redaction-integration.security.mdnew file mode 100644index 0000000000..ceeabd520e--- /dev/null+++ b/changelog.d/+v2-log-redaction-integration.security.md@@ -0,0 +1,3 @@+Log sinks now redact prefixed and dotted credential assignments, additional header and DSN formats, and secrets in rendered exceptions across the web, MCP and benchmark processes. Exception sanitization preserves tracebacks when rendering fails and keeps queued log records picklable. Unlabeled secrets still require call-site scrubbing.++Error logging also preserves redaction when credential formats overlap, masks complete supported Authorization values, and limits expensive processing of large provider errors by safely omitting the diagnostic tail.diff --git a/changelog.d/6581.security.md b/changelog.d/6581.security.mdnew file mode 100644index 0000000000..16af3b434d--- /dev/null+++ b/changelog.d/6581.security.md@@ -0,0 +1 @@+Credential and error-log scrubbing now repeats bounded passes until the output settles. URL-query redaction preserves closing Markdown autolink and code-span wrappers, and `scrub_error` also recognizes credential shapes and known secrets split by control or invisible characters without joining the original lines. A guarded assignment reading prevents a value glued to an earlier redaction marker from hiding the next credential name; the log patcher keeps its previous readings as well, so values they masked stay masked. The control-stripped view is limited to 4,096 characters, and log-sink text remains subject to its 32 KiB bound.diff --git a/changelog.d/7142.security.md b/changelog.d/7142.security.mdnew file mode 100644index 0000000000..d10cb0bd02--- /dev/null+++ b/changelog.d/7142.security.md@@ -0,0 +1 @@+Hide bound values in user-database errors and log downloader persistence failures by exception class, preventing stored URL credentials and tokens from appearing in server logs. Cached arXiv PDF save failures now return a fixed caller-safe error.diff --git a/docs/developing/credential-scrubbing.md b/docs/developing/credential-scrubbing.mdindex 5582476878..0098ac673b 100644--- a/docs/developing/credential-scrubbing.md+++ b/docs/developing/credential-scrubbing.md@@ -14,6 +14,19 @@ for that, which this repo already runs in pre-commit/CI).`sk-`/`pk-`, Google `AIza`/`ya29.`, GitHub `ghp_`/`github_pat_`, AWS`AKIA`/`ASIA`, Slack `xox*-`, JWTs). `sanitize_error_for_client()` composesit with control-char stripping + length capping.+ Log records get more coverage than this helper: the loguru patcher+ (`redact_log_record`) also recognizes prefixed and dotted credential+ assignments such as `OPENAI_API_KEY=...` and `llm.openai.api_key=...`.+ After its ordinary passes, it applies `_ADDITIONAL_CREDENTIAL_PATTERNS`+ to messages, `extra` string leaves, and rendered exception fields. These+ patterns cover slash-bearing DSN passwords, unprefixed `Api-Key:` headers,+ credential parameters after `;` or `,`, and quoted credential keys in+ JSON or Python reprs. The database sink applies them to the exception+ prefix before and after its 240-character cap. Values whose boundaries+ the patterns cannot determine are left whole. Client and agent error+ helpers, `scrub_error`, and `sanitize_error_message` do not apply these+ additional log-only patterns; their output may pass through other+ redaction stages with different boundaries.`sanitize_error_for_agent()` is the agent/tool-facing sibling — it delegatesto `sanitize_error_for_client()` with a 500-char cap instead of 200, so aclassification signal such as a rate-limit phrase sitting deep in a provider@@ -34,6 +47,18 @@ subclasses use `self._scrub_error(error)`, which resolves the engine's`_secret_attrs` and delegates to the same helper. Don't hand-inline thetwo calls: per-site copies are how scrub passes drift apart.+`scrub_error` keeps ordinary long diagnostics intact. When an error combines a+URL query with a credential assignment (including a name split by invisible+characters), preserving later log redaction requires more expensive tracking.+In each scrub round, those diagnostics keep at most the log redactor's 32 KiB+prefix, cut at its whitespace-safe boundary, before that tracking runs. Shape+and known-literal redaction run before the cut, so a known secret containing+spaces cannot be cut into an unrecognized fragment. The omitted tail is+replaced by one character-count marker after the fixed-point rounds. The+initial shape and literal scans still process the full input; the bound applies+to the added query-composition tracking. As with the other length-capped+helpers, scrubbing above-limit output again may omit additional text.+## Design constraints (why it is curated, not exhaustive)This runs on **arbitrary, possibly attacker-influenced** strings at runtime, so:@@ -44,6 +69,28 @@ This runs on **arbitrary, possibly attacker-influenced** strings at runtime, so:- **Over-redaction is the safe failure; under-redaction (a leak) is not** —but gratuitous over-redaction harms log readability, so patterns areanchored/length-floored to avoid eating prose.+- **Idempotent, and never by redacting less.** Scrubbed text gets scrubbed+ again (an error is scrubbed, re-raised and scrubbed by an outer handler;+ the log patcher re-runs on every record), so each public scrub function+ returns its own output unchanged, within the limits below. They get+ there by repeating their passes until the text stops changing+ (`_scrub_to_fixed_point`, at most five rounds), not by narrowing a+ pattern: the first round includes all existing redaction readings, and+ later rounds only replace more text. When a new stop rule shortens a match,+ keep the previous reading in the pipeline union so its masked values stay+ masked; otherwise text after the stop could be logged. `TestScrubIsIdempotent`+ and `TestScrubNeverRedactsLessThanOnePass` in+ `tests/security/test_log_sanitizer.py` check both directions. Limits: a+ length cap is not a fixed point, and a known secret can occur inside+ the marker. `redact_log_message` and the log patcher cut text longer+ than `_LOG_REDACTION_MAX_CHARS` and append an omitted-length marker, and+ redaction can push text over that bound (`token=a` becomes+ `token=[REDACTED]`), so scrubbing such output again cuts it again; that+ only drops more text, never shows more. `sanitize_error_for_client` and+ `sanitize_error_for_agent` are only guaranteed fixed points below+ their length cap. And `scrub_error` given a known secret that occurs+ inside its own `***REDACTED***` marker (such as `REDACTED`) lengthens+ the marker on every call.- Keep the set **small and high-signal**. Matching gitleaks' full 100+ rulesat runtime is overkill and raises false positives; the `redact_secrets`backstop covers the long tail for known secrets.diff --git a/src/local_deep_research/benchmarks/cli/benchmark_commands.py b/src/local_deep_research/benchmarks/cli/benchmark_commands.pyindex 73a5f02554..5596addf71 100644--- a/src/local_deep_research/benchmarks/cli/benchmark_commands.py+++ b/src/local_deep_research/benchmarks/cli/benchmark_commands.py@@ -349,10 +349,27 @@ def main():# bypasses config_logger, so the LDR_LOGURU_DIAGNOSE gate does not reach# it. Pinned off here unconditionally — the CLI has --verbose for level# but no operator workflow that needs frame-local repr dumps.+ # For the same reason, install config_logger's credential-redaction+ # patcher explicitly, or credentials in messages, bound extras and+ # exception text would reach stderr unscrubbed. Imported here, not at+ # module top, to keep log_utils' web/database imports off `--help`.+ #+ # local_deep_research/__init__.py disables the package's own loguru+ # namespace, so until it is re-enabled every record logged from inside+ # the package is dropped before the patcher or any sink sees it. Enable+ # it as config_logger and the MCP server do -- but only after removing+ # loguru's default stderr handler, which keeps loguru's diagnose=True+ # (frame-local repr dumps) and would otherwise print those records a+ # second time, unredacted locals included.+ from ...utilities.log_utils import install_log_redaction++ logger.remove()+ install_log_redaction()if args.verbose:logger.add(sys.stderr, level="DEBUG", diagnose=False)else:logger.add(sys.stderr, level="INFO", diagnose=False)+ logger.enable("local_deep_research")# Run commandif hasattr(args, "func"):diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex eb063e1986..c1c342a4c8 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -1045,6 +1045,7 @@ class DatabaseManager:creator=create_engine_connection,poolclass=self._pool_class,echo=False,+ hide_parameters=True,query_cache_size=1000,**self._get_pool_kwargs(),)@@ -1068,6 +1069,7 @@ class DatabaseManager:connect_args={"check_same_thread": False, "timeout": 30},poolclass=self._pool_class,echo=False,+ hide_parameters=True,query_cache_size=1000,**self._get_pool_kwargs(),)@@ -1531,6 +1533,7 @@ class DatabaseManager:creator=create_open_connection,poolclass=self._pool_class,echo=False,+ hide_parameters=True,query_cache_size=1000,**self._get_pool_kwargs(),)@@ -1546,6 +1549,7 @@ class DatabaseManager:connect_args={"check_same_thread": False, "timeout": 30},poolclass=self._pool_class,echo=False,+ hide_parameters=True,query_cache_size=1000,**self._get_pool_kwargs(),)diff --git a/src/local_deep_research/mcp/server.py b/src/local_deep_research/mcp/server.pyindex ce95429cdf..b9f6fa7799 100644--- a/src/local_deep_research/mcp/server.py+++ b/src/local_deep_research/mcp/server.py@@ -1018,13 +1018,8 @@ def get_configuration() -> Dict[str, Any]:def configure_mcp_logging(sink=None):"""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``.+ log messages, bound ``extra`` fields and rendered exceptions (value,+ notes, chained and grouped exceptions), and control characters stripped.MCP uses stdout for JSON-RPC, so logging goes to stderr. This runs in aseparate subprocess (ldr-mcp), so logger.remove() only affects this MCP@@ -1038,18 +1033,17 @@ 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 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.+ # The same redaction chokepoint config_logger's _sanitize_record installs+ # 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, a secret+ # bound via logger.bind(), or one inside an exception logged by the+ # logger.exception() calls in this file), 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.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()diff --git a/src/local_deep_research/metrics/token_counter.py b/src/local_deep_research/metrics/token_counter.pyindex 99ed2096f9..9507c02ba0 100644--- a/src/local_deep_research/metrics/token_counter.py+++ b/src/local_deep_research/metrics/token_counter.py@@ -776,12 +776,9 @@ class TokenCountingCallback(BaseCallbackHandler):# is the search context in production flows, which carries# user_password ("for metrics tracking", see# api/research_functions.py) and a settings_snapshot that can- # hold engine credentials. No logger in this codebase redacts- # values inside a log message — the secure_logging.logger- # wrapper only gates exception() tracebacks behind diagnose- # mode (every other call, including .warning(), still- # forwards straight to loguru unmodified), and the global- # loguru patcher only strips control characters. A value+ # hold engine credentials. The sink patcher is shape-based;+ # it cannot guarantee that an arbitrary setting value or an+ # unlabeled password inside this dict repr is removed. A value# must never be interpolated into a log message unless it# has already been passed through redact_secrets()/# scrub_error() at the call site, so we log key names only.diff --git a/src/local_deep_research/research_library/downloaders/base.py b/src/local_deep_research/research_library/downloaders/base.pyindex 2a427441c5..26714d6905 100644--- a/src/local_deep_research/research_library/downloaders/base.py+++ b/src/local_deep_research/research_library/downloaders/base.py@@ -613,8 +613,8 @@ class BaseDownloader(ABC):# so it is not an error here; ERROR records reach the# user's browser via frontend_progress_sink.unexpected_error = (- f"Unexpected error downloading from {redact_url_for_log(url)} "- f"({type(e).__name__})"+ f"Unexpected error downloading from "+ f"{redact_url_for_log(url)} ({type(e).__name__})")if on_transport_failure is not None:logger.warning(unexpected_error)diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex 1ae6c2138d..924626e774 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -1039,10 +1039,11 @@ class DownloadService:logger.warning(f"Text production returned empty text for: {resource_title[:50]}")- except Exception as e:- logger.warning(+ except Exception as exc:+ logger.opt(exception=False).warning("Failed to produce text after PDF download "- f"({type(e).__name__}), but PDF download succeeded"+ "({error_type}), but PDF download succeeded",+ error_type=type(exc).__name__,)text_details = None@@ -1109,7 +1110,8 @@ class DownloadService:# after this early return.sess.commit()logger.info(- f"Download failed with reason: {failure_reason_for_log(error_msg)}"+ "Download failed with reason: "+ f"{failure_reason_for_log(error_msg)}")return False, error_msg, status_code@@ -1231,9 +1233,10 @@ class DownloadService:self.username, self.password))- except Exception:- logger.exception(- "Failed to get library collection for dedup link"+ except Exception as exc:+ log_exception_type(+ "Failed to get library collection for dedup link",+ exc,)dedup_collection_id = Noneif dedup_collection_id:@@ -1302,9 +1305,10 @@ class DownloadService:sibling.file_name = (target_tracker.file_name)- except Exception:- logger.exception(- "Failed to sync sibling trackers after storage upgrade"+ except Exception as exc:+ log_exception_type(+ "Failed to sync sibling trackers after storage upgrade",+ exc,)elif existing_by_hash.storage_mode == "database":target_tracker.file_path = "database"@@ -1341,9 +1345,10 @@ class DownloadService:# re-download, not data loss.target_tracker.file_path = Nonetarget_tracker.file_name = None- except Exception:- logger.exception(- "Failed to reuse/upgrade deduped PDF storage"+ except Exception as exc:+ log_exception_type(+ "Failed to reuse/upgrade deduped PDF storage",+ exc,)if hasattr(tracker, "file_path"):tracker.file_path = target_tracker.file_path@@ -1367,9 +1372,10 @@ class DownloadService:self.username, self.password))- except Exception:- logger.exception(- "Failed to get source type or library collection"+ except Exception as exc:+ log_exception_type(+ "Failed to get source type or library collection",+ exc,)raise@@ -1475,23 +1481,23 @@ class DownloadService:logger.info(f"Successfully produced and saved text for: {staging_resource_title[:50]}")- except Exception:- logger.exception(- "Failed to save text after PDF download, but PDF download succeeded"+ except Exception as exc:+ log_exception_type(+ "Failed to save text after PDF download, but PDF download succeeded",+ exc,)return True, None, status_codeexcept Exception as e:- # Transport exceptions can embed credentials or a signed URL.- logger.warning(- f"Download failed ({type(e).__name__}) for "- f"{redact_url_for_log(url)}"+ logger.opt(exception=False).warning(+ "Download failed ({error_type}) for {url}",+ error_type=type(e).__name__,+ url=redact_url_for_log(url),)# Two distinct outputs:- # * server-side diagnostic persisted in DownloadAttempt.error_message- # — full str(e), with credential scrubbing applied. The log- # above carries only the exception class and redacted URL.+ # * server-side diagnostic (persisted in DownloadAttempt.error_message)+ # — full str(e), with credential scrubbing applied before storage.# * caller-safe skip_reason (the second tuple element, and what# flows into retry-manager / bulk-stream SSE messages) — must# never carry SQL text, target URLs, or file paths. The Zotero@@ -1542,9 +1548,9 @@ class DownloadService:))err_sess.commit()- except Exception:- logger.exception(- "Failed to record failed attempt in database"+ except Exception as exc:+ log_exception_type(+ "Failed to record failed attempt in database", exc)return False, skip_reason, None@@ -1736,8 +1742,8 @@ class DownloadService:logger.warning("No text could be extracted from PDF")return None- except Exception:- logger.exception("Failed to extract text from PDF")+ except Exception as exc:+ log_exception_type("Failed to extract text from PDF", exc)return Nonedef download_as_text(self, resource_id: int) -> Tuple[bool, Optional[str]]:@@ -2047,9 +2053,11 @@ class DownloadService:cached_outcome = self._text_from_cached_pdf(session, resource)- except Exception:+ except Exception as exc:safe_rollback(session, "_try_arxiv_text_extraction")- logger.exception("Stored arXiv PDF text extraction failed")+ log_exception_type(+ "Stored arXiv PDF text extraction failed", exc+ )return Noneif cached_outcome is not None and cached_outcome[0]:return cached_outcome@@ -2071,9 +2079,11 @@ class DownloadService:cached_outcome = self._text_from_cached_pdf(session, resource)- except Exception:+ except Exception as exc:safe_rollback(session, "_try_arxiv_text_extraction")- logger.exception("Stored arXiv PDF text extraction failed")+ log_exception_type(+ "Stored arXiv PDF text extraction failed", exc+ )cached_outcome = Noneif cached_outcome is not None and cached_outcome[0]:return cached_outcome@@ -2094,8 +2104,9 @@ class DownloadService:)except Exception as exc:safe_rollback(session, "_try_arxiv_text_extraction")- logger.warning(- f"Canonical arXiv text extraction failed ({type(exc).__name__})"+ logger.opt(exception=False).warning(+ "Canonical arXiv text extraction failed ({error_type})",+ error_type=type(exc).__name__,)# Caller-visible: fixed token only. sanitize_error_for_client()# scrubs credentials but leaves SQL text / URLs / paths intact,@@ -2123,7 +2134,7 @@ class DownloadService:session.commit()except Exception as exc:safe_rollback(session, "_try_arxiv_text_extraction")- logger.exception("Failed to save canonical arXiv text")+ log_exception_type("Failed to save canonical arXiv text", exc)# Same caller-safe mapping as above — never str(exc) (see comment# on the fetch-failure path).safe_error = _client_safe_download_message(exc)@@ -2194,10 +2205,8 @@ class DownloadService:session.commit()except Exception as exc:safe_rollback(session, "_try_arxiv_text_extraction")- logger.exception("Failed to save local arXiv PDF text")- safe_error = sanitize_error_for_client(- f"Failed to extract arXiv text: {exc}"- )+ log_exception_type("Failed to save local arXiv PDF text", exc)+ safe_error = _client_safe_download_message(exc)return False, safe_errorreturn True, None@@ -2257,10 +2266,8 @@ class DownloadService:session.commit()return True, None- except Exception:- logger.exception(- f"Failed to extract text from existing PDF: {pdf_path}"- )+ except Exception as exc:+ log_exception_type("Failed to extract text from existing PDF", exc)# The commit above can fail and poison the shared session.# download_as_text swallows this None and may then return cleanly# (e.g. a non-retry decision), so the with-block exits without an@@ -2339,7 +2346,7 @@ class DownloadService:# download_as_text reuses this session (_record_retry_attempt)# after we return, so it must be clean.safe_rollback(session, "_try_api_text_extraction")- logger.exception(f"Failed to save text for resource {resource.id}")+ log_exception_type("Failed to save text for resource", e)# Caller-visible: fixed token only (CWE-209). sanitize_error_for_client# leaves SQL text intact and this flows into download_as_text's# return and the bulk-stream SSE `error` field.@@ -2425,7 +2432,7 @@ class DownloadService:# PendingRollbackError. download_as_text reuses this session after# we return.safe_rollback(session, "_fallback_pdf_extraction")- logger.exception(f"Failed to save text for resource {resource.id}")+ log_exception_type("Failed to save text for resource", e)# Caller-visible: fixed token only (CWE-209) — same mapping as# _download_pdf; never str(e).safe_error = _client_safe_download_message(e)@@ -2920,9 +2927,9 @@ class DownloadService:source_type_id = get_source_type_id(self.username, "research_download", self.password)- except Exception:- logger.exception(- "Failed to get source type for text document"+ except Exception as exc:+ log_exception_type(+ "Failed to get source type for text document", exc)raise@@ -2971,14 +2978,14 @@ class DownloadService:)return None- except Exception:+ except Exception as exc:# Rollback BEFORE re-raising so the shared thread-local session# is clean by the time the caller's loop reaches its next# iteration. Without this, an IntegrityError leaves the session# in PendingRollbackError state and every subsequent ORM access# cascades (issue #3827).safe_rollback(session, "_save_text_with_db")- logger.exception("Error saving text to encrypted database")+ log_exception_type("Error saving text to encrypted database", exc)raise # Re-raise so caller can handle the errordef _create_text_document_record(@@ -3017,8 +3024,10 @@ class DownloadService:f"No document found to update for resource {resource.id}")- except Exception:- logger.exception("Error updating document with text from file")+ except Exception as exc:+ log_exception_type(+ "Error updating document with text from file", exc+ )def _record_failed_text_extraction(self, session: Session, resource: ResearchResource, error: str@@ -3075,5 +3084,5 @@ class DownloadService:f"{resource.id}: {failure_reason_for_log(error)}")- except Exception:- logger.exception("Error recording failed text extraction")+ except Exception as exc:+ log_exception_type("Error recording failed text extraction", exc)diff --git a/src/local_deep_research/security/client_safe_errors.py b/src/local_deep_research/security/client_safe_errors.pyindex d60fa13950..0e80ef8021 100644--- a/src/local_deep_research/security/client_safe_errors.py+++ b/src/local_deep_research/security/client_safe_errors.py@@ -11,8 +11,8 @@ import from here so they cannot drift again.Contract (CWE-209): never pass ``str(exc)`` to the caller. The exception textcan carry SQL text (``INSERT INTO document_collections ...``), target URLs,or absolute file paths. Caller-visible ``skip_reason`` values are fixed-tokens or ``download_error:<ClassName>`` only. Full diagnostics stay-server-side via ``logger.exception`` and ``DownloadAttempt.error_message``.+tokens or ``download_error:<ClassName>`` only. Server-side logs retain the+exception class; ``DownloadAttempt.error_message`` stores scrubbed detail.``sanitize_error_for_client()`` is NOT a substitute — it scrubs credentialshapes only, not SQL/paths/URLs."""@@ -56,10 +56,10 @@ def client_safe_download_message(exc: BaseException) -> str:Author-written constant for known classes; the exception's class namefor everything else. Never passes ``str(exc)`` through — that can carry- SQL text, target URLs, or file paths the caller should not see. The full- exception text is preserved server-side via ``logger.exception`` and- stored in ``DownloadAttempt.error_message`` only after the same safe- mapping (see ``download_service._download_pdf``'s outer except).+ SQL text, target URLs, or file paths the caller should not see. The+ downloader service logs only the exception class and stores a+ credential-scrubbed message in ``DownloadAttempt.error_message`` (see its+ outer PDF handler).``OSError`` is the one exception family where ``str(exc)`` is *not*free of app-controlled text — Python formats it asdiff --git a/src/local_deep_research/security/log_sanitizer.py b/src/local_deep_research/security/log_sanitizer.pyindex 08960a01f9..4ff3f3dd00 100644--- a/src/local_deep_research/security/log_sanitizer.py+++ b/src/local_deep_research/security/log_sanitizer.py@@ -17,13 +17,52 @@ concerns:and redact credential *shapes* from its string leaves before it isserialized to a client. (Value-shape based; contrast``data_sanitizer.DataSanitizer``, which redacts by key *name*.)++Threat model of the log-record redaction (:func:`redact_log_record`):+exception classes and the code that logs are application code, and are+trusted; the *data* inside exceptions -- messages, ``args``, fields and+notes built from upstream responses, URLs or user input -- and bound+``extra`` values are not. Credential-shaped data in exception text,+``args``, notes and ``extra`` (known key and token shapes, URL userinfo,+sensitive ``name=value`` pairs, and ``extra`` values under sensitive key+names) is redacted before any sink renders it, and every record is+picklable by an ``enqueue=True`` sink. Redaction matches shapes, not+meaning: a secret in another form passes through, such as an arbitrary+application-specific ``name: value`` pair with a colon, or a bare password+or token with no label and no known shape. Nothing is claimed about an+exception class or object deliberately written to defeat the redactor:+metaclass, descriptor, ``__class__`` or ``__dict__`` hooks, a ``__str__``+with side effects on other exceptions, a class registered in+:mod:`builtins` under its own name, and the like. Such code can leak a+secret in many other ways anyway. The checks below that reject such+classes (rebuilding the exception from its checked text) are defence in+depth, not a complete barrier; where a docstring says a check or a step+"runs no code", that holds for exception classes and objects that do not+hook those mechanisms."""+import builtins+import collections.abc+import contextlib+import contextvars+import copyreg+import bisectimport dataclasses+import functools+import itertools+import operatorimport re-from typing import Any, Optional, Union--from .data_sanitizer import DataSanitizer, REDACTION_TEXT+import sys+import types+from importlib.machinery import ModuleSpec+from multiprocessing.reduction import ForkingPickler+from typing import Any, Callable, Iterable, NamedTuple, Optional, Union++from .data_sanitizer import (+ DataSanitizer,+ REDACTION_TEXT,+ _EXEMPT_QUALIFIER_LEAF,+)# Strip C0/C1 control characters and dangerous Unicode format characters,@@ -62,10 +101,9 @@ def strip_control_chars(value: str) -> str:def sanitize_log_record(record) -> None:"""loguru patcher stripping control characters from a record's message.- loguru holds one patcher per process, so every process that builds its own- sink installs this itself. Shared from here rather than from ``log_utils``- because that module imports the web stack at module scope, and the MCP- subprocess does not.+ Control-character strip only. The web and MCP processes both install+ :func:`redact_log_record` instead, which does this strip as part of its+ message redaction and also redacts credentials."""record["message"] = strip_control_chars(record["message"])@@ -113,7 +151,9 @@ def redact_secrets(is replaced first.Args:- message: The string to scrub. Returned unchanged if falsy.+ message: The string to scrub (a ``str`` subclass is scrubbed, and+ returned, as a plain ``str``). Returned unchanged if it is+ empty or a falsy non-string.*secrets: Zero or more candidate secret values. ``None`` andvalues shorter than *min_length* are silently skipped \u2014 thecaller is responsible for noticing missing config.@@ -136,6 +176,7 @@ def redact_secrets(example value in this file, while other credential literals andtoken-shaped values remain scanned)."""+ message = _plain_text(message)if not message:return message# Longest-first prevents a shorter overlapping secret from@@ -375,14 +416,155 @@ _CREDENTIAL_PATTERNS: list[tuple[re.Pattern[str], str]] = [# all, so a sentence-final "...page? yes" must not be rewritten into# "...page?<redacted> yes", which would imply a query existed._URL_QUERY_STRING_RE = re.compile(- r"([A-Za-z][A-Za-z0-9+.\-]{0,31}://[^\s?#\"<>]{1,4096})\?[^\s)\"']+"+ r"([A-Za-z][A-Za-z0-9+.\-]{0,31}://[^\s?#\"<>]{1,4096})\?([^\s)\"']+)")+_URL_QUERY_MARKER = "<redacted>"+_URL_QUERY_WRAPPERS = {"<": ">", "`": "`"}+++def _restore_query_wrapper(match: "re.Match[str]") -> str:+ """Keep only a final Markdown wrapper character, never query content."""+ url, query = match.group(1), match.group(2)+ opener = match.string[match.start() - 1] if match.start() else ""+ closer = _URL_QUERY_WRAPPERS.get(opener)+ if (+ closer is not None+ and len(query) > 1+ and query.endswith(closer)+ and query != _URL_QUERY_MARKER+ ):+ return f"{url}?{_URL_QUERY_MARKER}{closer}"+ return f"{url}?{_URL_QUERY_MARKER}"+++def _query_needs_credential_guards(message: str, glued: str) -> bool:+ """Whether query removal must preserve later credential readings."""+ return "=" in message and (+ _has_name_assignment_hint(message) or _has_name_assignment_hint(glued)+ )++def _redact_url_query_strings(message: str) -> str:"""Replace the query component of any URL in *message* with a fixed- marker, preserving the scheme/host/path so the endpoint stays legible."""- return _URL_QUERY_STRING_RE.sub(r"\1?<redacted>", message)+ marker, preserving the scheme/host/path so the endpoint stays legible.++ A quoted value after a query assignment's ``=`` belongs to that query.+ The regex stops at its opening quote; consume the whole value before+ replacing the query, or a zero-width separator before the assignment+ could leave the quoted secret visible without its credential name.+ """+ if "?" not in message or "://" not in message:+ return message+ queries = list(_URL_QUERY_STRING_RE.finditer(message))+ if not queries:+ return message+ guards: list[list[tuple[int, int, int]]] = []+ glued_query_ends: dict[int, int] = {}+ glued = strip_control_chars(message)+ split_offsets = _glued_offsets(message) if glued != message else None+ if _query_needs_credential_guards(message, glued):+ if glued == message:+ to_text: Callable[[int], int] = int+ else:+ glued_starts, text_starts = _glued_offsets(message)++ def to_text(offset: int) -> int:+ run = bisect.bisect_right(glued_starts, offset) - 1+ return text_starts[run] + offset - glued_starts[run]++ guards = _log_patcher_spans(message, glued, to_text)+ if glued != message:+ glued_query_ends = {+ to_text(query.start(2) - 1): to_text(query.end() - 1) + 1+ for query in _URL_QUERY_STRING_RE.finditer(glued)+ }++ pieces: list[str] = []+ done = 0+ for match in queries:+ if match.start() < done:+ continue+ query_end = match.end()+ end = _cover_query_cut_credentials(+ match.start(2) - 1, query_end, guards, query_end+ )+ if end > query_end:+ # A name split by a control can sit inside a longer query in+ # the stripped view. Consume that whole query so the suffix+ # cannot be mistaken for URL userinfo on the next scrub round.+ end = _cover_query_cut_credentials(+ match.start(2) - 1,+ max(end, glued_query_ends.get(match.start(2) - 1, end)),+ guards,+ query_end,+ )+ if (+ end == match.end()+ and match.group(2).endswith("=")+ and end < len(message)+ ):+ quote = message[end]+ if quote in ('"', "'"):+ end += 1+ while end < len(message):+ if message[end] == "\\":+ end += 2+ elif message[end] == quote:+ end += 1+ break+ else:+ end += 1+ end = min(end, len(message))+ # Extending through a quoted query value can consume the+ # name of a later credential. Include its complete value+ # so the log patcher is not left an unlabelled suffix.+ end = _cover_query_cut_credentials(+ match.start(2) - 1, end, guards, query_end+ )+ if split_offsets is not None:+ while True:+ extended = _cover_query_cut_credentials(+ match.start(2) - 1,+ _extend_over_split_credential(+ glued,+ *split_offsets,+ match.start(2) - 1,+ end,+ ),+ guards,+ query_end,+ )+ if extended == end:+ break+ end = extended+ pieces.append(message[done : match.start()])+ pieces.append(_restore_query_wrapper(match))+ if end > query_end:+ pieces.extend(+ char+ for char in message[query_end:end]+ if _UNSAFE_CHAR_RE.fullmatch(char)+ )+ done = end+ if not pieces:+ return message+ pieces.append(message[done:])+ return "".join(pieces)+++_MAX_SCRUB_ROUNDS = 5+++def _scrub_to_fixed_point(scrub_once: Callable[[str], str], text: str) -> str:+ """Repeat redaction until stable, with a bound on adversarial input."""+ for _ in range(_MAX_SCRUB_ROUNDS):+ scrubbed = scrub_once(text)+ if scrubbed == text:+ break+ text = scrubbed+ return textdef sanitize_error_message(message: str) -> str:@@ -403,6 +585,11 @@ def sanitize_error_message(message: str) -> str:GitHub ``ghp_``/``github_pat_``, AWS ``AKIA``/``ASIA``, Slack ``xox*-``,and JWTs (``eyJ….….…``). See ``docs/developing/credential-scrubbing.md``."""+ message = _plain_text(message)+ return _scrub_to_fixed_point(_sanitize_error_message_once, message)+++def _sanitize_error_message_once(message: str) -> str:if not message:return messagefor pattern, replacement in _CREDENTIAL_PATTERNS:@@ -410,6 +597,463 @@ def sanitize_error_message(message: str) -> str:return message+# A match found in the stripped view: start, end, replacement, and whether+# the replacement is a fixed string holding none of the matched text.+_GluedMatch = tuple[int, int, str, bool]+++def _glued_offsets(text: str) -> tuple[list[int], list[int]]:+ """Map the text :func:`strip_control_chars` leaves back onto *text*.++ Returns the start of each run of kept characters in the stripped text+ and in *text*, in step, so a stripped offset ``i`` in run ``k`` is+ ``text_starts[k] + i - glued_starts[k]`` in *text*.+ """+ glued_starts: list[int] = []+ text_starts: list[int] = []+ glued = 0+ pos = 0+ for unsafe in _UNSAFE_CHAR_RE.finditer(text):+ if unsafe.start() > pos:+ glued_starts.append(glued)+ text_starts.append(pos)+ glued += unsafe.start() - pos+ pos = unsafe.end()+ if pos < len(text):+ glued_starts.append(glued)+ text_starts.append(pos)+ return glued_starts, text_starts+++def _log_patcher_spans(+ text: str, glued: str, to_text: Callable[[int], int]+) -> list[list[tuple[int, int, int]]]:+ """Credentials in *text* that the log patcher's bare passes redact.++ Every pass in :data:`_LOG_PATCHER_BARE_PASSES`, the list the patcher+ itself applies (``name=value`` assignments and ``?name=value``+ parameters), found both with the original separators and in the+ stripped view (mapped back), as ``(start, value_start, end)``: one+ sorted, non-overlapping list per pass and view.+ """+ lists = []+ for pattern, _, name_group, value_after, _ in _LOG_PATCHER_BARE_PASSES:++ def span(+ m: "re.Match[str]",+ name: int = name_group,+ value: int = value_after,+ ) -> tuple[int, int, int]:+ return m.start(name), m.end(value), m.end()++ lists.append([span(m) for m in pattern.finditer(text)])+ lists.append(+ [+ (to_text(start), to_text(value), to_text(end - 1) + 1)+ for start, value, end in map(span, pattern.finditer(glued))+ ]+ )+ # Later passes can read a value differently after an inner name+ # has been redacted. Guard those actual readings as well as the+ # direct matches above; removing the outer name must also remove+ # every value that any of the log pipelines associates with it.+ for spans in _pipeline_credential_spans(text):+ lists.extend(([], spans))+ return lists+++def _fit_around_credentials(+ start: int, end: int, guards: list[list[tuple[int, int, int]]]+) -> Optional[tuple[int, int, bool]]:+ """Fit the span ``[start, end)`` so the log patcher can still redact+ every credential it touches.++ A guard is a credential the patcher redacts (see+ :func:`_log_patcher_spans`); the patcher needs its name to find its+ value. A span that covers the whole value, or starts inside the value,+ leaves nothing of the value visible without its name and is kept. A+ span that starts before the guard and ends inside it is cut back to+ end where the guard starts. A span that starts in the name and ends+ before the value does is dropped (``None``). Returns the new span and+ whether it changed.+ """+ lo, hi = start, end+ changed = True+ while changed: # cutting a span can uncover another partial overlap+ changed = False+ for spans in guards:+ # Non-overlapping and sorted, so the ends are sorted too.+ i = bisect.bisect_right(spans, lo, key=lambda span: span[2])+ while i < len(spans) and spans[i][0] < hi:+ g_start, value_start, g_end = spans[i]+ i += 1+ if lo >= value_start or hi >= g_end:+ continue+ if lo >= g_start:+ return None+ hi = g_start+ changed = True+ return lo, hi, (lo, hi) != (start, end)+++def _cover_cut_credentials(+ start: int, end: int, guards: list[list[tuple[int, int, int]]]+) -> int:+ """End of the span ``[start, end)``, extended to the end of every+ credential in *guards* (see :func:`_log_patcher_spans`) whose name it+ takes without the whole of its value, so the patcher is never left that+ value without its name."""+ changed = True+ while changed:+ changed = False+ for spans in guards:+ i = bisect.bisect_right(spans, start, key=lambda span: span[2])+ while i < len(spans) and spans[i][0] < end:+ g_start, value_start, g_end = spans[i]+ i += 1+ if start < value_start and end < g_end:+ end = g_end+ changed = True+ return end+++def _cover_query_cut_credentials(+ start: int,+ end: int,+ guards: list[list[tuple[int, int, int]]],+ query_end: int,+) -> int:+ """Cover credentials cut by a query, retaining intact later assignments.++ A glued-view match can begin in the final query character and extend+ across a line break into a complete assignment. If the original-view+ patcher already covers that whole assignment after *query_end*, leave+ the line and its credential untouched. Span lists alternate original+ and glued views, so only overlapping spans need to be checked.+ """++ def preserved_in_original(value_start: int, value_end: int) -> bool:+ for originals in guards[::2]:+ j = bisect.bisect_left(+ originals, value_start, key=lambda span: span[1]+ )+ if (+ j < len(originals)+ and originals[j][0] >= query_end+ and originals[j][1] == value_start+ and originals[j][2] >= value_end+ ):+ return True+ return False++ changed = True+ while changed:+ changed = False+ for view, spans in enumerate(guards):+ i = bisect.bisect_right(spans, start, key=lambda span: span[2])+ while i < len(spans) and spans[i][0] < end:+ g_start, value_start, g_end = spans[i]+ i += 1+ if start >= value_start or end >= g_end:+ continue+ if view % 2 and preserved_in_original(value_start, g_end):+ continue+ end = g_end+ changed = True+ return end+++# What the log patcher's bare passes take as an unquoted value: the run of+# non-whitespace after the ``=`` (a stop inside it only makes it shorter).+_NON_SPACE_RUN_RE = re.compile(r"\S*")+++def _reveals_log_patcher_name(covered: str, replacement: str) -> bool:+ """True when *replacement*, written in place of *covered*, shows the log+ patcher a ``name=`` or ``?name=`` it does not see in *covered*.++ The stripped view can join a name split by an invisible character+ (``authorizatio<U+200B>n=...``), and a credential pattern's replacement+ keeps it (``authorization=[REDACTED]``). The patcher then takes the run+ of text after the replacement as that name's value, up to the next+ whitespace, and that run can be the first half of another name split by+ a line break (``'api_`` of ``'api_\\nkey=...``), which it would no+ longer recognise. :func:`_splice_across_controls` therefore takes that+ run into the redaction, and so the credential it starts.+ """+ return any(+ bare.unanchored.search(replacement)+ and not bare.unanchored.search(covered)+ for bare in _LOG_PATCHER_BARE_PASSES+ )+++# How many line breaks (or other stripped characters) at the end of a span+# :func:`_extend_over_split_credential` looks at, and how far before the+# first of them and past the span it searches at a time. Bounds its cost+# on adversarial input.+_MAX_PROBED_CROSSINGS = 64+_PROBE_WINDOW = 128+++def _extend_over_split_credential(+ glued: str,+ glued_starts: list[int],+ text_starts: list[int],+ start: int,+ end: int,+) -> int:+ """End of the span ``[start, end)`` of *text*, extended so it does not+ take only the start of a credential that runs on past it.++ In the stripped view a span can run on through a line break into the+ next line and take the start of a credential there: a name, or a+ ``Bearer``/``Authorization:`` anchor split by a stripped character+ (``Beare\\rr``), whose value lies past the span. Without that start+ the log patcher no longer recognises the value. So when a credential+ pattern the patcher uses matches across the span's end (as a scan from+ before the span finds it, or starting right after a stripped character+ inside the span) and would still redact something, the span is extended+ to the end of that match, and the value is redacted with it. *glued_starts* and *text_starts* are from :func:`_glued_offsets`.+ """+ probes = [+ *_CREDENTIAL_PATTERNS,+ *(+ (bare.unanchored, bare.replacement)+ for bare in _LOG_PATCHER_BARE_PASSES+ ),+ ]+ anchored = {+ bare.unanchored: bare.pattern for bare in _LOG_PATCHER_BARE_PASSES+ }++ def to_glued(offset: int) -> int:+ """Stripped-view offset of the first kept character at or after+ *offset* in *text*."""+ run = bisect.bisect_right(text_starts, offset) - 1+ if run < 0:+ return 0+ run_len = (+ glued_starts[run + 1] if run + 1 < len(glued_starts) else len(glued)+ ) - glued_starts[run]+ return glued_starts[run] + min(offset - text_starts[run], run_len)++ def to_text_end(glued_end: int) -> int:+ """Offset in *text* just after the kept character before+ *glued_end*."""+ run = bisect.bisect_right(glued_starts, glued_end - 1) - 1+ return text_starts[run] + glued_end - glued_starts[run]++ # Bound chains that repeatedly expose another credential. If the work+ # limit is reached, redact the remaining tail instead of leaving a value+ # behind after consuming its label.+ extensions_left = 16+ while True:+ if extensions_left == 0:+ return to_text_end(len(glued))+ extensions_left -= 1+ # Runs of kept text that begin inside the span follow a stripped+ # character there.+ first = bisect.bisect_right(text_starts, start)+ last = bisect.bisect_left(text_starts, end)+ runs = range(max(first, last - _MAX_PROBED_CROSSINGS), last)+ if not runs:+ return end+ crossings = [glued_starts[run] for run in runs]+ glued_end = to_glued(end)+ window_end = min(len(glued), glued_end + _PROBE_WINDOW)+ reach = glued_end++ def runs_on(m: Optional["re.Match[str]"], template: str) -> int:+ """End of *m* if it runs past the span and would still redact+ something, else 0. A match cut off by the window is redone+ without it, so the whole value is covered."""+ if (+ m is None+ or m.end() <= glued_end+ or m.expand(template) == m.group()+ ):+ return 0+ if m.end() >= window_end:+ whole = m.re.match(glued, m.start())+ if whole is not None:+ return max(m.end(), whole.end())+ return m.end()++ window_start = max(0, crossings[0] - _PROBE_WINDOW)+ for pattern, template in probes:+ # A match as the patcher finds it, scanning from before the+ # span, that straddles the span's end.+ natural = anchored.get(pattern, pattern)+ for m in natural.finditer(glued, window_start, window_end):+ if m.start() >= glued_end:+ break+ reach = max(reach, runs_on(m, template))+ if "://" in pattern.pattern:+ continue # a URL scheme has no fixed start to anchor at+ # A match starting right after a stripped character: the+ # patcher may see it there once what precedes it is redacted.+ for crossing in crossings:+ m = pattern.match(glued, crossing, window_end)+ reach = max(reach, runs_on(m, template))+ if reach == glued_end:+ return end+ end = to_text_end(reach)+++def _splice_across_controls(+ text: str, glued: str, matches: Iterable[_GluedMatch]+) -> str:+ """Apply redactions found in *glued* (``strip_control_chars(text)``)+ to *text* itself.++ Each match is mapped back to the span of *text* it covers, then fitted+ around any credential the log patcher would redact (see+ :func:`_fit_around_credentials`) and extended over any credential it+ would otherwise cut into (see :func:`_extend_over_split_credential`),+ and over the whole of any credential that extension takes the name of+ (see :func:`_cover_cut_credentials`). A replacement that would show the+ patcher a name it does not see in the span (a split name the stripped+ view joined, see :func:`_reveals_log_patcher_name`) is extended over the+ run of text the patcher would take as that name's value. These rules+ keep the patcher from being left a value without its name in the+ shapes they model; they are not a proof for every input. A span that+ had to change gets a plain+ ``[REDACTED]`` unless its replacement holds no matched text. The+ whitespace control characters inside a replaced span (line breaks,+ tabs, U+2028, ...) are written back after the replacement, so no two+ lines are joined. A span whose stripped text already equals its+ replacement is left alone.+ """+ glued_starts, text_starts = _glued_offsets(text)++ def to_text(offset: int) -> int:+ run = bisect.bisect_right(glued_starts, offset) - 1+ return text_starts[run] + offset - glued_starts[run]++ guards = _log_patcher_spans(text, glued, to_text)+ pieces: list[str] = []+ done = 0+ for g_start, g_end, replacement, literal in matches:+ if g_end <= g_start:+ continue+ fitted = _fit_around_credentials(+ to_text(g_start), to_text(g_end - 1) + 1, guards+ )+ if fitted is None:+ continue+ start, end, shrunk = fitted+ if shrunk and not literal:+ # A shape replacement retains its anchor (header name, URL+ # scheme, ...). Cutting its match short and replacing that+ # anchor with a plain marker would expose the original value.+ # Keep the whole match; the extension below also conceals any+ # overlapping assignment whose name this span would take.+ end = to_text(g_end - 1) + 1+ if start < done:+ continue # inside a span an earlier match was extended over+ if not (shrunk and not literal) and _reveals_log_patcher_name(+ text[start:end], replacement+ ):+ run_end = _NON_SPACE_RUN_RE.match(text, end).end()+ if run_end != end:+ end, shrunk = run_end, True+ while True:+ # Extending can take the name of a credential the patcher sees+ # in *text*; the span then takes its whole value as well.+ extended = _cover_cut_credentials(+ start,+ _extend_over_split_credential(+ glued, glued_starts, text_starts, start, end+ ),+ guards,+ )+ if extended == end:+ break+ end, shrunk = extended, True+ if shrunk and not literal:+ replacement = REDACTION_TEXT+ covered = text[start:end]+ if strip_control_chars(covered) == replacement:+ continue+ kept = "".join(+ c for c in covered if c.isspace() and _UNSAFE_CHAR_RE.match(c)+ )+ pieces.append(text[done:start])+ pieces.append(replacement + kept)+ done = end+ pieces.append(text[done:])+ return "".join(pieces)+++# Longest text :func:`_scrub_across_controls` scans. On adversarial input+# (a line break inside every ``Bearer``, ``Authorization:`` or URL) it costs+# up to about 55 microseconds per character, against about 0.4 for the+# plain passes, so at this bound about 0.2 s per round. Longer text gets the+# plain passes only, as before that view existed.+_GLUED_VIEW_MAX_CHARS = 4096+++def _scrub_across_controls(text: str, secrets: list) -> str:+ """Re-run :func:`scrub_error`'s passes on *text* with control and+ invisible format characters removed, applying what they find to+ *text* itself (see :func:`_splice_across_controls`).++ Text without such characters is returned as it is: the plain passes+ already saw it exactly as this view would. So is text longer than+ ``_GLUED_VIEW_MAX_CHARS``, which bounds the cost of this view; such text+ keeps only the plain passes, and the log patcher still strips control+ characters and redacts again before it is logged.+ """+ if len(text) > _GLUED_VIEW_MAX_CHARS or not _UNSAFE_CHAR_RE.search(text):+ return text+ glued = strip_control_chars(text)++ def apply(find: Callable[[str], Iterable[_GluedMatch]]) -> None:+ nonlocal text, glued+ matches = list(find(glued))+ if matches:+ spliced = _splice_across_controls(text, glued, matches)+ if spliced != text:+ text = spliced+ glued = strip_control_chars(text)++ for pattern, template in _CREDENTIAL_PATTERNS:+ apply(+ lambda glued, p=pattern, t=template: (+ (m.start(), m.end(), m.expand(t), "\\" not in t)+ for m in p.finditer(glued)+ )+ )+ for secret in sorted(+ (s for s in secrets if s and len(s) >= _MIN_SECRET_LENGTH),+ key=len,+ reverse=True,+ ):+ apply(lambda glued, s=secret: _literal_matches(glued, s))++ def query_matches(glued: str) -> Iterable[_GluedMatch]:+ for m in _URL_QUERY_STRING_RE.finditer(glued):+ # Only the query is replaced; the URL before it keeps its text.+ yield (+ m.start(2) - 1,+ m.end(),+ _restore_query_wrapper(m)[len(m.group(1)) :],+ True,+ )++ apply(query_matches)+ return text+++def _literal_matches(glued: str, secret: str) -> Iterable[_GluedMatch]:+ """Non-overlapping occurrences of *secret*, as ``str.replace`` finds them."""+ pos = glued.find(secret)+ while pos != -1:+ yield (pos, pos + len(secret), _REDACTION_TOKEN, True)+ pos = glued.find(secret, pos + len(secret))++def scrub_error(error: Union[BaseException, str], *secrets: Any) -> str:"""Return a log/DB-safe rendering of *error* (the "triple-scrub").@@ -433,6 +1077,13 @@ def scrub_error(error: Union[BaseException, str], *secrets: Any) -> str:``BaseSearchEngine._scrub_error`` delegates here, resolving itsengine's ``_secret_attrs`` into the *secrets* arguments.+ Query removal needs additional credential-boundary analysis when a+ URL query and a sensitive assignment occur together. Such text is cut+ at the log redactor's whitespace-safe 32 KiB bound after shape and+ known-literal redaction, before that expensive analysis; the omitted+ tail is replaced by a marker outside the fixed-point rounds. Other+ long diagnostics retain their full-text behavior.+Defensive by design: this runs inside ``except`` blocks, so it mustnever raise. ``str(error)`` is guarded (a custom exception whose``__str__`` raises won't crash the handler) and each secret is coerced@@ -450,7 +1101,7 @@ def scrub_error(error: Union[BaseException, str], *secrets: Any) -> str:try:message = str(error)except Exception:- message = f"<unprintable {type(error).__name__}>"+ message = "<unprintable {}>".format(type(error).__name__)# Coerce truthy non-str secrets to str; keep None/falsy as-is# (redact_secrets filters those out). Guarded per secret: a# pathological value whose __bool__/__str__ raises cannot be@@ -462,9 +1113,35 @@ def scrub_error(error: Union[BaseException, str], *secrets: Any) -> str:safe_secrets.append(v and str(v))except Exception:continue- return _redact_url_query_strings(- redact_secrets(sanitize_error_message(message), *safe_secrets)- )++ omitted = 0++ def scrub_once(text: str) -> str:+ nonlocal omitted+ text = redact_secrets(sanitize_error_message(text), *safe_secrets)+ if (+ len(text) > _LOG_REDACTION_MAX_CHARS+ and "?" in text+ and "://" in text+ and _query_needs_credential_guards(text, strip_control_chars(text))+ and _URL_QUERY_STRING_RE.search(text) is not None+ ):+ # Shape and known-literal redaction must precede the cut: a+ # known secret containing spaces could straddle its boundary.+ # Guarded query removal tracks every character through several+ # readings; limit that work before creating the origin arrays.+ # Ordinary long diagnostics keep their existing full-text path.+ head, _ = _truncate_for_log_redaction(text)+ omitted += len(text) - len(head)+ text = head+ text = _redact_url_query_strings(text)+ return _scrub_across_controls(text, safe_secrets)++ result = _scrub_to_fixed_point(scrub_once, message)+ if omitted:+ # Keep generated metadata outside subsequent redaction rounds.+ result += f" [... {omitted} characters omitted from log output]"+ return resultdef sanitize_error_for_client(message: str, max_length: int = 200) -> str:@@ -507,9 +1184,11 @@ def sanitize_error_for_client(message: str, max_length: int = 200) -> str:opt-ins (``utilities/log_utils.py``), but that is exactly theconfiguration an operator debugging such a failure runs."""- return sanitize_for_log(- sanitize_error_message(message), max_length=max_length+ scrubbed = _scrub_to_fixed_point(+ lambda text: strip_control_chars(_sanitize_error_message_once(text)),+ message,)+ return sanitize_for_log(scrubbed, max_length=max_length)# Larger cap than ``sanitize_error_for_client``'s HTTP-client default: these@@ -610,9 +1289,11 @@ def sanitize_error_details(value: Any) -> Any:* ``dict`` — recurse into values; ``str`` keys are also run through:func:`sanitize_error_message` (a credential used *as* a key would- otherwise ship verbatim as a JSON key). Two distinct keys that both- redact to the same token collapse to one entry — an acceptable- fidelity loss for the pathological case of credential-shaped keys.+ otherwise ship verbatim as a JSON key). A key whose redacted form is+ already taken (two URLs with different passwords, or a redacted key+ equal to a later literal key) gets a ``#2``/``#3`` suffix instead of+ overwriting that entry; the first key in iteration order keeps the+ unsuffixed name.* ``list`` / ``tuple`` — both rebuilt as a plain ``list``: the payload isabout to be JSON-serialized (a tuple already becomes a JSON array), andrebuilding via ``type(value)(<generator>)`` would raise on a namedtuple /@@ -637,12 +1318,11 @@ def sanitize_error_details(value: Any) -> Any:reference."""if isinstance(value, dict):- return {- (sanitize_error_message(k) if isinstance(k, str) else k): (- sanitize_error_details(v)- )- for k, v in value.items()- }+ out: dict = {}+ for k, v in value.items():+ safe_key = sanitize_error_message(k) if isinstance(k, str) else k+ out[_unique_log_key(out, safe_key)] = sanitize_error_details(v)+ return outif isinstance(value, (list, tuple)):return [sanitize_error_details(v) for v in value]# dataclass *instance* (not the class itself) — Flask serializes it via@@ -673,11 +1353,11 @@ def sanitize_error_details(value: Any) -> Any:# 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.+# exact names. Message text also recognises environment-variable and dotted+# setting prefixes for these names (``OPENAI_API_KEY``, ``db_password``,+# ``llm.openai.api_key``); structured ``extra`` keys use the same suffix rule+# (see ``_is_sensitive_log_key``). The later quoted-key pass also handles+# JSON and Python-repr credential keys (see ``_QUOTED_KEY_PREFIX``).LOG_SENSITIVE_KEYS: frozenset = frozenset(DataSanitizer.DEFAULT_SENSITIVE_KEYS) | frozenset(@@ -714,18 +1394,426 @@ _LOG_SENSITIVE_NAME_PATTERN = "|".join(re.escape(name).replace("_", r"[_-]?")for name in sorted(LOG_SENSITIVE_KEYS, key=lambda name: (-len(name), name)))+# A following assignment can use the same prefixed or dotted credential+# names as the log patcher. The settings flag remains exempt: its value is+# not a credential and must not be used to shorten a preceding redaction.+_STOP_SENSITIVE_NAME_PATTERN = "".join(+ (+ r"(?!(?:[a-z0-9]+[._])*requires[_-]api[_-]key\s*=)",+ r"(?:[a-z0-9]+[._])*(?:",+ _LOG_SENSITIVE_NAME_PATTERN,+ r")",+ )+)_SENSITIVE_QUERY_RE = re.compile(r"(?i)([?&](?:" + _LOG_SENSITIVE_NAME_PATTERN + r")=)([^&\s#]+)")+# The name is a sensitive name, optionally preceded by any number of+# ``<alnum>_`` / ``<alnum>.`` segments: the same suffix rule ``extra`` keys+# get, applied to env-var (``OPENAI_API_KEY``), prefixed (``db_password``)+# and dotted setting (``llm.openai.api_key``) spellings. The whole name must+# start a word (not after ``\w``, ``.``, ``-``, or a query's ``?``/``&``),+# so ``mytoken=`` and ``x-token=`` stay readable, and it must END at the+# ``=``: ``max_tokens=`` is not ``_token``. After ``?``/``&``,+# ``_SENSITIVE_QUERY_RE`` redacts the exact names only: a prefixed name in+# a query string (``&google_api_key=x``) is not redacted, nor is any name+# after ``-`` (``--db_password=x``, ``--password=x``). The prefix+# segments cannot contain a separator, so each start position scans one+# identifier once -- linear, like the rest of the pass.+## 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.+# punctuation that may be part of a password -- except that ONE trailing+# ``,`` or ``;`` directly before whitespace or the end of the text is left+# as the list delimiter it almost always is (``max token = 4096, temp``).+# An unquoted value also ends where another credential assignment starts,+# but only where that assignment, redacted in its own right, covers+# everything the longer value would have covered and leaves nothing after+# it that a later pass would have redacted. Stripping control characters+# glues such an assignment onto the value before it+# (``token = [REDACTED]\nap<U+200B>i_key = x`` becomes+# ``token = [REDACTED]api_key = x``); without the stop, the value of+# ``token`` would run on and take the name ``api_key``, leaving ``x``+# visible. The next assignment qualifies in these shapes only:+#+# * ``name=`` with no whitespace in its match: an unquoted value, or a+# quoted value without whitespace that closes or runs to the end of the+# text. Its match ends at the same whitespace the longer value would+# have, which must be one ``strip_control_chars`` keeps (or the end of+# the text): at a stripped line break the patcher's second pass would+# glue the next line onto the visible name.+# * a quoted value that never closes: its match takes the rest of the text.+# * whitespace around the ``=`` or inside a quoted value+# (``token=x;password="p q" r``): its match then runs on past the+# whitespace that ended the longer value, over text the scan after it+# would otherwise read. So that text must hold nothing such a scan, or a+# later pass, could redact differently: no character+# ``strip_control_chars`` removes (a later pass would glue it to its+# neighbours), no ``name=`` inside a quoted value (the value would close on+# that name's opening quote, leaving the rest of its value visible), and+# in an unquoted value, or in the text glued after a closing quote up to+# the next whitespace, no ``name=`` and no ``Bearer``, ``Authorization:``+# or ``x-api-key:`` (anchors whose value lies past that whitespace), which+# must again be kept whitespace or the end of the text.+#+# Anything else is not a stop, and the longer value runs on as before.+_DOUBLE_QUOTED_VALUE = r"\"(?:\\.|[^\"\\])*"+_SINGLE_QUOTED_VALUE = r"'(?:\\.|[^'\\])*"+# A character ``strip_control_chars`` keeps, and kept whitespace.+_KEPT = r"(?!{})".format(_UNSAFE_CHAR_RE.pattern)+_KEPT_SPACE = _KEPT + r"\s"+_ENDS_AT_KEPT_SPACE = r"(?={}|\Z)".format(_KEPT_SPACE)+# How far past a candidate stop its lookahead reads to the end of a run of+# non-whitespace. Each candidate in one run reads to the same end, so the+# bound keeps a run dense with credential names linear; a value that runs+# on longer is not a stop.+_STOP_LOOKAHEAD_CHARS = 256+_GAP = r"(?:\s|{})*".format(_UNSAFE_CHAR_RE.pattern)+# An assignment as a pass reads it, before or after that strip: a credential+# name where an assignment can start, then ``=``, with any whitespace or+# character ``strip_control_chars`` removes between them.+_NAME_THEN_EQUALS = (+ r"(?<![\w.?&-])(?:" + _STOP_SENSITIVE_NAME_PATTERN + r")" + _GAP + r"="+)+# The same, or the anchor of a credential shape whose value may lie past+# whitespace (``Authorization: Basic ...``, ``Bearer ...``, ``x-api-key: ...``).+_NAME_OR_SHAPE_ANCHOR = (+ _NAME_THEN_EQUALS + r"|bearer|(?:authorization|x-api-key)" + _GAP + r"[:=]"+)+++# A run of non-whitespace up to kept whitespace or the end of the text,+# holding no assignment or credential-shape anchor.+_PLAIN_RUN = (+ r"(?:(?!"+ + _NAME_OR_SHAPE_ANCHOR+ + r")"+ + _KEPT+ + r"\S){0,"+ + str(_STOP_LOOKAHEAD_CHARS)+ + r"}"+ + _ENDS_AT_KEPT_SPACE+)+++def _spread_quoted_value(quote: str) -> str:+ """A quoted value whose match may reach past whitespace (see above)."""+ return (+ quote+ + r"(?:(?!"+ + _NAME_THEN_EQUALS+ + r")"+ + _KEPT+ + r"(?:\\"+ + _KEPT+ + r"\S|[^"+ + quote+ + r"\\]))*(?:"+ + quote+ + r"(?="+ + _PLAIN_RUN+ + r")|\\?\Z)"+ )+++def _space_before_closing(quote: str) -> str:+ """Lookahead: whitespace inside the quoted value that starts here."""+ return r"(?=" + quote + r"(?:\\\S|[^" + quote + r"\\\s])*\s)"+++# An unquoted value that may reach past whitespace (see above).+_SPREAD_UNQUOTED_VALUE = r"(?=[^\s\"'])" + _PLAIN_RUN+_NEXT_ASSIGNMENT = (+ r"(?<![\w.?&-])(?:" + _STOP_SENSITIVE_NAME_PATTERN + r")"+ # ``name=`` with no whitespace in its match.+ r"(?:=(?:\"(?:\\[^\s]|[^\"\\\s])*(?:\"|\\?\Z)"+ r"|'(?:\\[^\s]|[^'\\\s])*(?:'|\\?\Z)"+ r"|[^\s\"']\S{0,"+ + str(_STOP_LOOKAHEAD_CHARS)+ + r"})"+ + _ENDS_AT_KEPT_SPACE+ # A quoted value that never closes: its match takes the rest of the text.+ + r"|\s*=\s*(?:"+ + _DOUBLE_QUOTED_VALUE+ + r"|"+ + _SINGLE_QUOTED_VALUE+ + r")\\?$"+ # Whitespace around the ``=``.+ + r"|(?:(?:"+ + _KEPT_SPACE+ + r")+=(?:"+ + _KEPT_SPACE+ + r")*|=(?:"+ + _KEPT_SPACE+ + r")+)(?:"+ + _SPREAD_UNQUOTED_VALUE+ + r"|"+ + _spread_quoted_value('"')+ + r"|"+ + _spread_quoted_value("'")+ + r")"+ # Whitespace inside a quoted value.+ + r"|="+ + _space_before_closing('"')+ + _spread_quoted_value('"')+ + r"|="+ + _space_before_closing("'")+ + _spread_quoted_value("'")+ + r")"+)+_ASSIGNMENT_SEPARATOR_PATTERN = r"(\s*=\s*)"+_ASSIGNMENT_VALUE_PATTERN = (+ r"(?:\"(?:\\.|[^\"\\])*(?:\"|\\?$)|'(?:\\.|[^'\\])*(?:'|\\?$)"+ r"|\S+?(?=[,;]?(?:\s|$)))"+)+_STOP_ASSIGNMENT_VALUE_PATTERN = (+ r"(?:\"(?:\\.|[^\"\\])*(?:\"|\\?$)|'(?:\\.|[^'\\])*(?:'|\\?$)"+ r"|(?:(?!"+ + _NEXT_ASSIGNMENT+ + r")\S)+?(?=(?:"+ + _NEXT_ASSIGNMENT+ + r"|[,;]?(?:\s|$))))"+)+_ASSIGNMENT_REPLACEMENT = r"\1\2" + REDACTION_TEXT+_ASSIGNMENT_REPLACEMENT_PARTS = (1, 2, REDACTION_TEXT)++# The exact names (``password``, ``client_secret``, ``api-key``). Every+# pass of the log redaction runs this before the prefixed-name pattern+# below, which skips these names. Run after it, the prefixed pattern only+# replaces more of the text: a prefixed value that swallows the start of an+# exact-name assignment (``OPENAI_API_KEY=abc,password = x``) no longer+# hides it. Across the two passes of :func:`_redact_log_text`'s+# "restricted first pass" pipeline the same holds through+# :data:`_FIRST_PASS_SENSITIVE_ASSIGNMENT_RE`.+_BARE_SENSITIVE_ASSIGNMENT_RE = re.compile(+ r"(?i)(?<![\w.?&-])("+ + _LOG_SENSITIVE_NAME_PATTERN+ + r")"+ + _ASSIGNMENT_SEPARATOR_PATTERN+ + _ASSIGNMENT_VALUE_PATTERN+)+_STOP_BARE_SENSITIVE_ASSIGNMENT_RE = re.compile(+ r"(?i)(?<![\w.?&-])("+ + _LOG_SENSITIVE_NAME_PATTERN+ + r")"+ + _ASSIGNMENT_SEPARATOR_PATTERN+ + _STOP_ASSIGNMENT_VALUE_PATTERN+)++# Names the prefixed pattern must never match, checked by a lookahead+# BEFORE anything is consumed, so the regex scans on inside their values:+# - an exact name: the bare pass has already replaced its value, and+# matching it again would let the unquoted rule run that value on into a+# glued name (``client_secret='x'llm.api_key='y z'``) and hide it;+# - the one leaf settings redaction exempts (``requires_api_key``, a+# boolean flag; see ``data_sanitizer._has_non_secret_qualifier``),+# following a ``.`` or starting the name, as that leaf is computed there.+# A match that consumed the flag's value and handed it back unchanged+# would make ``re.sub`` resume after that value, so an assignment inside+# it (``requires_api_key=true,password=x``, or an unterminated quote+# running to the end of the text) would never be scanned.+_EXEMPT_ASSIGNMENT_NAME_PATTERN = "".join(+ (+ r"(?:(?:(?:[a-z0-9]+[._])*[a-z0-9]+\.)?",+ re.escape(_EXEMPT_QUALIFIER_LEAF).replace("_", "[_-]"),+ r")",+ )+)+_NOT_PREFIXED_ASSIGNMENT_NAME_PATTERN = (+ r"(?!(?:"+ + _EXEMPT_ASSIGNMENT_NAME_PATTERN+ + r"|(?:"+ + _LOG_SENSITIVE_NAME_PATTERN+ + r"))\s*=)"+)+_PREFIXED_ASSIGNMENT_NAME_PATTERN = (+ # ``(?=[a-z0-9])`` first: rejects a non-name position before the+ # lookahead's long alternation runs (a run of spaces stays cheap).+ r"(?i)(?<![\w.?&-])(?=[a-z0-9])"+ + _NOT_PREFIXED_ASSIGNMENT_NAME_PATTERN+ + r"((?:[a-z0-9]+[._])*(?:"+ + _LOG_SENSITIVE_NAME_PATTERN+ + r"))"+ + _ASSIGNMENT_SEPARATOR_PATTERN+)_SENSITIVE_ASSIGNMENT_RE = re.compile(- r"(?i)(?<![\w.?&-])(" + _LOG_SENSITIVE_NAME_PATTERN + r")"- r"(\s*=\s*)"- r"(?:\"(?:\\.|[^\"\\])*(?:\"|\\?$)|'(?:\\.|[^'\\])*(?:'|\\?$)|[^\s]+)"+ _PREFIXED_ASSIGNMENT_NAME_PATTERN + _ASSIGNMENT_VALUE_PATTERN+)+_STOP_SENSITIVE_ASSIGNMENT_RE = re.compile(+ _PREFIXED_ASSIGNMENT_NAME_PATTERN + _STOP_ASSIGNMENT_VALUE_PATTERN+)++# Exact and prefixed names in ONE pattern, so whichever assignment starts+# first wins. Two readings of it run, each as a pipeline of+# :func:`_redact_log_text`:+# - "next-line names" (:data:`_LEFTMOST_SENSITIVE_ASSIGNMENT_RE`, first+# pass only, on the original separators; also a pipeline of+# :func:`redact_log_message`): the exempt flag is skipped by+# the lookahead, and a name at the start of the next line followed by+# ``=`` is never taken as a value: ``DB_PASSWORD=\nOPENAI_API_KEY = x``+# is an empty ``DB_PASSWORD`` and an ``OPENAI_API_KEY`` whose value is+# ``x``. Read otherwise, the name is the value and `` = x`` is left+# unredacted. "The next line" is any run of whitespace and+# :func:`strip_control_chars` characters between the ``=`` and the name+# that holds at least one of the latter (``\n``, ``\r\n``, ``\x1c``,+# U+2028, ...): the indentation of a pretty-printed dump+# (``DB_PASSWORD =\n OPENAI_API_KEY = x``) and an invisible character+# before the name (``\n<U+200B>OPENAI_API_KEY``) included. A name after+# only spaces on the same line (``password= api_key = x``) is still read+# as the value.+# - "flag kept whole" (:data:`_START_ORDER_SENSITIVE_ASSIGNMENT_RE`, both+# passes): the exempt flag's assignment is matched like any other and+# kept as it is, value included, so nothing in its value starts an+# assignment (``requires_api_key=a,db_password\n=x;token=y``: the value+# ``a,db_password`` is the flag's, and ``token=y`` is still found).+_ANY_SENSITIVE_NAME_PATTERN = (+ r"(?=[a-z0-9])(?!"+ + _EXEMPT_ASSIGNMENT_NAME_PATTERN+ + r"\s*=)(?:[a-z0-9]+[._])*(?:"+ + _LOG_SENSITIVE_NAME_PATTERN+ + r")"+)+# Whitespace that :func:`strip_control_chars` keeps: a space, U+00A0,+# U+3000, ... -- not a tab or a line break, which it removes.+_KEPT_WHITESPACE_PATTERN = "".join(+ (r"(?:(?!", _UNSAFE_CHAR_RE.pattern, r")\s)")+)+# The next-line guard of :data:`_LEFTMOST_SENSITIVE_ASSIGNMENT_RE`, checked+# right after the ``=``: kept whitespace, one stripped character, then any+# mix of whitespace and stripped characters (ONE character class --+# ``_UNSAFE_CHAR_RE`` is a single class, whose inside is reused -- so a+# long run is scanned once, not re-split), then a name and ``=``. The parts+# before the name are disjoint or a single class, so the check is linear in+# the run it scans.+_NEXT_LINE_NAME_GUARD_PATTERN = (+ r"(?!"+ + _KEPT_WHITESPACE_PATTERN+ + r"*"+ + _UNSAFE_CHAR_RE.pattern+ + r"[\s"+ + _UNSAFE_CHAR_RE.pattern[1:-1]+ + r"]*"+ + _ANY_SENSITIVE_NAME_PATTERN+ + r"\s*=)")+_LEFTMOST_SENSITIVE_ASSIGNMENT_RE = re.compile(+ r"(?i)(?<![\w.?&-])("+ + _ANY_SENSITIVE_NAME_PATTERN+ + r")(\s*="+ + _NEXT_LINE_NAME_GUARD_PATTERN+ + r"\s*)"+ + _ASSIGNMENT_VALUE_PATTERN+)+_START_ORDER_SENSITIVE_ASSIGNMENT_RE = re.compile(+ r"(?i)(?<![\w.?&-])((?:[a-z0-9]+[._])*(?:"+ + _LOG_SENSITIVE_NAME_PATTERN+ + r"))"+ + _ASSIGNMENT_SEPARATOR_PATTERN+ + _ASSIGNMENT_VALUE_PATTERN+)+# Run the guarded stop as one additional reading, leaving the established+# pipelines intact. Their union keeps every value the old readings masked+# while the stop reading can preserve and redact a glued next name.+_STOP_START_ORDER_SENSITIVE_ASSIGNMENT_RE = re.compile(+ r"(?i)(?<![\w.?&-])((?:[a-z0-9]+[._])*(?:"+ + _LOG_SENSITIVE_NAME_PATTERN+ + r"))"+ + _ASSIGNMENT_SEPARATOR_PATTERN+ + _STOP_ASSIGNMENT_VALUE_PATTERN+)+_EXEMPT_ASSIGNMENT_NAME_RE = re.compile(+ r"(?i)" + _EXEMPT_ASSIGNMENT_NAME_PATTERN + r"\Z"+)+++def _start_order_replacement_parts(match: "re.Match[str]") -> tuple:+ """Replacement for :data:`_START_ORDER_SENSITIVE_ASSIGNMENT_RE`, as parts.++ The exempt flag's whole assignment is kept (group 0); any other keeps+ its name and separator and redacts the value.+ """+ if _EXEMPT_ASSIGNMENT_NAME_RE.match(match.group(1)):+ return (0,)+ return _ASSIGNMENT_REPLACEMENT_PARTS+++def _redact_start_order_match(match: "re.Match[str]") -> str:+ """Replacement for :data:`_START_ORDER_SENSITIVE_ASSIGNMENT_RE`."""+ return _join_replacement_parts(match, _start_order_replacement_parts)+++# The prefixed pattern for the first pass of the "restricted" pipeline of+# :func:`_redact_log_text`. It must not change how that pipeline's second+# pass parses the text around the value it replaces, or that pass -- whose+# bare-name half is exactly what the bare names alone would redact -- could+# match less. So it only takes a value the second pass could never read+# differently:+# - no ``=`` and not followed by ``\s*=``, so no name inside it (one that+# only becomes recognisable once invisible characters are stripped,+# ``pass<U+200B>word = x``) is lost;+# - followed by whitespace that survives :func:`strip_control_chars` (or by+# the end of the text), so the stripped text never glues the replacement+# onto the next token and makes a name there newly recognisable, whose+# value could then swallow the next one;+# - unquoted with no quote character in it, or quoted with no quote+# character or backslash inside the quotes -- and a quoted value keeps+# its quotes (``"[REDACTED]"``) -- so a quote the second pass opens+# earlier still closes where it would have. The second pass then+# redacts the kept quotes along with the value.+# Any other value is left for the second pass, which can MISS it: on the+# stripped text a name the newline separated is glued to the line before+# (``-\nDB_PASSWORD=x`` reads ``-DB_PASSWORD=x``, a name after ``-``), or+# the value before it runs on into it. That is why this pipeline never+# runs alone: the others read the first kind on the original separators,+# where the newline still separates the name. The second kind is missed by+# every reading -- each reads the quoted value's start as part of the value+# before it, and none redacts the rest -- when this pattern cannot take it+# either: a prefixed name's quoted value followed by a line break, a tab+# or another stripped character (``OPENAI_API_KEY=abc,DB_PASSWORD="a b c"``+# and ``\n`` leaves `` b c"``), by any other non-whitespace character+# (``")``) or by whitespace and ``=`` (``" = x``); one whose run-on value+# belongs to an exact name, which this pipeline's bare-name step has+# already redacted to the end of the quote's first word+# (``token=abc,DB_PASSWORD="a b c"``); or a quoted assignment glued on+# with ``&``, ``?`` or ``-`` (``OPENAI_API_KEY=abc&DB_PASSWORD="a b c"``,+# also with an exact name), which no reading takes as a quoted value.+_FIRST_PASS_SENSITIVE_ASSIGNMENT_RE = re.compile(+ _PREFIXED_ASSIGNMENT_NAME_PATTERN+ + r"(?:([\"'])[^\"'\\=]*(\3|\Z)|[^\s=\"']+?)"+ + r"(?=[,;]?(?:"+ + _KEPT_WHITESPACE_PATTERN+ + r"|\Z))(?!\s*=)"+)+++def _first_pass_replacement_parts(match: "re.Match[str]") -> tuple:+ """Replacement for :data:`_FIRST_PASS_SENSITIVE_ASSIGNMENT_RE`, as parts.++ The name, the separator and any quotes are kept (group numbers); only+ the value becomes :data:`REDACTION_TEXT` (a literal). See+ :func:`_substitute_tracked` for the part format.+ """+ parts: list = [1, 2]+ if match.group(3):+ parts.append(3)+ parts.append(REDACTION_TEXT)+ if match.group(4):+ parts.append(4)+ return tuple(parts)+++def _join_replacement_parts(match: "re.Match[str]", parts_for) -> str:+ """The replacement text *parts_for* gives for *match*."""+ return "".join(+ part if isinstance(part, str) else match.group(part)+ for part in parts_for(match)+ )+++def _redact_first_pass_match(match: "re.Match[str]") -> str:+ """Replacement for :data:`_FIRST_PASS_SENSITIVE_ASSIGNMENT_RE`."""+ return _join_replacement_parts(match, _first_pass_replacement_parts)def redact_sensitive_assignments(message: str) -> str:@@ -734,12 +1822,21 @@ def redact_sensitive_assignments(message: str) -> str: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.+ ``OPENAI_API_KEY=``, ``llm.openai.api_key=``, ...) is preserved; only+ its value is replaced. Returns *message*+ unchanged when it is empty or contains no sensitive assignment."""+ message = _plain_text(message)+ return _scrub_to_fixed_point(_redact_sensitive_assignments_once, message)+++def _redact_sensitive_assignments_once(message: str) -> str:if not message:return message- return _SENSITIVE_ASSIGNMENT_RE.sub(r"\1\2" + REDACTION_TEXT, message)+ bare = _STOP_BARE_SENSITIVE_ASSIGNMENT_RE.sub(+ _ASSIGNMENT_REPLACEMENT, message+ )+ return _STOP_SENSITIVE_ASSIGNMENT_RE.sub(_ASSIGNMENT_REPLACEMENT, bare)# Upper bound on how much of ONE string the log-path redaction scans. The@@ -750,10 +1847,18 @@ def redact_sensitive_assignments(message: str) -> str:# 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).+# to 10,000 characters) intact. On adversarial 32 KiB input the passes of+# :func:`_redact_log_text` measured up to ~280 ms together on an idle+# machine and about twice that on a loaded one, and those of+# :func:`redact_log_message` up to ~240 ms idle (``pwd="a"b=c `` repeated):+# a text whose pipelines disagree on every line (that one,+# ``db_password = a, `` repeated, or ``DB_PASSWORD=x`` lines) runs all of+# them with origins tracked, several times the cost of one pipeline. A+# text with no credential name followed by ``=`` skips the name steps (see+# :func:`_result_without_name_assignments`): about 10-50 ms at 32 KiB.+# The cost is linear in the length scanned (8x the time for 8x the text,+# measured from 4 KiB to 32 KiB), so it is 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``,@@ -831,28 +1936,322 @@ def log_length_before_truncation(message: str) -> int: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+ Runs the credential-*shape* patterns :func:`sanitize_error_message`+ runs (its ``_CREDENTIAL_PATTERNS``: URL userinfo, ``?param=``+ credentials, ``Bearer``/``x-api-key`` headers, well-known key prefixes,+ JWTs) -- the shape redaction the sanctioned :func:`scrub_error` applies,+ run as a backstop on every record -- then ``?name=``/``&name=`` query+ parameters for every :data:`LOG_SENSITIVE_KEYS` name, then+ ``name=value`` assignments of those names, exact or prefixed (the+ names :func:`redact_sensitive_assignments` recognises), in each reading+ of :data:`_LOG_MESSAGE_PIPELINES`; what any reading redacts is+ redacted. Control characters are kept (exception text is rendered+ with its newlines). Non-sensitive text up to``_LOG_REDACTION_MAX_CHARS`` characters is returned unchanged; a longerstring is cut there (see :func:`_truncate_for_log_redaction`) and theremainder replaced by an omitted-length marker, so the cost per stringis bounded."""+ message = _plain_text(message)if not message:- return message+ return _exact_str(message)head, marker = _truncate_for_log_redaction(message)- return _redact_bounded_log_text(head) + marker+ return _scrub_to_fixed_point(_redact_bounded_log_text, head) + marker+++# One substitution of a redaction pass: a pattern and its replacement,+# given as the string or callable ``re.sub`` takes and as PARTS -- a list+# (or a callable giving one per match) of group numbers, which keep that+# group's text, and literal strings, which are inserted. The parts let+# :func:`_substitute_tracked` follow every kept character back to the+# position it came from.+_TEMPLATE_GROUP_RE = re.compile(r"\\([0-9])")+++def _template_parts(template: str) -> tuple:+ """Parts of a ``re.sub`` template that uses only ``\\1``-style groups."""+ if "\\" in _TEMPLATE_GROUP_RE.sub("", template):+ raise ValueError(f"unsupported replacement template: {template!r}")+ parts: list = []+ for index, piece in enumerate(_TEMPLATE_GROUP_RE.split(template)):+ if index % 2:+ parts.append(int(piece))+ elif piece:+ parts.append(piece)+ return tuple(parts)+++def _step(pattern: "re.Pattern[str]", replacement: Any, parts: Any = None):+ if parts is None:+ parts = _template_parts(replacement)+ return pattern, replacement, parts+++# The credential-shape and query-parameter steps every pass starts with.+_SHAPE_STEPS = tuple(+ _step(pattern, replacement) for pattern, replacement in _CREDENTIAL_PATTERNS+) + (_step(_SENSITIVE_QUERY_RE, r"\1" + REDACTION_TEXT),)+_BARE_STEP = _step(_BARE_SENSITIVE_ASSIGNMENT_RE, _ASSIGNMENT_REPLACEMENT)+_PREFIXED_STEP = _step(_SENSITIVE_ASSIGNMENT_RE, _ASSIGNMENT_REPLACEMENT)+# The name steps of :func:`redact_log_message`'s pass before the glued+# tails were closed (below). The bare names run before the prefixed ones+# (see :data:`_BARE_SENSITIVE_ASSIGNMENT_RE`); the prefixed ones run twice,+# because a quoted value glued to the next text (``OPENAI_API_KEY="x"tail``)+# leaves ``[REDACTED]tail``, which a second scan reads as one unquoted value.+# An exact name's tail (``password="x"tail``) was left.+_NAME_STEPS_BEFORE_CLOSING = (_BARE_STEP, _PREFIXED_STEP, _PREFIXED_STEP)+# A quoted value glued to the next text leaves that text behind when it is+# redacted: ``password="x"tail`` becomes ``password=[REDACTED]tail``. This+# step reads such an assignment again, as a scan for names would (the same+# names, word start and separator; not the exempt flag), but only where the+# value starts with ``[REDACTED]``, and redacts the tail up to the+# whitespace (or ``,``/``;`` before it) where an unquoted value ends --+# unless the tail holds an ``=`` or is followed by one, i.e. is itself the+# name of an assignment (``passwd=""apikey =""tail``: ``apikey`` stays,+# its own ``tail`` goes). So, unlike another scan for names, it never reads+# a value on into the name of an assignment whose own tail it has not yet+# redacted.+_GLUED_TAIL_RE = re.compile(+ r"(?i)(?<![\w.?&-])("+ + _ANY_SENSITIVE_NAME_PATTERN+ + r")"+ + _ASSIGNMENT_SEPARATOR_PATTERN+ + re.escape(REDACTION_TEXT)+ + r"(?![,;]?(?:\s|$))[^\s=]+?(?=[,;]?(?:\s|$))(?!\s*=)"+)+_GLUED_TAIL_STEP = _step(_GLUED_TAIL_RE, _ASSIGNMENT_REPLACEMENT)+# The "exact names first" name steps: the bare names, the prefixed ones,+# the glued tails, then both name scans once more, the bare names last+# (see :data:`_BARE_SENSITIVE_ASSIGNMENT_RE`). The last two scans redact a+# tail the tail step leaves (one holding an ``=``: ``password="x"a=b``) as+# part of an unquoted value. Running these steps again on their result+# changes nothing (seeded fuzz: 0 of 50,000 messages).+_FULL_PASS_NAME_STEPS = (+ _BARE_STEP,+ _PREFIXED_STEP,+ _GLUED_TAIL_STEP,+ _PREFIXED_STEP,+ _BARE_STEP,+)+_FULL_PASS_STEPS = _SHAPE_STEPS + _FULL_PASS_NAME_STEPS+_RESTRICTED_FIRST_PASS_STEPS = (+ _BARE_STEP,+ _step(+ _FIRST_PASS_SENSITIVE_ASSIGNMENT_RE,+ _redact_first_pass_match,+ _first_pass_replacement_parts,+ ),+)+_LEFTMOST_STEP = _step(+ _LEFTMOST_SENSITIVE_ASSIGNMENT_RE, _ASSIGNMENT_REPLACEMENT+)+# The "next-line names" steps, closed the same way, so+# ``DB_PASSWORD=\nOPENAI_API_KEY = "x"tail`` does not leave ``tail`` -- which+# the second pass, reading ``OPENAI_API_KEY`` as ``DB_PASSWORD``'s value on+# the stripped text, would not redact either.+_LEFTMOST_STEPS = (_LEFTMOST_STEP, _GLUED_TAIL_STEP, _LEFTMOST_STEP)+_START_ORDER_STEPS = (+ _step(+ _START_ORDER_SENSITIVE_ASSIGNMENT_RE,+ _redact_start_order_match,+ _start_order_replacement_parts,+ ),+)+_STOP_START_ORDER_STEPS = (+ _step(+ _STOP_START_ORDER_SENSITIVE_ASSIGNMENT_RE,+ _redact_start_order_match,+ _start_order_replacement_parts,+ ),+)+# The pipelines of :func:`_redact_log_text`: the name steps each runs after+# :data:`_SHAPE_STEPS`, in its first pass (on the original text) and+# in its second (on the text with control characters stripped). The first+# pipeline's text is the one kept; the others only add redactions to it.+_LOG_TEXT_PIPELINES = (+ # "exact names first": :func:`redact_log_message`'s name steps, on the+ # original separators and again on the stripped text. Its result is+ # the one kept.+ (_FULL_PASS_NAME_STEPS, _FULL_PASS_NAME_STEPS),+ # "restricted first pass": a first pass that never changes how the+ # second reads the text around a value it replaces (see+ # :data:`_FIRST_PASS_SENSITIVE_ASSIGNMENT_RE`).+ (_RESTRICTED_FIRST_PASS_STEPS, _FULL_PASS_NAME_STEPS),+ # "next-line names": names in start order, in the first pass (see+ # :data:`_LEFTMOST_SENSITIVE_ASSIGNMENT_RE`).+ (_LEFTMOST_STEPS, _FULL_PASS_NAME_STEPS),+ # "flag kept whole": names in start order, in both passes (see+ # :data:`_START_ORDER_SENSITIVE_ASSIGNMENT_RE`).+ (_START_ORDER_STEPS, _START_ORDER_STEPS),+ # "exact names only": the redaction as it was before the prefix rule+ # (with the trailing ``,``/``;`` rule of the value pattern), so this+ # one never removes less than the exact names alone would.+ ((_BARE_STEP,), (_BARE_STEP,)),+ # "exact names first" and "next-line names" with their first pass as+ # it was before the glued tails were closed. Closing them changes the+ # text the later steps of that pass read, and removes text before the+ # strip, which can join what follows onto a different neighbour and+ # change how the second pass reads it; with these readings kept,+ # closing never shows anything that leaving it open would hide.+ (_NAME_STEPS_BEFORE_CLOSING, _FULL_PASS_NAME_STEPS),+ ((_LEFTMOST_STEP,), _FULL_PASS_NAME_STEPS),+ # Preserve names that an earlier value would otherwise swallow.+ (_STOP_START_ORDER_STEPS, _STOP_START_ORDER_STEPS),+)+# The pipelines of :func:`redact_log_message`, which also renders exception+# text (``str()``, notes, ``SyntaxError`` fields) and so keeps every+# control character: the first passes of :data:`_LOG_TEXT_PIPELINES`, in+# that order, on the text as it is -- one pass each, no second pass+# (``None``) -- except that the "restricted first pass" reading, which+# leaves values for its second pass, runs the "exact names first" steps+# after it on the same text, and the unclosed "next-line names" reading is+# left out: its closed steps start with it and only run more steps after+# it on the same text, so they only redact more. So an empty+# ``DB_PASSWORD=`` at the end of a line does not take the name starting the+# next line as its value, and ``OPENAI_API_KEY=abc,DB_PASSWORD="a b c"``+# followed by the end of the text or by a space (with no ``=`` after it)+# does not leave `` b c"`` readable, in an exception's text as in a log+# message (followed by a line break, or by `` = x``, it does in both; see+# :data:`_FIRST_PASS_SENSITIVE_ASSIGNMENT_RE`).+_LOG_MESSAGE_PIPELINES = (+ (_FULL_PASS_NAME_STEPS, None),+ (_NAME_STEPS_BEFORE_CLOSING, None),+ (_RESTRICTED_FIRST_PASS_STEPS + _FULL_PASS_NAME_STEPS, None),+ (_LEFTMOST_STEPS, None),+ (_START_ORDER_STEPS, None),+ ((_BARE_STEP,), None),+ (_STOP_START_ORDER_STEPS, None),+)+++class _BarePass(NamedTuple):+ """A name-based log pass and its unanchored variant for glued text."""++ pattern: "re.Pattern[str]"+ replacement: str+ name_group: int+ value_after_group: int+ unanchored: "re.Pattern[str]"+++def _without_name_boundary(pattern: "re.Pattern[str]") -> "re.Pattern[str]":+ return re.compile(pattern.pattern.replace(r"(?<![\w.?&-])", "", 1))+++def _log_patcher_bare_passes() -> tuple[_BarePass, ...]:+ """Find the query and name patterns in every live log pipeline.++ The control-splice guard must follow new name passes automatically;+ otherwise a splice could consume a name and expose its value to a sink.+ All current name passes capture the name and separator as groups 1/2.+ The replacement here is used only to detect whether a prospective match+ would hide anything, so a conservative value marker is sufficient for+ passes with conditional replacement callbacks.+ """+ passes = [+ _BarePass(+ _SENSITIVE_QUERY_RE,+ r"\1" + REDACTION_TEXT,+ 1,+ 1,+ _SENSITIVE_QUERY_RE,+ )+ ]+ seen = {_SENSITIVE_QUERY_RE}+ for pipelines in (_LOG_TEXT_PIPELINES, _LOG_MESSAGE_PIPELINES):+ for first, second in pipelines:+ for steps in (first, second or ()):+ for pattern, _replacement, _parts in steps:+ if pattern in seen:+ continue+ seen.add(pattern)+ passes.append(+ _BarePass(+ pattern,+ _ASSIGNMENT_REPLACEMENT,+ 1,+ 2,+ _without_name_boundary(pattern),+ )+ )+ return tuple(passes)+++_LOG_PATCHER_BARE_PASSES = _log_patcher_bare_passes()+_LOG_PATCHER_BARE_GROUPS = {+ bare.pattern: (bare.name_group, bare.value_after_group)+ for bare in _LOG_PATCHER_BARE_PASSES+}+++def _run_steps(text: str, steps) -> str:+ for pattern, replacement, _parts in steps:+ text = pattern.sub(replacement, text)+ return text+++def _substitute_tracked(+ pattern: "re.Pattern[str]", parts: Any, text: str, origins: list+) -> tuple[str, list]:+ """``pattern.sub`` on *text*, carrying each character's origin along.++ *origins* gives, for every character of *text*, the position in the+ original string it came from, or ``-1`` for an inserted one. The result+ is the same text ``re.sub`` gives with the matching replacement, and its+ origins: a kept group keeps its characters' origins, a literal part is+ inserted (``-1``).+ """+ pieces: list = []+ # Accumulate directly to avoid retaining one list per match fragment,+ # which can trigger repeated garbage collections on dense credentials.+ merged: list = []+ position = 0+ for match in pattern.finditer(text):+ start = match.start()+ pieces.append(text[position:start])+ merged.extend(origins[position:start])+ for part in parts(match) if callable(parts) else parts:+ if isinstance(part, str):+ pieces.append(part)+ merged.extend([-1] * len(part))+ continue+ group_start, group_end = match.span(part)+ if group_start < 0:+ continue+ pieces.append(text[group_start:group_end])+ merged.extend(origins[group_start:group_end])+ position = match.end()+ if not pieces:+ return text, origins+ pieces.append(text[position:])+ merged.extend(origins[position:])+ return "".join(pieces), merged+++def _strip_control_chars_tracked(text: str, origins: list) -> tuple[str, list]:+ """:func:`strip_control_chars`, carrying origins as+ :func:`_substitute_tracked` does."""+ kept: list = []+ kept_origins: list = []+ position = 0+ for match in _UNSAFE_CHAR_RE.finditer(text):+ kept.append(text[position : match.start()])+ kept_origins.extend(origins[position : match.start()])+ position = match.end()+ if not kept:+ return text, origins+ kept.append(text[position:])+ kept_origins.extend(origins[position:])+ return "".join(kept), kept_originsdef _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)+ """:func:`redact_log_message`'s pass, on text already within the bound.++ Runs the pipelines of :data:`_LOG_MESSAGE_PIPELINES` and shows nothing+ that any of them leaves out (see :func:`_redact_by_pipelines`).+ """+ return _redact_by_pipelines(text, _LOG_MESSAGE_PIPELINES)def _redact_log_text(value: str) -> str:@@ -864,117 +2263,1052 @@ def _redact_log_text(value: str) -> str:(``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 neverre-truncates the first pass's output.++ Several pipelines run these passes, differing only in how they redact+ names (see :data:`_LOG_TEXT_PIPELINES`), because no single order is+ safe on its own: a replacement made in the first pass changes how the+ second pass, on the stripped text, splits the text around it, and a+ value left for the second pass can be missed there+ (``-\nDB_PASSWORD=x`` is stripped to ``-DB_PASSWORD=x``, a name after+ ``-``). The result shows nothing that any pipeline's result leaves+ out (see :func:`_redact_by_pipelines`)."""+ value = _plain_text(value)if not value:- return value+ return _exact_str(value)head, marker = _truncate_for_log_redaction(value)- first = _redact_bounded_log_text(head)- return _redact_bounded_log_text(strip_control_chars(first)) + marker+ return (+ _scrub_to_fixed_point(+ lambda text: _redact_by_pipelines(text, _LOG_TEXT_PIPELINES), head+ )+ + marker+ )-def redact_for_log(value: str) -> str:- """Run the log patcher's credential redaction on *value* alone.+# A credential name directly followed by ``\s*=``. Every name step's+# pattern (:data:`_BARE_SENSITIVE_ASSIGNMENT_RE`,+# :data:`_SENSITIVE_ASSIGNMENT_RE`, :data:`_GLUED_TAIL_RE`,+# :data:`_LEFTMOST_SENSITIVE_ASSIGNMENT_RE`,+# :data:`_START_ORDER_SENSITIVE_ASSIGNMENT_RE`,+# :data:`_FIRST_PASS_SENSITIVE_ASSIGNMENT_RE`) ends its name with an+# alternative of :data:`_LOG_SENSITIVE_NAME_PATTERN` followed by+# ``\s*=``, under the same ``(?i)``, so a text this does not match is+# left unchanged by every name step.+_NAME_ASSIGNMENT_HINT_RE = re.compile(+ "".join((r"(?i)(?:", _LOG_SENSITIVE_NAME_PATTERN, r")\s*="))+)- The same two passes and the same ``_LOG_REDACTION_MAX_CHARS`` bound the- loguru patcher applies to every record (:func:`_redact_log_text`), for a- caller that is about to shorten *value* before it reaches a log line.- Shortening first can hide a credential from the patcher: a cut that drops- ``?key=`` or the ``@`` after URL userinfo, but keeps part of the secret,- leaves text no credential pattern matches. Redacting first means any cut- afterwards only removes text the patcher already judged safe or already- replaced. Cost is bounded the same way as the patcher's.- """- return _redact_log_text(value)+def _has_name_assignment_hint(text: str) -> bool:+ # No ``=`` at all is the common case, and a substring test is far+ # cheaper than the case-insensitive scan over every name.+ return "=" in text and _NAME_ASSIGNMENT_HINT_RE.search(text) is not None-# How much of one value :func:`redact_and_bound_for_log` scans: at least-# this many characters, or four times the output cap if that is more, and-# never more than the patcher's own ``_LOG_REDACTION_MAX_CHARS``. The-# result keeps at most ``max_length`` characters, so scanning the full-# 32 KiB made one call cost ~50-100 ms on adversarial input (a run of-# spaces, or of ``https://a:b@ ``) for a 256-character result; 1,024-# characters cost a few milliseconds.-_LOG_BOUNDED_REDACTION_MIN_CHARS = 1_024+def _result_without_name_assignments(+ shaped: str, pipelines: tuple+) -> Optional[str]:+ """What every pipeline gives when no name step can match, else ``None``.-def bounded_redaction_chars(max_length: int) -> int:- """How many characters of a value to redact for a *max_length* result."""- return min(- _LOG_REDACTION_MAX_CHARS,- max(_LOG_BOUNDED_REDACTION_MIN_CHARS, 4 * max_length),+ *shaped* is the text after :data:`_SHAPE_STEPS`, where every first+ pass starts. When neither it nor (for pipelines with a second pass)+ the second pass's text after its shape steps holds a credential name+ followed by ``=`` (:data:`_NAME_ASSIGNMENT_HINT_RE`), every name step+ is a no-op and every pipeline gives the same text, which is returned+ -- the text :func:`_redact_by_pipelines` would return, without running+ the name steps of each pipeline (most log records). ``None`` means the+ pipelines must run.+ """+ if _has_name_assignment_hint(shaped):+ return None+ second_passes = {second is None for _first, second in pipelines}+ if second_passes == {True}:+ return shaped+ if second_passes != {False}:+ return None+ second_text = _run_steps(strip_control_chars(shaped), _SHAPE_STEPS)+ if _has_name_assignment_hint(second_text):+ return None+ return second_text+++def _redact_by_pipelines(head: str, pipelines: tuple) -> str:+ """*head* as every pipeline of *pipelines* redacts it, together.++ Runs them untracked first. When the text holds no credential name+ followed by ``=`` (before or after control characters are stripped),+ no name step can match and the shape-redacted text is returned+ directly (see :func:`_result_without_name_assignments`). In the usual+ remaining case they all give the same text, which is returned;+ otherwise :func:`_redact_log_text_union` reruns them with origins+ tracked.+ """+ run = _PipelineRun(head, tracked=False, pipelines=pipelines)+ without_names = _result_without_name_assignments(run.shaped, pipelines)+ if without_names is not None:+ return without_names+ indexes = range(len(pipelines))+ if len({run.first_pass(index) for index in indexes}) == 1:+ # The first passes agree, so the pipelines differ at most in the+ # name steps of the second.+ results = {run.result(index)[0] for index in indexes}+ if len(results) == 1:+ return results.pop()+ return _redact_log_text_union(head, run.unmatched, pipelines)+++class _PipelineRun:+ """The pipelines of *pipelines* (by default :data:`_LOG_TEXT_PIPELINES`)+ on one text.++ Each pipeline is a pair: the name steps of its first pass and those of+ its second, or ``None`` for a pipeline with no second pass (no control+ characters stripped). Steps several pipelines share on the same text+ (the shape steps of the first pass, the bare names, a second pass+ reached from the same first pass) run once. *tracked* carries each+ character's origin along (see :func:`_substitute_tracked`); otherwise+ origins are ``None``. An untracked run records each step that matched+ nothing on a text (:attr:`unmatched`); a tracked run given that set+ skips those steps, which leave both the text and its origins unchanged.+ """++ def __init__(+ self,+ head: str,+ *,+ tracked: bool,+ unmatched: Optional[set] = None,+ pipelines: Optional[tuple] = None,+ credential_spans: Optional[list] = None,+ origins: Optional[list] = None,+ ) -> None:+ self._tracked = tracked+ self._pipelines = (+ _LOG_TEXT_PIPELINES if pipelines is None else pipelines+ )+ self._memo: dict = {}+ self.unmatched: set = set() if unmatched is None else unmatched+ self._credential_spans = credential_spans+ if tracked and origins is None:+ origins = list(range(len(head)))+ self._shared = self._run((head, origins), _SHAPE_STEPS)++ @property+ def shaped(self) -> str:+ """The text after :data:`_SHAPE_STEPS`, where every first pass+ starts."""+ return self._shared[0]++ def _cached(self, key: tuple, state: tuple, compute) -> tuple:+ # Keyed by text; reused only for equal origins, so two pipelines+ # that reach the same text from different characters stay apart.+ entries = self._memo.setdefault(key, [])+ for origins, result in entries:+ if origins is state[1] or origins == state[1]:+ return result+ result = compute()+ entries.append((state[1], result))+ return result++ def _substitute(self, step: tuple, state: tuple) -> tuple:+ pattern, replacement, parts = step+ if self._tracked:+ if (state[0], step) in self.unmatched:+ return state+ if self._credential_spans is not None:+ self._collect_credential_spans(step, state)+ return _substitute_tracked(pattern, parts, *state)+ text, count = pattern.subn(replacement, state[0])+ if not count:+ self.unmatched.add((state[0], step))+ return text, None++ def _collect_credential_spans(self, step: tuple, state: tuple) -> None:+ collected = self._credential_spans+ if collected is None:+ return+ pattern, replacement, _parts = step+ groups = _LOG_PATCHER_BARE_GROUPS.get(pattern)+ if groups is None:+ return+ name_group, value_after = groups+ text, origins = state+ spans = []+ for match in pattern.finditer(text):+ rendered = (+ replacement(match)+ if callable(replacement)+ else match.expand(replacement)+ )+ if rendered == match.group():+ continue+ name = [+ offset+ for offset in origins[+ match.start(name_group) : match.end(value_after)+ ]+ if offset >= 0+ ]+ value = [+ offset+ for offset in origins[match.end(value_after) : match.end()]+ if offset >= 0+ ]+ if name and value:+ spans.append((min(name), min(value), max(value) + 1))+ if spans:+ collected.append(spans)++ def _run(self, state: tuple, steps: tuple) -> tuple:+ for step in steps:+ # Reuse identical steps reached through different pipelines.+ # _cached also checks origins before reusing a tracked result.+ state = self._cached(+ (state[0], step),+ state,+ lambda: self._substitute(step, state),+ )+ return state++ def first_pass(self, index: int) -> tuple:+ return self._run(self._shared, self._pipelines[index][0])++ def result(self, index: int) -> tuple:+ state = self.first_pass(index)+ second = self._pipelines[index][1]+ if second is None:+ return state+ if self._tracked:+ stripped = self._cached(+ (state[0], "strip"),+ state,+ lambda: _strip_control_chars_tracked(*state),+ )+ else:+ stripped = (strip_control_chars(state[0]), None)+ return self._run(stripped, _SHAPE_STEPS + second)+++_LOG_TEXT_PIPELINE_INDEXES = range(len(_LOG_TEXT_PIPELINES))+++def _pipeline_credential_spans(text: str) -> list:+ """Map later name/value readings back to the original input."""+ spans: list = []+ run = _PipelineRun(text, tracked=True, credential_spans=spans)+ for index in _LOG_TEXT_PIPELINE_INDEXES:+ run.result(index)+ # A plain query replacement can expose a name that the original URL+ # made part of another value. Cover the later log-pipeline readings+ # after that replacement too, before extending across line breaks or+ # quoted values would remove the newly exposed name.+ pieces: list[str] = []+ origins: list[int] = []+ position = 0+ for match in _URL_QUERY_STRING_RE.finditer(text):+ pieces.append(text[position : match.start()])+ origins.extend(range(position, match.start()))+ replacement = _restore_query_wrapper(match)+ pieces.append(replacement)+ origins.extend(range(match.start(), match.start(2)))+ origins.extend([-1] * len(_URL_QUERY_MARKER))+ if len(replacement) > len(match.group(1)) + 1 + len(_URL_QUERY_MARKER):+ origins.append(match.end() - 1)+ position = match.end()+ if pieces:+ pieces.append(text[position:])+ origins.extend(range(position, len(text)))+ projected = "".join(pieces)+ if projected != text:+ run = _PipelineRun(+ projected,+ tracked=True,+ credential_spans=spans,+ origins=origins,+ )+ for index in _LOG_TEXT_PIPELINE_INDEXES:+ run.result(index)+ return spans+++def _redact_log_text_union(+ head: str, unmatched: set, pipelines: Optional[tuple] = None+) -> str:+ """Every pipeline of *pipelines* (by default :data:`_LOG_TEXT_PIPELINES`),+ with origins tracked.++ Each character of a pipeline's result is followed back to the position+ of *head* it came from (see :func:`_substitute_tracked`). A position+ that some pipeline's result no longer holds was redacted (or stripped)+ there; the first pipeline's result is returned with every run of such+ characters replaced by one ``[REDACTED]``. A pipeline whose result is+ the same text as the first's adds nothing and is skipped. *unmatched*+ is :attr:`_PipelineRun.unmatched` of an untracked run on *head*.+ """+ run = _PipelineRun(+ head, tracked=True, unmatched=unmatched, pipelines=pipelines+ )+ kept_text, kept_origins = run.result(0)+ removed = bytearray(len(head))+ for index in range(1, len(run._pipelines)):+ text, origins = run.result(index)+ if text == kept_text:+ # Prints exactly what the kept text prints.+ continue+ survived = bytearray(len(head))+ for origin in origins:+ if origin >= 0:+ survived[origin] = 1+ for origin in kept_origins:+ if origin >= 0 and not survived[origin]:+ removed[origin] = 1+ out: list = []+ in_run = False+ width = len(REDACTION_TEXT)+ for position, (character, origin) in enumerate(+ zip(kept_text, kept_origins)+ ):+ if origin >= 0 and removed[origin]:+ # A run next to a replacement the kept pipeline made already+ # reads ``[REDACTED]``; do not double it.+ if not in_run and not "".join(out[-width:]).endswith(+ REDACTION_TEXT+ ):+ out.append(REDACTION_TEXT)+ in_run = True+ continue+ if (+ in_run+ and out[-1] is REDACTION_TEXT+ and kept_text.startswith(REDACTION_TEXT, position)+ and max(kept_origins[position : position + width]) < 0+ ):+ out.pop()+ in_run = False+ out.append(character)+ return "".join(out)+++def _type_is_one_of(kind: Any, types: tuple) -> bool:+ """True when *kind* is one of *types* (by identity).++ ``kind in types`` compares with ``==``, which a metaclass ``__eq__`` of+ an application class can answer ``True`` for ``str`` or ``list``.+ """+ return any(kind is candidate for candidate in types)+++# Credential shapes the log-record path redacts on top of the passes above.+# They run ONLY as the last step of :func:`redact_log_record`'s message and+# ``extra`` string redaction (:func:`_redact_log_record_text`), its rendered+# exception fields (:func:`_redact_exception_text`), and the exception prefix+# of a database log row (``utilities.log_utils._exception_context``), whose+# output goes straight to the sinks: no pass of+# ``sanitize_error_message``, ``scrub_error``, the client helpers or+# :func:`redact_log_message` ever runs over what these patterns write. Those+# functions do not apply them, so their output is what it was before these+# patterns existed. These patterns only replace part of the text they are+# given with a ``[REDACTED]`` marker; whatever the earlier passes redacted+# stays redacted, so where they run they can hide more, never less.+#+# Their value boundaries are conservative, and what may follow a value is an+# allowlist. A value stops before a credential label (``_VALUE_STOP``; that+# label is then matched on its own) and before a URL scheme, and it is+# redacted only when what follows it ends a value in its syntax: one of the+# structural followers listed below for its kind, after optional whitespace+# that is not a line break, or a line break, or the end of the text+# (``_cuts_a_value``, ``_API_KEY_FOLLOWER_RE``, ``_DSN_HOST_RE``). Anything+# else -- a word after a space, another quote, a backslash, an opening+# bracket, or a symbol a secret may contain (``&``, ``!``, ``$``, ``/``,+# ``.``, ``@`` ...) -- means the value may go on past the match, so the+# text is left exactly as the earlier passes left it: replacing only part+# of a value would print the rest of it behind a marker that makes the+# line look redacted. A+# quoted value holding the other kind of quote, an unquoted value that+# starts with a string prefix before a quote (``_UNQUOTED_PREFIX_STOP``) and+# one that leaves a bracket it opened unclosed are left as they were too.+#+# What no allowlist can tell apart: a secret written raw into a quoted or+# unquoted slot (JSON and a repr escape a quote inside a string; a+# hand-built ``f"{{'password': '{pw}'}}"`` does not) that itself holds a+# quote or a value end followed by a structural follower. ``'ab',cd'`` or+# ``{'password': ab,cd}`` has exactly the shape of the value ``'ab'`` (or+# ``ab``) followed by another item, so the part after the follower prints+# behind the marker. The same holds for a DSN password that holds an '@'+# followed by what reads as a host and its end (``_DSN_HOST_RE``).+#+# The structural followers, by the kind of value they follow. After a+# quoted value's closing quote (a JSON or repr string, a quoted parameter):+# ``,`` the next item of an object, a list, a call or a parameter list;+# ``}``, ``]`` and ``)`` the end of an object, a list, a call or a tuple;+# ``:`` the separator after an item in a ``name: value`` listing+# (``f"{key!r}: {value!r}: {reason}"``); ``;`` the next parameter or cookie+# attribute (``password="..."; Path=/``); ``&`` the next query or form+# parameter; ``#`` a URL fragment or a trailing comment.+_QUOTED_VALUE_FOLLOWERS = ",}]):;&#"+# After an unquoted value of a quoted key (JSON or a repr, where an unquoted+# value is a number, a literal, a name or a call): ``,`` the next item, and+# ``}`` or ``]`` the end of the object or list. Nothing else ends such a+# value: ``&`` and ``#`` never do in JSON or a repr, the run takes ``;``,+# ``:`` and ``)`` in (a call ends at its own ``)``), and a word after a+# space means the value may be several words (``Basic dXNl...``,+# ``correct horse battery staple``).+_KEY_VALUE_FOLLOWERS = ",}]"+# After an unquoted ``;``/``,`` parameter value (matrix parameters, joined+# lists, call arguments): ``,`` and ``;`` the next parameter, and ``)``,+# ``]`` and ``}`` the end of the call, list or object the parameters are+# in. ``&`` and ``#`` belong to ``?``/``&`` query syntax (its separator+# and the fragment), not to these parameters, so a value that stops at one+# may go on past it (``;key=ab&cd``), and a word after a space means the+# value may be several words.+_PARAM_VALUE_FOLLOWERS = ",;)]}"+# After an ``Api-Key:`` header value (a run of the header pattern's token+# class, below): ``,``, ``;``, ``)``, ``]`` and ``}`` end the list, call or+# object the header sits in, and a word after a space means the value may+# be several words, as above. A quote that closes the string the header+# sits in counts too, when one of ``_QUOTED_VALUE_FOLLOWERS``, a line break+# or the end of the text follows it (``['Api-Key: ...', ...]``), and so+# does ``://`` straight after the run: a URL glued to the key, whose scheme+# letters the run took in.+_API_KEY_VALUE_FOLLOWERS = ",;)]}"+++def _followers_pattern(followers: str) -> str:+ """Matches at the end of a value only when the value ends there:+ optional whitespace other than a line break, then one of *followers*,+ a line break (``\\n``, ``\\r``) or the end of the text."""+ return r"[^\S\r\n]*+(?:[" + re.escape(followers) + r"\r\n]|\Z)"+++_QUOTED_VALUE_FOLLOWER_RE = re.compile(+ _followers_pattern(_QUOTED_VALUE_FOLLOWERS)+)+_KEY_VALUE_FOLLOWER_RE = re.compile(_followers_pattern(_KEY_VALUE_FOLLOWERS))+_PARAM_VALUE_FOLLOWER_RE = re.compile(+ _followers_pattern(_PARAM_VALUE_FOLLOWERS)+)+_API_KEY_FOLLOWER_RE = re.compile(+ "://|"+ + _followers_pattern(_API_KEY_VALUE_FOLLOWERS)+ + r"|[^\S\r\n]*+[\"'](?="+ + _followers_pattern(_QUOTED_VALUE_FOLLOWERS)+ + ")"+)+# After the '@' that ends a would-be DSN's userinfo: a host (a name or an+# IPv4 address, an IPv6 literal in brackets, or a ``${VAR}`` placeholder)+# followed by what ends a host: whitespace, ``:`` before a port, ``/``,+# ``?``, ``#``, a quote, ``<``, ``>``, ``,``, ``;``, ``)``, ``]``, ``}``, a+# backslash or the end of the text. Anything else after the '@' (another+# '@', a symbol, a space) means the password may hold an unescaped '@' and+# go on past it.+_DSN_HOST_RE = re.compile(+ r"(?:[A-Za-z0-9][A-Za-z0-9.\-_~%]*+|\[[0-9A-Za-z:.%]++\]|\$\{\w++\})"+ r"(?=[\s:/?#\"'<>,;)\]}\\]|\Z)"+)+# Credential parameter names for the ``;``/``,`` parameter pattern below:+# the same names the ``?``/``&`` query-parameter pattern above redacts.+_CREDENTIAL_PARAM_NAMES = (+ r"api[_-]?key|access[_-]?token|refresh[_-]?token|id[_-]?token|"+ r"auth[_-]?token|session[_-]?token|secret[_-]?key|bearer[_-]?token|"+ r"subscription[_-]?key|client[_-]?secret|api[_-]?secret|"+ r"app[_-]?secret|private[_-]?key|"+ r"key|token|secret|password|passwd|pwd"+)+# A credential label: a ``name=`` that ``redact_sensitive_assignments``+# redacts (a ``LOG_SENSITIVE_KEYS`` name, optional whitespace before the+# ``=``) or that the parameter pattern below redacts+# (``_CREDENTIAL_PARAM_NAMES``).+_CREDENTIAL_LABEL = (+ r"(?:(?i:" + _LOG_SENSITIVE_NAME_PATTERN + r")\s*="+ r"|(?i:" + _CREDENTIAL_PARAM_NAMES + r")=)"+)+# Checked before each character of a value matched below. A credential+# label is found only after a character outside ``[\w.-]`` (the assignment+# pass's left boundary; the ``,``/``;`` anchors of the parameter pattern),+# so the value stops before such a character when a label follows it: the+# label and its anchor stay as they were, legible, and the label's own+# value is matched separately.+_LABEL_STOP = "".join((r"(?![^\w.\-]", _CREDENTIAL_LABEL, r")"))+# At the first character of a value: no label there either.+_NO_LABEL = "".join((r"(?!", _CREDENTIAL_LABEL, r")"))+# Also checked before each character: a value stops before a URL scheme+# that starts a run of scheme characters (a letter, then letters, digits,+# ``+``, ``.`` or ``-`` reaching ``://`` within 32 characters), so a URL+# after a value stays legible; the URL-credential patterns have already+# redacted its userinfo.+_SCHEME_STOP = r"(?!(?<![A-Za-z0-9+.\-])[A-Za-z][A-Za-z0-9+.\-]{0,31}://)"+_VALUE_STOP = _LABEL_STOP + _SCHEME_STOP+# A name the assignment pass redacts, at the start of its ``name=``.+_ASSIGNMENT_NAME = "".join((r"(?:(?i:", _LOG_SENSITIVE_NAME_PATTERN, r")\s*=)"))+# Quoted keys (JSON, Python repr) name a credential with the names an+# ``extra`` key is redacted under: ``LOG_SENSITIVE_KEYS``, through+# ``_LOG_SENSITIVE_NAME_PATTERN`` (``_`` also matching ``-`` or nothing), so+# the message text and the ``extra`` keys cannot drift apart. As for an+# ``extra`` key (``_is_sensitive_log_key``: the last dotted segment, equal+# to a name or ending in ``_`` and the name), the name may follow any+# prefix that ends in a ``_``, ``.`` or ``-`` (``_QUOTED_KEY_PREFIX``):+# ``"_api_key"``, ``"db__password"``, ``"csrf_token"``, the request-header+# dicts the search engines send (``'X-API-KEY'``, ``'x-api-key'``,+# ``'X-Api-Key'``, ``'X-Subscription-Token'``), settings dumps+# (``"openai_api_key"``, ``"Ocp-Apim-Subscription-Key"``), the project's+# dotted settings keys (``"llm.openai.api_key"``) and its environment+# variables (``"LDR_SEARCH_ENGINE_WEB_TAVILY_API_KEY"``). A ``-`` before the+# name counts too, which an ``extra`` key does not need. The name must end+# the key, so ``"secret_name"`` or ``"password_hint"`` is not a credential+# key; a name glued to a camelCase prefix (``"dbPassword"``) is not one+# either, as for an ``extra`` key. Any key that ends in one is, so+# ``"show_password"`` or ``"use_secret"`` is redacted unless its value is a+# bare literal (over-redaction only); ``"requires_api_key"``, which+# ``_is_sensitive_log_key`` exempts, is redacted too when its value is not+# a bare literal.+#+# The cost stays linear in the key: the prefix cannot contain a quote, a+# backslash or a newline, so the scan from one opening quote ends before+# the next one starts; the prefix is lazy, so a name is tried once at each+# position, and the atomic group commits to the first position whose name+# reaches the closing quote (every decomposition ends at that same quote),+# so the value is matched once per key.+_QUOTED_CREDENTIAL_KEY_NAMES = _LOG_SENSITIVE_NAME_PATTERN+_QUOTED_KEY_PREFIX = r"(?:[^\"'\n\\]*?[_.\-])?"+# An unquoted value that is a whole JSON/Python literal (``true``,+# ``False``, ``None``, ``null``) is not a secret; with prefixed names+# (``"requires_api_key": True``) it is common, so it is left legible.+_UNQUOTED_LITERAL_STOP = r"(?!(?:true|false|none|null)(?![^\s,}\]&#\"'\\]))"+# A label inside a would-be DSN password, with the assignment pass's own+# left boundary.+_LABEL_IN_USERINFO_RE = re.compile(r"(?<![\w.?&-])" + _CREDENTIAL_LABEL)++# A quoted value for the parameter and quoted-key patterns below: to its+# closing quote (or the end of the text), with no credential label or URL+# scheme inside, and no quote character of the other kind (escaped or+# not). ``_VALUE_STOP`` is checked before every character, the one after a+# backslash included: a backslash escape is two characters, and checking+# only before the backslash would let an escaped separator (a backslash and+# a comma) hide a quoted label's ``password =`` after it, so the value would+# run on to that label's own opening quote and take the label with it.+_QUOTED_VALUE = "".join(+ (+ r"\"",+ _NO_LABEL,+ r"(?:",+ _VALUE_STOP,+ r"(?:\\",+ _VALUE_STOP,+ r"[^'\n]|[^\"'\\]))*(?:\"|\\?$)",+ r"|'",+ _NO_LABEL,+ r"(?:",+ _VALUE_STOP,+ r"(?:\\",+ _VALUE_STOP,+ r"[^\"\n]|[^'\"\\]))*(?:'|\\?$)",+ )+)+# A quoted value as above, after an optional Python string prefix+# (``b'...'``, ``rb"..."``, ``f'...'``), so a bytes value or a bytes-keyed+# repr (``{b'password': b'...'}``) is redacted whole.+# ``_redacted_value`` keeps the prefix.+_PREFIXED_QUOTED_VALUE = "".join(+ (r"(?:[bruf]{1,2}(?=[\"']))?(?:", _QUOTED_VALUE, r")")+)+# At the first character of an unquoted value: not a string prefix before a+# quote. Matched as an unquoted run, ``b'secret'`` would stop at the quote,+# so the marker would replace only the ``b``; it is matched whole by+# ``_PREFIXED_QUOTED_VALUE`` instead, or left as it is when that refuses it.+_UNQUOTED_PREFIX_STOP = r"(?![bruf]{1,2}[\"'])"+# An unquoted value of a quoted key that is written as an ``Authorization``+# header's is: a scheme word (the schemes ``sanitize_error_message``'s+# ``Authorization`` pattern names) and one credential token. It is taken as+# one value, whatever the key, so the marker replaces both+# (``{'Authorization': Basic dXNl...}``). Anything but a structural+# follower after the token (a second token, the ``username=...,+# response=...`` list of a ``Digest`` value) leaves the text as it was.+_SCHEME_CREDENTIAL = (+ r"(?:basic|bearer|digest|negotiate|apikey|token)"+ r"[^\S\r\n]++[A-Za-z0-9\-._~+/]++=*"+)+# Brackets an unquoted value may open and the ones that close them.+_VALUE_BRACKETS = (("(", ")"), ("[", "]"), ("{", "}"))+++def _cuts_a_value(+ text: str,+ start: int,+ end: int,+ unquoted_followers: "re.Pattern[str]",+) -> bool:+ """True unless ``text[start:end]``, a value matched below, ends where+ its syntax ends a value, so that replacing it cannot print the rest of+ the value behind a ``[REDACTED]`` marker that makes the line look+ redacted. The callers then return the text unchanged.++ An allowlist: the value is taken as whole only when what follows it+ matches ``_QUOTED_VALUE_FOLLOWER_RE`` (after a quoted value's closing+ quote, or its end when it runs to the end of the text) or+ *unquoted_followers* (after an unquoted run): a structural follower for+ that kind of value, after optional whitespace that is not a line+ break, or a line break, or the end of the text. Any other character+ refuses it: a quote (``'''secret'''``, whose first two quotes are an+ empty string, or a quote that opens a string belonging to the value,+ ``SecretStr('...')``), a backslash, a word after a space, or a symbol a+ secret may hold (``'Pa'$$w0rd'``, ``hunter2&rest``). An unquoted value+ that leaves a bracket it opened unclosed is not whole either, whatever+ follows it: a nested container or a call stops at its first separator+ (``(1, '...')``, ``{0: '...'}``, ``Foo(a, '...')``), so the rest of it+ is outside the match.+ """+ value = text[start:end]+ if _redacted_value(value) != "[REDACTED]":+ # A quoted value, string prefix and all (``b'...'``).+ return _QUOTED_VALUE_FOLLOWER_RE.match(text, end) is None+ if unquoted_followers.match(text, end) is None:+ return True+ return any(+ value.count(opener) > value.count(closer)+ for opener, closer in _VALUE_BRACKETS)-def redact_head_for_log(value: str, max_chars: int) -> str:- """:func:`redact_for_log` on at most *max_chars* characters of *value*.+def _redacted_value(value: str) -> str:+ """``[REDACTED]`` in place of a value matched by the patterns below.- For a caller that shows only a short prefix of the result. The value- is cut first by the patcher's own rule- (:func:`_truncate_for_log_redaction` with *max_chars* as the bound:- only at a whitespace boundary, dropping the whole run the bound falls- in), then the kept head is redacted, and the rest is replaced by the- omitted-length marker. The patcher's own argument applies: a- credential token holds no boundary character, so the head never keeps- part of a token whose label or ``@`` was cut off, and text past the- cut is never shown. The cost is bounded by *max_chars*.+ A quoted value keeps its quotes (its closing quote only when it has+ one) and its string prefix (``b'[REDACTED]'``), so the text after it+ is still delimited as it was."""- if not value:- return value- head, marker = _truncate_for_log_redaction(value, max_chars)- return redact_for_log(head) + marker+ stripped = value.lstrip("bBrRuUfF")+ prefix = value[: len(value) - len(stripped)]+ quote = stripped[:1]+ if quote not in ('"', "'") or len(prefix) > 2:+ return "[REDACTED]"+ body = stripped[1:]+ closed = False+ if body.endswith(quote):+ inner = body[:-1]+ closed = (len(inner) - len(inner.rstrip("\\"))) % 2 == 0+ return prefix + quote + "[REDACTED]" + (quote if closed else "")+++def _redact_slash_dsn(match: "re.Match[str]") -> str:+ """Replacement for the slash-DSN pattern below.++ A password run that holds a credential label (``/password=...``,+ ``;token=...``) is not userinfo but a path running into that label's+ value, up to an '@' inside it. Redacting it would remove the label the+ parameter pattern below needs and print the value's tail, so the text+ is returned unchanged for it. Checked here rather than inside the+ regex: a per-character label lookahead made the capped scan several+ times slower.++ The '@' is taken as the end of the userinfo only when a host follows+ it and ends where a host ends (``_DSN_HOST_RE``). Anything else, such+ as a second '@' (``u:pa/ss@word@host``), a symbol or a space after it,+ means the password may hold an unescaped '@', so which '@' ends the+ userinfo cannot be told: the text is returned unchanged rather than+ printing the password's tail behind the marker.+ """+ if _LABEL_IN_USERINFO_RE.search(match.string, match.start(4), match.end(4)):+ return match.group(0)+ if _DSN_HOST_RE.match(match.string, match.end()) is None:+ return match.group(0)+ return match.group(1) + match.group(2) + "[REDACTED]:[REDACTED]@"-def redact_and_bound_for_log(value: str, max_length: int) -> str:- """:func:`redact_for_log`, then :func:`sanitize_for_log` (strip + cap).+def _redact_api_key_header(match: "re.Match[str]") -> str:+ """Replacement for the ``Api-Key:`` header pattern below.- Use instead of plain ``sanitize_for_log`` for a value that a call site- previously logged in full, where the patcher saw (and redacted) the whole- value: truncating first would let it see less than it did before.+ The text is returned unchanged unless the value ends where a header+ value ends (``_API_KEY_FOLLOWER_RE``).+ """+ if _API_KEY_FOLLOWER_RE.match(match.string, match.end()) is None:+ return match.group(0)+ return match.group(1) + "[REDACTED]"- Only the first :func:`bounded_redaction_chars` characters (at least- 1,024) are redacted, cut by the patcher's whitespace-boundary rule (see- :func:`redact_head_for_log`); the result keeps at most *max_length* of- them. A value whose first whitespace-free run reaches past that bound- is shown as the omitted-length marker only.++def _redact_credential_param(match: "re.Match[str]") -> str:+ """Replacement for the ``;``/``,`` credential-parameter pattern below.++ The text is returned unchanged unless the matched value ends where a+ value ends (:func:`_cuts_a_value`, with ``_PARAM_VALUE_FOLLOWERS`` after+ an unquoted value)."""- return sanitize_for_log(- redact_head_for_log(value, bounded_redaction_chars(max_length)),- max_length,+ group = 3 if match.group(3) is not None else 5+ if _cuts_a_value(+ match.string,+ match.start(group),+ match.end(group),+ _PARAM_VALUE_FOLLOWER_RE,+ ):+ return match.group(0)+ return (+ match.group(1)+ + (match.group(2) or match.group(4))+ + "="+ + _redacted_value(match.group(group)))-def _is_sensitive_log_key(key: Any) -> bool:- """True when *key* names a secret under settings redaction's rules.+def _redact_quoted_key(match: "re.Match[str]") -> str:+ """Replacement for the quoted-credential-key pattern below.++ The text is returned unchanged unless the matched value ends where a+ value ends (:func:`_cuts_a_value`, with ``_KEY_VALUE_FOLLOWERS`` after+ an unquoted value).+ """+ if _cuts_a_value(+ match.string, match.start(4), match.end(4), _KEY_VALUE_FOLLOWER_RE+ ):+ return match.group(0)+ return (+ match.group(1)+ + match.group(2)+ + match.group(1)+ + match.group(3)+ + _redacted_value(match.group(4))+ )+++_ADDITIONAL_CREDENTIAL_PATTERNS: list[+ tuple[re.Pattern[str], Union[str, Callable[["re.Match[str]"], str]]]+] = [+ # Slash-bearing DSN passwords — base64/base64-ish generated secrets+ # pasted into a connection string routinely contain an unescaped '/',+ # which the URL-credentials pattern in ``_CREDENTIAL_PATTERNS`` refuses+ # by design. Admitting the slash makes one URL shape look like+ # userinfo: ``host:port/path...@...``+ # (``https://api.example.com:443/users/[email protected]``), where the+ # "user" is really the host and the "password" a port followed by a+ # path. A password that is a run of digits followed by ``/``, ``?`` or+ # ``#`` (or that starts with one of them) is that shape, so it is+ # refused; the user part also refuses ``[``/``]`` so an IPv6 literal+ # host is never read as userinfo. Any host is accepted after the '@'+ # (``@postgres:5432``, ``@localhost``, ``@10.0.0.5`` are the usual+ # container DSNs). Known gap: a real password that is digits followed+ # by '/' is left alone.+ #+ # Neither group crosses a JSON, list or query boundary: the user refuses+ # ``"'<>,`` and ``?#&=;``, the password ``"'<>,`` and ``?#&``. A+ # match whose password holds a credential label (``/password=``,+ # ``;token=``, ``=api_key=``), or whose '@' is not followed by a host+ # and a host's end (``_DSN_HOST_RE``; ``u:pa/ss@word@host``, where the+ # password may hold an unescaped '@'), is left alone+ # (``_redact_slash_dsn``). Known gap: a slash-bearing password that+ # also contains one of those characters is not redacted by this+ # pattern, nor one that contains an '@' unless what follows that '@'+ # reads as a host and its end (``u:pa/ss@word/x@host``), which cannot+ # be told from a DSN followed by more text, so the rest of such a+ # password prints behind the marker.+ #+ # Both groups are length-capped: an uncapped password class that may+ # run through '/' made matching quadratic on a whitespace-free run of+ # ``scheme://:`` with no '@' (seconds of GIL-holding CPU at ~30k+ # chars). The caps bound the work per start position, which keeps the+ # scan linear; a longer user or password is not redacted by this+ # pattern.+ #+ # Each ``://`` is also tried once, not once per scheme start: a run of+ # scheme characters is entered only at its first character (the+ # lookbehind), a lazy prefix (group 1, put back by the replacement)+ # skips to the leftmost position where a scheme reaches the ``://`` --+ # where an unanchored search would have started -- and the atomic group+ # commits to that scheme. Every later start before the same ``://``+ # would retry the identical user/password tail, so dropping them changes+ # no result; without this, a 32-letter scheme repeated with ``://:``+ # ran up to 31 capped tails per ``://`` (about 6x the cost of the+ # URL-credentials pattern on the same run). The user and password+ # quantifiers are possessive: the character that must follow each is+ # outside its class, so giving characters back can never succeed.+ (+ re.compile(+ r"(?<![A-Za-z0-9+.\-])"+ r"(?>([A-Za-z0-9+.\-]*?)([A-Za-z][A-Za-z0-9+.\-]{1,31}://))"+ r"([^:\s/@\[\]\"'<>,?#&=;]{0,128}+):(?![0-9]*[/?#])"+ r"([^@\s\"'<>,?&#]{1,256}+)@"+ ),+ _redact_slash_dsn,+ ),+ # API-key header spellings the ``x-api-key`` pattern in+ # ``_CREDENTIAL_PATTERNS`` misses — the unprefixed ``Api-Key:`` form is+ # what Anthropic, Azure Cognitive Services and several search APIs+ # send, plus ``x-api_key``/``x-apikey``. Like the ``x-api-key``+ # pattern, the label is a strong anchor, so any value of >=16+ # characters is redacted regardless of shape; short values like+ # "invalid"/"missing" stay intact. The unprefixed forms match only the+ # ``:`` header-dump shape — an ``=`` assignment is prose (``api_key=...``+ # mid-sentence is not redacted by this pattern). The value stops where+ # a credential label begins (``KEY/client_secret=...``) or a URL scheme+ # starts a run (``api_key: postgresql+asyncpg://...``), and is not+ # redacted when fewer than 16 characters come before that. It is+ # redacted only when it ends where a value ends+ # (``_API_KEY_FOLLOWER_RE``): one of ``_API_KEY_VALUE_FOLLOWERS``, a+ # line break or the end of the text, after optional whitespace; a+ # quote that closes the string the header sits in; or ``://`` glued to+ # it. A key followed by a word after a space, by ``&``, ``!``, ``:``,+ # a ``/`` before a label or any other character its class lacks is+ # left as the earlier passes left it.+ #+ # Known gap: where a key glued straight to a scheme (``KEYhttps://``)+ # ends and the scheme begins cannot be told apart. When the run of+ # scheme characters starts at a letter within 32 characters of+ # ``://``, the value stops there, so the key prints, all of it, since+ # what follows the stop is a letter and not a header value's end. A run+ # that starts with a digit or is longer than that is taken whole,+ # scheme included.+ (+ re.compile(+ r"(?i)((?:x-api[_-]?key\s*[:=]|api[_-]?key\s*:)\s*)"+ + _NO_LABEL+ + r"(?:"+ + _VALUE_STOP+ + r"[A-Za-z0-9\-._~+/]){16,}+=*"+ ),+ _redact_api_key_header,+ ),+ # Credential parameters after ``;`` (matrix parameters, ``;token=...``)+ # or ``,`` (joined lists, ``,password=...``), with the ``?``/``&``+ # parameter pattern's names. The value is a quoted string, optionally+ # string-prefixed (``_PREFIXED_QUOTED_VALUE``), or an unquoted run that+ # does not start with a string prefix before a quote+ # (``_UNQUOTED_PREFIX_STOP``). For a name the assignment+ # pass also redacts (``password``, ``token``, ``api_key``, ...) an+ # unquoted run must reach whitespace (or the end of the text) without a+ # ``&``, ``#``, quote, backslash, label or scheme on the way; any other+ # value of such a name is left as the earlier passes left it. Any other+ # name (``key``) takes a run that stops at whitespace, ``&``, ``#``, a+ # quote, a backslash or a ``,``/``;`` starting a credential label+ # (``,key=abc,password="example secret"`` redacts both). Either is+ # redacted only when what follows it ends a value (``_cuts_a_value``):+ # one of ``_QUOTED_VALUE_FOLLOWERS`` after a quoted value, one of+ # ``_PARAM_VALUE_FOLLOWERS`` after an unquoted one, after optional+ # whitespace, or a line break or the end of the text; so a run that+ # stops at a space before a word (``;key=abc def``), at a quote, at a+ # backslash, or at a label after any character but ``,``/``;`` is not+ # redacted, nor an unquoted value that leaves a bracket it opened+ # unclosed (``,key=[b'...']``). Such a value is left as the earlier+ # passes left it.+ (+ re.compile(+ r"(?i)([,;])(?:"+ r"(?=" + _ASSIGNMENT_NAME + r")(" + _CREDENTIAL_PARAM_NAMES + r")="+ r"("+ + _PREFIXED_QUOTED_VALUE+ + r"|(?![\"'])"+ + _UNQUOTED_PREFIX_STOP+ + _NO_LABEL+ + r"(?:"+ + _VALUE_STOP+ + r"[^\s&#\"'\\])++(?!\S))"+ r"|(?!" + _ASSIGNMENT_NAME + r")(" + _CREDENTIAL_PARAM_NAMES + r")="+ r"("+ + _PREFIXED_QUOTED_VALUE+ + r"|"+ + _UNQUOTED_PREFIX_STOP+ + _NO_LABEL+ + r"(?:[,;]"+ + _NO_LABEL+ + r"|"+ + _VALUE_STOP+ + r"[^\s,;&#\"'\\])++)"+ r")"+ ),+ _redact_credential_param,+ ),+ # Quoted credential keys in JSON or a Python repr ("password": "...",+ # {'api-key': '...'}, {'X-API-KEY': '...'}, "llm.openai.api_key": ...).+ # The value is a quoted string, optionally string-prefixed+ # (``_PREFIXED_QUOTED_VALUE``: ``b'...'``), a scheme word and one+ # credential token (``_SCHEME_CREDENTIAL``: ``Basic dXNl...``), or an+ # unquoted run (to whitespace, ``,``, ``}``, ``]``, ``&``, ``#``, a+ # quote, a backslash, a credential label or a scheme); an unquoted run+ # never starts with a quote or ``[``, so an already-redacted+ # ``[REDACTED]`` value is left as it is, nor with a string prefix before+ # a quote (``_UNQUOTED_PREFIX_STOP``), and is never a bare+ # ``true``/``false``/``None``/``null``. It is redacted only when what+ # follows it ends a value (``_cuts_a_value``): one of+ # ``_QUOTED_VALUE_FOLLOWERS`` after a quoted value, one of+ # ``_KEY_VALUE_FOLLOWERS`` (``,``, ``}``, ``]``) after an unquoted one,+ # after optional whitespace, or a line break or the end of the text; an+ # unquoted value that leaves a bracket it opened unclosed (``(b'...',)``,+ # ``bytearray(b'...')``, ``{0: '...'}``) is not whole either. Any other+ # value is left as the earlier passes left it: ``'''...'''``,+ # ``'Pa'$$w0rd'``, ``hunter2&rest``, ``correct horse battery staple``,+ # ``ApiKey(key=...)``.+ (+ re.compile(+ r"(?i)([\"'])(?>("+ + _QUOTED_KEY_PREFIX+ + r"(?:"+ + _QUOTED_CREDENTIAL_KEY_NAMES+ + r"))\1)(\s*:\s*)"+ r"("+ + _PREFIXED_QUOTED_VALUE+ + r"|"+ + _SCHEME_CREDENTIAL+ + r"|(?![\"'\[])"+ + _UNQUOTED_PREFIX_STOP+ + _UNQUOTED_LITERAL_STOP+ + _NO_LABEL+ + r"(?:"+ + _VALUE_STOP+ + r"[^\s,}\]&#\"'\\])+)"+ ),+ _redact_quoted_key,+ ),+]+++def _redact_additional_shapes(message: str) -> str:+ """Apply ``_ADDITIONAL_CREDENTIAL_PATTERNS`` in order, as plain substitutions.++ Used as the final redaction step for record text, rendered exception+ fields, and the database log row's exception prefix. Callers bound the+ text before applying these patterns.+ """+ if not message:+ return message+ for pattern, replacement in _ADDITIONAL_CREDENTIAL_PATTERNS:+ message = pattern.sub(replacement, message)+ return message+++def _redact_log_record_text(value: str) -> str:+ """:func:`_redact_log_text`, then ``_ADDITIONAL_CREDENTIAL_PATTERNS``.++ For the log record's message and its ``extra`` string leaves, whose+ redacted text goes straight to the sinks. The text is cut to the bound+ first, :func:`_redact_log_text` redacts that head, and the added+ patterns run on its output, so they see what its passes left and can+ only replace more of it; the omission marker is appended after them.+ """+ value = _plain_text(value)+ if not value:+ return _exact_str(value)+ # Cut once here so the added patterns see a bounded string and the+ # omission marker stays outside their reach. ``head`` is within the+ # bound, so ``_redact_log_text`` cuts nothing more and appends no+ # marker of its own: its output is exactly its two passes over+ # ``head``. Calling it (rather than repeating its passes) keeps any+ # change to it in force on the log-record path.+ head, marker = _truncate_for_log_redaction(value)+ return _redact_additional_shapes(_redact_log_text(head)) + marker+++def redact_for_log(value: str) -> str:+ """Run the log patcher's credential redaction on *value* alone.++ The same two passes and the same ``_LOG_REDACTION_MAX_CHARS`` bound the+ loguru patcher applies to every record (:func:`_redact_log_text`), for a+ caller that is about to shorten *value* before it reaches a log line.+ Shortening first can hide a credential from the patcher: a cut that drops+ ``?key=`` or the ``@`` after URL userinfo, but keeps part of the secret,+ leaves text no credential pattern matches. Redacting first means any cut+ afterwards only removes text the patcher already judged safe or already+ replaced. Cost is bounded the same way as the patcher's.+ """+ return _redact_log_text(value)+++# How much of one value :func:`redact_and_bound_for_log` scans: at least+# this many characters, or four times the output cap if that is more, and+# never more than the patcher's own ``_LOG_REDACTION_MAX_CHARS``. The+# result keeps at most ``max_length`` characters, so scanning the full+# 32 KiB made one call cost ~50-100 ms on adversarial input (a run of+# spaces, or of ``https://a:b@ ``) for a 256-character result; 1,024+# characters cost a few milliseconds.+_LOG_BOUNDED_REDACTION_MIN_CHARS = 1_024+++def bounded_redaction_chars(max_length: int) -> int:+ """How many characters of a value to redact for a *max_length* result."""+ return min(+ _LOG_REDACTION_MAX_CHARS,+ max(_LOG_BOUNDED_REDACTION_MIN_CHARS, 4 * max_length),+ )+++def redact_head_for_log(value: str, max_chars: int) -> str:+ """:func:`redact_for_log` on at most *max_chars* characters of *value*.++ For a caller that shows only a short prefix of the result. The value+ is cut first by the patcher's own rule+ (:func:`_truncate_for_log_redaction` with *max_chars* as the bound:+ only at a whitespace boundary, dropping the whole run the bound falls+ in), then the kept head is redacted, and the rest is replaced by the+ omitted-length marker. The patcher's own argument applies: a+ credential token holds no boundary character, so the head never keeps+ part of a token whose label or ``@`` was cut off, and text past the+ cut is never shown. The cost is bounded by *max_chars*.+ """+ if not value:+ return value+ head, marker = _truncate_for_log_redaction(value, max_chars)+ return redact_for_log(head) + marker+++def redact_and_bound_for_log(value: str, max_length: int) -> str:+ """:func:`redact_for_log`, then :func:`sanitize_for_log` (strip + cap).++ Use instead of plain ``sanitize_for_log`` for a value that a call site+ previously logged in full, where the patcher saw (and redacted) the whole+ value: truncating first would let it see less than it did before.++ Only the first :func:`bounded_redaction_chars` characters (at least+ 1,024) are redacted, cut by the patcher's whitespace-boundary rule (see+ :func:`redact_head_for_log`); the result keeps at most *max_length* of+ them. A value whose first whitespace-free run reaches past that bound+ is shown as the omitted-length marker only.+ """+ return sanitize_for_log(+ redact_head_for_log(value, bounded_redaction_chars(max_length)),+ max_length,+ )+++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 exactlyor 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.-- The check walks the whole key, so a key longer than- ``_LOG_REDACTION_MAX_CHARS`` is not checked and counts as sensitive- (fail closed: its value is masked), keeping the cost per key bounded- like the cost per string.+ ``db_password``), after invisible characters are removed from it. Message+ text also recognizes prefixed and dotted assignments, and the additional+ shape pass recognizes quoted credential keys. A ``str`` subclass key is+ checked by its plain characters: its own ``rsplit``, ``lower`` or+ ``__eq__`` could otherwise hide a name. A key longer than+ ``_LOG_REDACTION_MAX_CHARS`` is treated as sensitive without scanning it,+ keeping the cost per key bounded and masking its value."""if not isinstance(key, str):return Falseif len(key) > _LOG_REDACTION_MAX_CHARS:return Truereturn DataSanitizer.is_sensitive_setting(- key, sensitive_keys=LOG_SENSITIVE_KEYS+ _exact_str(key), sensitive_keys=LOG_SENSITIVE_KEYS)+def _is_structural_extra_key(key: Any) -> bool:+ """True when *key* is one of the routing keys, as an exact ``str``.++ A ``str`` subclass can hash and compare equal to ``"username"`` while+ holding (and rendering) other text, so only an exact ``str`` passes+ unredacted as a routing key.+ """+ return type(key) is str and key in _LOG_STRUCTURAL_EXTRA_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 witha raising ``__eq__`` cannot abort the redaction of the whole record.+ Exact types only: a subclass can override ``__len__`` (or iterate items+ its storage does not hold) to look empty under a sensitive key, so a+ subclass is never "empty" and is masked like any other value."""if value is None:return True- return isinstance(value, (str, list, dict)) and len(value) == 0+ return _type_is_one_of(type(value), (str, list, dict)) and len(value) == 0# Nesting bound for ``extra`` values: a container at this depth or deeper@@ -982,13 +3316,110 @@ def _is_empty_log_value(value: Any) -> bool:_LOG_EXTRA_MAX_DEPTH = 32+def _scrub_log_key(key: Any) -> Any:+ """Scrub a dict key in ``extra`` the way a string value is scrubbed.++ A ``str`` key is redacted (:func:`_redact_log_text`). ``None``, ``bool``,+ ``int`` and ``float`` keys cannot carry a credential and pass through. A+ key whose text is fixed by its type (``bytes``, or a tuple or frozenset+ of such values, see :func:`_is_stable_text_value`) is kept as is unless+ its ``str()`` redacts differently, in which case the redacted text+ replaces it. Any other key (an object with its own ``__str__`` or+ ``__repr__``, a ``str`` subclass) is always replaced by its checked,+ redacted text: the sinks render the key again, and an object may render+ a secret the second time, or (when its ``str()`` raised here) render+ text that was never checked at all.+ """+ if isinstance(key, str):+ return _redact_log_text(key)+ if key is None or _type_is_one_of(type(key), (bool, int, float)):+ return key+ try:+ text = _exact_str(str(key))+ printable = True+ except Exception:+ text = _unprintable_placeholder(key)+ printable = False+ redacted = _redact_log_text(text)+ if printable and redacted == text and _is_stable_text_value(key):+ return key+ return redacted+++def _unique_log_key(out: dict, key: Any, reserved: Any = ()) -> Any:+ """*key*, or ``key#2``, ``key#3``, ... when it is already taken.++ Redaction can map two different keys to the same text (two URLs with+ different passwords, or ``"a\\nb"`` and ``"ab"``); the second must not+ overwrite the first. *reserved* holds keys that may not be produced at+ all (the routing keys of the top-level ``extra``).++ Keys are taken in the input's iteration order, so the first key to+ produce a given text keeps it unsuffixed and later ones are suffixed; a+ reserved key is never produced, even for the first key that redacts to+ it (the caller keeps a routing key itself under its own name, whether+ it comes before or after a key that redacts to it).+ """+ if key not in out and key not in reserved:+ return key+ base = key if isinstance(key, str) else _safe_log_str(key)+ n = 2+ while f"{base}#{n}" in out or f"{base}#{n}" in reserved:+ n += 1+ return f"{base}#{n}"+++def _scrub_log_bytes(value: Any) -> Any:+ """Scrub a ``bytes``/``bytearray`` ``extra`` leaf.++ Only the first ``4 * _LOG_REDACTION_MAX_CHARS + 4`` bytes are decoded+ (UTF-8, undecodable bytes become U+FFFD, which cannot join a credential+ name the way a ``\\xNN`` escape's hex digits would), so the cost does not+ grow with the value. A value that decodes to at most+ ``_LOG_REDACTION_MAX_CHARS`` characters is returned unchanged (a+ ``bytearray`` or ``bytes`` subclass as a plain copy of itself) unless+ :func:`_redact_log_text` redacts something in it, in which case the+ redacted text replaces it. A longer value is always replaced by its+ redacted, truncated text, ending in a marker that gives its total size+ in bytes.+ """+ if type(value) is not bytes:+ # A ``bytearray`` (or a ``bytes`` subclass) can change or render+ # differently after the check; check and return a plain copy (read+ # through the buffer, so a ``__bytes__`` override is not called).+ value = (+ bytearray(memoryview(value))+ if isinstance(value, bytearray)+ else bytes(memoryview(value))+ )+ limit = 4 * _LOG_REDACTION_MAX_CHARS + 4+ text = bytes(value[:limit]).decode("utf-8", "replace")+ head, marker = _truncate_for_log_redaction(text)+ if not marker:+ # Compared with the control-stripped text rather than ``text``:+ # ``_redact_log_text`` always strips control characters, so only a+ # difference beyond that strip is a redaction (``api_<U+001F>key=``+ # included), while benign bytes holding a newline stay bytes.+ redacted = _redact_log_text(text)+ if redacted == strip_control_chars(text):+ return value+ return redacted+ return (+ _redact_log_text(head)+ + f" [... {len(value)} bytes in total, the rest omitted from log output]"+ )++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 anykey is scrubbed) — the two halves that a name-only or shape-only check- would each miss. Non-string, non-container leaves pass through.+ would each miss. Dict keys are scrubbed too (:func:`_scrub_log_key`);+ sets and tuples come back as lists; a ``bytes``/``bytearray`` leaf is+ handled by :func:`_scrub_log_bytes`. Other non-container leaves pass+ through.A container that contains itself (directly or further down) is renderedas ``"<cycle>"`` and a container at depth :data:`_LOG_EXTRA_MAX_DEPTH`@@ -997,8 +3428,10 @@ def _scrub_log_leaf(value: Any, _depth: int = 0, _active: Any = None) -> Any:fallback for the whole record."""if isinstance(value, str):- return _redact_log_text(value)- if not isinstance(value, (dict, list, tuple)):+ return _redact_log_record_text(value)+ if isinstance(value, (bytes, bytearray)):+ return _scrub_log_bytes(value)+ if not isinstance(value, (dict, list, tuple, set, frozenset)):return valueif _depth >= _LOG_EXTRA_MAX_DEPTH:return "<nested too deep>"@@ -1010,14 +3443,14 @@ def _scrub_log_leaf(value: Any, _depth: int = 0, _active: Any = None) -> Any:_active.add(marker)try:if isinstance(value, dict):- return {- k: (+ out: dict = {}+ for k, v in value.items():+ out[_unique_log_key(out, _scrub_log_key(k))] = (REDACTION_TEXTif _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 outreturn [_scrub_log_leaf(v, _depth + 1, _active) for v in value]finally:_active.discard(marker)@@ -1027,14 +3460,21 @@ 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.+ ``policy_audit``) pass through untouched -- as exact ``str`` keys only+ (:func:`_is_structural_extra_key`); a ``str`` subclass key is checked+ by its plain characters like any other key.* A value under a sensitive key name (:data:`LOG_SENSITIVE_KEYS`, exactor as an ``_``-delimited suffix such as ``openai_api_key``) is maskedwhole (empty values are left readable, mirroring ``DataSanitizer``).+ * Other keys are scrubbed for credential shapes like string values; a+ key whose scrubbed form is a routing key or an earlier key gets a+ ``#2``/``#3`` suffix instead of overwriting it.* Every other value is recursively scrubbed for credential *shapes*, soa token/URL/query bound under an innocuous key (the family of bug thename-based checks miss) is still caught. String values get the same- control-character strip as the message, between two redaction passes.+ control-character strip as the message, between two redaction passes,+ and then the same ``_ADDITIONAL_CREDENTIAL_PATTERNS``+ (:func:`_redact_log_record_text`).Returns a new dict; the input is not mutated. A non-dict ``extra`` isreturned unchanged.@@ -1046,61 +3486,2096 @@ def redact_log_extra(extra: Any) -> Any:# 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:+ if _is_structural_extra_key(key):out[key] = value- elif _is_sensitive_log_key(key) and not _is_empty_log_value(value):- out[key] = REDACTION_TEXT+ continue+ safe_key = _unique_log_key(+ out, _scrub_log_key(key), _LOG_STRUCTURAL_EXTRA_KEYS+ )+ if _is_sensitive_log_key(key) and not _is_empty_log_value(value):+ out[safe_key] = REDACTION_TEXTelse:- out[key] = _scrub_log_leaf(value, 1, active)+ out[safe_key] = _scrub_log_leaf(value, 1, active)return out+def _unprintable_placeholder(obj: Any) -> str:+ """Stand-in text for an object whose ``str()`` raised or was not a str."""+ return f"<unprintable {_type_name(type(obj))}>"+++def _safe_log_str(obj: Any) -> str:+ """``str(obj)``, or a placeholder when that raises.++ ``str()`` raises ``TypeError`` itself when ``__str__`` returns a+ non-str, so one guard covers both a raising and a mistyped ``__str__``.+ Only the one node's text is replaced; the rest of the exception graph+ and its traceback are still rendered. A ``__str__`` may return a ``str``+ subclass, which can render differently later (its own ``__str__``,+ ``__format__`` or ``__repr__``); the result is always an exact ``str``.+ """+ try:+ return _exact_str(str(obj))+ except Exception:+ return _unprintable_placeholder(obj)+++def _exact_str(text: str) -> str:+ """*text* as an exact ``str`` (a copy when it is a ``str`` subclass)."""+ return text if type(text) is str else str.__str__(text)+++def _plain_text(value: Any) -> Any:+ """*value* as an exact ``str`` when it is a ``str``; anything else as is.++ Called before a ``not value`` shortcut: a ``str`` subclass can override+ ``__bool__`` or ``__len__`` to look empty while holding text, and would+ then be returned unredacted. The copy's truth value and length are its+ real characters'.+ """+ return _exact_str(value) if isinstance(value, str) else value+++# Line breaks and tabs that exception text keeps: ``\t``, ``\n`` and ``\r``+# are never drawn as nothing in a sink -- terminal, log file, and the DB log+# shown in the browser -- (a tab, a line break, or for ``\r`` a line break+# or, in a terminal, a return to the start of the line), so a credential+# name they split is not shown as one unbroken name, and a multi-line+# message keeps its lines.+_EXCEPTION_KEPT_BREAKS = "\t\n\r"++# Every other character ``strip_control_chars`` removes: zero-width and bidi+# format characters, and all other C0/C1 controls. That deliberately+# includes the ones ``str.isspace()`` calls whitespace -- ``\x1c``-``\x1f``,+# U+0085, ``\v``, ``\f``, U+2028 and U+2029. Terminals draw ``\x1c``-``\x1f``+# as nothing, browsers draw U+0085 and ``\v`` as nothing, and ``\f``,+# U+2028 and U+2029 are a line break in some sinks and nothing in others.+# Only a character that is a visible separator in every sink may stay, since+# any of these can hide a credential name (``api_<U+200B>key=``,+# ``tok<U+001F>en=``) or split URL userinfo exactly like a zero-width space.+# Derived from ``_UNSAFE_CHAR_RE`` so the two cannot drift apart.+_EXCEPTION_INVISIBLE_RE = re.compile(+ "["+ + "".join(+ re.escape(char)+ for char in map(+ chr,+ [+ *range(0xA0),+ 0x61C,+ *range(0x2000, 0x2070),+ 0xFEFF,+ ],+ )+ if _UNSAFE_CHAR_RE.match(char) and char not in _EXCEPTION_KEPT_BREAKS+ )+ + "]"+)+++def _redact_exception_text(value: str) -> str:+ """Redact one rendered exception field (value, group message or note).++ The first pass sees the text as loguru will render it. The second pass+ runs on that output with every character :func:`strip_control_chars`+ removes, except ``\t``, ``\n`` and ``\r``, removed+ (:data:`_EXCEPTION_INVISIBLE_RE`), catching a credential name or URL+ those characters split; its result is used only when it redacts+ something more. Tabs and line breaks are kept in both passes, so a+ multi-line exception message keeps its lines, and a value the first+ pass redacted at a line end is not glued onto the next line's text.+ When removing those characters leaves exactly the original text (none+ in it, and the first pass changed nothing), the second pass would scan+ that same text again and return the first pass's result, so it is+ skipped: clean text, the common case, costs one pass. The additional+ credential shapes run on the selected redacted text before the omission+ marker is appended.+ """+ value = _plain_text(value)+ if not value:+ return _exact_str(value)+ head, marker = _truncate_for_log_redaction(value)+ first = _redact_bounded_log_text(head)+ visible = _EXCEPTION_INVISIBLE_RE.sub("", first)+ if visible == head:+ # ``_redact_bounded_log_text(visible)`` is ``first`` itself, which+ # the line below would return either way.+ result = first+ else:+ second = _redact_bounded_log_text(visible)+ result = first if second == visible else second+ return _exact_str(_redact_additional_shapes(result) + marker)+++def _rendered_exception_notes(node: Any) -> tuple[list, bool]:+ """The notes the traceback module renders for *node*, and an exactness flag.++ Mirrors ``TracebackException.format_exception_only`` on Python 3.12 to+ 3.14 (which loguru calls): a ``__notes__`` that is a+ ``collections.abc.Sequence`` other than ``str``/``bytes`` is iterated+ and each item rendered with ``str()``; any other value except ``None``+ (a ``str``, a ``set``, an arbitrary object) is rendered as one note,+ its ``repr()``. The flag is true only for a ``list`` or ``tuple`` of+ exact ``str`` objects, which renders as exactly the returned texts as+ long as reading ``__notes__`` again returns the same object; a+ ``__notes__`` property or ``__getattr__`` on the class is caught by+ :func:`_exception_text_is_stable` instead.+ Anything else (a ``UserList``, a note object, a non-sequence) is+ evaluated again when the traceback is rendered and may produce+ different text from what was checked, so the caller rebuilds the node+ with the checked texts. Raises when getting or iterating ``__notes__``+ raises.+ """+ notes = getattr(node, "__notes__", None)+ if notes is None:+ return [], True+ if isinstance(notes, collections.abc.Sequence) and not isinstance(+ notes, (str, bytes)+ ):+ items = list(notes)+ exact = _type_is_one_of(type(notes), (list, tuple)) and all(+ type(item) is str for item in items+ )+ return [_safe_log_str(item) for item in items], exact+ try:+ text = repr(notes)+ except Exception:+ text = None+ if not isinstance(text, str):+ text = _unprintable_placeholder(notes)+ return [text], False+++# Nodes visited per record when rebuilding an exception graph (causes,+# contexts and group members together); the rest become placeholders.+_LOG_EXCEPTION_NODE_BUDGET = 200++# Values whose ``str()`` and ``repr()`` are fixed by their type: an+# exception holding only these (in ``args`` or in a field its builtin base+# renders) renders the same text every time it is rendered.+_STABLE_TEXT_TYPES = (str, int, float, complex, bool, type(None), bytes)++# Attributes the sinks read or call on an exception they render: its text,+# chained exceptions and notes, and a group's message and members (the+# traceback module), its truth value (loguru's ``if exc_value:``, which+# calls ``__bool__`` or ``__len__``), ``__class__`` (the ``isinstance``+# group check falls back to it), a chained exception's ``__traceback__``,+# and the pickling hooks (an ``enqueue=True`` sink pickles the record,+# exception included, after rendering it and before the next sink renders+# it; ``BaseException.__reduce__`` calls neither ``__getstate__`` nor+# ``__getnewargs__``/``__getnewargs_ex__`` today, but a kept class defines+# no pickling hook at all). A non-builtin class anywhere in the exception+# type's MRO (a mixin listed after a builtin base included) that defines+# one of these (a+# ``__str__`` override, a ``__notes__`` or ``__cause__`` property, a+# ``__getattr__`` that supplies ``__notes__``, a ``__len__`` or+# ``__reduce_ex__`` that rewrites ``args``) can render, or make a later+# sink render, different text from what the redactor checked.+_RENDER_ATTRIBUTES = frozenset(+ {+ "__str__",+ "__getattribute__",+ "__getattr__",+ "args",+ "__notes__",+ "__cause__",+ "__context__",+ "__suppress_context__",+ "message",+ "exceptions",+ "__bool__",+ "__len__",+ "__class__",+ "__traceback__",+ "__reduce__",+ "__reduce_ex__",+ "__getstate__",+ "__getnewargs__",+ "__getnewargs_ex__",+ }+)++# Attributes read on the exception's *type*: the traceback module renders+# ``__qualname__`` and ``__module__``, pickling looks the class up by them,+# and the stability check itself reads ``__mro__`` and ``__dict__``. A+# non-builtin metaclass whose class dict holds anything under one of these+# names (a property, a function, a callable object that is not a+# descriptor) can run its code or make the attribute read something other+# than the type's own value -- an entry under ``__name__`` or+# ``__qualname__``, even a plain string, shadows the type's own. The one+# exception is a plain ``str`` under ``__module__``, which every class+# statement puts in a metaclass's dict: it is inert, because the class's+# own ``__module__`` entry is found first.+_METACLASS_RENDER_ATTRIBUTES = frozenset(+ {+ "__getattribute__",+ "__getattr__",+ "__name__",+ "__qualname__",+ "__module__",+ "__mro__",+ "__dict__",+ }+)++# ``type``'s own descriptors for the attributes above: reading through them+# returns the type's real MRO (the order attribute lookup uses), class dict+# and names, without running a metaclass's code.+_TYPE_MRO = vars(type)["__mro__"]+_TYPE_DICT = vars(type)["__dict__"]+_TYPE_NAME = vars(type)["__name__"]+_TYPE_QUALNAME = vars(type)["__qualname__"]+_TYPE_MODULE = vars(type)["__module__"]++# Fields a builtin exception renders besides ``args`` (in ``str()`` or in+# the traceback module's extra lines), by the builtin base that renders+# them. An exception that is an instance of the base must hold only+# :data:`_STABLE_TEXT_TYPES` there, and no non-builtin class in the+# exception type's MRO may redefine them. ``SyntaxError._metadata``+# (Python 3.13+) holds the source the traceback module's keyword-typo+# suggestion reads its replacement line from. ``AttributeError.obj`` is not+# listed: it feeds only the "Did you mean" suggestion, and an exception for+# which the traceback module would compute one is never kept (see+# :func:`_exception_text_is_stable`).+_RENDERED_FIELDS = (+ (OSError, ("errno", "strerror", "filename", "filename2")),+ (+ SyntaxError,+ (+ "msg",+ "filename",+ "lineno",+ "offset",+ "text",+ "end_lineno",+ "end_offset",+ "print_file_and_line",+ "_metadata",+ ),+ ),+ (UnicodeError, ("encoding", "object", "start", "end", "reason")),+ (ImportError, ("msg", "name", "path", "name_from")),+ (NameError, ("name",)),+ (AttributeError, ("name",)),+)+++# ``BaseException``'s ``__dict__`` descriptor: the instance dict, read+# without going through the instance's (possibly overridden) attribute+# lookup.+_BASE_EXCEPTION_DICT = vars(BaseException)["__dict__"]+++# Answers computed during the current decision phase of+# :func:`redact_log_exception` (``None`` outside one), by the check and the+# identity of what it was asked about (:func:`_once_per_phase`).+_DECISION_MEMO: contextvars.ContextVar = contextvars.ContextVar(+ "ldr_log_decision_memo", default=None+)+++def _once_per_phase(check: Any) -> Any:+ """*check*, answered once per decision phase for the same subjects.++ The checks wrapped with this (whether pickling a class runs code, a+ class's rendering hooks and names, the reducers registered for a type,+ ``sys.modules``'s keys) depend only on the class or object they are+ asked about and on global tables: class and metaclass dicts, MROs, the+ picklers' dispatch tables, ``sys.modules`` and module namespaces. A+ decision phase (:func:`_decision_phase`) runs no application code for+ exception classes that do not hook the machinery those checks read+ through, so nothing changes any of these between two nodes' checks+ (another thread could, which the threat model in the module docstring+ does not cover either way), and the first answer for a subject holds for+ the rest of the phase: a group of many members of one class pays for+ its class's checks once, not per member. The subjects are compared by+ identity (``id()``, so no ``__hash__`` or ``__eq__`` of theirs runs)+ and held by the memo, so an id cannot be reused while it lives. Outside+ a phase, every call computes its answer. A check that raises is not+ remembered.+ """++ @functools.wraps(check)+ def memoized(*subjects: Any) -> Any:+ memo = _DECISION_MEMO.get()+ if memo is None:+ return check(*subjects)+ key = (check, *map(id, subjects))+ entry = memo.get(key)+ if entry is None:+ entry = memo[key] = (subjects, check(*subjects))+ return entry[1]++ return memoized+++def _decision_phase():+ """Scope of one record's decisions, and of :func:`_once_per_phase`'s memo.++ Entered by :func:`redact_log_exception` only after every step that can+ run application code has run (the read phase,+ :func:`_plan_redacted_exception`), so an answer remembered in it cannot+ go stale through code the redaction itself runs.+ """+ token = _DECISION_MEMO.set({})+ try:+ yield+ finally:+ _DECISION_MEMO.reset(token)+++def _is_builtin_class(kind: Any) -> bool:+ """True when *kind* is the builtin class of that name (not a lookalike).++ The name is read through ``type``'s own descriptor, so a metaclass's+ ``__name__`` is never called.+ """+ try:+ name = _TYPE_NAME.__get__(kind)+ return type(name) is str and getattr(builtins, name, None) is kind+ except Exception:+ return False+++def _type_name(kind: Any, default: str = "object") -> str:+ """*kind*'s own ``__name__``, redacted; *default* if it is not a type.++ Read through ``type``'s descriptor (a metaclass's ``__name__`` property+ is never called, and cannot return one name now and another later) and+ redacted like exception text, since a class can be created under any+ name (``type("token=...", (Exception,), {})``). Used wherever the+ redactor writes a type's name into text a sink renders.+ """+ try:+ name = _exact_str(_TYPE_NAME.__get__(kind))+ return _redact_name_text(name)+ except Exception:+ return default+++# Longest name :func:`_redact_name_text` remembers; a longer one (a class+# can be created under any name) is redacted on every call.+_NAME_CACHE_MAX_LEN = 256+++def _redact_name_text(name: str) -> str:+ """:func:`_redact_exception_text` of the exact ``str`` *name*, remembered.++ Class, module and qualified names are redacted on every record that+ renders or keeps an exception, and the same few recur. Redaction is a+ function of the text alone (fixed patterns, no state), so a remembered+ result cannot go stale; names longer than :data:`_NAME_CACHE_MAX_LEN`+ are not remembered, which bounds the memory the cache holds.+ """+ if len(name) > _NAME_CACHE_MAX_LEN:+ return _redact_exception_text(name)+ return _redact_short_name(name)++[email protected]_cache(maxsize=1024)+def _redact_short_name(name: str) -> str:+ """:func:`_redact_exception_text` of *name* (:func:`_redact_name_text`)."""+ return _redact_exception_text(name)+++def type_name_for_log(kind: Any, default: str = "Exception") -> str:+ """Public form of :func:`_type_name` for sinks that print a type name.++ The DB sink's row prefix (``utilities.log_utils._exception_context``)+ names ``record["exception"].type``, which the patcher leaves as the+ original class unless :func:`_record_type_is_safe` rejects it; this+ reads and redacts that name the way the patcher's own rebuilt text does,+ so the two agree.+ """+ return _type_name(kind, default)+++def _rendered_block(header: str, notes: list) -> str:+ """The text a sink renders for one exception: its header line, then notes.++ ``TracebackException.format_exception_only`` writes the header line+ (``TypeName: text``, see :func:`_rendered_header_tails`) and then each+ note on lines of its own, so a credential label at the end of one and+ its value at the start of the next are adjacent text.+ """+ return "\n".join([header, *notes])+++def _syntax_error_header_text(node: Any, location: bool = True) -> str:+ """The text a ``SyntaxError``'s header line shows after ``TypeName: ``.++ ``TracebackException._format_syntax_error`` prints ``msg`` (or+ ``<no detail available>`` when it is empty), followed by `` (filename)``+ only when ``lineno`` is ``None`` and ``filename`` is not; the file and+ line number otherwise go on the ``File ...`` line above it. That is not+ ``str(node)``, which adds `` (basename, line N)``: a suffix the sinks do+ not print between ``msg`` and the notes on the following lines. On+ Python 3.13+ the keyword-typo suggestion can replace an ``invalid+ syntax`` message, or one mentioning a forgotten comma, with the fixed+ text ``invalid syntax. Did you mean 'kw'?`` (``kw`` a Python keyword).+ With *location* false, the `` (filename)`` suffix is left out.+ """+ msg = node.msg+ if msg is None or (_is_stable_text_value(msg) and not msg):+ text = "<no detail available>"+ else:+ text = _safe_log_str(msg)+ if location and node.lineno is None and node.filename is not None:+ text += f" ({_safe_log_str(node.filename)})"+ return text+++def _rendered_header_tails(node: Any, text: str) -> tuple:+ """What the traceback module prints after the type name for *node*.++ The header line is ``TypeName: text`` (``format_exception_only``), but+ only ``TypeName`` when *text* (the node's ``str()``) is empty. A+ ``SyntaxError`` (the class or a subclass, as the traceback module tests+ it) shows :func:`_syntax_error_header_text` instead of *text*; its form+ without the `` (filename)`` suffix is returned too, so that the suffix+ the sinks print between ``msg`` and the notes is not what keeps a label+ ending ``msg`` apart from its value in a note. The first item is the+ line the sinks print.+ """+ if issubclass(type(node), SyntaxError):+ return (+ f": {_syntax_error_header_text(node)}",+ f": {_syntax_error_header_text(node, location=False)}",+ )+ return (f": {text}" if text else "",)+++def _named_text(kind: Any, text: str) -> str:+ """``TypeName: text`` for a rebuilt node's text, redacted.++ Only ``TypeName`` when *text* is empty, as the traceback module renders+ an exception whose ``str()`` is empty: ``TypeName: `` would put text+ the original rendering did not have between the name and the notes on+ the following lines.+ """+ name = _type_name(kind)+ return _redact_exception_text(f"{name}: {text}" if text else name)+++def _type_header_changed(+ kind: Any, text: str, notes: list = (), tails: tuple = ()+) -> bool:+ """True when a sink's rendered ``TypeName: text`` block redacts differently.++ The traceback module renders ``qualname`` and the header line's rest+ (*tails*, :func:`_rendered_header_tails`), with ``module.`` in front+ outside ``__main__`` and ``builtins``, followed by the notes, one per+ line (:func:`_rendered_block`); the DB row renders ``name: text``. Each+ header form (:func:`_rendered_type_prefixes`) is checked with the notes+ after it.+ The name, the text and each note can be clean while the joined block is+ not: a credential pattern can span them (a class named+ ``InvalidAuthorization`` and the text ``abc123...`` render as an+ ``Authorization: abc123...`` header; a message ending in ``password=``+ and a note holding the value render as ``password=`` and the value on+ the next line). The names are read through ``type``'s own descriptors;+ a name that is not an exact ``str`` counts as a change.+ """+ prefixes = _rendered_type_prefixes(kind)+ if prefixes is None:+ return True+ tails = dict.fromkeys((f": {text}", *tails))+ for prefix in prefixes:+ for header_tail in tails:+ block = _rendered_block(prefix + header_tail, notes)+ if _redact_exception_text(block) != block:+ return True+ return False+++@_once_per_phase+def _rendered_type_prefixes(kind: Any) -> Optional[tuple]:+ """The forms of *kind*'s name a sink renders before ``: text``.++ ``name`` (the DB row), ``qualname``, and ``module.qualname`` (the+ traceback module, except for a class of ``builtins`` or ``__main__``,+ which it renders as ``qualname`` alone), without repeats; ``None`` when+ a name is not an exact ``str``. The names are read through ``type``'s+ own descriptors, so no metaclass code runs.+ """+ name = _TYPE_NAME.__get__(kind)+ qualname = _TYPE_QUALNAME.__get__(kind)+ module = _TYPE_MODULE.__get__(kind)+ if not all(type(part) is str for part in (name, qualname, module)):+ return None+ prefixes = [name, qualname]+ if module not in ("builtins", "__main__"):+ prefixes.append(f"{module}.{qualname}")+ return tuple(dict.fromkeys(prefixes))+++def _notes_fitting_header(header: str, notes: list) -> list:+ """*notes*, redacted together with *header* as the sinks render them.++ *header* is a rebuilt node's own clean header line (``TypeName: text``,+ see :func:`_rendered_header_tails`) and each note is clean on its own;+ a credential can still span a line break between them+ (:func:`_rendered_block`). When redacting the joined block+ changes it but leaves the header line as it is, the redacted rest is+ returned as one note (one note holding line breaks renders as the same+ lines as several notes). Otherwise a placeholder note is returned, or+ no notes when even that does not render cleanly after the header.+ """+ if not notes:+ return notes+ block = _rendered_block(header, notes)+ redacted = _redact_exception_text(block)+ if redacted == block:+ return notes+ start = header + "\n"+ if redacted.startswith(start):+ rest = [redacted[len(start) :]]+ block = _rendered_block(header, rest)+ if _redact_exception_text(block) == block:+ return rest+ placeholder = ["<exception notes omitted: they joined into a credential>"]+ block = _rendered_block(header, placeholder)+ if _redact_exception_text(block) == block:+ return placeholder+ return []+++def _record_type_is_safe(kind: Any) -> bool:+ """True when a record may keep *kind* as its exception's ``type``.++ An ``enqueue=True`` sink pickles the whole record before queueing it,+ and loguru's ``RecordException.__reduce__`` pickles ``type`` by+ reference outside the guard it puts around ``value``. A class pickle+ cannot find by its name (one defined inside a function, one made with+ ``type()``) makes the put raise, and loguru's error handler then writes+ ``str(record)`` and the pickling traceback to ``sys.stderr``; that+ traceback's ``__context__`` is the exception being logged, unredacted,+ with its whole chain. The repr of the type in ``str(record)`` shows its+ module and qualified name, so these must also be clean.++ Trying the pickle here (:func:`_pickles`) is not enough on its own: it+ runs once, and the sink pickles again later. So *kind* is kept only+ when pickling it by reference runs no code that could answer+ differently the second time (:func:`_pickled_by_reference_runs_no_code`,+ the check every exception kept in the rendered graph passes too), and+ only then is the pickle tried.+ """+ try:+ if not _pickled_by_reference_runs_no_code(kind):+ return False+ if not _type_names_are_clean(kind):+ return False+ qualname = _TYPE_QUALNAME.__get__(kind)+ module = _TYPE_MODULE.__get__(kind)+ text = "{}.{}".format(module, qualname)+ if _redact_name_text(text) != text:+ return False+ except Exception:+ return False+ return _pickles(kind)+++@_once_per_phase+def _type_names_are_clean(kind: Any) -> bool:+ """True when *kind*'s names are exact ``str`` that redaction leaves as is.++ The names are ``__name__``, ``__qualname__`` and ``__module__``, read+ through ``type``'s own descriptors, so no metaclass code runs.+ """+ for read in (_TYPE_NAME, _TYPE_QUALNAME, _TYPE_MODULE):+ text = read.__get__(kind)+ if type(text) is not str or _redact_name_text(text) != text:+ return False+ return True+++# Type attributes pickling a class, or an instance of it, reads or calls:+# the class's ``__module__``, ``__qualname__`` and ``__name__`` (looked up+# with ``getattr``, so through the metaclass's ``__getattribute__``,+# ``__getattr__`` and data descriptors); for a class nested in another+# (``Outer.Inner``), the ``__get__`` that ``getattr(Outer, "Inner")`` calls+# when ``Inner``'s metaclass defines one; ``__hash__`` and ``__eq__``, with+# which the pickler's dispatch-table lookup of an instance's class hashes+# and compares it; and ``__reduce__`` (and ``__reduce_ex__``), which+# ``object.__reduce_ex__`` reads on the instance's class to see whether it+# is overridden.+_PICKLE_METACLASS_ATTRIBUTES = _METACLASS_RENDER_ATTRIBUTES | {+ "__get__",+ "__hash__",+ "__eq__",+ "__reduce__",+ "__reduce_ex__",+}+++@_once_per_phase+def _pickled_by_reference_runs_no_code(kind: Any) -> bool:+ """True when pickling *kind*, or an instance of it, runs none of its code.++ An ``enqueue=True`` sink pickles the record's ``type`` and, through+ loguru's ``RecordException.__reduce__`` (``pickle.dumps(value)``), the+ exception and everything its ``args`` and instance dict hold (a group's+ members, through its ``args``), after that sink rendered the record and+ before the next sink renders it. Pickling an object of class *kind*+ looks *kind* up in the picklers' dispatch tables and saves it by module+ and qualified name; code run on the way (a metaclass hook, a reducer+ registered for *kind*, an enclosing class's metaclass, the module's+ ``__spec__``) could change what a later sink renders, or succeed in a+ trial pickle and fail in the sink's. So every exception kept in the+ rendered graph (:func:`_exception_text_is_stable`), and the record's+ ``type`` (:func:`_record_type_is_safe`), must pass this one check:++ * *kind* is a class whose metaclass's own metaclass is ``type`` (which+ hashes and dispatches the metaclass when *kind* itself is pickled);+ * no non-builtin metaclass of *kind* defines+ :data:`_PICKLE_METACLASS_ATTRIBUTES` (:func:`_metaclass_is_inert`;+ a ``__module__`` property, say, that names the real module on the+ first read and another on the next);+ * no reducer is registered for *kind* or its metaclass+ (:func:`_has_registered_reducer`); and+ * pickle's lookup of *kind* by its module and qualified name runs no+ code (:func:`_pickle_lookup_runs_no_code`): it finds *kind*, or+ pickle refuses a class defined in a function before looking it up+ (that pickle then fails, which loguru's ``__reduce__`` guards for a+ value, and :func:`_record_type_is_safe` rejects for the ``type``).++ The instance side (the exception's own ``__reduce_ex__``, ``args`` and+ instance dict) is checked by :func:`_exception_text_is_stable`.+ Everything is read through the builtin descriptors, so this check runs+ no code of *kind*'s either.+ """+ if not issubclass(type(kind), type):+ return False+ meta = type(kind)+ if type(meta) is not type:+ return False+ if not _metaclass_is_inert(kind, _PICKLE_METACLASS_ATTRIBUTES):+ return False+ if _has_registered_reducer(kind) or _has_registered_reducer(meta):+ return False+ qualname = _TYPE_QUALNAME.__get__(kind)+ module = _TYPE_MODULE.__get__(kind)+ if type(qualname) is not str or type(module) is not str:+ return False+ return _pickle_lookup_runs_no_code(kind, module, qualname)+++# The reducer ``copyreg`` registers for ``complex``: the only stock entry+# for a type :func:`_is_plain_data` and :func:`_is_stable_text_value`+# accept (the pickler saves the others without consulting the tables).+_STOCK_COMPLEX_REDUCER = getattr(copyreg, "pickle_complex", None)++# Metaclass attributes a dict lookup runs on a key it compares.+_DICT_KEY_ATTRIBUTES = frozenset({"__hash__", "__eq__"})+++@_once_per_phase+def _has_registered_reducer(kind: Any, stock: Any = None) -> bool:+ """True when a pickler may call a reducer other than *stock* for *kind*.++ ``pickle.dumps`` (which loguru pickles an exception with) looks the+ exact class of every object it saves, other than its builtin fast-path+ types (``str``, ``int``, ``list`` ...), up in ``copyreg.dispatch_table``,+ and the ``ForkingPickler`` the queue uses looks it up there and in its+ own ``_extra_reducers``; a reducer found there runs. A table that is not+ an exact ``dict``, or a key that is not a class whose metaclasses leave+ ``__hash__`` and ``__eq__`` alone (one that could claim to equal *kind*+ and run its own code while the lookup compares it), counts as a+ reducer too. Keys are compared by identity, so nothing here runs code.+ """+ try:+ # What ``_metaclass_is_inert`` answers for every key whose metaclass+ # is ``type`` itself, the usual case (see its fast path).+ plain_classes_inert = _plain_metaclass_is_builtin()+ tables = (+ copyreg.dispatch_table,+ ForkingPickler._copyreg_dispatch_table,+ ForkingPickler._extra_reducers,+ )+ for table in tables:+ if type(table) is not dict:+ return True+ for key, reducer in dict.items(table):+ if key is kind:+ if reducer is not stock:+ return True+ elif type(key) is type:+ # A plain class: ``_metaclass_is_inert``'s fast path.+ if not plain_classes_inert:+ if not _metaclass_is_inert(key, _DICT_KEY_ATTRIBUTES):+ return True+ elif not (+ issubclass(type(key), type)+ and _metaclass_is_inert(key, _DICT_KEY_ATTRIBUTES)+ ):+ return True+ except Exception:+ return True+ return False+++def _pickle_lookup_runs_no_code(kind: Any, module: str, qualname: str) -> bool:+ """True when pickle's lookup of *kind* by name runs no code.++ That is, pickle refuses the name before looking anything up (a class+ defined in a function, whose qualified name has a ``<locals>`` part),+ or it finds *kind* and runs no code on the way. Pickle saves a class as+ its module and qualified name: it imports the module+ (:func:`_module_import_runs_no_code`) and checks that following the+ name (``getattr`` for each part of ``qualname``) gives back the class. Each ``getattr`` runs the code of the object it is called on: a+ module that is an instance of a ``ModuleType`` subclass, or an+ enclosing class whose metaclass defines ``__getattribute__``,+ ``__getattr__``, ``__get__`` or an attribute of the part's name, could+ find *kind* when :func:`_pickles` tries it and fail when the+ ``enqueue=True`` sink pickles it, or change what a later sink renders.+ So the module must already be in ``sys.modules`` as an exact+ ``ModuleType``, each part must be found as the attribute lookup finds it+ (no entry of that name in the lookup object's type's MRO, then the+ module's dict or the first dict of the enclosing class's MRO holding+ the name), through dicts whose keys are all exact ``str`` (a key of+ another type could compare equal to the part by running its own code),+ each enclosing class's metaclasses must be inert+ (:func:`_metaclass_is_inert`), and the last part must be *kind* itself.+ Everything is read through the builtin descriptors, so nothing here runs+ code either.+ """+ parts = qualname.split(".")+ if "<locals>" in parts:+ # Pickle refuses a class defined in a function by its qualified+ # name alone, before it imports or looks anything up: no code runs+ # (and the pickle fails, which :func:`_pickles` reports).+ return True+ if not _module_import_runs_no_code(module):+ return False+ owner = sys.modules.get(module)+ if type(owner) is not types.ModuleType:+ return False+ for index, part in enumerate(parts):+ if index and not (+ issubclass(type(owner), type)+ and _metaclass_is_inert(owner, _PICKLE_METACLASS_ATTRIBUTES)+ ):+ return False+ # Any entry under ``part`` in the type of ``owner`` (the module+ # type, or the enclosing class's metaclass) is found before+ # ``owner``'s own: a data descriptor there wins.+ for cls in _TYPE_MRO.__get__(type(owner)):+ namespace = _TYPE_DICT.__get__(cls)+ if not _plain_names(namespace) or part in namespace:+ return False+ if index:+ namespaces = [+ _TYPE_DICT.__get__(cls) for cls in _TYPE_MRO.__get__(owner)+ ]+ else:+ namespaces = [_MODULE_DICT.__get__(owner)]+ for namespace in namespaces:+ if not _plain_names(namespace):+ return False+ if part in namespace:+ owner = namespace[part]+ break+ else:+ return False+ return owner is kind+++# ``ModuleType``'s ``__dict__`` descriptor: a module's own namespace.+_MODULE_DICT = vars(types.ModuleType)["__dict__"]++# ``ModuleSpec``'s ``__dict__`` descriptor: a spec's instance attributes.+_MODULE_SPEC_DICT = vars(ModuleSpec)["__dict__"]++# Attributes the import system reads on a module's ``__spec__``.+_MODULE_SPEC_ATTRIBUTES = frozenset(+ {"_initializing", "__getattribute__", "__getattr__"}+)+++def _module_spec_read_is_plain(kind: Any) -> bool:+ """True when reading ``__spec__`` on a module of class *kind* runs no code.++ *kind* is ``ModuleType`` or a subclass whose own classes (other than+ ``ModuleType`` and ``object``) define neither ``__getattribute__`` nor+ an entry named ``__spec__``, so the read finds the module's own+ ``__spec__`` entry through ``ModuleType``'s lookup.+ """+ if not issubclass(kind, types.ModuleType):+ return False+ for cls in _TYPE_MRO.__get__(kind):+ if cls is types.ModuleType or cls is object:+ continue+ namespace = _TYPE_DICT.__get__(cls)+ if not _plain_names(namespace):+ return False+ if "__getattribute__" in namespace or "__spec__" in namespace:+ return False+ return True+++@_once_per_phase+def _sys_modules_names_are_plain(modules: dict) -> bool:+ """:func:`_plain_names` of *modules* (``sys.modules``), once per record.++ :func:`_module_import_runs_no_code` runs for every class kept in the+ rendered graph, and ``sys.modules`` holds thousands of entries in the+ web process, so scanning it for each one made a large exception group+ cost tens of milliseconds on the logging thread. Inside a decision+ phase it is scanned once (:func:`_once_per_phase`); it is scanned again+ if ``sys.modules`` is no longer the dict that was scanned.+ """+ return _plain_names(modules)+++def _module_import_runs_no_code(module: str) -> bool:+ """True when pickle's import of the imported module *module* runs no code.++ Pickle imports the module of every class it saves by reference. For a+ module already in ``sys.modules`` the import system still reads the+ module's ``__spec__`` and that spec's ``_initializing`` flag (and its+ truth value), and for a dotted name it does the same for the top-level+ package: a ``__spec__`` object with its own ``__getattr__`` or an+ ``_initializing`` property, or a module without ``__spec__`` whose+ ``__getattr__`` then supplies one, runs code there. So each of those+ modules must be in ``sys.modules`` (whose keys must all be exact+ ``str``) as a module whose class reads ``__spec__`` from its namespace+ (:func:`_module_spec_read_is_plain`; a lazy-loading ``ModuleType``+ subclass with only a ``__getattr__`` for missing names does), and that+ namespace (exact ``str`` keys only) must hold ``__spec__`` as ``None``+ or an exact ``ModuleSpec`` whose class leaves those attributes alone+ and whose ``_initializing``, if set, is an exact ``bool``. The module+ a class is then looked up in must also be an exact ``ModuleType``+ (:func:`_pickle_lookup_runs_no_code`). ``sys.modules``'s keys are+ scanned once per record, not once per call+ (:func:`_sys_modules_names_are_plain`).+ """+ modules = sys.modules+ if type(modules) is not dict or not _sys_modules_names_are_plain(modules):+ return False+ for name in {module, module.partition(".")[0]}:+ owner = modules.get(name)+ if not _module_spec_read_is_plain(type(owner)):+ return False+ namespace = _MODULE_DICT.__get__(owner)+ if not _plain_names(namespace) or "__spec__" not in namespace:+ return False+ spec = namespace["__spec__"]+ if spec is None:+ continue+ if type(spec) is not ModuleSpec:+ return False+ for cls in _TYPE_MRO.__get__(ModuleSpec):+ if _MODULE_SPEC_ATTRIBUTES.intersection(_TYPE_DICT.__get__(cls)):+ # ``object`` defines ``__getattribute__``: builtin.+ if not _is_builtin_class(cls):+ return False+ state = _MODULE_SPEC_DICT.__get__(spec)+ # An exact ``dict``: a subclass's ``__iter__``, ``__contains__`` or+ # ``__getitem__`` would run here.+ if type(state) is not dict or not _plain_names(state):+ return False+ if (+ "_initializing" in state+ and type(state["_initializing"]) is not bool+ ):+ return False+ return True+++def _picklable_extra(extra: Any) -> Any:+ """*extra*, with every value that is not plain data replaced.++ An ``enqueue=True`` sink pickles the whole record before queueing it.+ One value it cannot pickle (a lock, an open file, an instance of a class+ defined in a function) makes the put raise, and loguru's error handler+ then writes ``str(record)`` and the pickling traceback to+ ``sys.stderr``; that traceback's ``__context__`` is the exception being+ handled when the log call was made (whether or not the call logged it),+ unredacted. Trying the pickle here would not settle it: an object's own+ pickling code (``__reduce_ex__``, ``__getstate__``) can succeed now and+ raise when the sink pickles it. So every value that is not plain data+ (:func:`_is_plain_data`: an exact ``str``, ``int``, ``float``,+ ``complex`` (while ``copyreg``'s own reducer pickles it), ``bool``,+ ``None``, ``bytes`` or ``bytearray``, or an exact ``list``, ``tuple``,+ ``dict``, ``set`` or ``frozenset`` of plain data),+ whose pickling runs builtin code only, is replaced, for every sink, by+ ``<unpicklable TypeName>``. If a key is not plain data, only the routing+ keys (:data:`_LOG_STRUCTURAL_EXTRA_KEYS`) are kept, and ``{}`` if their+ values are not plain data either.+ """+ if _is_plain_data(extra):+ return extra+ try:+ out = {+ key: value+ if _is_plain_data(value)+ else f"<unpicklable {_type_name(type(value))}>"+ for key, value in dict.items(extra)+ }+ except Exception:+ out = None+ if out is None or not _is_plain_data(out):+ out = _structural_extra_only(extra)+ return out if _is_plain_data(out) else {}+++# How deep :func:`_is_plain_data` follows nested containers; a deeper one is+# not counted as plain data. ``redact_log_extra`` already replaces a+# container nested :data:`_LOG_EXTRA_MAX_DEPTH` deep, except under a+# routing key, which it passes through as is.+_PLAIN_DATA_MAX_DEPTH = _LOG_EXTRA_MAX_DEPTH + 2++_PLAIN_DATA_SCALARS = (+ str,+ int,+ float,+ complex,+ bool,+ type(None),+ bytes,+ bytearray,+)+_PLAIN_DATA_CONTAINERS = (list, tuple, set, frozenset)+++def _is_plain_data(value: Any, _depth: int = 0, _seen: Any = None) -> bool:+ """True when pickling *value* runs builtin code only.++ *value* is an instance of exactly one of :data:`_PLAIN_DATA_SCALARS`, or+ an exact ``list``, ``tuple``, ``set``, ``frozenset`` or ``dict`` whose+ items (keys and values) are plain data, nested at most+ :data:`_PLAIN_DATA_MAX_DEPTH` deep (a ``complex`` only while+ :func:`_complex_pickles_as_stock`). Types are compared by identity+ (:func:`_type_is_one_of`), so no subclass and no metaclass ``__eq__``+ counts, and nothing here runs code of *value*'s own. A container that+ contains itself is not counted as plain data; one reached again by+ another path is checked once (so shared sub-containers cost linear,+ not exponential, time).+ """+ kind = type(value)+ if _type_is_one_of(kind, _PLAIN_DATA_SCALARS):+ return kind is not complex or _complex_pickles_as_stock()+ if _depth >= _PLAIN_DATA_MAX_DEPTH:+ return False+ if kind is not dict and not _type_is_one_of(kind, _PLAIN_DATA_CONTAINERS):+ return False+ if _seen is None:+ _seen = {}+ marker = id(value)+ if marker in _seen:+ # ``False`` while it is still being checked: a cycle.+ return _seen[marker]+ _seen[marker] = False+ if kind is dict:+ result = all(+ _is_plain_data(key, _depth + 1, _seen)+ and _is_plain_data(item, _depth + 1, _seen)+ for key, item in dict.items(value)+ )+ else:+ result = all(_is_plain_data(item, _depth + 1, _seen) for item in value)+ _seen[marker] = result+ return result+++def _complex_pickles_as_stock() -> bool:+ """True when pickling a ``complex`` calls ``copyreg``'s own reducer only.++ The pickler saves ``str``, ``int``, ``float``, ``bool``, ``None``,+ ``bytes``, ``bytearray`` and the exact builtin containers itself, but+ looks ``complex`` up in its dispatch tables, where a reducer registered+ in place of ``copyreg``'s would run (:func:`_has_registered_reducer`).+ """+ return _STOCK_COMPLEX_REDUCER is not None and not _has_registered_reducer(+ complex, _STOCK_COMPLEX_REDUCER+ )+++def _pickles(obj: Any) -> bool:+ """True when *obj* pickles the way an ``enqueue=True`` sink pickles it.++ loguru queues the record with ``multiprocessing.SimpleQueue.put``, which+ serializes with :class:`multiprocessing.reduction.ForkingPickler`. That+ pickler has its own reducers on top of :mod:`pickle`'s (registered, for+ example, for a ``ctypes`` type once ``multiprocessing.sharedctypes`` has+ created a value of it), so ``pickle.dumps`` succeeding does not mean+ the put will.+ """+ try:+ ForkingPickler.dumps(obj)+ except Exception:+ return False+ return True+++def _is_stable_text_value(value: Any, _depth: int = 0) -> bool:+ """True when *value* renders the same text every time.++ An exact :data:`_STABLE_TEXT_TYPES` instance, or a ``tuple`` or+ ``frozenset`` (exact types) of such values. A subclass of ``str`` or+ ``int``, or any other object, may render differently on each call. A+ ``complex`` counts only while the reducer pickle calls for it is+ ``copyreg``'s own (:func:`_complex_pickles_as_stock`): it is the one+ such type the pickler dispatches through ``copyreg.dispatch_table``.+ """+ kind = type(value)+ if _type_is_one_of(kind, _STABLE_TEXT_TYPES):+ return kind is not complex or _complex_pickles_as_stock()+ if _type_is_one_of(kind, (tuple, frozenset)) and _depth < 4:+ return all(_is_stable_text_value(item, _depth + 1) for item in value)+ return False+++def _plain_names(namespace: Any) -> bool:+ """True when every key of the class dict *namespace* is an exact ``str``.++ ``type(name) is str`` for every key, run in C (``map`` and+ ``operator.is_``) rather than as a generator: ``sys.modules`` is checked+ once per record and holds thousands of keys in the web process.+ """+ return all(map(operator.is_, map(type, namespace), itertools.repeat(str)))+++def _plain_metaclass_is_builtin() -> bool:+ """True when :func:`_is_builtin_class` holds for ``type`` and ``object``.++ They are the whole MRO of ``type``, the metaclass of a class statement+ without one, so :func:`_metaclass_is_inert` holds for every class whose+ metaclass is exactly ``type`` (it skips builtin classes).+ """+ return (+ getattr(builtins, "type", None) is type+ and getattr(builtins, "object", None) is object+ )+++def _metaclass_is_inert(kind: Any, attributes: frozenset) -> bool:+ """True when no non-builtin metaclass of *kind* defines *attributes*.++ Every metaclass in ``type(kind)``'s MRO that is not a builtin class must+ have a class dict whose keys are all exact ``str`` (a subclass with its+ own ``__hash__``/``__eq__`` could hide from the check) and that holds+ none of *attributes* -- except a plain ``str`` under ``__module__``,+ which every class statement puts in a metaclass's dict and which is+ inert, because the class's own ``__module__`` entry is found first. The+ MRO and class dicts are read through ``type``'s own descriptors, so no+ metaclass code runs here.+ """+ if type(kind) is type and _plain_metaclass_is_builtin():+ # The common case, answered without the loop: ``type``'s MRO is+ # ``type`` and ``object``, both builtin, so the loop skips both.+ return True+ for meta in _TYPE_MRO.__get__(type(kind)):+ if _is_builtin_class(meta):+ continue+ namespace = _TYPE_DICT.__get__(meta)+ if not _plain_names(namespace):+ return False+ for name in attributes.intersection(namespace):+ if name == "__module__" and type(namespace[name]) is str:+ continue+ return False+ return True+++def _group_args_are_its_members(node: Any) -> bool:+ """True when an exception group's ``args`` are its message and members.++ An ``enqueue=True`` sink pickles a group through its ``args`` (the+ message and the container it was built from), not its ``exceptions``,+ after that sink rendered it and before the next sink renders it. The+ container is the caller's own object: a ``list`` subclass whose+ ``__reduce_ex__`` rewrites a member's ``args`` would change the text+ the later sinks render, and a list appended to after the group was+ built would pickle objects never checked. So ``args`` must be an exact+ 2-tuple of the message (an exact ``str`` equal to ``message``) and an+ exact ``list`` or ``tuple`` holding exactly the group's members, the+ same objects in the same order; the members themselves are checked as+ nodes of their own.+ """+ args = node.args+ if type(args) is not tuple or len(args) != 2:+ return False+ message, members = args+ if type(message) is not str or message != _exact_str(node.message):+ return False+ if not _type_is_one_of(type(members), (list, tuple)):+ return False+ exceptions = node.exceptions+ return len(members) == len(exceptions) and all(+ member is exception for member, exception in zip(members, exceptions)+ )+++def _exception_text_is_stable(node: Any, is_group: bool) -> bool:+ """True when rendering *node* again yields exactly the text checked.++ The redactor reads an exception's text once and keeps the original+ object only when that text was clean, but the sinks render the object+ again (loguru's ``format_exception_only``, the DB row's ``str()``) and+ run its code while doing so. Keeping it is safe only when no code the+ exception's own classes define runs then, and the values the builtin+ rendering reads cannot render other text. That holds when:++ * every non-builtin class in ``type(node).__mro__`` (including a mixin+ listed after a builtin base) leaves the rendering attributes alone+ (:data:`_RENDER_ATTRIBUTES` and the base's :data:`_RENDERED_FIELDS`);+ * the type is one that pickling by reference runs no code of+ (:func:`_pickled_by_reference_runs_no_code`, the check the record's+ ``type`` passes too): an ``enqueue=True`` sink pickles every kept+ node an exception's ``args`` reach (a group's members) after it+ rendered the record and before the next sink renders it, and the+ check is applied to every kept node, so one node can be kept or+ rebuilt only one way wherever it appears in the graph. Among other+ things, no non-builtin metaclass of the type defines the type+ attributes the sinks, the pickler and this check read+ (:data:`_PICKLE_METACLASS_ATTRIBUTES`, which include+ :data:`_METACLASS_RENDER_ATTRIBUTES`; the MRO, class dicts and names+ are read here through ``type``'s own descriptors, so a metaclass+ cannot hide a class or override from this check), and no class or+ module pickle looks it up through runs code;+ * the type's own ``__name__``, ``__qualname__`` and ``__module__``+ (which the traceback module and the DB row render) are plain ``str``+ that redaction leaves unchanged;+ * the values the builtin rendering reads (``args``, a group's+ ``message``, the base's fields) and the instance attributes an+ ``enqueue=True`` sink pickles are of :data:`_STABLE_TEXT_TYPES`+ (``__notes__`` aside, which the caller checks), and a group's+ ``args``, which that sink pickles in place of its ``exceptions``,+ hold nothing but its message and a plain container of exactly its+ members (:func:`_group_args_are_its_members`); and+ * the traceback module computes no "Did you mean" suggestion for it (an+ ``AttributeError`` or ``NameError`` with a ``str`` ``name``, an+ ``ImportError`` with a ``str`` ``name_from``): that runs code of+ other objects -- ``obj.__dir__()``, importing the named module and+ calling its ``__dir__``, and, for a renderer that passes the+ traceback (loguru does not), ``hasattr`` on the failing frame's+ ``self`` -- which can change the exception after its text was+ checked. A rebuilt node has no ``name``, so its traceback shows no+ suggestion.++ Otherwise (a ``__str__`` that returns benign text first and a secret+ later, a ``__notes__`` property, a ``__len__`` that rewrites ``args``,+ an argument object with its own ``__str__``, a class nested in one+ whose metaclass hooks attribute lookup) the caller rebuilds the node+ from the text it checked. Code that changes the exception from outside+ its rendering and pickling is not covered: another thread; the class's+ own construction code (``__init__``, ``__new__``, ``__setattr__``, a+ metaclass ``__call__``), which runs when an ``enqueue=True`` sink+ unpickles its own copy in its writer thread; a reducer registered for+ a builtin exception type, which also runs for the rebuilt nodes; and+ patches to the pickling or import machinery itself. Nor is a class or+ object written to defeat this check (see the module docstring's threat+ model): the reads here are made through builtin descriptors and exact+ type tests (an instance ``__dict__`` must be an exact ``dict``, a+ ``name`` an exact ``str``) as defence in depth, not as a guarantee.+ """+ kind = type(node)+ # Everything that depends on the class alone, checked once per class in+ # a decision phase.+ if not _exception_class_is_stable(kind):+ return False+ # ``type(...) is str``, not ``isinstance``: the latter falls back to a+ # non-``str`` value's ``__class__``, which runs its code. Any value+ # other than an exact ``str`` or ``None`` fails the field check below.+ if issubclass(kind, ImportError):+ if type(getattr(node, "name_from", None)) is str:+ return False+ if issubclass(kind, (NameError, AttributeError)):+ if type(getattr(node, "name", None)) is str:+ return False+ # Read through ``BaseException``'s own descriptor: the attribute lookup+ # is guarded (:func:`_exception_class_is_stable`), and this is the dict+ # pickling copies. It must be an exact ``dict``+ # (``exc.__dict__ = SomeDictSubclass()`` is accepted), read with+ # ``dict``'s own methods, so no ``__len__`` or ``items`` of the node's+ # runs here or in the pickler.+ state = _BASE_EXCEPTION_DICT.__get__(node)+ if type(state) is not dict:+ return False+ if state:+ for name, value in dict.items(state):+ if type(name) is not str:+ return False+ if name != "__notes__" and not _is_stable_text_value(value):+ return False+ if is_group:+ if type(node.message) is not str:+ return False+ if not _group_args_are_its_members(node):+ return False+ elif not _is_stable_text_value(node.args):+ return False+ return all(+ _is_stable_text_value(getattr(node, name, None))+ for name in _rendered_fields(kind)+ )+++def _rendered_fields(kind: Any) -> list:+ """The :data:`_RENDERED_FIELDS` of the builtin bases *kind* derives from."""+ # ``issubclass`` on the type, not ``isinstance`` on the node: the latter+ # falls back to the node's ``__class__``, which runs its code.+ return [+ name+ for base, names in _RENDERED_FIELDS+ if issubclass(kind, base)+ for name in names+ ]+++@_once_per_phase+def _exception_class_is_stable(kind: Any) -> bool:+ """The class-level conditions of :func:`_exception_text_is_stable`.++ No non-builtin class in *kind*'s MRO defines a rendering attribute,+ pickling *kind* by reference runs no code, and its names are clean.+ These depend on the class alone, so a decision phase checks them once+ per class (:func:`_once_per_phase`).+ """+ guarded = _RENDER_ATTRIBUTES.union(_rendered_fields(kind))+ # Every non-builtin class in the MRO counts, not only those before the+ # first builtin: in ``class E(ValueError, Mixin)`` the order is E,+ # ValueError, Exception, BaseException, Mixin, object, and the builtins+ # do not define ``__str__``, ``__notes__``, ``__getattr__`` or+ # ``__getattribute__`` themselves, so Python still finds Mixin's.+ # The MRO and class dicts are read through ``type``'s own descriptors:+ # ``kind.__mro__`` and ``vars(cls)`` go through the metaclass, which+ # could report builtin bases only, or an empty dict.+ # A class dict key that is not an exact ``str`` (a subclass with its+ # own ``__hash__``/``__eq__``) could hide from the name checks.+ for cls in _TYPE_MRO.__get__(kind):+ if _is_builtin_class(cls):+ continue+ namespace = _TYPE_DICT.__get__(cls)+ if not _plain_names(namespace) or guarded.intersection(namespace):+ return False+ # The sinks read the type's names and an ``enqueue=True`` sink pickles+ # the kept node, so its class must be one that rendering and pickling+ # by reference run no code of (a superset of the metaclass attributes+ # rendering alone reads).+ if not _pickled_by_reference_runs_no_code(kind):+ return False+ return _type_names_are_clean(kind)+++# A ``SyntaxError``'s fields the interpreter fills, by the exact type it+# fills them with (or ``None``). Only a node whose fields all have these+# types is kept; anything else (a ``str`` line number, ``bytes`` source+# text, a ``str`` offset) is rendered differently by each Python version's+# traceback module, and on Python 3.12 a ``bytes`` text or non-``int``+# offset makes it raise, so loguru's error handler prints the context of+# that error -- the exception being handled -- unredacted to stderr. The+# ``int`` fields must also be in the accepted ranges+# (:func:`_syntax_error_fields_out_of_range`).+_SYNTAX_ERROR_FIELD_TYPES = (+ ("msg", str),+ ("filename", str),+ ("text", str),+ ("lineno", int),+ ("offset", int),+ ("end_lineno", int),+ ("end_offset", int),+)++# The largest line number a kept ``SyntaxError`` may carry: the interpreter+# fills ``lineno`` and ``end_lineno`` from a C ``int``. A larger one is not+# an interpreter value, and one past ``sys.get_int_max_str_digits()`` digits+# makes the ``File ...`` line raise ``ValueError`` when it is printed.+_SYNTAX_ERROR_MAX_LINENO = 2**31 - 1++# How far past the UTF-8 length of ``text`` (plus one) a kept+# ``SyntaxError``'s ``offset`` and ``end_offset`` may run, in columns. The+# interpreter counts columns in UTF-8 bytes of the reported line, not in+# characters: the tokenizer passes raw byte offsets, and the compiler and+# symtable stages (errors raised when a file is compiled or imported) report+# byte offsets too. Those stages also report the ``end_offset`` of a span+# that ends on a later line as a column of that later line, which ``text``+# does not hold and which can be longer than it. This slack covers such a+# later line of up to this many bytes; a span ending further right than that+# is not kept (the caller rebuilds the node). It also bounds the caret line+# Python 3.12 draws (``'^' * (end_offset - offset)``), so a value like+# ``10**9`` is rejected before anything is rendered+# (:func:`_syntax_error_fields_out_of_range`).+_SYNTAX_ERROR_SPAN_END_SLACK = 2**16++# How much longer than the text it prints verbatim (``msg``, ``filename``+# and ``text``, each counted three times) plus its caret line (at most its+# largest offset, when ``text`` is a ``str``) a kept ``SyntaxError``'s+# rendering may be, in characters. On Python 3.13+ the keyword-typo+# suggestion may replace ``msg`` and the source line with ones from at most+# 1024 characters of source. Anything longer is not a rendering of these+# fields, and the caller rebuilds the node+# (:func:`_syntax_error_renders_bounded`).+_SYNTAX_ERROR_RENDER_SLACK = 4096+++def _syntax_error_fields_out_of_range(node: Any) -> bool:+ """True when a ``SyntaxError``'s ``int`` fields are not interpreter values.++ Called only for fields of the canonical types+ (:data:`_SYNTAX_ERROR_FIELD_TYPES`) and a ``text`` of at most+ ``_LOG_REDACTION_MAX_CHARS`` characters, so encoding it is bounded. The traceback module does+ arithmetic on the offsets to draw the caret line (``'^' * (end - start)``+ on Python 3.12, and on 3.14 too when ``text`` is empty), so an offset+ near ``2**63`` makes it raise ``OverflowError`` or ``MemoryError``, and a+ moderate one (``10**9``) makes every sink build a caret line that long.+ Loguru's error handler then prints the context of that error -- the+ exception being handled -- unredacted to stderr. The interpreter+ reports ``lineno`` and ``end_lineno`` between ``0`` and+ :data:`_SYNTAX_ERROR_MAX_LINENO`. It reports ``offset`` and+ ``end_offset`` as ``-1`` (unknown) or as columns counted in+ UTF-8 bytes, not characters, so on a line with non-ASCII text they can+ exceed ``len(text) + 1``; and for an error raised when a file is+ compiled or imported, an ``end_offset`` on a later line than+ ``lineno`` is a column of that later line, not of ``text``. The+ accepted range is therefore ``-1`` to the UTF-8 length of ``text``+ plus ``1`` plus :data:`_SYNTAX_ERROR_SPAN_END_SLACK`, or up to+ :data:`_SYNTAX_ERROR_MAX_LINENO` when ``text`` is ``None`` (the offsets+ are then not drawn). Anything outside these ranges makes the caller+ rebuild the node, which drops these fields; that includes a real error+ whose span ends more than :data:`_SYNTAX_ERROR_SPAN_END_SLACK` bytes+ into a later line.+ """+ for value in (node.lineno, node.end_lineno):+ if value is not None and not 0 <= value <= _SYNTAX_ERROR_MAX_LINENO:+ return True+ limit = (+ _SYNTAX_ERROR_MAX_LINENO+ if node.text is None+ else len(node.text.encode("utf-8", "surrogatepass"))+ + 1+ + _SYNTAX_ERROR_SPAN_END_SLACK+ )+ for value in (node.offset, node.end_offset):+ if value is not None and not -1 <= value <= limit:+ return True+ return False+++def _syntax_error_renders_bounded(node: Any) -> bool:+ """True when the traceback module renders *node*'s lines within bounds.++ Runs ``traceback.format_exception_only`` -- what loguru's formatter+ calls -- on a detached builtin ``SyntaxError`` carrying *node*'s+ rendered fields (``msg``, ``filename``, ``lineno``, ``offset``,+ ``text``, ``end_lineno``, ``end_offset`` and ``_metadata``), not on+ *node* itself, so no chained exception is formatted and no frame's+ source is read. Called only for a node that is about to be kept, whose+ fields have passed :func:`_syntax_error_details_changed` (canonical+ types, in range, and a keyword-typo source that is an exact ``str``, so+ the rendering reads no file). False when that rendering raises+ (``OverflowError``, ``MemoryError``, ``ValueError`` or any other+ ``Exception`` a sink would hit, whose error handler prints the+ exception being handled unredacted) or is longer than+ :data:`_SYNTAX_ERROR_RENDER_SLACK` allows; the caller then rebuilds the+ node. ``KeyboardInterrupt`` and ``SystemExit`` propagate.+ """+ import traceback++ try:+ probe = SyntaxError()+ verbatim = 0+ for name, _kind in _SYNTAX_ERROR_FIELD_TYPES:+ value = getattr(node, name)+ setattr(probe, name, value)+ if type(value) is str:+ verbatim += len(value)+ metadata = getattr(node, "_metadata", None)+ if metadata is not None:+ probe._metadata = metadata+ size = sum(len(line) for line in traceback.format_exception_only(probe))+ # Python 3.12 draws ``end_offset - offset`` carets, unclamped.+ caret = 0+ if type(node.text) is str:+ caret = max(0, node.offset or 0, node.end_offset or 0)+ except Exception:+ return False+ return size <= 3 * verbatim + caret + _SYNTAX_ERROR_RENDER_SLACK+++def _syntax_error_location_block(node: Any) -> str:+ """The ``File ...`` and source lines the traceback prints for *node*.++ ``TracebackException._format_syntax_error`` prints+ `` File "<filename>", line <lineno>`` (only when ``lineno`` is not+ ``None``; ``<string>`` for an empty or missing file name) and, on the+ next line, the source ``text`` without its trailing newlines and+ leading spaces, so a label ending one line and a value starting the+ next are adjacent text. Called only for fields of the canonical types+ (:data:`_SYNTAX_ERROR_FIELD_TYPES`).+ """+ lines = []+ if node.lineno is not None:+ lines.append(+ f' File "{node.filename or "<string>"}", line {node.lineno}'+ )+ if node.text is not None:+ lines.append(" " + node.text.rstrip("\n").lstrip(" \n\f"))+ return "\n".join(lines)+++def _syntax_error_details_changed(node: Any) -> bool:+ """True when a ``SyntaxError``'s extra traceback lines need redacting.++ The traceback module renders ``filename``, ``lineno``, ``text`` and+ ``msg`` outside ``str(node)``. A field that is not ``None`` or of the+ exact type the interpreter fills it with+ (:data:`_SYNTAX_ERROR_FIELD_TYPES`: ``str`` for ``msg``, ``filename``+ and ``text``, ``int`` -- not ``bool`` -- for ``lineno``, ``offset``,+ ``end_lineno`` and ``end_offset``) makes the caller rebuild the node,+ and so does a ``text`` longer than ``_LOG_REDACTION_MAX_CHARS`` (which+ redaction would cut) or an ``int`` field outside the accepted ranges+ (:func:`_syntax_error_fields_out_of_range`). Otherwise each of ``msg``, ``filename``, ``lineno`` and ``text`` is+ checked on its own, and the ``File ...`` line joined with the source+ line below it (:func:`_syntax_error_location_block`). On Python 3.13++ the keyword-typo suggestion may also replace the shown line with one+ from the source in ``_metadata``, or from the file ``filename`` names+ when that source is ``None``; that happens only when ``msg`` is+ ``"invalid syntax"`` or mentions a forgotten comma. Any of these that+ redacts differently, a source that is not an exact ``str``, or a file+ the sink would read makes the caller rebuild the node, which drops+ these details.+ """+ for name, kind in _SYNTAX_ERROR_FIELD_TYPES:+ value = getattr(node, name, None)+ if value is not None and type(value) is not kind:+ return True+ # Redaction cuts a longer ``text`` and appends a marker, so it changes+ # anyway; returning here also bounds what the range check encodes.+ if node.text is not None and len(node.text) > _LOG_REDACTION_MAX_CHARS:+ return True+ if _syntax_error_fields_out_of_range(node):+ return True+ for value in (node.msg, node.filename, node.lineno, node.text):+ if value is None:+ continue+ text = _safe_log_str(value)+ if _redact_exception_text(text) != text:+ return True+ block = _syntax_error_location_block(node)+ if _redact_exception_text(block) != block:+ return True+ metadata = getattr(node, "_metadata", None)+ if metadata is None:+ return False+ # Plain characters: a ``str`` subclass's own ``__ne__`` or+ # ``__contains__`` could answer differently here than in the sink.+ msg = _plain_text(node.msg)+ if not isinstance(node.text, str) or (+ isinstance(msg, str)+ and msg != "invalid syntax"+ and "Perhaps you forgot a comma" not in msg+ ):+ return False+ source = (+ metadata[2] if type(metadata) is tuple and len(metadata) == 3 else None+ )+ if type(source) is not str or len(source) > _LOG_REDACTION_MAX_CHARS:+ return True+ return any(+ _redact_exception_text(text) != text+ for text in (+ source,+ *source.splitlines(),+ *(line.lstrip() for line in source.splitlines()),+ )+ )+++def redact_log_exception(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,+ as are those of a SyntaxError whose fields are not of the types the+ interpreter fills them with (:data:`_SYNTAX_ERROR_FIELD_TYPES`), not in+ the accepted ranges (:func:`_syntax_error_fields_out_of_range`), or whose+ rendering by the traceback module raises or runs long+ (:func:`_syntax_error_renders_bounded`).+ Tracebacks and safe notes are retained. Cycles and traversal limits become+ explicit placeholders instead of links back to unsanitized objects. An+ exception, cause, context, group member or note whose ``str()`` fails is+ rendered as ``<unprintable TypeName>`` rather than aborting the rebuild.+ An exception is kept as the original object only when its text was clean+ and no code its classes define, and no "Did you mean" suggestion, runs+ when the sinks render it again (:func:`_exception_text_is_stable` lists+ the conditions and what they do not cover) and its type's name joined+ with its text and notes (the ``TypeName: text`` header line, as the+ sinks render it, and the notes on the lines after it) is clean too;+ otherwise the sinks get a rebuilt node carrying exactly the text that+ was checked. The record's ``type`` stays the original class only when an+ ``enqueue=True`` sink can pickle it and its names are clean+ (:func:`_record_type_is_safe`); otherwise the top node is rebuilt even+ when it could be kept, and ``type`` becomes the rebuilt node's builtin+ type, so that sink never fails and dumps the unredacted original. A+ record with a ``type`` but no value (``None``) gets the same check: a+ ``type`` it rejects becomes ``RuntimeError``, with a value naming the+ original class (``RuntimeError: TypeName``).++ Application code the redaction itself runs (an exception's or a note+ object's ``__str__``, a ``__notes__`` or ``__cause__`` property) runs+ only while the graph is read (:func:`_plan_redacted_exception`), for+ every node, before anything is decided: such code can change any+ object, including one already read. Every decision -- which nodes are+ kept, and whether the record's ``type`` is -- is made afterwards, on+ the objects as they are then, by code that runs no application code+ for exception classes that do not hook the type, descriptor and+ instance-dict machinery those checks read through+ (:func:`_build_redacted_exception`), so for them nothing changes+ between those checks and the sinks. A class written to defeat this+ is outside the threat model (see the module docstring).+ """+ 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]++ kind = getattr(exc, "type", None)+ if kind is None and isinstance(exc, tuple) and len(exc) >= 1:+ kind = exc[0]+ if value is None:+ # No value to redact (``logger.opt(exception=(Type, None, tb))``),+ # but the sink still pickles ``type``: one it cannot keep is+ # replaced by a ``RuntimeError`` naming it, as the traceback module+ # renders a type with no value.+ if kind is None:+ return+ with _decision_phase():+ kind_is_safe = _record_type_is_safe(kind)+ if kind_is_safe:+ return+ new_value = RuntimeError(_named_text(kind, ""))+ traceback = getattr(exc, "traceback", None)+ if traceback is None and isinstance(exc, tuple) and len(exc) >= 3:+ traceback = exc[2]+ new_value.__traceback__ = traceback+ _replace_record_exception(record, exc, RuntimeError, new_value)+ return++ plans: dict = {}+ root = _plan_redacted_exception(+ value, plans, set(), [_LOG_EXCEPTION_NODE_BUDGET]+ )+ # Every step that can run application code has run. Everything below+ # reads the objects as they are now and runs builtin code only, so no+ # code can change a node, or the record's type, after it was checked.+ # Checks that depend on a class alone (its pickling, rendering hooks+ # and names, and ``sys.modules``'s keys) are answered once per class+ # for all of them (:func:`_once_per_phase`).+ with _decision_phase():+ kind_is_safe = _record_type_is_safe(kind)+ # A top node whose type cannot stay in the record+ # (:func:`_record_type_is_safe`) is rebuilt even when its text is+ # clean, so that its builtin type replaces it.+ new_value = _build_redacted_exception(+ root, plans, {}, force=None if kind_is_safe else root+ )+ if new_value is value:+ return+ # ``type`` stays the original class when it is safe to keep (the DB+ # row's prefix names it); otherwise it becomes the rebuilt value's+ # builtin type.+ new_kind = kind if kind_is_safe else type(new_value)+ _replace_record_exception(record, exc, new_kind, new_value)+++def _replace_record_exception(+ record: Any, exc: Any, kind: Any, value: Any+) -> None:+ """Set *record*'s exception to *exc* with *kind* and *value* replaced."""+ if hasattr(exc, "_replace"):+ record["exception"] = exc._replace(type=kind, value=value)+ elif isinstance(exc, tuple) and len(exc) >= 3:+ record["exception"] = (kind, value, exc[2])+ else:+ record["exception"] = None+++def _exception_redaction_failed(exc: Any) -> Any:+ """Replacement for a record exception whose redaction raised.++ Keeps the traceback (frames and source lines carry no exception text)+ and replaces the value with a fixed placeholder, so the record neither+ ships unredacted exception text nor silently loses where the error+ happened. ``None`` when even that cannot be built.+ """+ try:+ traceback = getattr(exc, "traceback", None)+ kind = getattr(exc, "type", None)+ name = _type_name(kind, "Exception")+ placeholder = RuntimeError(+ f"{name}: <exception text omitted: redaction failed>"+ )+ placeholder.__traceback__ = traceback+ if not _record_type_is_safe(kind):+ kind = RuntimeError+ return exc._replace(type=kind, value=placeholder, traceback=traceback)+ except Exception:+ return None+++# ``BaseException``'s own ``__traceback__`` descriptor: the traceback a node+# carries, read without running anything its class defines.+_BASE_EXCEPTION_TRACEBACK = vars(BaseException)["__traceback__"]++[email protected](eq=False)+class _ExceptionNodePlan:+ """What was read from one exception node and redacted, before any decision.++ :func:`_plan_redacted_exception` fills one per node; it is the pass+ that runs every step that can run application code.+ :func:`_build_redacted_exception` then decides, from this and from the+ node as it is by then, whether the original can be kept, and otherwise+ rebuilds it from the texts recorded here. A child is referred to by the+ ``id()`` of the original (a key of the plans, which hold the originals,+ so the ids stay unique), by a placeholder text, or by ``None``.+ """++ node: Any+ kind: Any+ is_group: bool+ cause: Any+ cause_ref: Any+ context: Any+ context_ref: Any+ suppress_context: Any+ subs: tuple+ sub_refs: list+ traceback: Any+ rendered_message: str+ message: str+ safe_message: str+ note_texts: list+ safe_notes: list+ # The texts read here were clean, as one would render them: printable,+ # unchanged by redaction, with notes that are a list or tuple of exact+ # ``str``. A node is kept only when this holds and it is unchanged.+ text_clean: bool+++def _plan_redacted_exception(+ node: Any, plans: dict, in_progress: set, budget: list+) -> Any:+ """Read and redact the exception graph under *node*, deciding nothing.++ Every step of the redaction that can run application code runs here,+ for every node, before anything is decided: an exception's or a note+ object's ``str()``, a ``__notes__``, ``__cause__``, ``__context__``,+ ``exceptions`` or ``message`` that a class overrides, a group's+ message. That code can change any object, a node already read here+ included, so :func:`_build_redacted_exception` makes every decision+ afterwards, against the objects as they are by then. Each node's texts+ are read once and recorded (:class:`_ExceptionNodePlan`), and a node+ that is rebuilt carries exactly those texts.++ Returns the reference to *node*'s plan: its ``id()``, a placeholder+ text (the traversal budget ran out, which bounds both depth and group+ width, or the node is its own ancestor), or ``None``.+ """+ if node is None:+ return None+ if budget[0] <= 0:+ return "<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 plans:+ return key+ if key in in_progress:+ return "<exception cycle omitted>"+ in_progress.add(key)+ try:+ cause = node.__cause__+ cause_ref = _plan_redacted_exception(cause, plans, in_progress, budget)+ suppress_context = node.__suppress_context__+ # Not only when there is no cause: the sinks render each exception+ # once, so a cause already rendered elsewhere in the graph (shared+ # by two group members) is skipped, and an unsuppressed context is+ # rendered in its place.+ context = node.__context__ if not suppress_context else None+ context_ref = _plan_redacted_exception(+ context, plans, in_progress, budget+ )++ is_group = isinstance(node, BaseExceptionGroup)+ subs = tuple(node.exceptions) if is_group else ()+ sub_refs: list = []+ for child in subs:+ if budget[0] <= 0:+ sub_refs.append("<remaining exceptions omitted>")+ break+ sub_refs.append(+ _plan_redacted_exception(child, plans, in_progress, budget)+ )++ # The text is read once here and, if the node is rebuilt, the+ # rebuilt node carries exactly what was checked. A ``str()`` that+ # raised (the placeholder below is not what a sink would render)+ # rules out keeping the original.+ try:+ rendered_message = _exact_str(str(node))+ printable = True+ except Exception:+ rendered_message = _unprintable_placeholder(node)+ printable = False+ if is_group:+ try:+ message = node.message+ except Exception:+ message = None+ if isinstance(message, str):+ # A ``str`` subclass compares and renders on its own terms;+ # check, compare and rebuild with its plain characters.+ message = _exact_str(message)+ else:+ message = _unprintable_placeholder(node)+ elif printable and issubclass(type(node), SyntaxError):+ # The header line shows ``msg``, not ``str(node)`` with its+ # `` (file, line N)`` suffix (:func:`_syntax_error_header_text`):+ # a rebuilt node carries ``msg`` alone (the file and line are+ # details it drops), redacted as one with the notes printed+ # right after it.+ try:+ message = _syntax_error_header_text(node, location=False)+ except Exception:+ message = rendered_message+ else:+ message = rendered_message+ safe_message = _redact_exception_text(message)+ # A group renders ``str(node)`` (message plus sub-exception count),+ # and a ``SyntaxError``'s ``str()`` (which the DB row renders) is+ # not its header text; for any other exception ``str(node)`` is+ # ``message`` itself, so there this check would only repeat+ # ``safe_message != message`` below: the guard only saves that+ # second redaction pass (dropping it is an equivalent mutant, not a+ # missing check).+ rendered_changed = (+ is_group or message is not rendered_message+ ) and _redact_exception_text(rendered_message) != rendered_message+ # A ``__notes__`` property that raises: the traceback module reports+ # it with the error's repr ("Ignored error getting __notes__: ..."),+ # which is not redacted, so the node is rebuilt with a placeholder+ # note instead (the placeholder alone marks the node as changed).+ # The same placeholder covers notes that raise while being iterated.+ notes_failed = False+ try:+ note_texts, notes_exact = _rendered_exception_notes(node)+ except Exception:+ notes_failed = True+ note_texts, notes_exact = [], True+ safe_notes = [_redact_exception_text(note) for note in note_texts]+ if notes_failed:+ safe_notes = ["<exception notes omitted: __notes__ raised>"]+ plans[key] = _ExceptionNodePlan(+ node=node,+ kind=type(node),+ is_group=is_group,+ cause=cause,+ cause_ref=cause_ref,+ context=context,+ context_ref=context_ref,+ suppress_context=suppress_context,+ subs=subs,+ sub_refs=sub_refs,+ traceback=_BASE_EXCEPTION_TRACEBACK.__get__(node),+ rendered_message=rendered_message,+ message=message,+ safe_message=safe_message,+ note_texts=note_texts,+ safe_notes=safe_notes,+ text_clean=(+ printable+ and not notes_failed+ and notes_exact+ and safe_message == message+ and not rendered_changed+ and safe_notes == note_texts+ ),+ )+ return key+ finally:+ in_progress.discard(key)+++def _build_redacted_exception(+ ref: Any, plans: dict, built: dict, force: Any = None+) -> Any:+ """The graph the sinks get for plan *ref*: originals kept, the rest rebuilt.++ Runs after :func:`_plan_redacted_exception` has read the whole graph,+ and runs no application code itself for exception classes and objects+ that do not hook the machinery it reads through (see the module+ docstring's threat model), so for those nothing can change a node+ between the decision to keep it and the sinks rendering it. A node+ retains identity only when its recorded text was clean, it is still+ the node that text was read from (:func:`_node_is_kept_as_planned`),+ and every chained exception and member it links to is kept too; any+ other node is rebuilt from the texts recorded for it, so the text,+ notes and chained exceptions a sink renders for it are the ones checked+ (a node for which the traceback module would compute a "Did you mean"+ suggestion is rebuilt, so no suggestion is rendered for it). Rebuilt+ nodes are builtin exceptions (a class counts as builtin when+ :mod:`builtins` holds it under its name): application constructors,+ copy hooks and group derive methods are never called. Omitted branches (traversal+ budget, cycles) become placeholders. *force* is the reference of a node+ rebuilt even when it could be kept (see :func:`redact_log_exception`);+ its chained exceptions and members are not forced.+ """+ if ref is None:+ return None+ if type(ref) is str:+ return RuntimeError(ref)+ if ref in built:+ return built[ref]+ plan = plans[ref]+ new_cause = _build_redacted_exception(plan.cause_ref, plans, built)+ new_context = _build_redacted_exception(plan.context_ref, plans, built)+ new_subs = [+ _build_redacted_exception(sub_ref, plans, built)+ for sub_ref in plan.sub_refs+ ]+ keep = (+ ref != force+ and new_cause is plan.cause+ and new_context is plan.context+ and len(new_subs) == len(plan.subs)+ and all(new is old for new, old in zip(new_subs, plan.subs))+ and _node_is_kept_as_planned(plan)+ )+ if keep:+ new_node = plan.node+ else:+ new_node = _rebuilt_exception(plan, new_cause, new_context, new_subs)+ built[ref] = new_node+ return new_node+++def _exact_note_texts(node: Any) -> Optional[list]:+ """*node*'s notes when they are a ``list`` or ``tuple`` of exact ``str``.++ ``[]`` for no notes, ``None`` for notes of any other form. Called only+ for a node :func:`_exception_text_is_stable` accepts, for which the+ lookup and the iteration run builtin code only.+ """+ notes = getattr(node, "__notes__", None)+ if notes is None:+ return []+ if not _type_is_one_of(type(notes), (list, tuple)):+ return None+ items = list(notes)+ if not all(type(item) is str for item in items):+ return None+ return items+++def _node_is_kept_as_planned(plan: _ExceptionNodePlan) -> bool:+ """True when *plan*'s original node may go to the sinks as it is now.++ Its recorded texts were clean, and it is still what they were read+ from: the same class; its rendering and pickling still run no code of+ its own classes (:func:`_exception_text_is_stable`, checked first, by+ code that runs none of the node's); and its ``str()``, notes, chained+ exceptions, suppress flag, a group's message and members, a+ ``SyntaxError``'s rendered details, and its type's name joined with+ its text and notes (:func:`_type_header_changed`) are as recorded and+ clean. Application code that ran while the graph was read (a parent's+ or a note object's ``__str__``, say) may have changed any of these+ after the node itself was read. Once the stability check passes, every+ read and call below runs builtin code only, so nothing changes between+ this check and the sinks -- for classes and objects that do not hook+ the machinery these checks read through; the module docstring's threat+ model says why one that does is not covered.+ """+ if not plan.text_clean:+ return False+ node = plan.node+ try:+ if type(node) is not plan.kind:+ return False+ if not _exception_text_is_stable(node, plan.is_group):+ return False+ if node.__cause__ is not plan.cause:+ return False+ suppress_context = node.__suppress_context__+ if suppress_context is not plan.suppress_context:+ return False+ context = None if suppress_context else node.__context__+ if context is not plan.context:+ return False+ if plan.is_group:+ exceptions = node.exceptions+ if len(exceptions) != len(plan.subs) or not all(+ live is old for live, old in zip(exceptions, plan.subs)+ ):+ return False+ if node.message != plan.message:+ return False+ rendered = str(node)+ if type(rendered) is not str or rendered != plan.rendered_message:+ return False+ if _exact_note_texts(node) != plan.note_texts:+ return False+ is_syntax_error = issubclass(plan.kind, SyntaxError)+ if is_syntax_error:+ if _syntax_error_header_text(node, location=False) != plan.message:+ return False+ if _syntax_error_details_changed(node):+ return False+ # The sinks render the type's name, the text and the notes joined,+ # so a credential can span them; checked last, as it costs one more+ # redaction pass per name form (:func:`_rendered_type_prefixes`: one+ # for a builtin class, two for one defined at module level, three+ # for a nested one) and header form (two for an empty text, up to+ # three for a ``SyntaxError``, one otherwise).+ if _type_header_changed(+ plan.kind,+ rendered,+ plan.note_texts,+ _rendered_header_tails(node, rendered),+ ):+ return False+ # Rendered as the sinks will, last: the caret line is drawn from the+ # offsets, and a rendering that raises or runs long makes the sinks'+ # error handler print the exception being handled.+ if is_syntax_error and not _syntax_error_renders_bounded(node):+ return False+ except Exception:+ return False+ return True+++def _rebuilt_exception(+ plan: _ExceptionNodePlan, new_cause: Any, new_context: Any, new_subs: list+) -> BaseException:+ """A builtin exception carrying the texts recorded in *plan*."""+ kind = plan.kind+ safe_message = plan.safe_message+ if plan.is_group:+ # The builtin constructor rebuilds the read-only message and+ # members, without trusting a subclass's derive implementation.+ # The type's name is read through ``type``'s descriptor, and+ # redacted (:func:`_type_name`).+ if not _is_builtin_class(kind):+ # Keep a group subclass's name visible in the rebuilt group.+ safe_message = _redact_exception_text(+ f"{_type_name(kind)}: {safe_message}"+ )+ new_node = BaseExceptionGroup(safe_message, new_subs)+ elif _is_builtin_class(kind):+ try:+ new_node = kind(safe_message)+ except Exception:+ new_node = RuntimeError(_named_text(kind, safe_message))+ else:+ new_node = RuntimeError(_named_text(kind, safe_message))+ new_node.__traceback__ = plan.traceback+ new_node.__cause__ = new_cause+ new_node.__context__ = new_context+ new_node.__suppress_context__ = plan.suppress_context+ safe_notes = plan.safe_notes+ if safe_notes:+ # Each note was redacted on its own; a credential can still span+ # the rebuilt header line and the notes.+ header = (+ _TYPE_NAME.__get__(type(new_node))+ + _rendered_header_tails(new_node, _exact_str(str(new_node)))[0]+ )+ safe_notes = _notes_fitting_header(header, safe_notes)+ if safe_notes:+ new_node.__notes__ = safe_notes+ return new_node++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.+ """loguru patcher: control-char strip + credential redaction of a record.++ Scrubs the message and bound ``extra`` values (:func:`_redact_log_record_text`,+ :func:`redact_log_extra`) and the rendered exception graph+ (:func:`redact_log_exception`), so a credential that reaches a record+ without going through ``scrub_error`` first -- bare ``field=value`` in+ the message, a secret bound via ``logger.bind()``, or one embedded in an+ exception's text -- is caught before any sink renders it. 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: this is the patcher+ both processes install (the web process through+ ``utilities.log_utils._sanitize_record``).++ Fail-closed per field: a field that fails to redact is replaced rather+ than passed through as-is. Routing keys in ``extra``+ (:data:`_LOG_STRUCTURAL_EXTRA_KEYS`) are preserved so a failed field+ does not change the destination of a database log record. An exception+ that fails to redact keeps its traceback with a placeholder value.++ The result is always picklable: an ``enqueue=True`` sink pickles the+ record, and a pickling failure makes loguru print the original exception+ to stderr. Non-plain ``extra`` values and unsafe exception types are+ replaced before reaching a sink. Kept exception nodes are checked for+ pickling hooks that could change later rendering, within the threat+ model in the module docstring.++ The message and every ``extra`` string leaf use+ :func:`_redact_log_record_text`, which adds the unprefixed ``Api-Key:``+ header, slash-bearing DSN password, separator-delimited credential+ parameter, and quoted credential-key patterns after the ordinary+ redaction passes. Exception values use :func:`redact_log_exception`,+ which applies the patterns to rendered fields too; the database row's+ exception prefix applies them separately. Application code invoked while+ reading an exception graph runs before the keep decisions and+ picklability checks."""try:# Preserve credential boundaries that control stripping may remove,# then catch names that become recognizable after normalization.- record["message"] = _redact_log_text(record["message"])+ record["message"] = _redact_log_record_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)+ extra = redact_log_extra(extra)except Exception:- record["extra"] = _structural_extra_only(extra)+ extra = _structural_extra_only(extra)+ record["extra"] = extra+ else:+ extra = None++ exc = record.get("exception")+ if exc:+ try:+ redact_log_exception(record)+ except Exception:+ record["exception"] = _exception_redaction_failed(exc)++ if extra is not None:+ # Last, after the exception's redaction, which runs application code+ # (:func:`redact_log_exception`) that could change a value passed+ # through above (a routing key's); this check runs none.+ record["extra"] = _picklable_extra(extra)def _structural_extra_only(extra: Any) -> dict:- """The routing keys of *extra* alone; ``{}`` if even that fails."""+ """The routing keys of *extra* alone; ``{}`` if even that fails.++ Taken from the keys *extra* holds, by :func:`_is_structural_extra_key`,+ rather than looked up by name: ``extra["username"]`` would also find a+ ``str`` subclass key that only compares equal to ``"username"``.+ """try:return {- key: extra[key]- for key in _LOG_STRUCTURAL_EXTRA_KEYS- if key in extra+ key: value+ for key, value in dict.items(extra)+ if _is_structural_extra_key(key)}except Exception:return {}diff --git a/src/local_deep_research/security/ssrf_validator.py b/src/local_deep_research/security/ssrf_validator.pyindex ef1d236b0e..3192006328 100644--- a/src/local_deep_research/security/ssrf_validator.py+++ b/src/local_deep_research/security/ssrf_validator.py@@ -821,9 +821,9 @@ def redact_url_for_log(url: str) -> str:if scheme.lower() not in _HOSTLESS_LOGGABLE_SCHEMES:scheme = "?"return f"{scheme}://<redacted>"- host = u.host- # (#6938: scheme and host are unbounded in a request-supplied URL,- # so each is capped — every caller's log line stays bounded.)+ host = u.host or "<no-host>"+ # Scheme and host are unbounded in a request-supplied URL; preserve+ # the preview cap after excluding ambiguous userinfo authorities.scheme = redact_and_bound_for_log(scheme, _LOG_COMPONENT_MAX_CHARS)host = redact_and_bound_for_log(host, _LOG_COMPONENT_MAX_CHARS)host_port = f"{host}:{u.port}" if u.port else hostdiff --git a/src/local_deep_research/utilities/log_utils.py b/src/local_deep_research/utilities/log_utils.pyindex ab9a46d770..0fe780baa4 100644--- a/src/local_deep_research/utilities/log_utils.py+++ b/src/local_deep_research/utilities/log_utils.py@@ -6,7 +6,6 @@ Utilities for logging.from __future__ import annotationsimport asyncio-import builtinsimport inspect# import logging - needed for InterceptHandler compatibility@@ -631,24 +630,72 @@ def _exception_context(record) -> str:exc_value = exc[1]if exc_type is None:return ""- type_name = getattr(exc_type, "__name__", str(exc_type))+ # Deferred import to avoid potential circular imports during module initialization+ from ..security.log_sanitizer import (+ _redact_additional_shapes,+ sanitize_error_message,+ type_name_for_log,+ )++ # ``type`` is the original class unless the patcher had to replace it+ # (``security.log_sanitizer._record_type_is_safe``). Its name is read+ # through ``type``'s own descriptor (never a metaclass's ``__name__``)+ # and redacted, as in the patcher's rebuilt+ # ``RuntimeError("<TypeName>: ...")`` text.+ type_name = type_name_for_log(exc_type)if exc_value is None:return f"[{type_name}] "+ truncated = Falsetry:value_text = str(exc_value)+ # The patcher renders an application exception as a rebuilt+ # ``RuntimeError("<TypeName>: ...")`` (``RuntimeError("<TypeName>")``+ # when its text is empty) while ``type`` stays the original class;+ # drop the repeated name so the row does not read+ # ``[TypeName: TypeName: ...]`` or ``[TypeName: TypeName]``.+ repeated = "{}: ".format(type_name)+ if type(exc_value) is not exc_type:+ if value_text.startswith(repeated):+ value_text = value_text[len(repeated) :]+ elif value_text == type_name:+ value_text = ""if len(value_text) > 4096:value_text = value_text[:4096]- # Deferred import to avoid potential circular imports during module initialization- from ..security.log_sanitizer import sanitize_error_message-- value_text = sanitize_error_message(value_text)+ # The credential shapes the log-record path adds on top of+ # sanitize_error_message (``Api-Key:`` headers, slash-bearing DSN+ # passwords, ``;``/``,`` credential parameters, quoted credential+ # keys) run on the 4096-bounded text BEFORE the 240-character cap:+ # a value the cap cuts below a pattern's minimum length (or a DSN+ # cut before its '@') would no longer be recognised, and its head+ # would print. This prefix goes into the DB row with no other+ # redaction pass after it.+ value_text = _redact_additional_shapes(+ sanitize_error_message(value_text)+ )+ if len(value_text) > 240:+ # And once more on the capped text (before the ellipsis, which+ # an unterminated quoted value would otherwise take): these+ # patterns only ever replace part of their input with a+ # marker, so a second pass can hide more, never less.+ value_text = _redact_additional_shapes(value_text[:237])+ truncated = Trueexcept Exception:value_text = "<unprintable exception>"if not value_text:return f"[{type_name}] "- if len(value_text) > 240:- value_text = value_text[:237] + "…"- return f"[{type_name}: {value_text}] "+ # The name and the text are each clean, but a credential pattern can+ # span the two (a class named ``InvalidAuthorization`` and a bare token+ # read as an ``Authorization:`` header): sanitize the joined line.+ line = _redact_additional_shapes(+ sanitize_error_message(f"{type_name}: {value_text}")+ )+ cap = len(type_name) + 2 + 240+ if len(line) > cap - int(truncated):+ line = _redact_additional_shapes(line[: cap - 1])+ truncated = True+ if truncated:+ line += "…"+ return f"[{line}] "def _truncate_for_frontend(message: str) -> str:@@ -821,183 +868,32 @@ def _sanitize_record(record) -> None:sensitive key name AND by embedded credential shape, catching therecurring 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.+ * The *rendered* exception graph (value, notes, chained and grouped+ exceptions) is scrubbed too, as a rebuilt copy, 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.++ All of this is ``security.log_sanitizer.redact_log_record``, which the+ MCP subprocess installs as its own patcher too (``mcp/server.py``'s+ ``configure_mcp_logging``); it fails closed per field. It is 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)- )+def install_log_redaction() -> None:+ """Install the shared credential-redaction patcher without adding sinks.- 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)+ Entry points that configure their own sinks, such as the benchmark CLI,+ use this before enabling their package logger. Importing this module+ alone does not change the host process's Loguru configuration.+ """+ logger.configure(patcher=_sanitize_record)def config_logger(name: str, debug: bool = False) -> None:@@ -1009,7 +905,7 @@ def config_logger(name: str, debug: bool = False) -> None:debug: Whether to enable unsafe debug logging."""- logger.configure(patcher=_sanitize_record)+ install_log_redaction()logger.enable("local_deep_research")logger.remove()diff --git a/tests/benchmarks/test_benchmark_commands_high_value.py b/tests/benchmarks/test_benchmark_commands_high_value.pyindex 9c149c2ada..629a97185f 100644--- a/tests/benchmarks/test_benchmark_commands_high_value.py+++ b/tests/benchmarks/test_benchmark_commands_high_value.py@@ -330,6 +330,16 @@ class TestCompareConfigsCli:class TestMainEntryPoint:"""Tests for the main() entry point."""+ @pytest.fixture(autouse=True)+ def _restore_loguru(self):+ # main() installs the redaction patcher on the process-wide logger+ # (log_utils' logger, which the patch of benchmark_commands.logger+ # below does not replace); put it back for the rest of the session.+ from tests.test_utils import restored_loguru_state++ with restored_loguru_state():+ yield+def test_main_verbose_flag_sets_debug(self, mock_data_directory):"""--verbose adds DEBUG-level loguru handler."""from local_deep_research.benchmarks.cli.benchmark_commands import maindiff --git a/tests/benchmarks/test_cli.py b/tests/benchmarks/test_cli.pyindex 9ade89b4e2..037fefa20d 100644--- a/tests/benchmarks/test_cli.py+++ b/tests/benchmarks/test_cli.py@@ -13,6 +13,7 @@ import argparseimport sysfrom unittest.mock import patch, MagicMockimport pytest+from loguru import logger@pytest.fixture@@ -25,6 +26,11 @@ def mock_data_directory(tmp_path):yield tmp_path+def _log_benchmark_marker():+ """Log a credential marker; rebound to a package module's globals."""+ logger.info("OPENAI_API_KEY=PkgBenchmarkMarker654 db ready")++class TestSetupBenchmarkParser:"""Tests for setup_benchmark_parser function."""@@ -504,6 +510,82 @@ class TestListBenchmarksCli:class TestMain:"""Tests for main function."""+ @pytest.fixture(autouse=True)+ def _restore_loguru(self):+ # main() installs the redaction patcher and adds stderr sinks on the+ # process-wide logger; put both back for the rest of the session.+ from tests.test_utils import restored_loguru_state++ with restored_loguru_state():+ yield++ def test_main_installs_log_redaction(self, mock_data_directory):+ """main() bypasses config_logger, so it installs the redaction+ patcher itself before any benchmark code logs (#5768 follow-up)."""+ from loguru import logger++ from local_deep_research.benchmarks.cli.benchmark_commands import main+ from local_deep_research.utilities.log_utils import _sanitize_record++ records = []+ with patch.object(sys, "argv", ["ldr-benchmark", "list"]):+ with patch(+ "local_deep_research.benchmarks.cli.benchmark_commands.get_available_datasets",+ return_value=[],+ ):+ main()+ assert logger._core.patcher is _sanitize_record+ logger.remove()+ logger.add(lambda m: records.append(m.record["message"]))+ logger.info("OPENAI_API_KEY=BenchmarkMarker987")+ assert records == ["OPENAI_API_KEY=[REDACTED]"]++ def test_main_redacts_records_from_the_package_namespace(+ self, mock_data_directory, capsys+ ):+ """local_deep_research/__init__.py disables the package's loguru+ namespace; main() must re-enable it, or every record from the+ benchmark code itself is dropped before the redaction patcher runs,+ and must first remove the handler loguru starts with (diagnose=True)+ so that handler never sees those records."""+ import types++ from local_deep_research.benchmarks.cli.benchmark_commands import main++ # The state a fresh `python -m ...benchmark_commands` starts in: the+ # package namespace disabled by the package import, and a default+ # handler (loguru's handler 0, diagnose=True) still attached.+ logger.disable("local_deep_research")+ default_handler_records = []+ logger.add(+ lambda m: default_handler_records.append(m.record["message"]),+ diagnose=True,+ )++ with patch.object(sys, "argv", ["ldr-benchmark", "list"]):+ with patch(+ "local_deep_research.benchmarks.cli.benchmark_commands.get_available_datasets",+ return_value=[],+ ):+ main()+ capsys.readouterr()++ # loguru names a record after its caller's module globals, so run+ # the logging call with a package module's ``__name__``.+ log_from_package = types.FunctionType(+ _log_benchmark_marker.__code__,+ {+ "__name__": "local_deep_research.benchmarks.runners",+ "logger": logger,+ },+ )+ log_from_package()++ err = capsys.readouterr().err+ assert "OPENAI_API_KEY=[REDACTED] db ready" in err+ assert "PkgBenchmarkMarker654" not in err+ assert default_handler_records == []+def test_main_requires_command(self, mock_data_directory):"""Test that main requires a command."""from local_deep_research.benchmarks.cli.benchmark_commands import maindiff --git a/tests/mcp/test_stderr_control_chars.py b/tests/mcp/test_stderr_control_chars.pyindex a62578f13a..fe3f5fcd7c 100644--- a/tests/mcp/test_stderr_control_chars.py+++ b/tests/mcp/test_stderr_control_chars.py@@ -115,3 +115,104 @@ def test_bound_secret_is_redacted(emit):# tests/security/test_log_sink_redaction.py.assert "BoundSecretPw999" not in outassert records[-1]["extra"].get("user_password") == "[REDACTED]"+++def test_credential_in_exception_is_redacted(emit):+ """The MCP patcher scrubs rendered exception text, not just the message.++ The ``logger.exception()`` calls in mcp/server.py render the exception+ value to this sink; a credential inside it must not reach the MCP+ client's stderr log.+ """++ # Assembled at runtime: the traceback renders the source line of the+ # raise, which must not itself carry the value the assertion looks for.+ secret = "McpException" + "Secret739"+ error = ValueError(f"upstream refused token={secret}")++ def _log_exception():+ try:+ raise error+ except ValueError:+ logger.exception("research failed")++ out = emit(_log_exception)+ assert secret not in out+ assert "ValueError" in out+ assert "token=" in out+++_ENQUEUE_SECRET = "McpEnqueueDump" + "Secret739"+++def _local_class_with_secret_text():+ class ProviderError(Exception):+ pass++ return ProviderError(f"request failed: api_key=sk-live-{_ENQUEUE_SECRET}")+++def _clean_local_class_with_secret_cause():+ class LocalError(Exception):+ pass++ exc = LocalError("clean text")+ exc.__cause__ = ValueError(f"token=ghp_{_ENQUEUE_SECRET}")+ return exc+++def _secret_named_class():+ return type(f"password={_ENQUEUE_SECRET}", (ValueError,), {})("benign")+++def _builtin_with_secret_text():+ return ValueError(f"token=ghp_{_ENQUEUE_SECRET}")+++ "make, bind_lock, with_exception",+ [+ (_local_class_with_secret_text, False, True),+ (_clean_local_class_with_secret_cause, False, True),+ (_secret_named_class, False, True),+ (_builtin_with_secret_text, True, True),+ (_builtin_with_secret_text, True, False),+ ],+ ids=[+ "local_class",+ "local_class_cause",+ "secret_class_name",+ "unpicklable_extra",+ "unpicklable_extra_no_exception",+ ],+)+def test_enqueue_sink_never_dumps_the_unredacted_exception(+ monkeypatch, make, bind_lock, with_exception+):+ """The real sink pickles each record; a failure must not dump the original.++ loguru's error handler writes the record and the pickling traceback to+ ``sys.stderr``, and that traceback's ``__context__`` is the exception+ being handled, unredacted. ``sys.stderr`` is replaced before the sink is+ added, so it captures both the sink and that handler.+ """+ import sys+ import threading++ stderr = io.StringIO()+ monkeypatch.setattr(sys, "stderr", stderr)+ bound = {"lock": threading.Lock()} if bind_lock else {}+ with restored_loguru_state():+ configure_mcp_logging()+ exc = make()+ try:+ raise exc+ except BaseException:+ logger.bind(**bound).opt(exception=with_exception).error(+ "handled failure"+ )+ logger.complete()+ out = stderr.getvalue()+ assert "handled failure" in out+ assert "Logging error in Loguru Handler" not in out+ assert "McpEnqueueDumpSecret739" not in outdiff --git a/tests/security/test_downloader_error_url_redaction.py b/tests/security/test_downloader_error_url_redaction.pyindex 4e5a397dc7..109fc014b5 100644--- a/tests/security/test_downloader_error_url_redaction.py+++ b/tests/security/test_downloader_error_url_redaction.py@@ -52,8 +52,8 @@ Not covered (documented residuals):``NETWORK_CALL``: the traceback rule keys on the called name, not onwhat the callee does;* a traceback-attaching call in an ``except`` block whose ``try`` makes- no network-shaped call (persistence and extraction handlers; the- SQLAlchemy parameter echo there is tracked in #6829);+ no network-shaped call (other persistence and extraction handlers;+ ``download_service`` is covered by the #6829 regression separately);* modules outside ``SCANNED_RELATIVE``.``ALLOWED`` lists the reviewed exceptions, each keyed to the exact calldiff --git a/tests/security/test_guard_internals.py b/tests/security/test_guard_internals.pyindex 82f9e4abef..28ccea9fa8 100644--- a/tests/security/test_guard_internals.py+++ b/tests/security/test_guard_internals.py@@ -39,6 +39,7 @@ from local_deep_research.security.account_lockout import ()from local_deep_research.security.ip_ranges import PRIVATE_IP_RANGESfrom local_deep_research.security.log_sanitizer import (+ redact_log_record,redact_secrets,sanitize_error_message,)@@ -462,12 +463,13 @@ class TestCredentialShapeCoverage:strict=True,reason=("DEFECT (security): only the literal 'x-api-key' header name "- "is anchored. The unprefixed 'Api-Key:' header -- what "- "Anthropic, Azure Cognitive Services and several search "- "APIs actually send -- is not matched by any pattern, so a "- "raw request-header dump inside an exception message ships "- "the key verbatim to logs and to the client via "- "sanitize_error_for_client()."+ "is anchored in sanitize_error_message. The unprefixed "+ "'Api-Key:' header -- what Anthropic, Azure Cognitive Services "+ "and several search APIs actually send -- is not matched by "+ "any of its patterns, so a raw request-header dump inside an "+ "exception message ships the key verbatim to the client via "+ "sanitize_error_for_client() and in scrub_error text. Log "+ "records redact it (TestCredentialShapesOnTheLogRecordPath)."),)def test_unprefixed_api_key_header_is_redacted(self, label):@@ -486,7 +488,8 @@ class TestCredentialShapeCoverage:"password class ([^@\\s/]+), so a password containing an ""unescaped '/' -- routine for base64/base64-ish generated ""passwords pasted into a DSN -- makes the whole match fail "- "and the entire credential is logged verbatim."+ "and sanitize_error_message keeps the entire credential. Log "+ "records redact it (TestCredentialShapesOnTheLogRecordPath)."),)def test_url_userinfo_with_a_slash_in_the_password_is_redacted(self):@@ -538,6 +541,369 @@ class TestCredentialShapeCoverage:assert longer not in redact_secrets(f"pw was {longer}", longer)+def _logged(msg: str) -> str:+ """*msg* as the loguru patcher (``redact_log_record``) hands it to the+ sinks."""+ record = {"message": msg}+ redact_log_record(record)+ return record["message"]+++class TestCredentialShapesOnTheLogRecordPath:+ """The shapes the log-record path adds on top of the patterns above.++ ``redact_log_record`` (the loguru patcher every sink sits behind) runs+ ``_ADDITIONAL_CREDENTIAL_PATTERNS`` as the last step over the message+ and every ``extra`` string; ``sanitize_error_message`` does not run+ them, which the two strict-xfails above pin.+ """++ @pytest.mark.parametrize("label", ["Api-Key", "api-key", "api_key"])+ def test_unprefixed_api_key_header_is_redacted(self, label):+ """The unprefixed ``Api-Key:`` header -- what Anthropic, Azure+ Cognitive Services and several search APIs actually send -- does+ not ship the key verbatim to the logs."""+ msg = f"upstream said {label}: {_SECRET_BODY}"+ assert _SECRET_BODY not in _logged(msg)++ @pytest.mark.parametrize(+ ("msg", "password"),+ [+ ("postgresql://admin:Sup3r/[email protected]/app", "Sup3r/S3cret"),+ ("postgresql://ldr:ab/cd+ef@postgres:5432/ldr", "ab/cd+ef"),+ ("redis://:ab/cdEF12345@redis:6379/0", "ab/cdEF12345"),+ ("postgresql://ldr:ab/cd@localhost/db", "ab/cd"),+ ("mysql+pymysql://u:x/[email protected]:3306/db", "x/y=z"),+ ],+ ids=[+ "dotted-host",+ "compose-service",+ "password-only",+ "localhost",+ "ip",+ ],+ )+ def test_url_userinfo_with_a_slash_in_the_password_is_redacted(+ self, msg, password+ ):+ """A password containing an unescaped ``/`` (routine for+ base64-ish generated passwords pasted into a DSN) is redacted in a+ log record, whatever the host after the ``@`` looks like:+ container DSNs name a compose service, ``localhost`` or an IP, not+ a dot-qualified domain."""+ assert password not in _logged(msg)++ @pytest.mark.parametrize(+ "msg",+ [+ "GET https://api.example.com:443/users/[email protected] failed",+ "http://localhost:5000/notes/api/u/[email protected] returned 404",+ "https://h.example:8080?next=a/[email protected] rejected",+ "http://[::1]:8080/a/[email protected] timed out",+ "https://example.com/a:b/[email protected] moved",+ ],+ ids=["port-path", "localhost-port-path", "port-query", "ipv6", "path"],+ )+ def test_a_host_port_path_with_an_at_sign_is_not_userinfo(self, msg):+ """Admitting ``/`` in the password must not read+ ``host:port/path@x`` as ``user:password@host``: that erased the+ real host and port from the message and kept the email-shaped+ path segment instead."""+ assert _logged(msg) == msg++ _X_API_KEY_SHIELDS_A_DSN = pytest.mark.xfail(+ strict=True,+ reason=(+ "DEFECT (pre-existing, unchanged by #6888): the x-api-key "+ "pattern in _CREDENTIAL_PATTERNS runs before the URL-credential "+ "pattern, so it eats the DSN's scheme as part of its >=16-char "+ "value and the resulting '[REDACTED]://user:pass@' no longer "+ "matches any scheme-anchored pattern, in sanitize_error_message "+ "and in the log record's passes alike."+ ),+ )++ @pytest.mark.parametrize(+ "label",+ [+ "api_key: ",+ "api-key: ",+ pytest.param("x-api-key: ", marks=_X_API_KEY_SHIELDS_A_DSN),+ pytest.param("x-api-key=", marks=_X_API_KEY_SHIELDS_A_DSN),+ ],+ ids=[+ "api_key-colon",+ "api-key-colon",+ "x-api-key-colon",+ "x-api-key-equals",+ ],+ )+ def test_key_label_does_not_shield_a_following_dsn(self, label):+ """The API-key header value class admits ``+``, ``/`` and letters,+ so a header pattern that runs before the URL-credential patterns+ eats a pasted DSN's scheme as a bare header value -- and the+ resulting ``[REDACTED]://user:pass@...`` can never match the+ scheme-anchored URL-credential patterns, so the password survives.+ The unprefixed ``api_key:``/``api-key:`` pattern runs after every+ other pass of the log record, so the userinfo is already redacted+ when it runs. The ``x-api-key`` pattern in ``_CREDENTIAL_PATTERNS``+ runs before the URL-credential patterns, which is the strict-xfail+ defect pinned here, with a plain and a slash-bearing password."""+ for password in ("secretpw", "secr/etpw"):+ msg = (+ f"{label}postgresql+asyncpg://user:{password}@db.example.com/x"+ )+ out = _logged(msg)+ assert password not in out+ assert "@db.example.com/x" in out++ @pytest.mark.parametrize(+ ("msg", "key"),+ [+ (+ "api-key: 0123456789abcdefhttps://user:[email protected]/x",+ "0123456789abcdef",+ ),+ ("Api-Key: sk_live_9f8e7d6c5b4a3210ZZZZ://x", "9f8e7d6c5b4a3210"),+ ("x-api-key: ABCDEFGHIJKLMNOPQRSTUVWX://foo", "ABCDEFGHIJKLMNOP"),+ (+ "x-api-key=ABCDEFGHIJKLMNOPQRSTUVWXYZ012345.https://h.example.com/",+ "ABCDEFGHIJKLMNOP",+ ),+ (+ "x-api-key: AbCdEf0123456789XyZaBcDeFgHiJkLmhttps://example.com/v1",+ "AbCdEf0123456789",+ ),+ ],+ ids=[+ "digits-then-scheme",+ "unprefixed-glued-to-separator",+ "x-prefixed-glued-to-separator",+ "equals-dot-scheme",+ "long-key-then-scheme",+ ],+ )+ def test_key_glued_to_a_scheme_is_still_redacted(self, msg, key):+ """A >=16-char value run that ends in ``://`` (a key glued to a+ URL scheme, or to a bare ``://``) is still a key, and is redacted+ whole, scheme included, when the value's scheme stop does not fire+ at the start of the run: the run of scheme characters before+ ``://`` starts with a digit (``0123...https``), starts after a+ ``_`` with a digit (``sk_live_9f8e...``), or is longer than 32+ characters; the ``x-api-key`` pattern takes the whole run+ regardless. The URL-credentials pattern is not anchored to a run's+ start and still finds a scheme inside such a run, and it runs+ first, so any userinfo after it is redacted too. A run that does+ read as a scheme from its first letter is the known gap pinned+ below."""+ out = _logged(msg)+ assert key not in out+ assert "secretpw" not in out++ @pytest.mark.xfail(+ strict=True,+ reason=(+ "Known gap (as on main): a key glued to a URL scheme whose run of "+ "letters, digits, '+', '.' and '-' starts with a letter and "+ "reaches '://' within 32 characters reads as that scheme. The "+ "unprefixed Api-Key value stops where the scheme starts (so a "+ "URL after a value stays legible), and the key is not redacted "+ "when fewer than 16 characters come before it."+ ),+ )+ @pytest.mark.parametrize(+ ("msg", "key"),+ [+ (+ "Api-Key: AbCdEf0123456789XyZaBcDehttps://example.com/v1",+ "AbCdEf0123456789",+ ),+ ("api_key: AbCdEf0123456789XyZaBcDe://x", "AbCdEf0123456789"),+ (+ "Api-Key: sk_live_AbCdEf0123456789https://example.com/v1",+ "AbCdEf0123456789",+ ),+ ],+ ids=["scheme-from-first-char", "bare-separator", "short-head"],+ )+ def test_key_read_as_a_glued_scheme_is_a_known_gap(self, msg, key):+ assert key not in _logged(msg)++ @pytest.mark.parametrize(+ "label", ["Api-Key: ", "api_key: ", "x-api_key: ", "x-apikey= "]+ )+ def test_userinfo_the_strip_completes_after_a_key_label_is_redacted(+ self, label+ ):+ """A password holding a character the log record's strip removes+ (``\\x1c``, which ``\\s`` also matches, so no pass before the strip+ reads it as userinfo) becomes userinfo only after the strip. The+ added patterns run after the record's second pass, so the+ URL-credential pattern has already redacted it there."""+ msg = label + "postgresql+asyncpg://user:pas\[email protected]/x"+ logged = _logged(msg)+ assert "user:pass@" not in logged+ assert "[REDACTED]:[REDACTED]@db.example.com/x" in logged++ @pytest.mark.parametrize(+ "dsn",+ [+ "redis://:pa/ss@redis:6379/0",+ "postgres://u:pa/ss@localhost:5432/db",+ "postgresql://user:Secr/t@"+ + ".".join(["10", "0", "0", "1"])+ + ":5432/db",+ "postgres://u:pa/ss@[::1]:5432/db",+ "postgresql://admin:Sup3r/[email protected]/app",+ ],+ ids=[+ "service-name-host",+ "localhost",+ "ipv4-literal",+ "ipv6-literal",+ "dotted-host",+ ],+ )+ def test_slash_bearing_dsn_is_redacted_across_host_shapes(self, dsn):+ """Any host shape a real DSN uses is accepted after the ``@``+ (service names such as ``redis`` on container networks,+ ``localhost``, IP literals), and the host[:port] stays legible."""+ password = dsn.split(":", 2)[2].split("@", 1)[0]+ assert password in dsn # sanity: we really extracted the password+ out = _logged(dsn)+ assert password not in out+ assert out.endswith(dsn.split("@", 1)[1])++ @pytest.mark.parametrize(+ "url",+ [+ "https://example.com:8080/a:[email protected]/x",+ "https://example.com:8080/[email protected]/x",+ "https://localhost:8080/a:[email protected]/x",+ "https://[::1]:8080/a:[email protected]/x",+ "https://example.com/a:[email protected]/x",+ "https://api.example.com:443/users/[email protected]",+ "http://localhost:8888/search?q=@alice",+ ],+ ids=[+ "port-colon-path",+ "port-nocolon-path",+ "localhost-port",+ "ipv6-port",+ "portless-path",+ "port-path-email",+ "port-path-query-at",+ ],+ )+ def test_host_port_url_with_userinfo_shaped_path_is_not_mangled(self, url):+ """Counterexample contract: ``scheme://host:port/path`` whose+ path, query or fragment merely contains ``@`` must keep its real+ host:port. The slash-DSN pattern refuses a would-be password+ that is an all-digit run followed by ``/``, ``?`` or ``#`` (a+ port), and its user class refuses ``[``/``]`` (an IPv6+ authority)."""+ assert _logged(url) == url++ def test_benign_slash_bearing_strings_are_untouched(self):+ """A slash alone is not a credential: config paths and ratio+ strings without ``://`` never match any pattern."""+ for msg in (+ "config pair key/value = enabled",+ "retry count 3/5 for job db-migrate/12",+ ):+ assert _logged(msg) == msg++ @pytest.mark.parametrize(+ ("msg", "password"),+ [+ ("postgres://svc.app:12345/[email protected]/x", "12345/678"),+ ("postgresql://user:1234/56:[email protected]/x", "1234/56:78"),+ ("postgres://u:12345/678@db/x", "12345/678"),+ ("postgres://u:/abcdefgh@db/x", "/abcdefgh"),+ ("postgres://u:12?ab/cd@db/x", "12?ab/cd"),+ ],+ ids=[+ "dotted-user",+ "colon-after-slash",+ "plain-user",+ "leading-slash",+ "digits-then-query",+ ],+ )+ def test_digit_run_password_is_the_documented_gap(self, msg, password):+ """Documented gap — recorded so the boundary is explicit: a+ slash-bearing password whose characters before its first ``/``,+ ``?`` or ``#`` are all digits (none at all included) is+ indistinguishable from ``host:port/path`` and is left alone here.+ Redacting it would mangle every ``scheme://host:port/...@...``+ URL; the dual-scrub literal pass (:func:`redact_secrets` with the+ known DSN password) remains the backstop."""+ assert _logged(msg) == msg+ assert password not in redact_secrets(msg, password)++ def test_overlong_slash_bearing_password_is_the_documented_gap(self):+ """Documented gap: the slash-DSN pattern caps the password at+ 256 characters (the cap is what keeps the scan linear, see+ test_log_sanitizer's linear-time tests), so a longer+ slash-bearing password is left to the dual-scrub literal pass.+ A 256-character one is still redacted."""+ at_cap = "a/" * 128+ assert at_cap not in _logged(f"postgres://u:{at_cap}@db/x")+ over = "a/" * 129+ msg = f"postgres://u:{over}@db/x"+ assert _logged(msg) == msg+ assert over not in redact_secrets(msg, over)++ @pytest.mark.timeout(15)+ @pytest.mark.parametrize(+ "unit",+ [+ '"redis://cache:6379",',+ '"https://api.example.com:443",',+ '"postgresql://db:5432",',+ '"https://a.com:443/x",',+ "https://u:p",+ "ab://u:p/",+ "postgresqlpostgresql://a:",+ ],+ ids=[+ "json-redis-host-port",+ "json-https-host-port",+ "json-pg-host-port",+ "json-host-port-path",+ "glued-userinfo-no-at",+ "short-scheme-slash-pw",+ "long-scheme-letters",+ ],+ )+ def test_slash_dsn_pattern_is_linear_on_host_port_runs(self, unit):+ """The realistic trigger for the slash-DSN pattern's former+ quadratic scan: a whitespace-free run of ``scheme://host:port``+ entries with no ``@`` (a minified JSON list of service URLs).+ Uncapped, every scheme start scanned to the end of the run+ (measured 2-10 s CPU at 32 KB, GIL held); the length caps bound+ the work per start. The run is sized to the 32 KB log-record+ bound; CPU-clock budget as in test_log_sanitizer."""+ run = unit * (32_760 // len(unit))+ t0 = time.process_time()+ _logged(run)+ elapsed = time.process_time() - t0+ assert elapsed < 2.0, (+ f"the log-record redaction took {elapsed:.2f}s cpu on a "+ f"{len(run)}-char run of {unit!r} (budget: 2.0s)"+ )++ def test_bracket_in_password_is_redacted(self):+ """A ``]`` in the password is exactly as illegal unencoded as+ the ``/`` this pattern exists to tolerate, so it must redact;+ ``[`` and ``]`` are excluded only from the username class so an+ IPv6 authority cannot be read as user:pass."""+ msg = "postgres://u:pa]ss/[email protected]/x"+ assert _logged(msg) == (+ "postgres://[REDACTED]:[REDACTED]@db.example.com/x"+ )++# ---------------------------------------------------------------------# 4. account_lockout# ---------------------------------------------------------------------diff --git a/tests/security/test_log_sanitizer.py b/tests/security/test_log_sanitizer.pyindex dc3951a4c2..a4055722c0 100644--- a/tests/security/test_log_sanitizer.py+++ b/tests/security/test_log_sanitizer.py@@ -534,6 +534,39 @@ class TestScrubError:assert exported is scrub_error[email protected]("control", ["\r", "\n", "\r\n"])[email protected]("long_guarded", [False, True])+def test_p6_premise_scrub_error_does_not_strip_control_chars(+ control, long_guarded+):+ """Guard the credential-only classification in the P6 source sweep.++ Analysis may inspect a stripped view without stripping returned text.+ If output starts neutralizing controls, revisit the sweep's scrubber+ classification and inventory rather than preserving this behavior just+ to satisfy the premise.+ """+ prefix = f"first line{control}second line "+ message = prefix+ if long_guarded:+ message += (+ "https://host/path?query=value password=value details "+ + "ordinary detail " * 3_000+ )++ result = scrub_error(message)++ assert result.startswith(prefix), (+ "scrub_error now neutralizes controls; revisit pattern 6's "+ "credential-only classification and inventory"+ )+ if long_guarded:+ assert "https://host/path?<redacted>" in result+ assert result.endswith("characters omitted from log output]")+ else:+ assert result == message++class TestScrubErrorUrlQueryRedaction:"""scrub_error() must strip a URL's query string even when it carries nocredential-shaped parameter (#6403) — e.g. a search engine's own query@@ -763,6 +796,89 @@ class TestScrubErrorUrlQueryRedaction:f"removed.")+ @pytest.mark.timeout(15)+ @pytest.mark.parametrize(+ "unit",+ ["abcdefghijklmnopqrstuvwxyzabcdef://:", "ab://:"],+ ids=["long-scheme", "short-scheme"],+ )+ def test_slash_dsn_pattern_is_linear_on_userinfo_like_runs(self, unit):+ # Regression for the slash-bearing DSN pattern the log-record path+ # adds: its password class may run through '/', and uncapped it+ # scanned to the end of a whitespace-free "scheme://:" run with no+ # '@' at every scheme start (measured ~9s CPU for 32k chars of the+ # long-scheme unit, holding the GIL for the whole pass). Capping the+ # user and password groups bounds the work per start position.+ # CPU-clock budget and wall-clock backstop follow the bare-schemes+ # test above (#6612).+ run = unit * (32_760 // len(unit))+ t0 = time.process_time()+ _logged(run)+ elapsed = time.process_time() - t0+ assert elapsed < 2.0, (+ f"the log-record redaction took {elapsed:.2f}s cpu on a "+ f"{len(run)}-char run of {unit!r} (budget: 2.0s) — the "+ f"slash-bearing DSN pattern may have lost its length caps."+ )++ @pytest.mark.timeout(15)+ @pytest.mark.parametrize(+ "unit",+ [+ "abcdefghijklmnopqrstuvwxyzabcdef://:",+ "abcdefghijklmnopqrstuvwxyzabcde://:",+ "abcdefghijklmnopqrstuvwxyzabcdef://u:1",+ ],+ ids=["32-letter-scheme", "31-letter-scheme", "32-letter-user-digit"],+ )+ def test_slash_dsn_pattern_tries_each_scheme_separator_once(self, unit):+ # The capped slash-DSN pattern is linear, but tried from every+ # scheme start it re-ran the same capped user/password tail up to+ # 31 times per '://' on a run of long schemes: ~5-6x the cost of+ # the generic URL-credential pattern on the same run. Entering a+ # scheme run once (lookbehind + atomic group) makes it a fraction+ # of the generic pattern's cost there. The comparison is a ratio+ # measured in the same process, so it holds on slow CI cores where+ # an absolute budget would have to be loose enough to let a 5x+ # slowdown through.+ from local_deep_research.security import log_sanitizer++ def only(predicate):+ found = [+ entry+ for entry in (+ log_sanitizer._CREDENTIAL_PATTERNS+ + log_sanitizer._ADDITIONAL_CREDENTIAL_PATTERNS+ )+ if predicate(entry[0].pattern)+ ]+ assert len(found) == 1, found+ return found[0]++ generic = only(+ lambda p: p.startswith(r"([A-Za-z][A-Za-z0-9+.\-]{1,31}://)")+ )+ slash = only(lambda p: "{1,256}" in p)+ run = unit * (32_760 // len(unit))++ def cpu(entry):+ pattern, replacement = entry+ best = float("inf")+ for _ in range(3):+ t0 = time.process_time()+ pattern.sub(replacement, run)+ best = min(best, time.process_time() - t0)+ return best++ generic_cpu = cpu(generic)+ slash_cpu = cpu(slash)+ assert slash_cpu < generic_cpu, (+ f"the slash-DSN pattern took {slash_cpu * 1000:.1f} ms cpu on a "+ f"{len(run)}-char run of {unit!r}, more than the generic URL "+ f"pattern's {generic_cpu * 1000:.1f} ms: it is retrying the "+ f"capped tail from every scheme start again."+ )+@pytest.mark.timeout(15)def test_scrub_error_is_linear_time_on_a_long_scheme_like_run(self):# @pytest.mark.timeout is a hard backstop, not just the assertion@@ -871,3 +987,1630 @@ class TestSanitizeErrorForAgent:# consults ``__all__``, so assert the export list separately: a# name dropped from ``__all__`` would otherwise pass unnoticed.assert "sanitize_error_for_agent" in security_pkg.__all__+++def _logged(msg):+ """*msg* as the loguru patcher (``redact_log_record``) hands it to the+ sinks."""+ from local_deep_research.security.log_sanitizer import redact_log_record++ record = {"message": msg}+ redact_log_record(record)+ return record["message"]+++def _secret_fragments_behind_a_marker(ls, exception_context, seeds):+ """The marker property, over *seeds*, for the module *ls* (a+ ``log_sanitizer``) and *exception_context* (``_exception_context``).++ Each seed plants one secret -- one to three words of ``Q``, ``Z``,+ ``J``, ``7``, ``8``, ``9`` and ``& # ! $ / . + - @ ' "`` -- as the value+ of a quoted key or a ``;``/``,`` parameter (bare, quoted,+ string-prefixed, or inside a container, a call or adjacent strings), as+ JSON and as a repr, after an ``Authorization`` scheme word, as an+ ``Api-Key:`` header (after a 16-character key run) or as a slash-bearing+ DSN password. The text before it holds no credential shape, so a+ marker before it on its line can only be the planted value's own. A+ violation is any 4-character fragment of the secret (with one of the+ six letters and digits in it, which no other part of the line has)+ anywhere after a marker on the secret's line, on the log-record path+ (``redact_log_record``) or in the database exception prefix.++ Two kinds of case are exempt, each decided by its own check:+ ``reference``, where the passes that run before the added shapes+ already print a fragment after a marker (``_redact_log_text`` for the+ record, ``sanitize_error_message`` and the 240-character cap for the+ prefix); and ``shaped``, where the planted text holds the shape of a+ whole value followed by more structure -- the value's own closing+ quote, then one of the quoted-value followers; for the header, the+ key run's end, then a structural follower; for a DSN, an '@' and a+ host, then a host's end -- which no allowlist can tell from a real+ end (see ``log_sanitizer._cuts_a_value``).+ """+ import json+ import random+ import re+ from types import SimpleNamespace++ distinct = "QZJ789"+ symbols = "&#!$/.+-@'\""+ quoted_followers = ",}]):;&#"+ key_names = [+ "password",+ "api_key",+ "token",+ "client_secret",+ "db_password",+ "X-API-KEY",+ "api-key",+ "llm.openai.api_key",+ "_api_key",+ "Authorization",+ ]+ param_names = ["password", "token", "api_key", "key", "secret", "pwd"]+ wrappers = [+ ("", ""),+ ("'", "'"),+ ('"', '"'),+ ("b'", "'"),+ ("Rb'", "'"),+ ("(b'", "',)"),+ ("bytearray(b'", "')"),+ ("SecretStr('", "')"),+ ("(1, '", "')"),+ ("{0: '", "'}"),+ ("Foo(a, '", "')"),+ ("'''", "'''"),+ ('"""', '"""'),+ ("x'", "'"),+ ("ab\\'", "'"),+ ("[1, 2, '", "']"),+ ]+ prefixes = ["", "{", "(", " ", "user=bob ", "{'n': 1, ", '{"m": "m", ']+ suffixes = [+ "",+ "}",+ ", 'n': 1}",+ ")",+ "]",+ " and more",+ "\n next",+ ";x=1",+ "&x=1",+ "#frag",+ " }",+ "!",+ "'",+ '"',+ ": rejected",+ ", 'token': 'abc'}",+ ]+ marker = re.compile(r"\[REDACTED|<redacted>|\*\*\*REDACTED")+ key_run = re.compile(r"[A-Za-z0-9\-._~+/]{16,}=*")+ host = re.compile(r"[A-Za-z0-9][A-Za-z0-9.\-_~%]*(?=[\s:/?#\"'<>,;)\]}\\])")++ def word(rng, size):+ chars = [rng.choice(distinct) for _ in range(2)]+ chars += [rng.choice(distinct + symbols) for _ in range(size - 2)]+ rng.shuffle(chars)+ return "".join(chars)++ def secret(rng):+ words = rng.choice([1, 1, 2, 3])+ return " ".join(word(rng, rng.randint(3, 8)) for _ in range(words))++ def ends_there(rest, followers):+ rest = rest.lstrip(" ")+ return rest[:1] in ("\n", "\r") or (rest != "" and rest[0] in followers)++ def quoted_shape(quote, text):+ # The regex's quoted value ends at the first quote of either kind;+ # the other kind refuses it.+ firsts = [i for i in (text.find("'"), text.find('"')) if i != -1]+ if not firsts or text[min(firsts)] != quote:+ return False+ return ends_there(text[min(firsts) + 1 :], quoted_followers)++ def shaped(slot, opener, closer, text):+ if slot in ("key", "param"):+ if opener == "":+ return text[:1] in ("'", '"') and quoted_shape(+ text[0], text[1:]+ )+ quote = opener.lstrip("bBrRuUfF")+ if quote in ("'", '"') and closer == quote:+ return quoted_shape(quote, text)+ return False+ if slot == "apikey":+ run = key_run.match(text)+ if run is None:+ return False+ rest = text[run.end() :]+ if ends_there(rest, ",;)]}"):+ return True+ rest = rest.lstrip(" ")+ return rest[:1] in ("'", '"') and ends_there(+ rest[1:], quoted_followers+ )+ if slot == "dsn":+ stops = [+ i for i in (text.find(c) for c in "@ \"'<>,?&#") if i != -1+ ]+ if not stops or text[min(stops)] != "@":+ return False+ return host.match(text, min(stops) + 1) is not None+ return False++ def lines_with_a_fragment_after_a_marker(out, text):+ fragments = {+ text[i : i + 4]+ for i in range(len(text) - 3)+ if any(c in distinct for c in text[i : i + 4])+ }+ for line in out.split("\n"):+ found = marker.search(line)+ if found and any(f in line[found.end() :] for f in fragments):+ return True+ return False++ def logged(text):+ record = {"message": text}+ ls.redact_log_record(record)+ return record["message"]++ def db_reference(text):+ text = ls.sanitize_error_message(text[:4096])+ return text[:237] + "…" if len(text) > 240 else text++ counts = {"checked": 0, "hidden": 0, "reference": 0, "shaped": 0}+ violations = []+ for seed in seeds:+ rng = random.Random(seed)+ planted = secret(rng)+ slot = rng.choice(+ ["key", "key", "param", "json", "repr", "auth", "apikey", "dsn"]+ )+ opener = closer = ""+ quote = rng.choice(["'", '"'])+ if slot == "key":+ opener, closer = rng.choice(wrappers)+ value = (+ quote+ + rng.choice(key_names)+ + quote+ + rng.choice([": ", ":"])+ + opener+ + planted+ + closer+ )+ elif slot == "param":+ opener, closer = rng.choice(wrappers)+ value = (+ rng.choice([",", ";"])+ + rng.choice(param_names)+ + "="+ + opener+ + planted+ + closer+ )+ elif slot == "json":+ value = json.dumps({rng.choice(key_names): planted, "n": 1})+ elif slot == "repr":+ value = repr({rng.choice(key_names): planted, "n": 1})+ elif slot == "auth":+ value = (+ f"{quote}{rng.choice(['Authorization', 'proxy-authorization'])}"+ f"{quote}: {rng.choice(['Basic', 'Bearer', 'Token', 'Digest'])} "+ + planted+ )+ elif slot == "apikey":+ run = "".join(rng.choice(distinct + "/.+-") for _ in range(18))+ planted = run + rng.choice(["", " "]) + planted+ value = (+ rng.choice(["Api-Key: ", "api_key: ", "x-apikey="]) + planted+ )+ else:+ value = f"postgres://u:{planted}@db.example/x"+ msg = rng.choice(prefixes) + value + rng.choice(suffixes)+ is_shaped = shaped(slot, opener, closer, planted)+ for shown, reference in (+ (logged(msg), ls._redact_log_text(msg)),+ (+ exception_context(+ {+ "exception": SimpleNamespace(+ type=ValueError, value=ValueError(msg)+ )+ }+ ),+ db_reference(msg),+ ),+ ):+ counts["checked"] += 1+ counts["hidden"] += planted not in shown+ if not lines_with_a_fragment_after_a_marker(shown, planted):+ continue+ if lines_with_a_fragment_after_a_marker(reference, planted):+ counts["reference"] += 1+ elif is_shaped:+ counts["shaped"] += 1+ else:+ violations.append((seed, msg, shown))+ return {**counts, "violations": violations}+++class TestAddedShapesOnTheLogRecordPath:+ """``_ADDITIONAL_CREDENTIAL_PATTERNS`` on the log-record path.++ ``redact_log_record`` runs them as the last step over the message and+ every ``extra`` string, after the passes ``_redact_log_text`` runs, and+ the database log row runs them over its exception prefix+ (``log_utils._exception_context``). No other function applies them, so+ no redaction pass ever runs over their output.+ """++ # One message per added shape, each with a value no other pass redacts.+ SHAPES = {+ "api-key-header": "upstream said Api-Key: Kq7ZrXw2Lp9Vt4NsSECRET",+ "slash-dsn": "connect failed postgresql://ldr:ab/cdSECRET@postgres/x",+ "semicolon-param": "GET /v1;key=abcSECRET;v=2",+ "quoted-key": "payload={'api-key': 'Kq7ZrXw2Lp9Vt4NsSECRET'}",+ }++ @pytest.mark.parametrize("msg", SHAPES.values(), ids=SHAPES.keys())+ def test_each_shape_is_redacted_in_a_log_record(self, msg):+ from local_deep_research.security.log_sanitizer import (+ redact_log_extra,+ )++ assert "SECRET" not in _logged(msg)+ assert "SECRET" not in redact_log_extra({"detail": msg})["detail"]+ assert "SECRET" not in str(redact_log_extra({"detail": [{"x": msg}]}))++ @pytest.mark.parametrize("msg", SHAPES.values(), ids=SHAPES.keys())+ def test_only_the_log_record_path_applies_them(self, msg):+ """The scope of the added shapes, pinned: client and agent+ responses, ``scrub_error`` text and the rendered exception value+ (``redact_log_message``) are redacted exactly as before, without+ them. Widening that scope means their output can reach a later+ pass of these functions; update the docs and the changelog with+ the analysis that makes that safe."""+ from local_deep_research.security.log_sanitizer import (+ _redact_log_text,+ redact_log_message,+ sanitize_error_message,+ )++ for fn in (+ sanitize_error_message,+ scrub_error,+ sanitize_error_for_client,+ sanitize_error_for_agent,+ redact_log_message,+ _redact_log_text,+ ):+ assert "SECRET" in fn(msg), fn.__name__++ @pytest.mark.parametrize(+ ("msg", "secret"),+ [+ ("payload={'api-key': 'Kq7ZrXw2Lp9Vt4Ns'}", "Kq7ZrXw2Lp9Vt4Ns"),+ ('{"password": "pa ss word123"}', "word123"),+ ("{'client_secret': Kq7ZrXw2Lp9Vt4Ns}", "Kq7ZrXw2Lp9Vt4Ns"),+ ],+ ids=["dict-repr", "json-with-space", "unquoted-value"],+ )+ def test_quoted_credential_key_value_is_redacted(self, msg, secret):+ assert secret not in _logged(msg)+ assert secret not in _logged(scrub_error(msg))++ # Assembled so no token-shaped literal appears in the file (gitleaks).+ _HEADER_VALUE = "Kq7ZrXw2" + "Lp9Vt4NsHeader"++ @pytest.mark.parametrize(+ "key",+ [+ "X-API-KEY",+ "x-api-key",+ "X-Api-Key",+ "X-API-Key",+ "x_api_key",+ "openai_api_key",+ "db_password",+ "Ocp-Apim-Subscription-Key",+ ],+ )+ @pytest.mark.parametrize("quote", ["'", '"'], ids=["repr", "json"])+ def test_prefixed_quoted_credential_key_is_redacted(self, key, quote):+ """A credential name after ``word-``/``word_`` segments: the+ request-header dicts of the Exa, Semantic Scholar, Serper, Serply+ and TinyFish engines (``x-api-key``, ``X-API-KEY``, ``X-Api-Key``,+ ``X-API-Key``) and prefixed settings names."""+ q = quote+ msg = f"headers={{{q}{key}{q}: {q}{self._HEADER_VALUE}{q}}}"+ out = _logged(msg)+ assert self._HEADER_VALUE not in out, out+ assert f"{q}{key}{q}: {q}[REDACTED]{q}" in out++ @pytest.mark.parametrize(+ "msg",+ [+ '{"secret_name": "prod-db", "password_hint": "pet name"}',+ "{'api_key_id': 'k-123', 'token_type': 'bearer'}",+ "{'max_tokens': 512, 'x-request-id': 'abc'}",+ ],+ ids=["name-not-last", "id-and-type", "non-credential"],+ )+ def test_quoted_key_must_end_with_a_credential_name(self, msg):+ assert _logged(msg) == msg++ def test_record_path_runs_redact_log_text(self, monkeypatch):+ """The record path calls ``_redact_log_text`` rather than a copy of+ its passes, so a change to ``_redact_log_text`` reaches the loguru+ patcher's message and ``extra`` strings too."""+ from local_deep_research.security import log_sanitizer as ls++ seen = []++ def spy(value):+ seen.append(value)+ return value.replace("PLAINWORD", "SPIED")++ monkeypatch.setattr(ls, "_redact_log_text", spy)+ record = {+ "message": "msg PLAINWORD",+ "extra": {"detail": "extra PLAINWORD"},+ }+ ls.redact_log_record(record)+ assert record["message"] == "msg SPIED"+ assert record["extra"]["detail"] == "extra SPIED"+ assert seen == ["msg PLAINWORD", "detail", "extra PLAINWORD"]++ def test_record_path_bounds_the_text_before_redact_log_text(+ self, monkeypatch+ ):+ """The added patterns and ``_redact_log_text`` both see only the+ bounded head; the omission marker is appended after them."""+ from local_deep_research.security import log_sanitizer as ls++ seen = []+ monkeypatch.setattr(+ ls, "_redact_log_text", lambda v: seen.append(v) or v+ )+ long = "word " * (ls._LOG_REDACTION_MAX_CHARS // 5 + 100)+ out = ls._redact_log_record_text(long)+ assert len(seen[0]) <= ls._LOG_REDACTION_MAX_CHARS+ assert out.startswith(seen[0])+ assert out.endswith("characters omitted from log output]")++ def test_quoted_credential_key_redaction_is_a_fixed_point(self):+ # The unquoted-value alternative never starts with '[', so a value+ # already redacted is not redacted again into ``[REDACTED]]``.+ once = _logged('{"password": "x", "api_key": abc123}')+ assert once == '{"password": "[REDACTED]", "api_key": [REDACTED]}'+ assert _logged(once) == once+ assert "]]" not in once++ @pytest.mark.parametrize(+ "key",+ [+ # Dotted settings keys, as the settings manager names them.+ "llm.openai.api_key",+ "llm.openai_endpoint.api_key",+ "embeddings.openai.api_key",+ "search.engine.web.serper.api_key",+ "search.engine.web.google_pse.api_key",+ "search.engine.web.semantic_scholar.api_key",+ # Environment variables, five or more segments before the name.+ "LDR_SEARCH_ENGINE_WEB_TAVILY_API_KEY",+ "LDR_SEARCH_ENGINE_WEB_GOOGLE_PSE_API_KEY",+ "LDR_LLM_OPENAI_ENDPOINT_API_KEY",+ ],+ )+ @pytest.mark.parametrize("quote", ["'", '"'], ids=["repr", "json"])+ def test_the_projects_own_credential_keys_are_redacted(self, key, quote):+ """The project's settings keys are dotted and its search-engine+ environment variables have five or more segments before+ ``API_KEY``: as an ``extra`` key (``_is_sensitive_log_key``, last+ dotted segment) they are redacted, and as a quoted key in message+ text too."""+ q = quote+ msg = f"settings={{{q}{key}{q}: {q}{self._HEADER_VALUE}{q}}}"+ out = _logged(msg)+ assert self._HEADER_VALUE not in out, out+ assert f"{q}{key}{q}: {q}[REDACTED]{q}" in out++ @pytest.mark.parametrize(+ "msg",+ [+ '{"password": {"value": "s3cretNested"}}',+ "{'password': {'value': 's3cretNested'}}",+ '{"password": { "value": "s3cretNested"}}',+ '{"password": ["s3cretNested"]}',+ "{'password': ('s3cretNested',)}",+ '{"llm.openai.api_key": {"value": "s3cretNested"}}',+ '{"password": {}}',+ ',key={"a": "s3cretNested"}',+ ],+ ids=[+ "json",+ "repr",+ "json-spaced",+ "list",+ "tuple",+ "settings-snapshot",+ "empty",+ "param",+ ],+ )+ def test_a_nested_container_value_is_not_corrupted(self, msg):+ """A nested container under a credential key is left whole: matched+ as an unquoted run it would stop after its opener, so the marker+ would eat the ``{`` and the nested value would still print."""+ assert _logged(msg) == msg++ @pytest.mark.parametrize(+ ("msg", "expected"),+ [+ (+ "{b'password': b'Zq7bytesSECRET'}",+ "{b'password': b'[REDACTED]'}",+ ),+ ('{"password": b"Zq7bytesSECRET"}', '{"password": b"[REDACTED]"}'),+ ("{'api_key': rb'Zq7bytesSECRET'}", "{'api_key': rb'[REDACTED]'}"),+ ("q=1,key=b'Zq7bytesSECRET'", "q=1,key=b'[REDACTED]'"),+ ],+ ids=["bytes-keyed", "bytes-value", "raw-bytes", "param"],+ )+ def test_a_string_prefixed_value_is_redacted_whole(self, msg, expected):+ """``b'...'`` is redacted inside its quotes, prefix kept, rather+ than as an unquoted ``b`` with the secret printed after it."""+ assert _logged(msg) == expected++ @pytest.mark.parametrize(+ "msg",+ [+ "{'password': (b'hunter2 secret',)}",+ "{'password': {b'value': b'hunter2 secret'}}",+ "{'password': {u'hunter2 secret'}}",+ "{'password': bytearray(b'hunter2 secret')}",+ "{'password': SecretStr('hunter2 secret')}",+ "{'access_token': UUID('hunter2 secret')}",+ "{'password': OrderedDict([('a', 'hunter2 secret')])}",+ "{'password': Foo(a, 'hunter2 secret')}",+ "{'password': f(g(1),'hunter2 secret')}",+ '{"password": (1, "hunter2 secret")}',+ "{'password': {0: 'hunter2 secret'}}",+ "{'password': '''hunter2 secret'''}",+ '{"password": """hunter2 secret"""}',+ "q=1,key=[b'hunter2 secret']",+ "q=1,key=(b'hunter2 secret',)",+ "q=1,key={b'hunter2 secret'}",+ "q=1;key=[u'hunter2 secret']",+ "q=1,key=ab'hunter2 secret'",+ "q=1,key=ab\\'hunter2 secret'",+ # What follows the value is not a structural follower: the+ # allowlist refuses it (#6888 final gate).+ "{'Authorization': Digest username=bob, response=Zq7digestRESP}",+ "{'Authorization': Basic Zq7basic SECRET}",+ "{'password': correct horse battery staple}",+ "{'X-API-KEY': abcd1234 efgh5678}",+ "{'password': hunter2&rest99}",+ "{'password': hunter2#rest99}",+ "{'api_key': Zq7live_abc&def&ghi}",+ '{"password": "Xy7"!kP@9qZ"}',+ "{'password': 'Pa'$$w0rd!'}",+ "{'api_key': 'ab'/cdEFgh12'}",+ "{'password': 'ab'.cd'}",+ '{"password": "abc" "def"}',+ '{"password": "abc"\\"def"}',+ "{'api_key': ApiKey(key='Zq7SECRETVALUE')}",+ "{'password': Secret(key=Zq7SECRET)}",+ "{'token': x/key=Zq7SECRET}",+ '"password": "abc,key=def ghi"',+ "q;key=ab&TAIL",+ "q;key=ab#TAIL",+ "q,key=correct horse",+ 'q;key="ab" cd',+ "Api-Key: Kq7ZrXw2Lp9Vt4NsSECRET then more",+ "Api-Key: Kq7ZrXw2Lp9Vt4NsSECRET&rest",+ "Api-Key: Kq7ZrXw2Lp9Vt4NsSECRET!rest",+ "'Api-Key: Kq7ZrXw2Lp9Vt4NsSECRET'rest",+ # A second '@', a symbol or a space after a DSN password's '@':+ # the password may hold an unescaped '@'.+ "postgres://u:pa/ss@word@host/db",+ "postgres://u:pa/ss@!x/y@db/x",+ "postgres://u:pa/ss@ word@db/x",+ ],+ )+ def test_a_value_whose_end_is_unclear_is_left_whole(self, msg):+ """A marker must never replace only the start of a value: the rest+ would print behind it and the line would look redacted. A value is+ redacted only when a structural follower for its syntax, a line+ break or the end of the text comes after it; a value that runs into+ a quote, a backslash, a symbol or a word after a space, leaves a+ bracket it opened unclosed, or is a quoted string followed straight+ by another quote is left exactly as the earlier passes left it."""+ from local_deep_research.security.log_sanitizer import (+ _redact_additional_shapes,+ )++ assert _logged(msg) == msg+ assert _redact_additional_shapes(msg) == msg++ @pytest.mark.parametrize(+ ("msg", "expected"),+ [+ ("{'password': SecretStr(1234)}", "{'password': [REDACTED]}"),+ ("{'password': f(x)}", "{'password': [REDACTED]}"),+ ("GET /v1;key=abc(1)SECRET", "GET /v1;key=[REDACTED]"),+ (+ "{'password': 'hunter2 secret', 'n': 1}",+ "{'password': '[REDACTED]', 'n': 1}",+ ),+ # Each structural follower of a quoted value.+ ("{'password': 'Zq7 secret'}", "{'password': '[REDACTED]'}"),+ (+ "{'password': 'Zq7 secret' , 'n': 1}",+ "{'password': '[REDACTED]' , 'n': 1}",+ ),+ (+ "{'password': 'Zq7 secret': rejected}",+ "{'password': '[REDACTED]': rejected}",+ ),+ (+ "set 'password': 'Zq7 secret'; Path=/",+ "set 'password': '[REDACTED]'; Path=/",+ ),+ ("f(a=1,key='Zq7 secret')", "f(a=1,key='[REDACTED]')"),+ ("[1,key='Zq7 secret']", "[1,key='[REDACTED]']"),+ ('x,key="Zq7 secret"&next=1', 'x,key="[REDACTED]"&next=1'),+ ('x;key="Zq7 secret"#frag', 'x;key="[REDACTED]"#frag'),+ ("{'password': 'Zq7 secret", "{'password': '[REDACTED]"),+ # Each structural follower of an unquoted value.+ (+ "{'password': Zq7secret, 'n': 1}",+ "{'password': [REDACTED], 'n': 1}",+ ),+ ("[{'password': Zq7secret]", "[{'password': [REDACTED]]"),+ ("{'password': Zq7secret }", "{'password': [REDACTED] }"),+ ("f(a=1,key=Zq7secret )", "f(a=1,key=[REDACTED] )"),+ (+ "x;key=Zq7secret;token=abc",+ "x;key=[REDACTED];token=[REDACTED]",+ ),+ # A scheme word and one credential token, taken whole.+ (+ "{'Authorization': Basic Zq7basicSECRET==}",+ "{'Authorization': [REDACTED]}",+ ),+ (+ "{'Proxy-Authorization': Token Zq7tokenSECRET, 'n': 1}",+ "{'Proxy-Authorization': [REDACTED], 'n': 1}",+ ),+ # The header value's followers.+ (+ "['Api-Key: Kq7ZrXw2Lp9Vt4NsSECRET', 'x']",+ "['Api-Key: [REDACTED]', 'x']",+ ),+ (+ "Api-Key: Kq7ZrXw2Lp9Vt4NsSECRET, retrying",+ "Api-Key: [REDACTED], retrying",+ ),+ # A host and its end after a DSN password's '@'.+ (+ "postgres://u:pa/ss@${DB_HOST}/x",+ "postgres://[REDACTED]:[REDACTED]@${DB_HOST}/x",+ ),+ ],+ )+ def test_a_value_with_a_clear_end_is_still_redacted(self, msg, expected):+ assert _logged(msg) == expected++ @pytest.mark.parametrize(+ "msg",+ [+ "{'password': 'Zq7 secret'\nnext line",+ "x;key=Zq7secret\nnext",+ "Api-Key: Kq7ZrXw2Lp9Vt4NsSECRET\nnext",+ ],+ ids=["quoted", "parameter", "header"],+ )+ def test_a_line_break_ends_a_value_where_one_is_kept(self, msg):+ """A line break ends a value. The record path strips it before the+ added shapes run (so the next line is glued on and the allowlist+ decides on what follows), but the database exception prefix keeps+ it, and there the value before it is redacted."""+ from local_deep_research.security.log_sanitizer import (+ _redact_additional_shapes,+ )++ out = _redact_additional_shapes(msg)+ assert "Zq7" not in out and "Kq7" not in out, out+ assert out.endswith("\nnext line") or out.endswith("\nnext")++ def test_no_marker_stands_before_an_unredacted_secret(self):+ """Seeded property over generated messages: a secret planted inside+ a credential key's value (wrapped in a container, a call, a string+ prefix, adjacent strings or nothing) is never printed straight+ after a ``[REDACTED]`` marker, with at most separators and a string+ prefix between them, on the log-record path or the database+ exception prefix, unless the passes that run before the added+ shapes already print it that way."""+ import random+ import re++ from local_deep_research.security import log_sanitizer as ls++ marker_then_secret = re.compile(+ r"\[REDACTED\][\s,:;]*[bBrRuUfF]{0,2}(?:'''|\"\"\"|[\"'])Zq7S"+ )+ wrappers = [+ ("(b'", "',)"),+ ("{b'k': b'", "'}"),+ ("{u'", "'}"),+ ("bytearray(b'", "')"),+ ("SecretStr('", "')"),+ ("OrderedDict([('a', '", "')])"),+ ("[b'", "']"),+ ("(1, '", "')"),+ ("{0: '", "'}"),+ ("Foo(a, '", "')"),+ ("f(g(1),'", "')"),+ ("((b'", "',),)"),+ ("'''", "'''"),+ ('"""', '"""'),+ ("{'v': '", "'}"),+ ("('", "',)"),+ ("b'", "'"),+ ("Rb'", "'"),+ ("'", "'"),+ ('"', '"'),+ ("x'", "'"),+ ("ab\\'", "'"),+ ("[1, 2, '", "']"),+ ("", ""),+ ]+ names = sorted(+ set(ls.LOG_SENSITIVE_KEYS)+ | {"api-key", "key", "X-API-KEY", "_api_key", "llm.x.api_key"}+ )+ noise = list("\"':=;,/@\\b()[]{} \n&#") + [+ "https://",+ "u:",+ "[REDACTED]",+ "'''",+ "abc",+ "x y",+ "Bearer ",+ "Api-Key: ",+ ]++ def junk(rng):+ out = ""+ for _ in range(rng.randint(0, 8)):+ if rng.random() < 0.3:+ q = rng.choice(['"', "'"])+ out += q + rng.choice(names) + q + rng.choice([": ", ":"])+ elif rng.random() < 0.2:+ out += rng.choice([",", ";"]) + rng.choice(names) + "="+ else:+ out += rng.choice(noise)+ return out++ def prefix_path(added, text):+ # The database exception prefix (log_utils._exception_context).+ text = added(ls.sanitize_error_message(text[:4096]))+ if len(text) > 240:+ text = added(text[:237]) + "…"+ return text++ checked = redacted = 0+ for seed in range(1500):+ rng = random.Random(seed)+ secret = f"Zq7S{seed}X"+ opener, closer = rng.choice(wrappers)+ if rng.random() < 0.5:+ q = rng.choice(['"', "'"])+ key = q + rng.choice(names) + q + rng.choice([": ", ":"])+ else:+ key = rng.choice([",", ";"]) + rng.choice(names) + "="+ msg = (+ junk(rng)+ + rng.choice(["", "{", " "])+ + key+ + opener+ + secret+ + closer+ + rng.choice(["", "}", ", 'n': 1}"])+ + junk(rng)+ )+ for shown, reference in (+ (_logged(msg), ls._redact_log_text(msg)),+ (+ prefix_path(ls._redact_additional_shapes, msg),+ prefix_path(lambda t: t, msg),+ ),+ ):+ checked += 1+ redacted += secret not in shown+ if marker_then_secret.search(reference):+ continue+ assert not marker_then_secret.search(shown), (+ f"seed {seed}: {secret} printed behind a marker\n"+ f" in: {msg!r}\n out: {shown!r}"+ )+ # The sample must exercise redaction, or the property is vacuous.+ assert redacted > checked // 5, (redacted, checked)++ def test_no_fragment_stands_behind_an_added_shape_marker(self):+ """Seeded property: a secret planted as a credential's value, with+ quotes, spaces, ``& # ! $ / . + - @`` and several words in it, has+ no 4-character fragment printed anywhere after a marker on its+ line, on the log-record path or in the database exception prefix+ (``_exception_context`` itself). See+ ``_secret_fragments_behind_a_marker`` for the slots it is planted+ in and the two exemptions, each checked rather than assumed."""+ from local_deep_research.security import log_sanitizer as ls+ from local_deep_research.utilities.log_utils import _exception_context++ found = _secret_fragments_behind_a_marker(+ ls, _exception_context, range(5000)+ )+ assert found["violations"] == [], found["violations"][:5]+ # The sample must redact the planted secret often and reach the+ # exempt shapes rarely, or the property proves little.+ assert found["hidden"] > found["checked"] // 4, found+ assert found["shaped"] < found["checked"] // 50, found++ @pytest.mark.parametrize("quote", ["'", '"'], ids=["repr", "json"])+ def test_every_log_sensitive_key_is_redacted_as_a_quoted_key(self, quote):+ """Quoted keys in message text use the names an ``extra`` key is+ redacted under (``LOG_SENSITIVE_KEYS``) and the same suffix rule,+ so the two cannot drift apart: each name, alone or after a prefix+ that ends in ``_``, ``.`` or ``-``, is redacted as a quoted key,+ as it is as an ``extra`` key."""+ from local_deep_research.security.log_sanitizer import (+ LOG_SENSITIVE_KEYS,+ _is_sensitive_log_key,+ redact_log_extra,+ )++ q = quote+ value = self._HEADER_VALUE+ for name in sorted(LOG_SENSITIVE_KEYS):+ for key in (+ name,+ name.upper(),+ f"_{name}",+ f"x__{name}",+ f"x..{name}",+ f"db_{name}",+ f"llm.openai.{name}",+ f"X-{name.replace('_', '-')}",+ ):+ if "-" not in key:+ assert _is_sensitive_log_key(key), key+ assert redact_log_extra({key: value})[key] == "[REDACTED]"+ msg = f"payload={{{q}{key}{q}: {q}{value}{q}, {q}n{q}: 1}}"+ out = _logged(msg)+ assert value not in out, out+ assert f"{q}{key}{q}: {q}[REDACTED]{q}" in out, out++ @pytest.mark.parametrize(+ "msg",+ [+ "{'Authorization': 'Basic Zq7tokenSECRET'}",+ "{'Authorization': 'Token Zq7tokenSECRET'}",+ "{'X-Subscription-Token': 'Zq7tokenSECRET'}",+ '{"api_token": "Zq7tokenSECRET", "csrf_token": "Zq7tokenSECRET"}',+ "{'encryption_key': 'Zq7tokenSECRET'}",+ "{'_password': 'Zq7tokenSECRET'}",+ ],+ )+ def test_header_and_private_credential_keys_are_redacted(self, msg):+ out = _logged(msg)+ assert "Zq7tokenSECRET" not in out, out++ def test_bare_literal_values_of_quoted_keys_stay_legible(self):+ # true/false/None/null is never a secret, and prefixed names make+ # it common (``"requires_api_key": True``).+ msg = (+ "{'requires_api_key': True, 'has_secret': false, "+ "'password': None, 'db_password': null}"+ )+ assert _logged(msg) == msg+ assert _logged("{'password': Nonesuch}") == ("{'password': [REDACTED]}")++ def test_a_key_header_glued_to_a_label_is_left_to_the_label(self):+ """The header value stops before the ``/client_secret=`` label, but+ a ``/`` is not where a header value ends (the key's class holds+ ``/``, so ``KEY/client_secret=`` could be one base64 run), so the+ key is left as the earlier passes left it, and the label's value is+ redacted by the record's assignment pass, never by a marker that+ covers only part of the run."""+ from local_deep_research.security.log_sanitizer import _redact_log_text++ msg = "api_key: Ab3Cd5Ef7Gh9Ij1Kl3Mn/client_secret=Zy8Xw6Vu4Ts2Rq;"+ out = _logged(msg)+ assert out == _redact_log_text(msg)+ assert "Zy8Xw6Vu4Ts2Rq" not in out+ assert "api_key: [REDACTED]" not in out++ @pytest.mark.parametrize(+ "dsn",+ [+ '"postgresql://u:pa/ss@db:5432/x"',+ "'postgresql://u:pa/ss@db:5432/x'",+ "<postgresql://u:pa/ss@db:5432/x>",+ "dsns=postgresql://u:pa/ss@db1,postgresql://v:pb/tt@db2",+ ],+ ids=["double-quoted", "single-quoted", "angle-bracketed", "listed"],+ )+ def test_delimited_slash_dsn_is_still_redacted(self, dsn):+ out = _logged(dsn)+ assert "pa/ss" not in out+ assert "pb/tt" not in out++ @pytest.mark.parametrize(+ "msg",+ [+ '{"base":"https://api.example.com","path":"/users/[email protected]"}',+ "http://searxng:8080,http://x/u/[email protected]",+ ],+ ids=["json-path-with-email", "list-path-with-email"],+ )+ def test_host_is_not_read_as_userinfo_across_a_boundary(self, msg):+ assert _logged(msg) == msg++ def test_slash_dsn_does_not_redact_through_a_path_label(self):+ # A "password" run holding ``/password=`` or ``=api_key=`` is a path+ # running into that label's value; redacting it up to the '@' inside+ # the value would remove the label and print the tail.+ for msg, tail in (+ (+ "http://localhost:${PORT}/cb/password=SFI_V%hoB@2DOuTAIL;",+ "2DOuTAIL",+ ),+ (+ "http://svc:http-metrics/x=api_key=Sg7z@55GR9obTAIL ",+ "55GR9obTAIL",+ ),+ ):+ out = _logged(msg)+ assert tail not in out, out++ @pytest.mark.parametrize(+ "msg",+ [+ 'params q=x,key=abc123,password="pass phrase SECRET"',+ "retry cfg;key=abc123;password = hunter2SECRET",+ "cfg;key=abc,token = hunter2SECRET",+ 'http://host:8080,key=abc,password="pass phrase SECRET"',+ ],+ ids=["comma-quoted", "semicolon-spaced", "key-then-token", "url"],+ )+ def test_a_parameter_does_not_swallow_the_next_label(self, msg):+ assert "SECRET" not in _logged(msg)++ @pytest.mark.parametrize(+ "msg",+ [+ '{"password": "a\\"b\\\\c\\/dSECRET"}',+ "{'api_key': 'a\\'b\\\\cSECRET'}",+ ',token="a\\"bSECRET"',+ ],+ ids=["json-escapes", "repr-escapes", "param-escapes"],+ )+ def test_a_quoted_value_with_escapes_is_redacted_whole(self, msg):+ # The label check after a backslash must not stop an ordinary+ # escape: a value with escaped quotes and backslashes and no label+ # is still redacted to its closing quote.+ out = _logged(msg)+ assert "SECRET" not in out+ assert "[REDACTED]" in out++ @pytest.mark.parametrize(+ "msg",+ [+ '{"api_key": "abc\\,password = "hunter2SECRET"}',+ "{'secret': 'abc\\;token = 'hunter2SECRET'}",+ "x;key='abc\\/client_secret = 'hunter2SECRET'",+ 'payload {"client_secret": "abc\\ password="hunter2 SECRET"}',+ '{"api_key": "abc\\ token="SECRET tail"}',+ '{"secret":"v\\/password="SECRET x"}',+ '"password": "x\\"api_secret=SECRET"',+ '{"api_key": "abc\\\\\\#password = "hunter2SECRET"}',+ 'password="abc;token=xyz"foo password="SECRET VALUE"',+ 'failed: password="x;pwd=y" retry api_key=" SECRET-1234"',+ 'error: password="p,secret=a"b" client_secret="two SECRET"',+ "password='pw \"api_key\": \"it's\" client_secret='pw2 SECRET'",+ ],+ )+ def test_labels_inside_values_are_still_redacted(self, msg):+ # A label after an escaped separator, or a parameter or quoted key+ # inside a quoted value: the record's assignment passes redact the+ # value after that label, and the added shapes, running after+ # them, only replace more of what those passes left.+ for out in (+ _logged(msg),+ _logged(scrub_error(msg)),+ _logged(sanitize_error_for_client(msg)),+ _logged(sanitize_error_for_agent(msg)),+ ):+ assert "SECRET" not in out, out++ def test_seeded_differential_against_the_record_passes(self):+ """The record path hides whatever ``_redact_log_text`` (its passes+ without the added shapes) hides, on a seeded sample of generated+ messages, logged as they are or after each public helper.++ Each variable part of a message carries unique markers; a marker+ the reference hides must be hidden on the record path too. The+ added shapes must also fire on part of the sample, or the+ comparison proves nothing.+ """+ import random++ from local_deep_research.security import log_sanitizer as ls++ def logged_extra(text):+ return ls.redact_log_extra({"detail": text})["detail"]++ def make_paths(secrets):+ return [+ lambda m: m,+ ls.sanitize_error_message,+ lambda m: ls.scrub_error(m, *secrets),+ lambda m: ls.sanitize_error_for_client(m, 10_000),+ ls.sanitize_error_for_agent,+ ls.strip_control_chars,+ ]++ names = sorted(+ set(ls.LOG_SENSITIVE_KEYS)+ | {"api-key", "key", "token", "secret", "pwd", "q", "url"}+ )+ punct = list("@/:?&;,#=\"'+.-_~%[]{}|<>\\ ")+ seps = [" ", ",", ";", "&", "?", "|", "\n", "", '","', "/", "#", ":"]+ stripped = ["\n", "\t", "\x1c", "", ""]+ fired = 0++ for seed in range(600):+ rng = random.Random(seed)+ markers = []++ def value(rng=rng, markers=markers):+ out = ""+ for _ in range(rng.randint(1, 3)):+ mark = "Q%c%c%d" % (+ rng.choice("ABCDEFGHJKLMNPRSTUVWXYZ"),+ rng.choice("ABCDEFGHJKLMNPRSTUVWXYZ"),+ rng.randrange(10),+ )+ markers.append(mark)+ out += mark + "".join(+ rng.choice(punct + ["a", "b", "7"])+ for _ in range(rng.randint(0, 3))+ )+ return out++ segments = []+ for _ in range(rng.randint(1, 4)):+ kind = rng.randrange(7)+ quote = rng.choice(["", '"', "'"])+ if kind == 0:+ segments.append(+ rng.choice(names)+ + rng.choice(["=", " = ", ": "])+ + quote+ + value()+ + quote+ )+ elif kind == 1:+ segments.append(+ rng.choice(["x-api-key: ", "Api-Key: ", "api_key: "])+ + value()+ + "abcdefghijklmnop"+ )+ elif kind == 2:+ user = value() + ":" + value() + "/" + value() + "@"+ segments.append(+ rng.choice(["https", "postgresql+asyncpg", "redis"])+ + "://"+ + (user if rng.random() < 0.7 else "")+ + rng.choice(["db", "localhost", "api.example.com"])+ + rng.choice(["", ":8080", ":${PORT}"])+ + rng.choice(["", "/x", "/a/b@c"])+ + rng.choice(["", "?", ";", ","])+ + rng.choice(names)+ + "="+ + value()+ )+ elif kind == 3:+ q = rng.choice(['"', "'"])+ segments.append(+ "{"+ + q+ + rng.choice(names)+ + q+ + ": "+ + quote+ + value()+ + quote+ + "}"+ )+ elif kind == 4:+ segments.append(+ rng.choice([",", ";"])+ + rng.choice(names)+ + "="+ + quote+ + value()+ + rng.choice(stripped + [""])+ + value()+ + quote+ )+ elif kind == 5:+ name = rng.choice(names)+ cut = rng.randint(0, len(name))+ segments.append(+ rng.choice(+ ["Api-Key: abcdefghijklmnopqrst/", ",key=abc/", ""]+ )+ + name[:cut]+ + rng.choice(stripped)+ + name[cut:]+ + rng.choice(["=", "= ", '="'])+ + value()+ )+ else:+ q = rng.choice(['"', "'"])+ inner = rng.choice(+ [+ rng.choice([";", ","]) + rng.choice(names) + "=",+ " " + q + rng.choice(names) + q + ": ",+ ]+ )+ segments.append(+ rng.choice(names)+ + rng.choice(["=", " = "])+ + q+ + value()+ + inner+ + value()+ + q+ )+ msg = segments[0]+ for segment in segments[1:]:+ msg += rng.choice(seps) + segment+ secrets = [value() for _ in range(rng.randrange(2))]+ for path in make_paths(secrets):+ text = path(msg)+ hidden = ls._redact_log_text(text)+ for shown in (_logged(text), logged_extra(text)):+ if shown != hidden:+ fired += 1+ for mark in markers:+ if msg.count(mark) == 1 and mark not in hidden:+ assert mark not in shown, (+ f"seed {seed}: the record path printed "+ f"{mark} that its passes hid\n"+ f" in: {text!r}\n ref: {hidden!r}\n"+ f" out: {shown!r}"+ )+ assert fired > 100, fired+++# Corpus for TestScrubIsIdempotent: URLs, autolinks, code spans, every+# marker a pass writes, credential shapes and the stop/control characters,+# alone and in every ordered pair.+# Built by concatenation so no literal here is credential-shaped.+_IDEM_SK_KEY = "sk-" + "a" * 24+_IDEM_GOOGLE_KEY = "AIza" + "B" * 30+_IDEM_SECRET = "KnownLiteralSecret123"++_IDEM_PIECES = [+ "https://h/p?q=1",+ "<https://h/p?q=1>",+ "`https://h/p?q=1`",+ "(https://h/p?q=1)",+ "[https://h/p?q=1]",+ '"https://h/p?q=1"',+ "https://h/p?q=1#frag",+ "https://h/p?<redacted>",+ "?<redacted>",+ "<redacted>",+ "[REDACTED]",+ "[REDACTED_KEY]",+ "***REDACTED***",+ "x://a?b>c",+ "https://u:pw@h/p",+ # A URL with no path: redacting a query value removes the "/" that kept+ # "h?...&z:pw@q" from reading as URL userinfo.+ "https://h?token=a/b&z:pw@q",+ "https://example.com?next=/x'",+ "z:pw@q",+ 'token="t";password="a b"',+ "?api_key=sekrit&q=2",+ "&token=t",+ "&token=t?\n",+ "api_key=abc",+ "token='x y'",+ 'password="a\\"b"',+ 'secret="unfinished',+ "password=hunter2",+ "Bearer abcdefghijkl",+ _IDEM_SK_KEY,+ _IDEM_GOOGLE_KEY,+ _IDEM_SECRET,+ " ",+ "?",+ ">",+ "<",+ "`",+ ")",+ "'",+ '"',+ "\\",+ "=",+ "\n",+ "\x1c",+ "\u200b",+]+_IDEM_CORPUS = _IDEM_PIECES + [+ a + b for a in _IDEM_PIECES for b in _IDEM_PIECES+]+++class TestScrubIsIdempotent:+ """Scrubbing already-scrubbed text must change nothing.++ Text is scrubbed twice in practice: Google PSE's ``_validate_connection``+ scrubs an error and re-raises ``type(e)(safe_msg)``, and the engine+ factory runs ``scrub_error`` over that exception again; the LLM+ rate-limit wrapper re-raises its scrubbed text the same way, and the+ log patcher runs ``redact_log_message`` over every record, scrubbed or+ not. A pass that is not a fixed point corrupts its own output on the+ second run (``?<redacted>`` grew one ``>`` per pass, breaking the+ autolink and code-span wrappers #6581 set out to keep).+ """++ _SK_KEY = _IDEM_SK_KEY+ _GOOGLE_KEY = _IDEM_GOOGLE_KEY+ _SECRET = _IDEM_SECRET+ CORPUS = _IDEM_CORPUS++ @staticmethod+ def _scrubbers():+ from local_deep_research.security.log_sanitizer import (+ _redact_log_text,+ redact_log_message,+ redact_sensitive_assignments,+ sanitize_error_message,+ )++ secret = TestScrubIsIdempotent._SECRET+ return {+ "scrub_error": scrub_error,+ "scrub_error_with_secret": lambda s: scrub_error(s, secret),+ "sanitize_error_message": sanitize_error_message,+ "redact_log_message": redact_log_message,+ "_redact_log_text": _redact_log_text,+ "redact_sensitive_assignments": redact_sensitive_assignments,+ # Above the length cap truncation is not a fixed point (a cut+ # marker can be completed by the next pass); every corpus+ # entry fits well under these caps.+ "sanitize_error_for_client": lambda s: sanitize_error_for_client(+ s, max_length=10_000+ ),+ "sanitize_error_for_agent": sanitize_error_for_agent,+ }++ @pytest.mark.parametrize(+ "name",+ [+ "scrub_error",+ "scrub_error_with_secret",+ "sanitize_error_message",+ "redact_log_message",+ "_redact_log_text",+ "redact_sensitive_assignments",+ "sanitize_error_for_client",+ "sanitize_error_for_agent",+ ],+ )+ def test_second_pass_is_a_no_op(self, name):+ scrub = self._scrubbers()[name]+ failures = []+ for text in self.CORPUS:+ once = scrub(text)+ twice = scrub(once)+ if twice != once:+ failures.append((text, once, twice))+ assert not failures, (+ f"{name} is not idempotent on {len(failures)} inputs, "+ f"first: {failures[:3]!r}"+ )++ def test_pse_rescrubbed_error_keeps_a_single_marker(self):+ # The live double-scrub path: scrub, re-raise the scrubbed text,+ # scrub the re-raised exception again.+ err = Exception(+ "403 Client Error: Forbidden for url: "+ "https://www.googleapis.com/customsearch/v1?cx=1&q=private+query"+ )+ once = scrub_error(err)+ twice = scrub_error(type(err)(once))+ assert (+ twice+ == once+ == (+ "403 Client Error: Forbidden for url: "+ "https://www.googleapis.com/customsearch/v1?<redacted>"+ )+ )++ @pytest.mark.parametrize(+ "text, expected",+ [+ ("see <https://h/p?q=1> end", "see <https://h/p?<redacted>> end"),+ ("run `https://h/p?q=1` now", "run `https://h/p?<redacted>` now"),+ ],+ )+ def test_wrappers_survive_a_second_scrub(self, text, expected):+ assert scrub_error(scrub_error(text)) == expected++ def test_quoted_assignment_glued_suffix_is_redacted_in_one_call(self):+ # A closed quote followed by non-whitespace: one pass leaves+ # "[REDACTED](tail", which the next pass reads as an unquoted value.+ # The function repeats its pass until nothing changes, so a single+ # call already returns the settled form.+ from local_deep_research.security.log_sanitizer import (+ redact_sensitive_assignments,+ )++ assert (+ redact_sensitive_assignments("token='x y'(tail) next")+ == "token=[REDACTED] next"+ )+ assert (+ redact_sensitive_assignments('password="abc"def count=3')+ == "password=[REDACTED] count=3"+ )++ def test_client_scrub_catches_a_token_joined_by_a_control_char(self):+ # Stripping the newline joins "&token=t?" and the Google key; the+ # second credential pass then redacts the joined value, so a+ # second call has nothing left to change.+ text = "&token=t?\n" + self._GOOGLE_KEY+ assert sanitize_error_for_client(text) == "&token=[REDACTED]"++ def test_literal_secret_glued_to_a_shaped_key_hides_neither(self):+ # "<secret>sk-..." has no word boundary before "sk-", so the shape+ # pass skips the key; once the literal pass replaces the secret,+ # the second shape pass sees the boundary and redacts the key.+ result = scrub_error(+ f"auth {self._SECRET}{self._SK_KEY} failed", self._SECRET+ )+ assert self._SK_KEY not in result+ assert result == "auth ***REDACTED***[REDACTED_KEY] failed"++ @pytest.mark.parametrize("name", ["redact_log_message", "_redact_log_text"])+ @pytest.mark.parametrize(+ "text",+ [+ # Over the bound before redaction.+ "token=a " * 5000,+ # Under the bound before redaction (32,100 chars), over it after.+ "token=a " * 4000 + "x" * 100,+ ],+ )+ def test_above_the_log_bound_a_second_call_only_drops_text(+ self, name, text+ ):+ # The docstrings promise a fixed point only up to+ # _LOG_REDACTION_MAX_CHARS. Above it a second call cuts again, so+ # the result changes, but only by dropping more text: what is left+ # before the new omission marker is a prefix of the first result.+ from local_deep_research.security import log_sanitizer++ scrub = getattr(log_sanitizer, name)+ once = scrub(text)+ assert len(once) > log_sanitizer._LOG_REDACTION_MAX_CHARS+ twice = scrub(once)+ assert twice != once+ marker = log_sanitizer._LOG_OMISSION_MARKER_RE.search(twice)+ assert marker is not None+ assert once.startswith(twice[: marker.start()])+ assert "token=a " not in twice++ @pytest.mark.timeout(15)+ def test_dense_marker_run_is_linear(self):+ # A whitespace-free run of already-scrubbed URLs: the first URL's+ # query runs to the end of the run (no stop character in it), so+ # the whole run collapses into one marker, and the confirming+ # round is on that short result. 20k repeats (~440 KB) keeps the+ # scrub well inside the budget on a slow CI core.+ run = "https://h/p?<redacted>" * 20_000+ t0 = time.process_time()+ result = scrub_error(run)+ elapsed = time.process_time() - t0+ assert result == "https://h/p?<redacted>"+ assert elapsed < 2.0, f"took {elapsed:.2f}s cpu on a dense marker run"+++class TestScrubNeverRedactsLessThanOnePass:+ """Each public scrub function repeats its passes until nothing changes.++ The first round starts with exactly the single pass these functions used+ to make, and everything after it only replaces more text, so nothing one+ pass redacted can reappear. These are the inputs where an earlier+ attempt at idempotence redacted less than one pass did.+ """++ @staticmethod+ def _log_scrubbers():+ from local_deep_research.security.log_sanitizer import (+ _redact_log_text,+ redact_log_message,+ redact_sensitive_assignments,+ )++ return [+ redact_log_message,+ _redact_log_text,+ redact_sensitive_assignments,+ ]++ @pytest.mark.parametrize(+ "text, secret_words",+ [+ (+ 'token="t";password="correct horse battery staple"',+ ["correct", "horse", "battery", "staple"],+ ),+ (+ 'conn(user="bob",password="a",api_key="long pass phrase here")',+ ["long", "pass phrase", "here"],+ ),+ ("token='x y'token='p q'", ["x", "y'", "p", "q'"]),+ ('token="t";password= "correct horse"', ["correct", "horse"]),+ ],+ )+ def test_glued_assignment_after_a_quoted_value_is_redacted(+ self, text, secret_words+ ):+ for scrub in self._log_scrubbers():+ once = scrub(text)+ leaked = [+ w for w in secret_words if w in once.replace("[REDACTED]", "")+ ]+ assert not leaked, f"{scrub.__name__}: {once!r} leaks {leaked}"+ assert scrub(once) == once++ @pytest.mark.parametrize(+ "text, expected",+ [+ (+ "GET https://h/search?q=a>b&term=private",+ "GET https://h/search?<redacted>",+ ),+ (+ "GET https://h/search?q=a`b&term=private",+ "GET https://h/search?<redacted>",+ ),+ (+ "403 for url: https://h/search?<redacted>&q=private+query",+ "403 for url: https://h/search?<redacted>",+ ),+ ("https://h/p?<redacted>?q=leak", "https://h/p?<redacted>"),+ ("x://a?b>c", "x://a?<redacted>"),+ # A wrapper is only given back when it ends the matched query+ # and the URL opened right after "<" or a backtick.+ ("<https://h/p?q=1>tail", "<https://h/p?<redacted>"),+ ("`https://h/p?q=1`tail", "`https://h/p?<redacted>"),+ ("see https://h/p?q=1> end", "see https://h/p?<redacted> end"),+ ("<https://h/p?q=1", "<https://h/p?<redacted>"),+ ("<https://h/p?<redacted>", "<https://h/p?<redacted>"),+ ],+ )+ def test_raw_wrapper_char_or_marker_does_not_end_the_query_redaction(+ self, text, expected+ ):+ once = scrub_error(text)+ assert once == expected+ assert scrub_error(once) == once++ def test_pathless_url_query_redaction_then_userinfo_settles_in_one_call(+ self,+ ):+ from local_deep_research.security.log_sanitizer import (+ _redact_log_text,+ redact_log_message,+ sanitize_error_message,+ )++ settled = "https://[REDACTED]:[REDACTED]@q"+ text = "https://h?token=a/b&z:pw@q"+ for scrub in (+ sanitize_error_message,+ redact_log_message,+ _redact_log_text,+ sanitize_error_for_client,+ sanitize_error_for_agent,+ ):+ assert scrub(text) == settled, scrub.__name__+ assert (+ sanitize_error_for_client("https://h?to\nken=a/b&z:pw@q") == settled+ )+ # scrub_error's query pass removes the "/" itself.+ for text, expected in (+ (+ "https://example.com?next=/x'user:hunter2@db",+ "https://[REDACTED]:[REDACTED]@db",+ ),+ (+ "https://host?a/b)x:secret@evil",+ "https://[REDACTED]:[REDACTED]@evil",+ ),+ ):+ once = scrub_error(text)+ assert once == expected+ assert scrub_error(once) == once++ @pytest.mark.parametrize("control", ["\n", "\r", "\x1c", "\u2028", "\x85"])+ def test_control_character_cannot_split_a_url_query_credential(+ self, control+ ):+ text = f"https://h?to{control}ken=a/b&z:pw@q"+ once = scrub_error(text)+ # The line break is written back after the marker, not deleted.+ assert once == f"https://h?<redacted>{control}"+ assert scrub_error(once) == once++ def test_lines_and_tabs_are_never_joined(self):+ text = "Traceback:\n File x\nValueError: bad\tthing\r\nnext\u2028end"+ assert scrub_error(text) == text++ @pytest.mark.parametrize("control", ["\n", "\t", "\u2028", "\x00"])+ def test_known_secret_split_by_a_control_character_is_redacted(+ self, control+ ):+ once = scrub_error(+ f"key: hunter2{control}secretXY tail", "hunter2secretXY"+ )+ kept = control if control.isspace() else ""+ assert once == f"key: ***REDACTED***{kept} tail"+ assert scrub_error(once, "hunter2secretXY") == once+++class TestScrubNeverLogsWhatMainRedacted:+ """Inputs where an earlier version of the #6581 change logged a secret+ that the code before it redacted, through the log patcher alone or+ through ``scrub_error`` followed by the log patcher."""++ @staticmethod+ def _patcher(text):+ from local_deep_research.security.log_sanitizer import (+ _redact_log_text,+ )++ return _redact_log_text(text)++ @pytest.mark.parametrize(+ "text",+ [+ 'password=a,token="b and api_key="correct horse battery staple"',+ "auth failed: user=bob;password=pw;"+ 'secret="x and password="correct horse battery staple"',+ "password=a,token = \"b and api_key='correct horse battery staple'",+ ],+ )+ def test_stop_never_pairs_a_quote_with_the_next_credential(self, text):+ """A quoted value still open at whitespace is not a stop: its match+ would close on the next credential's opening quote and leave the+ rest of that credential's value visible."""+ from local_deep_research.security.log_sanitizer import (+ redact_log_message,+ redact_sensitive_assignments,+ )++ for once in (+ redact_sensitive_assignments(text),+ redact_log_message(text),+ self._patcher(scrub_error(text)),+ ):+ for word in ("horse", "battery", "staple"):+ assert word not in once, once++ @pytest.mark.parametrize(+ "text, secret",+ [+ # The stripped view joins the split name; the patcher must not+ # take the next line's half name as its value.+ (+ "Error\nauthorizatio\u200bn=hunt3rq9zxw'api_\nkey=KEY12345678",+ "KEY12345678",+ ),+ (+ "Error\nauthorizatio\u200bn=hunt3rq9zxw'pass\nword=KEY12345678",+ "KEY12345678",+ ),+ # Extending a span over a split credential took the next+ # assignment's name; it now takes its value too.+ (+ 'passwd=?clients\necret="&;accesstoken= SECRETVAL9=',+ "SECRETVAL9",+ ),+ ],+ )+ def test_glued_view_leaves_no_value_without_its_name(self, text, secret):+ once = scrub_error(text)+ assert secret not in self._patcher(once)+ assert scrub_error(once) == once++ def test_glued_view_is_skipped_above_its_bound(self):+ from local_deep_research.security.log_sanitizer import (+ _GLUED_VIEW_MAX_CHARS,+ _scrub_across_controls,+ )++ split = "https://h/p?to\nken=abc "+ short = split + "x" * (_GLUED_VIEW_MAX_CHARS - len(split))+ assert _scrub_across_controls(short, []) != short+ long = short + "x"+ assert _scrub_across_controls(long, []) == long++ def test_adversarial_line_breaks_cost_stays_bounded(self):+ run = "https://h/p?q=1" + "\nBeare\rr x" * 25_000+ t0 = time.process_time()+ scrub_error(run)+ elapsed = time.process_time() - t0+ assert elapsed < 3.0, f"took {elapsed:.2f}s cpu on 250 KB"++ def test_glued_view_reads_the_patchers_pass_list(self, monkeypatch):+ """A pass added to the patcher is one the stripped view fits its+ redactions around, without a second list to update."""+ import re++ from local_deep_research.security import log_sanitizer++ name = r"(OPENAI_API_KEY)(\s*=\s*)(?:'[^']*'|\S+)"+ monkeypatch.setattr(+ log_sanitizer,+ "_LOG_PATCHER_BARE_PASSES",+ (+ *log_sanitizer._LOG_PATCHER_BARE_PASSES,+ log_sanitizer._BarePass(+ re.compile(r"(?<![\w.?&-])" + name),+ r"\1\2[REDACTED]",+ 1,+ 2,+ re.compile(name),+ ),+ ),+ )+ text = "GET https://h/p?q=1\nOPENAI_API_KEY='correct horse'"+ once = scrub_error(text)+ assert (+ once == "GET https://h/p?<redacted>\nOPENAI_API_KEY='correct horse'"+ )+ logged = log_sanitizer._redact_log_text(once)+ assert "correct" not in logged and "horse" not in logged+++ "name", ["api_key", "OPENAI_API_KEY", "db_password", "llm.openai.api_key"]+)[email protected]("separator", ["=", "= ", " = "])+ "value",+ ["PlainSecret739", '"PlainSecret739 extra"', "'PlainSecret739 extra'"],+)+def test_query_scrub_covers_glued_assignment_values(name, separator, value):+ """URL-query scrubbing must cover a name's whole quoted/spaced value."""+ message = f"GET https://h/p?q=1\u200b{name}{separator}{value}"+ scrubbed = scrub_error(message)+ assert scrubbed == "GET https://h/p?<redacted>"+ assert scrub_error(scrubbed) == scrubbeddiff --git a/tests/security/test_log_scrub_composition.py b/tests/security/test_log_scrub_composition.pynew file mode 100644index 0000000000..06febf9cff--- /dev/null+++ b/tests/security/test_log_scrub_composition.py@@ -0,0 +1,103 @@+"""Preserve credential coverage when query scrubbing precedes log sinks."""++import pytest+from loguru import logger++from local_deep_research.security.log_sanitizer import (+ redact_log_record,+ scrub_error,+)+from tests.test_utils import restored_loguru_state++[email protected]("control", ["\u2060", "\x00", "\n"])+ "template",+ [+ "x-api-key:{secret}.a{control}pikey=P",+ "redis://:{secret}_passwd={control}@db.example",+ ],+)[email protected]("known_secrets", [(), ("unrelated-known-secret",)])+def test_control_view_keeps_outer_credential_values_hidden(+ template, control, known_secrets+):+ # A credential-looking name inside a header/URL value must not shrink+ # the outer redaction to its label while leaving its value visible.+ secret = "Canary731xy"+ text = "Request failed: " + template.format(secret=secret, control=control)+ direct = {"message": text, "extra": {}}+ redact_log_record(direct)+ assert secret not in direct["message"]++ scrubbed = scrub_error(text, *known_secrets)+ with restored_loguru_state():+ logger.remove()+ logger.configure(patcher=redact_log_record)+ seen = []+ logger.add(seen.append, format="{message}", diagnose=False)+ logger.error(scrubbed)+ assert len(seen) == 1+ assert secret not in str(seen[0])+ assert str(seen[0]).startswith("Request failed: ")+ assert scrub_error(scrubbed, *known_secrets) == scrubbed++[email protected]("padding", ["none", "before", "after"])+ ("message", "secret"),+ [+ (+ "secret=b_password='s://p?\u2028r apik\rey=\"Authorization=Z\"' 'Canary1310x5Z",+ "Canary1310x5Z",+ ),+ ("s://p?pw\u2028d=s://x?1\u2028p\twd= Canary1382x5Z", "Canary1382x5Z"),+ ('s://p?="secret=" Canary1690x4Z', "Canary1690x4Z"),+ ("s://p?='ApiKey=''Canary2311x4Z", "Canary2311x4Z"),+ ("s://p?secret=\x1cpw\x1cd='secret=Z' Canary4109x3Z", "Canary4109x3Z"),+ ("s://x?='ApiKey=' Canary5416x5Z", "Canary5416x5Z"),+ ('s://x?="secret=" Canary6671x6Z', "Canary6671x6Z"),+ (+ "s://p?password=\nAu\u2028thorization: Canary7190x1Z",+ "Canary7190x1Z",+ ),+ ("s://x?}passwd=\u2028passwor\nd= Canary8032x3Z'pwd=", "Canary8032x3Z"),+ ('s://x?="pwd="\'Canary8504x3Z', "Canary8504x3Z"),+ ('s://{?="Authorization=""Canary10405x4Z', "Canary10405x4Z"),+ (+ '\rapi_key="x\rCanary128920x0Z\u2028?https://h/p?ap\ti_key=Canary128920x1Z\r\x85OPENAI_API_KEY: "Canary128920x2Z"\x1c\u2028Bearer Canary128920x3Zabcdefghijk"\u200bpass\u2028word= \'Canary128920x4Z\'\x00{\rBearer Canary128920x5Zabcdefghijk:[https://u:Canary128920x6Z@h/x?q=1',+ "Canary128920x4Z",+ ),+ (+ "https://h/p?api_key=Canary133226x0Z{{\t\u200bBearer Canary133226x1Zabcdefghijk{/api_key='x;Bearer='Canary133226x2Z'@https://h/p?O\tPENAI_API_KEY=Canary133226x3Z?\r\tclient_secret = \"Canary133226x4Z\"\tpas\x00sword = \"Canary133226x5Z\"\u2028?\"password = 'Canary133226x6Z'",+ "Canary133226x5Z",+ ),+ ],+)+def test_query_scrubbing_keeps_later_credentials_redacted(+ message, secret, padding+):+ # Query guards must still protect values beyond the control-view budget.+ if padding == "before":+ message = "context " * 600 + message+ elif padding == "after":+ message += " diagnostic" * 600+ record = {"message": scrub_error(message), "extra": {}}+ redact_log_record(record)+ assert secret not in record["message"]++[email protected]("repetitions", [1, 128])+def test_repeated_split_credentials_keep_no_value_after_scrubbing(repetitions):+ secret = "CanaryBounded12345678"+ message = (+ "Request failed: "+ + ("s://p?pw\u2028d=s://x?1\u2028p\twd= " + secret + "\n") * repetitions+ + " diagnostic-end"+ )+ record = {"message": scrub_error(message), "extra": {}}+ redact_log_record(record)+ assert secret not in record["message"]+ assert record["message"].startswith("Request failed: ")+ if repetitions == 1:+ assert record["message"].endswith(" diagnostic-end")diff --git a/tests/security/test_log_sink_redaction.py b/tests/security/test_log_sink_redaction.pyindex 78b4fe82cd..b10d300ac2 100644--- a/tests/security/test_log_sink_redaction.py+++ b/tests/security/test_log_sink_redaction.py@@ -23,6 +23,7 @@ from local_deep_research.security.log_sanitizer import (redact_log_extra,redact_log_message,redact_sensitive_assignments,+ scrub_error,)from tests.test_utils import restored_loguru_state@@ -231,7 +232,7 @@ 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+ the message scrub never touches; ``redact_log_exception`` closes thatgap by building a redacted COPY of the exception (and its``__cause__``/``__context__`` chain) for the sinks to render, leavingtraceback structure intact -- and leaving the original, live exception@@ -273,7 +274,7 @@ class TestExceptionValueRedactedInRenderedSink:class TestExceptionInstanceNotMutated:- """`_redact_exception_value` must copy, never mutate, the live exception.+ """`redact_log_exception` 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@@ -515,6 +516,85 @@ def test_redaction_preserves_control_character_boundaries()[email protected]("separator", ["\n", "\r\n", "\t", "\u2028", "\x1c"])[email protected]("name", ["password", "client_secret", "token"])+def test_scrub_error_output_keeps_control_character_boundaries(+ captured_records, separator, name+):+ """``logger.x(f"...{scrub_error(e)}")`` is the sanctioned pattern, so the+ patcher sees scrub_error's output, not the raw text. scrub_error must+ not glue a line-initial credential name onto the previous word."""+ safe = scrub_error(f"Request failed{separator}{name}=BoundaryCredential739")+ assert safe == f"Request failed{separator}{name}=BoundaryCredential739"+ logger.warning(f"Search failed: {safe}")+ assert captured_records, "sink captured nothing"+ message = captured_records[-1]["message"]+ assert "BoundaryCredential739" not in message+ assert message == f"Search failed: Request failed{name}=[REDACTED]"++[email protected]("name", ["password", "pass\u200bword"])+def test_scrub_error_never_takes_a_name_from_its_quoted_value(+ captured_records, name+):+ """Joining lines lets a URL query run on into the next line. It must+ stop before a credential name whose quoted value it cannot reach, or+ the patcher is left the value without its name."""+ safe = scrub_error(f"GET https://h/p?q=1\n{name}='correct horse'")+ assert safe == f"GET https://h/p?<redacted>\n{name}='correct horse'"+ logger.warning(f"Search failed: {safe}")+ assert captured_records, "sink captured nothing"+ message = captured_records[-1]["message"]+ assert "correct" not in message+ assert "horse" not in message+++def test_assignment_glued_onto_a_marker_is_redacted(captured_records):+ """Stripping the invisible character joins ``api_key`` onto the marker+ left by the assignment before it; that assignment's unquoted value must+ stop at the marker, not run on and take the name."""+ assert (+ redact_sensitive_assignments("token = [REDACTED]api_key = Glued739")+ == "token = [REDACTED]api_key = [REDACTED]"+ )+ assert (+ redact_sensitive_assignments('token=x;password="p q" r')+ == "token=[REDACTED]password=[REDACTED] r"+ )+ logger.info("token = abc\nap\u200bi_key = MarkerGlued739")+ assert captured_records, "sink captured nothing"+ assert "MarkerGlued739" not in captured_records[-1]["message"]+++ "name", ["OPENAI_API_KEY", "db_password", "llm.openai.api_key"]+)+def test_prefixed_assignment_glued_onto_a_marker_is_redacted(+ captured_records, name+):+ """The next name must survive the first assignment's value match."""+ from local_deep_research.security.log_sanitizer import _redact_log_text++ cases = (+ (f"token = [REDACTED]{name} = MarkerGlued739", "MarkerGlued739"),+ (f'token=x;{name}="correct horse" r', "correct horse"),+ )+ for message, secret in cases:+ for redact in (+ redact_sensitive_assignments,+ redact_log_message,+ _redact_log_text,+ ):+ redacted = redact(message)+ assert all(word not in redacted for word in secret.split()), (+ redact.__name__,+ redacted,+ )+ logger.info(message)+ logged = captured_records[-1]["message"]+ assert all(word not in logged for word in secret.split()), logged++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")@@ -563,6 +643,10 @@ def test_repeated_exception_children_respect_traversal_limit(captured_records):# 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+# The sink test also runs Loguru's patcher for both the message and bound+# extra. Under coverage and xdist, this can exceed 1 s on a busy runner even+# though scanning remains bounded to the first 32 KiB of each value.+_LOG_PATH_BUDGET_SECONDS = 2.0@pytest.mark.parametrize(@@ -575,14 +659,17 @@ def test_credential_shape_patterns_are_linear_on_repeated_prefixes("""sanitize_error_message (not length-capped) stays fast on a long run."""import time+ # Measure redaction's CPU work without counting xdist/runner preemption.+ # The same one-second budget still rejects pathological backtracking.+from local_deep_research.security.log_sanitizer import (sanitize_error_message,)message = fragment * (size // len(fragment))- started = time.perf_counter()+ started = time.thread_time()sanitize_error_message(message)- elapsed = time.perf_counter() - started+ elapsed = time.thread_time() - startedassert elapsed < _QUADRATIC_BUDGET_SECONDS, elapsed@@ -602,7 +689,7 @@ def test_log_path_redaction_cost_is_bounded(captured_records, message):started = time.perf_counter()logger.bind(detail=message).info(message)elapsed = time.perf_counter() - started- assert elapsed < _QUADRATIC_BUDGET_SECONDS, elapsed+ assert elapsed < _LOG_PATH_BUDGET_SECONDS, elapsedrecord = captured_records[-1]for value in (record["message"], record["extra"]["detail"]):assert value.endswith("characters omitted from log output]")@@ -861,6 +948,137 @@ def test_prefixed_sensitive_extra_keys_are_masked():assert out["max_tokens"] == 512+class TestAddedCredentialShapesThroughThePatcher:+ """``_ADDITIONAL_CREDENTIAL_PATTERNS`` reach every sink of a record.++ The patcher runs them last over the message and the ``extra`` strings,+ and the database sink runs them over its exception prefix. The rendered+ exception value (``_redact_exception_value``) is redacted by+ ``redact_log_message`` alone and does not get them.+ """++ # Assembled so no token-shaped literal appears in the file (gitleaks).+ SECRET = "Kq7ZrXw2Lp9Vt4Ns" + "AddedShape"++ def test_message_extra_and_database_exception_prefix(+ self, captured_records+ ):+ from local_deep_research.security.log_sanitizer import scrub_error+ from local_deep_research.utilities.log_utils import _exception_context++ # The shape of llm_config._log_llm_error: a gateway echoing the+ # rejected request, scrubbed with no known literal, then logged.+ error = RuntimeError(+ "401 from gateway: rejected request "+ f"{{'headers': {{'api-key': '{self.SECRET}'}}}}"+ )+ logger.opt(exception=error).bind(+ detail=f"sent Api-Key: {self.SECRET}"+ ).error(f"LLM Request - Failed with error: {scrub_error(error)}")++ record = captured_records[-1]+ assert "LLM Request - Failed with error" in record["message"]+ assert self.SECRET not in record["message"]+ assert self.SECRET not in record["extra"]["detail"]+ prefix = _exception_context(record)+ assert prefix.startswith("[RuntimeError: 401 from gateway")+ assert self.SECRET not in prefix++ @pytest.mark.parametrize(+ "pad",+ [205, 215, 225, 230],+ ids=["22-left", "12-left", "2-left", "label-cut"],+ )+ def test_database_exception_prefix_is_redacted_before_its_cap(self, pad):+ """The added shapes run on the 4096-bounded text before the+ 240-character cap: a key the cap would cut below the header+ pattern's 16-character floor (12 or 2 of its characters left, or+ its label itself cut) must not print its head."""+ from types import SimpleNamespace++ from local_deep_research.utilities.log_utils import _exception_context++ error = ValueError(+ "x" * pad + f" Api-Key: {self.SECRET}, then a long tail" * 3+ )+ prefix = _exception_context(+ {"exception": SimpleNamespace(type=ValueError, value=error)}+ )+ assert prefix.startswith("[ValueError: xxx")+ assert prefix.endswith("…] ")+ assert len(prefix) <= len("[ValueError: ] ") + 238+ assert f"Api-Key: {self.SECRET[:2]}" not in prefix, prefix++ def test_database_exception_prefix_slash_dsn_cut_before_its_at(self):+ """A slash-bearing DSN password whose ``@`` lies past the cap is+ redacted before the cap removes the ``@`` it is recognised by."""+ from types import SimpleNamespace++ from local_deep_research.utilities.log_utils import _exception_context++ password = "ab/cd" + "Zq7" * 12+ error = ValueError(+ "x" * 180 + f" postgresql://ldr:{password}@postgres:5432/ldr"+ )+ prefix = _exception_context(+ {"exception": SimpleNamespace(type=ValueError, value=error)}+ )+ assert "ab/cd" not in prefix, prefix+ assert "[REDACTED]:[REDACTED]@postgres" in prefix++ @pytest.mark.parametrize(+ "tail",+ [+ ' {"password": "hunter2' + "Zq" * 60 + " it's here\"}",+ " ;password=hunter2" + "Zq" * 60 + "&q=1",+ ],+ ids=["quote-of-the-other-kind", "ampersand"],+ )+ @pytest.mark.parametrize("pad", [100, 200])+ def test_database_exception_prefix_is_redacted_again_after_its_cap(+ self, pad, tail+ ):+ """A value the first pass leaves alone because of what follows it+ (a quote of the other kind, a ``&``) loses that to the cap; the+ pass on the capped text then redacts its head."""+ from types import SimpleNamespace++ from local_deep_research.utilities.log_utils import _exception_context++ error = ValueError("x" * pad + tail)+ prefix = _exception_context(+ {"exception": SimpleNamespace(type=ValueError, value=error)}+ )+ assert prefix.endswith("…] ")+ assert "hunter2" not in prefix, prefix+ assert "password" in prefix++ def test_one_match_in_a_long_message_costs_what_the_bound_allows(self):+ """One added-shape match in a long message is redacted at the cost+ of a few regex passes over the 32 KiB the patcher keeps: no+ per-character bookkeeping, no growth with the message."""+ import tracemalloc++ from local_deep_research.security.log_sanitizer import (+ redact_log_record,+ )++ message = '{"password": "q w"} ' + "lorem ipsum " * 90_000+ record = {"message": message, "extra": {"detail": message}}+ tracemalloc.start()+ try:+ redact_log_record(record)+ _, peak = tracemalloc.get_traced_memory()+ finally:+ tracemalloc.stop()+ assert record["message"].startswith('{"password": "[REDACTED]"}')+ assert record["extra"]["detail"].startswith(+ '{"password": "[REDACTED]"}'+ )+ # Two 32 KiB strings and their intermediate copies, with headroom.+ assert peak < 4 * 1024 * 1024, peak++# 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.@@ -876,3 +1094,4072 @@ def test_parametrized_node_ids_stay_short(request):if item.path == module_path and len(item.nodeid) > _MAX_NODE_ID_LENGTH]assert not long_ids, long_ids+++class _RaisingStrError(Exception):+ def __str__(self):+ raise RuntimeError("str refused")+++class _NonStrStrError(Exception):+ def __str__(self):+ return 42+++class _RaisingNote:+ def __str__(self):+ raise RuntimeError("note refused")+++def _raise_and_log(exc):+ """Raise *exc* from this frame and log it.++ The rendered traceback then shows this frame's source line, ``raise exc``,+ which only a rendered traceback contains (the log line's header names the+ function but not the source line).+ """+ try:+ raise exc+ except BaseException:+ logger.opt(exception=True).error("unprintable failure")+++ "exc_type", [_RaisingStrError, _NonStrStrError], ids=["raises", "non_str"]+)+def test_unprintable_exception_keeps_traceback_and_redacts_cause(+ rendered_sink, exc_type+):+ """A failing ``__str__`` replaces that node's text, not the traceback."""+ exc = exc_type()+ exc.__cause__ = ValueError("token=UnprintableCause739")+ _raise_and_log(exc)+ rendered = rendered_sink.getvalue()+ assert "Traceback" in rendered+ assert "raise exc" in rendered+ assert f"<unprintable {exc_type.__name__}>" in rendered+ assert "UnprintableCause739" not in rendered+++def test_unprintable_note_keeps_traceback_and_other_notes(rendered_sink):+ exc = ValueError("token=UnprintableNote739")+ exc.__notes__ = [_RaisingNote(), "kept diagnostic note"]+ _raise_and_log(exc)+ rendered = rendered_sink.getvalue()+ assert "Traceback" in rendered+ assert "raise exc" in rendered+ assert "<unprintable _RaisingNote>" in rendered+ assert "kept diagnostic note" in rendered+ assert "UnprintableNote739" not in rendered++[email protected]("link", ["__cause__", "__context__"])+def test_unprintable_cause_or_context_keeps_traceback(rendered_sink, link):+ exc = ValueError("token=UnprintableLink739")+ setattr(exc, link, _RaisingStrError())+ _raise_and_log(exc)+ rendered = rendered_sink.getvalue()+ assert "Traceback" in rendered+ assert "raise exc" in rendered+ assert "_RaisingStrError" in rendered+ assert "UnprintableLink739" not in rendered+++def test_unprintable_group_child_keeps_traceback(rendered_sink):+ exc = ExceptionGroup(+ "token=UnprintableGroup739",+ [_RaisingStrError(), ValueError("ordinary child")],+ )+ _raise_and_log(exc)+ rendered = rendered_sink.getvalue()+ assert "Traceback" in rendered+ assert "raise exc" in rendered+ assert "_RaisingStrError" in rendered+ assert "ordinary child" in rendered+ assert "UnprintableGroup739" not in rendered+++def test_exception_redaction_failure_keeps_traceback(+ rendered_sink, monkeypatch+):+ """If the rebuild itself raises, the value is replaced, not the record."""+ from local_deep_research.security import log_sanitizer++ def _fail(*args, **kwargs):+ raise RuntimeError("rebuild failed")++ monkeypatch.setattr(log_sanitizer, "_build_redacted_exception", _fail)+ _raise_and_log(ValueError("token=RebuildFailure739"))+ rendered = rendered_sink.getvalue()+ assert "Traceback" in rendered+ assert "raise exc" in rendered+ assert "redaction failed" in rendered+ assert "RebuildFailure739" not in rendered+++def test_normalized_credential_name_in_exception_is_redacted(rendered_sink):+ """An invisible character cannot hide a credential name in an exception."""+ _raise_and_log(ValueError("api_key=ExceptionZeroWidth739"))+ rendered = rendered_sink.getvalue()+ assert "ValueError" in rendered+ assert "ExceptionZeroWidth739" not in rendered+++# Characters ``str.isspace()`` calls whitespace that a sink can still draw+# as nothing; each must be removed like a zero-width space.+_HIDING_WHITESPACE = {+ "fs": "\x1c",+ "us": "\x1f",+ "nel": "\x85",+ "vt": "\x0b",+ "ff": "\x0c",+ "ls": "\u2028",+}+++ "char", list(_HIDING_WHITESPACE.values()), ids=list(_HIDING_WHITESPACE)+)+def test_whitespace_control_char_cannot_hide_a_credential_in_an_exception(+ rendered_sink, char+):+ """``str.isspace()`` is true for these, yet they can hide a split."""+ _raise_and_log(+ ValueError(+ f"db https://admin:hunt{char}[email protected]/ ; "+ f"tok{char}en=abcd1234NameSplit739"+ )+ )+ rendered = rendered_sink.getvalue()+ assert "raise exc" in rendered+ assert "UserInfo739" not in rendered+ assert "NameSplit739" not in rendered+++ "char", list(_HIDING_WHITESPACE.values()), ids=list(_HIDING_WHITESPACE)+)+def test_whitespace_control_char_cannot_hide_a_credential_in_the_db_prefix(+ captured_records, char+):+ from local_deep_research.utilities.log_utils import _exception_context++ _raise_and_log(ValueError(f"lookup failed: tok{char}en=abcd1234DbRow739"))+ prefix = _exception_context(captured_records[-1])+ assert prefix.startswith("[ValueError: ")+ assert "DbRow739" not in prefix+++def test_benign_multiline_exception_keeps_its_line_breaks(rendered_sink):+ exc = ValueError("first line\nsecond line")+ exc.__cause__ = ValueError("token=MultilineCause739")+ _raise_and_log(exc)+ rendered = rendered_sink.getvalue()+ assert "first line\nsecond line" in rendered+ assert "MultilineCause739" not in rendered+++class ApplicationError(Exception):+ """Module level, so an ``enqueue=True`` sink can pickle it by name."""+++def test_rebuilt_application_exception_names_its_type_once(captured_records):+ from local_deep_research.utilities.log_utils import _exception_context++ _raise_and_log(ApplicationError("token=ContextPrefix739"))+ prefix = _exception_context(captured_records[-1])+ assert prefix == "[ApplicationError: token=[REDACTED]] "+++def test_unpicklable_application_exception_type_is_replaced(captured_records):+ """A class defined in a function cannot stay the record's ``type``."""+ from local_deep_research.utilities.log_utils import _exception_context++ class LocalApplicationError(Exception):+ pass++ _raise_and_log(LocalApplicationError("token=ContextPrefix739"))+ record = captured_records[-1]+ assert record["exception"].type is RuntimeError+ assert _exception_context(record) == (+ "[RuntimeError: LocalApplicationError: token=[REDACTED]] "+ )+++def test_extra_keys_sets_and_bytes_are_scrubbed():+ out = redact_log_extra(+ {+ "hits": {"https://alice:[email protected]/x": 3},+ "https://bob:[email protected]/": 1,+ "raw": b"api_key=ExtraBytesSecret739",+ "tags": {"token=ExtraSetSecret739"},+ "frozen": frozenset({"token=ExtraFrozenSecret739"}),+ "plain": b"ordinary\nbytes",+ }+ )+ assert "Secret739" not in repr(out)+ assert out["raw"] == "api_key=[REDACTED]"+ assert out["tags"] == ["token=[REDACTED]"]+ assert out["plain"] == b"ordinary\nbytes"+++ "raw",+ [b"tok\x1fen=BytesHidden739", b"tok\nen=BytesHidden739"],+ ids=["unit_separator", "newline"],+)+def test_bytes_redacted_like_the_same_str(raw):+ """A bytes leaf is redacted whenever the same text as a str would be."""+ out = redact_log_extra({"raw": raw, "text": raw.decode()})+ assert out["text"] == "token=[REDACTED]"+ assert out["raw"] == "token=[REDACTED]"+++class _RaisingNotesError(Exception):+ @property+ def __notes__(self):+ raise RuntimeError("token=" + "NotesProperty739")+++def test_raising_notes_property_is_not_rendered(rendered_sink):+ """Python reports a raising ``__notes__`` with the error's repr."""+ _raise_and_log(_RaisingNotesError("ordinary failure"))+ rendered = rendered_sink.getvalue()+ assert "raise exc" in rendered+ assert "_RaisingNotesError: ordinary failure" in rendered+ assert "notes omitted" in rendered+ assert "NotesProperty739" not in rendered+++ ("text", "expected"),+ [+ (+ "request failed: api_key=abc123\nstatus: 401",+ "request failed: api_key=[REDACTED]\nstatus: 401",+ ),+ ("token=abc\nxyz", "token=[REDACTED]\nxyz"),+ ],+ ids=["next_line_label", "next_line_word"],+)+def test_redacted_line_end_keeps_the_next_line(rendered_sink, text, expected):+ """The second pass must not glue a redacted value onto the next line."""+ _raise_and_log(ValueError(text))+ assert f"ValueError: {expected}" in rendered_sink.getvalue()++[email protected]("routing_first", [True, False], ids=["first", "last"])+def test_redacted_key_cannot_replace_a_routing_key(routing_first):+ items = [("username", "alice"), ("user\u200bname", "attacker")]+ if not routing_first:+ items.reverse()+ out = redact_log_extra(dict(items))+ assert out["username"] == "alice"+ assert "attacker" in out.values()+++def test_colliding_redacted_keys_keep_every_entry():+ out = redact_log_extra(+ {+ "nested": {+ "https://alice:[email protected]/": 1,+ "https://alice:[email protected]/": 2,+ ("token=TupleKey739",): 3,+ },+ "a\nb": 4,+ "ab": 5,+ }+ )+ assert "739" not in repr(out)+ assert sorted(out["nested"].values()) == [1, 2, 3]+ assert sorted(v for k, v in out.items() if k != "nested") == [4, 5]+++def test_long_bytes_are_bounded_and_redacted():+ from local_deep_research.security.log_sanitizer import (+ _LOG_REDACTION_MAX_CHARS,+ )++ raw = b"api_key=LongBytes739 " + b"ab " * 100_000+ out = redact_log_extra({"raw": raw})["raw"]+ marker = (+ f" [... {len(raw)} bytes in total, the rest omitted from log output]"+ )+ assert isinstance(out, str)+ assert "LongBytes739" not in out+ assert out.startswith("api_key=[REDACTED] ab ab ")+ assert out.endswith(marker)+ # The kept text is the redacted head, cut at the character bound at a+ # space: no longer than the bound, and not much shorter.+ kept = out[: -len(marker)]+ assert (+ _LOG_REDACTION_MAX_CHARS - 16 <= len(kept) <= _LOG_REDACTION_MAX_CHARS+ )+ assert "omitted from log output" not in kept+++def test_undecodable_byte_does_not_hide_a_credential_name():+ out = redact_log_extra({"raw": b"\x80token=BytesGlue739"})+ assert "BytesGlue739" not in repr(out)+++def test_failed_redaction_keeps_the_type_in_the_db_prefix(+ captured_records, monkeypatch+):+ from local_deep_research.security import log_sanitizer+ from local_deep_research.utilities.log_utils import _exception_context++ def _fail(*args, **kwargs):+ raise RuntimeError("rebuild failed")++ monkeypatch.setattr(log_sanitizer, "_build_redacted_exception", _fail)+ _raise_and_log(ValueError("token=PrefixFailure739"))+ prefix = _exception_context(captured_records[-1])+ assert prefix == (+ "[ValueError: <exception text omitted: redaction failed>] "+ )+++class ApplicationGroup(ExceptionGroup):+ """Module level, so an ``enqueue=True`` sink can pickle it by name."""+++def test_group_subclass_keeps_its_name(rendered_sink):+ from local_deep_research.utilities.log_utils import _exception_context++ records = []+ sink = logger.add(+ lambda message: records.append(message.record), diagnose=False+ )+ try:+ _raise_and_log(+ ApplicationGroup("token=GroupSubclass739", [ValueError("child")])+ )+ finally:+ logger.remove(sink)+ rendered = rendered_sink.getvalue()+ # The rendered traceback names the subclass, not only a builtin group.+ assert "ApplicationGroup: token=[REDACTED]" in rendered+ assert "GroupSubclass739" not in rendered+ # The DB row took the name from the record's type before this change+ # too; what this pins is that the name the rebuilt group now carries in+ # its text is not repeated (``[ApplicationGroup: ApplicationGroup: ...``).+ assert _exception_context(records[-1]) == (+ "[ApplicationGroup: token=[REDACTED] (1 sub-exception)] "+ )+++class _NoteWithHiddenStr:+ """A note whose ``str()`` (what traceback renders) differs from repr."""++ def __str__(self):+ return "token=" + "NoteItemStr739"++ def __repr__(self):+ return "<note>"+++class _NotesObject:+ """A non-sequence ``__notes__``: traceback renders its ``repr()``."""++ def __str__(self):+ return "benign notes"++ def __repr__(self):+ return "token=" + "NotesRepr739"+++def test_user_list_notes_are_checked_item_by_item(rendered_sink):+ from collections import UserList++ exc = ValueError("ordinary failure")+ exc.__notes__ = UserList([_NoteWithHiddenStr(), "kept note"])+ _raise_and_log(exc)+ rendered = rendered_sink.getvalue()+ assert "raise exc" in rendered+ assert "token=[REDACTED]" in rendered+ assert "kept note" in rendered+ assert "NoteItemStr739" not in rendered+++def test_non_sequence_notes_are_checked_by_repr(rendered_sink):+ exc = ValueError("ordinary failure")+ exc.__notes__ = _NotesObject()+ _raise_and_log(exc)+ rendered = rendered_sink.getvalue()+ assert "raise exc" in rendered+ assert "token=[REDACTED]" in rendered+ assert "NotesRepr739" not in rendered+++class _ChangingNote:+ """A note whose text changes after the patcher has checked it."""++ def __init__(self):+ self.calls = 0++ def __str__(self):+ self.calls += 1+ if self.calls == 1:+ return "benign note"+ return "token=" + "ChangingNote739"+++def test_note_object_is_rendered_as_checked(rendered_sink):+ """Sinks render the note text that was checked, not a fresh ``str()``."""+ exc = ValueError("ordinary failure")+ exc.__notes__ = [_ChangingNote()]+ _raise_and_log(exc)+ rendered = rendered_sink.getvalue()+ assert "benign note" in rendered+ assert "ChangingNote739" not in rendered+++# The sinks render an exception again after the patcher checked it+# (loguru's ``format_exception_only``, the DB row's ``str()``). Each class+# below renders benign text, or raises, on the first call and a credential+# on every later one, so a patcher that checks the text and then passes the+# original object on lets the credential reach the sink.+_LATER_SECRET = "password=" + "LaterCallSecret739"+++class _FirstCall:+ """Benign on the first call (or raise, when *first* is an exception)."""++ def __init__(self, first):+ self.first = first+ self.calls = 0++ def __call__(self):+ self.calls += 1+ if self.calls > 1:+ return _LATER_SECRET+ if isinstance(self.first, BaseException):+ raise self.first+ return self.first+++def _changing_str_error(first):+ first_call = _FirstCall(first)++ class ChangingStrError(Exception):+ def __str__(self):+ return first_call()++ return ChangingStrError()+++def _changing_notes_error():+ first_call = _FirstCall("benign note")++ class ChangingNotesError(Exception):+ @property+ def __notes__(self):+ return [first_call()]++ return ChangingNotesError("ordinary failure")+++def _changing_cause_error():+ first_call = _FirstCall(None)++ class ChangingCauseError(Exception):+ @property+ def __cause__(self):+ text = first_call()+ return None if text is None else ValueError(text)++ @__cause__.setter+ def __cause__(self, value):+ pass++ return ChangingCauseError("ordinary failure")+++def _changing_group():+ first_call = _FirstCall("benign group")++ class ChangingGroup(ExceptionGroup):+ def __str__(self):+ return first_call()++ return ChangingGroup("group", [ValueError("ordinary child")])+++class _ChangingArg:+ """An argument object: ``ValueError(obj)`` renders ``str(obj)``."""++ def __init__(self):+ self.first_call = _FirstCall("benign argument")++ def __str__(self):+ return self.first_call()+++class _SecretStr(str):+ """A ``str`` subclass that renders a credential however it is shown."""++ def __str__(self):+ return _LATER_SECRET++ __repr__ = __str__++ def __format__(self, spec):+ return _LATER_SECRET+++def _str_subclass_error():+ class SubclassTextError(Exception):+ def __str__(self):+ return _SecretStr("benign text")++ return SubclassTextError()+++# The same overrides on a mixin listed after a builtin base. The builtin+# classes in between (``ValueError``, ``Exception``, ``BaseException``) do+# not define ``__str__``, ``__notes__``, ``__getattr__`` or+# ``__getattribute__`` themselves, so Python still finds the mixin's.+def _mixin_str_error():+ first_call = _FirstCall("benign text")++ class StrMixin(Exception):+ def __str__(self):+ return first_call()++ # MRO: MixinStrError, ValueError, StrMixin, Exception, BaseException.+ class MixinStrError(ValueError, StrMixin):+ pass++ return MixinStrError()+++def _mixin_notes_error():+ first_call = _FirstCall("benign note")++ class NotesMixin:+ @property+ def __notes__(self):+ return [first_call()]++ # MRO: MixinNotesError, ValueError, Exception, BaseException,+ # NotesMixin, object.+ class MixinNotesError(ValueError, NotesMixin):+ pass++ return MixinNotesError("ordinary failure")+++def _mixin_getattr_error():+ first_call = _FirstCall("benign note")++ class GetattrMixin:+ def __getattr__(self, name):+ if name == "__notes__":+ return [first_call()]+ raise AttributeError(name)++ class MixinGetattrError(KeyError, GetattrMixin):+ pass++ return MixinGetattrError("ordinary failure")+++def _mixin_getattribute_notes_error():+ first_call = _FirstCall("benign note")++ class GetattributeMixin:+ def __getattribute__(self, name):+ if name == "__notes__":+ return [first_call()]+ return super().__getattribute__(name)++ class MixinGetattributeError(RuntimeError, GetattributeMixin):+ pass++ return MixinGetattributeError("ordinary failure")+++def _mixin_getattribute_cause_error():+ first_call = _FirstCall(None)++ class CauseMixin:+ def __getattribute__(self, name):+ if name == "__cause__":+ text = first_call()+ return None if text is None else ValueError(text)+ return super().__getattribute__(name)++ class MixinCauseError(Exception, CauseMixin):+ pass++ return MixinCauseError("ordinary failure")+++ "make",+ [+ lambda: _changing_str_error(RuntimeError("first str() refused")),+ lambda: _changing_str_error("benign text"),+ _changing_notes_error,+ _changing_cause_error,+ _changing_group,+ lambda: ValueError(_ChangingArg()),+ _str_subclass_error,+ _mixin_str_error,+ _mixin_notes_error,+ _mixin_getattr_error,+ _mixin_getattribute_notes_error,+ _mixin_getattribute_cause_error,+ ],+ ids=[+ "str_raises_first",+ "str_benign_first",+ "notes_property",+ "cause_property",+ "group_str",+ "argument_object",+ "str_subclass",+ "mixin_after_builtin_str",+ "mixin_after_builtin_notes_property",+ "mixin_after_builtin_getattr",+ "mixin_after_builtin_getattribute_notes",+ "mixin_after_builtin_getattribute_cause",+ ],+)+def test_sinks_render_the_exception_text_that_was_checked(rendered_sink, make):+ """Text read again by a sink must be the text the patcher checked.++ A second sink on the same patcher captures the record, so the DB row+ prefix (``_exception_context``) is checked on the same record.+ """+ from local_deep_research.utilities.log_utils import _exception_context++ records = []+ sink = logger.add(+ lambda message: records.append(message.record), diagnose=False+ )+ try:+ _raise_and_log(make())+ finally:+ logger.remove(sink)+ rendered = rendered_sink.getvalue()+ assert "Traceback" in rendered+ assert "raise exc" in rendered+ assert "LaterCallSecret739" not in rendered+ assert "LaterCallSecret739" not in _exception_context(records[-1])+++def test_unprintable_exception_alone_is_rebuilt_with_placeholder(+ rendered_sink,+):+ """Nothing else changes, yet the placeholder text is what is rendered."""+ _raise_and_log(_RaisingStrError())+ rendered = rendered_sink.getvalue()+ assert "raise exc" in rendered+ assert "<unprintable _RaisingStrError>" in rendered+++def test_stable_exception_keeps_its_identity(captured_records):+ """A builtin exception with plain text is not rebuilt."""+ exc = OSError(2, "No such file", "plain-name.txt")+ _raise_and_log(exc)+ assert captured_records[-1]["exception"].value is exc+++class _ChangingKey:+ """A dict key whose ``str()`` raises once and then renders a secret."""++ def __init__(self):+ self.first_call = _FirstCall(RuntimeError("first str() refused"))++ def __str__(self):+ return self.first_call()++ __repr__ = __str__++ def __hash__(self):+ return 1+++def test_extra_object_key_is_replaced_by_its_checked_text():+ out = redact_log_extra({"hits": {_ChangingKey(): 1}})+ assert list(out["hits"]) == ["<unprintable _ChangingKey>"]+ assert "LaterCallSecret739" not in repr(out)+++def test_extra_empty_str_subclass_becomes_plain_str():+ out = redact_log_extra({"note": _SecretStr("")})+ assert type(out["note"]) is str+ assert "LaterCallSecret739" not in repr(out)+++# Hooks a sink runs on an exception while rendering it, after the patcher+# checked its text: loguru's ``if exc_value:`` (``__bool__``/``__len__``),+# the ``isinstance`` group check (``__class__``), a chained exception's+# ``__traceback__``, pickling by an ``enqueue=True`` sink (``__reduce_ex__``,+# and the objects in the instance dict), the type's ``__module__`` (a+# metaclass descriptor) and the "Did you mean" suggestion (``obj.__dir__()``+# and the named module's ``__dir__``). Each hook rewrites the exception's+# text once the record has been patched, so a kept original renders (or+# makes a later sink render) text that was never checked.+_ARMED = []+++def _rewrite_after_patching(exc):+ if _ARMED:+ exc.args = (_LATER_SECRET,)+ if issubclass(type(exc), ImportError):+ exc.msg = _LATER_SECRET+++def _bool_mixin_error():+ class BoolMixin:+ def __bool__(self):+ _rewrite_after_patching(self)+ return True++ class BoolMixinError(ValueError, BoolMixin):+ pass++ return BoolMixinError("benign text")+++def _len_error():+ class LenError(Exception):+ def __len__(self):+ _rewrite_after_patching(self)+ return 1++ return LenError("benign text")+++def _class_property_error():+ class ClassPropertyError(Exception):+ @property+ def __class__(self):+ _rewrite_after_patching(self)+ return type(self)++ return ClassPropertyError("benign text")+++def _traceback_property_cause():+ class TracebackPropertyError(Exception):+ @property+ def __traceback__(self):+ _rewrite_after_patching(self)+ return None++ @__traceback__.setter+ def __traceback__(self, value):+ pass++ exc = ValueError("outer failure")+ exc.__cause__ = TracebackPropertyError("benign cause")+ return exc+++def _reduce_ex_error():+ class ReduceExError(Exception):+ def __reduce_ex__(self, protocol):+ _rewrite_after_patching(self)+ return super().__reduce_ex__(protocol)++ return ReduceExError("benign text")+++def _pickled_attribute_error():+ exc = ValueError("benign text")++ class Payload:+ def __reduce__(self):+ _rewrite_after_patching(exc)+ return (str, ("payload",))++ exc.payload = Payload()+ return exc+++def _metaclass_module_error():+ holder = []++ class ModuleMeta(type):+ @property+ def __module__(cls):+ if holder:+ _rewrite_after_patching(holder[0])+ return "app.errors"++ class MetaclassError(Exception, metaclass=ModuleMeta):+ pass++ holder.append(MetaclassError("benign text"))+ return holder[0]+++def _len_override_class(meta):+ """An exception class with a ``__len__`` hook, under metaclass *meta*."""++ class HiddenHookError(Exception, metaclass=meta):+ def __len__(self):+ _rewrite_after_patching(self)+ return 1++ return HiddenHookError+++def _metaclass_mro_error():+ class MroMeta(type):+ @property+ def __mro__(cls):+ return (Exception, BaseException, object)++ return _len_override_class(MroMeta)("benign text")+++def _metaclass_dict_error():+ class DictMeta(type):+ @property+ def __dict__(cls):+ return {}++ return _len_override_class(DictMeta)("benign text")+++def _metaclass_callable_getattribute_error():+ holder = []++ class Hook:+ # Not a descriptor (no ``__get__``), but CPython still calls it for+ # every attribute read on the class.+ def __call__(self, *args):+ if holder:+ _rewrite_after_patching(holder[0])+ return type.__getattribute__(args[0], args[-1])++ class HookMeta(type):+ __getattribute__ = Hook()++ class HookedError(Exception, metaclass=HookMeta):+ pass++ holder.append(HookedError("benign text"))+ return holder[0]+++def _metaclass_name_error():+ class NameMeta(type):+ @property+ def __name__(cls):+ return _LATER_SECRET if _ARMED else "AppError"++ class NamedError(Exception, metaclass=NameMeta):+ pass++ return NamedError("password=hunter2 benign text")+++def _secret_class_name_error():+ return type(_LATER_SECRET, (Exception,), {})("benign text")+++class _AlwaysEqualMeta(type):+ """Answers ``True`` to ``==``, so ``kind in (str, int)`` holds for it."""++ def __eq__(cls, other):+ return True++ __hash__ = type.__hash__+++def _metaclass_eq_argument_error():+ class Argument(metaclass=_AlwaysEqualMeta):+ def __str__(self):+ return _LATER_SECRET if _ARMED else "benign text"++ __repr__ = __str__++ return ValueError(Argument())+++def _attribute_suggestion_error():+ holder = []++ class Target:+ def __dir__(self):+ _rewrite_after_patching(holder[0])+ return ["present"]++ holder.append(AttributeError("benign text", name="presnt", obj=Target()))+ return holder[0]+++def _import_suggestion_error(monkeypatch):+ import sys+ import types++ holder = []+ module = types.ModuleType("ldr_log_sink_probe_module")++ def __dir__():+ _rewrite_after_patching(holder[0])+ return ["present"]++ module.__dir__ = __dir__+ monkeypatch.setitem(sys.modules, module.__name__, module)+ holder.append(+ ImportError("benign text", name=module.__name__, name_from="presnt")+ )+ return holder[0]+++ "make",+ [+ lambda mp: _bool_mixin_error(),+ lambda mp: _len_error(),+ lambda mp: _class_property_error(),+ lambda mp: _traceback_property_cause(),+ lambda mp: _reduce_ex_error(),+ lambda mp: _pickled_attribute_error(),+ lambda mp: _metaclass_module_error(),+ lambda mp: _metaclass_mro_error(),+ lambda mp: _metaclass_dict_error(),+ lambda mp: _metaclass_callable_getattribute_error(),+ lambda mp: _metaclass_name_error(),+ lambda mp: _secret_class_name_error(),+ lambda mp: _metaclass_eq_argument_error(),+ lambda mp: _attribute_suggestion_error(),+ _import_suggestion_error,+ ],+ ids=[+ "bool_mixin",+ "len",+ "class_property",+ "cause_traceback_property",+ "reduce_ex",+ "pickled_attribute",+ "metaclass_module",+ "metaclass_mro",+ "metaclass_dict",+ "metaclass_callable_getattribute",+ "metaclass_name",+ "secret_class_name",+ "metaclass_eq_argument",+ "attribute_suggestion",+ "import_suggestion",+ ],+)+def test_render_time_hooks_cannot_change_a_kept_exception(make, monkeypatch):+ """Sinks: arm the hooks, render, pickle (as ``enqueue=True``), DB row."""+ import io+ import pickle++ from local_deep_research.utilities.log_utils import (+ _exception_context,+ _sanitize_record,+ )++ def pickle_like_enqueue(message):+ # What an ``enqueue=True`` sink's queue put does; the patcher makes+ # the record picklable, so this must not raise (loguru's error+ # handler would dump the unredacted original to stderr).+ pickle.dumps(message)++ exc = make(monkeypatch)+ stream = io.StringIO()+ records = []+ prefixes = []+ _ARMED.clear()+ try:+ with restored_loguru_state():+ logger.remove()+ logger.configure(patcher=_sanitize_record)+ logger.add(lambda message: _ARMED.append(True), diagnose=False)+ logger.add(stream, diagnose=False, backtrace=False, colorize=False)+ logger.add(pickle_like_enqueue, diagnose=False)+ logger.add(+ lambda message: records.append(message.record),+ diagnose=False,+ )+ # The DB row prefix, built at sink time like the DB sink does.+ logger.add(+ lambda message: prefixes.append(+ _exception_context(message.record)+ ),+ diagnose=False,+ )+ _raise_and_log(exc)+ finally:+ _ARMED.clear()+ rendered = stream.getvalue()+ assert "raise exc" in rendered+ assert "LaterCallSecret739" not in rendered+ assert "LaterCallSecret739" not in prefixes[-1]+ assert "LaterCallSecret739" not in _exception_context(records[-1])+++def test_suggestion_exception_is_rebuilt_as_its_builtin_type(rendered_sink):+ """A builtin exception rebuilt to skip the suggestion keeps its type."""+ import types++ target = types.SimpleNamespace(field=1)+ _raise_and_log(AttributeError("no such field", name="feild", obj=target))+ rendered = rendered_sink.getvalue()+ assert "AttributeError: no such field" in rendered+ assert "Did you mean" not in rendered+++def _syntax_error_with_typo_source():+ exc = SyntaxError("invalid syntax", ("<probe>", 1, 1, "improt os\n", 1, 7))+ # The keyword-typo suggestion (Python 3.13+) shows the source line it+ # fixed, from ``_metadata``, in place of ``text``.+ exc._metadata = (0, 0, "improt os # password=TypoSecret771\n")+ return exc+++ "make",+ [+ lambda: SyntaxError(+ "invalid syntax",+ (b"https://user:TypoSecret771@host/x.py", 1, 1, "x", 1, 2),+ ),+ lambda: SyntaxError(+ "invalid syntax",+ (+ b"https://user:TypoSecret771@host/x.py",+ None,+ None,+ None,+ None,+ None,+ ),+ ),+ lambda: SyntaxError(+ "invalid syntax", ("f.py", "password=TypoSecret771", 1, "x", 1, 2)+ ),+ _syntax_error_with_typo_source,+ ],+ ids=["bytes_filename", "bytes_filename_no_line", "str_lineno", "typo"],+)+def test_syntax_error_details_are_checked_as_rendered(rendered_sink, make):+ _raise_and_log(make())+ rendered = rendered_sink.getvalue()+ assert "raise exc" in rendered+ assert "TypoSecret771" not in rendered+++class _FalsyText(str):+ """Text that claims to be false, so ``not value`` holds."""++ def __bool__(self):+ return False+++class _ZeroLengthText(str):+ """Text that claims to have no characters."""++ def __len__(self):+ return 0+++ "kind", [_FalsyText, _ZeroLengthText], ids=["bool", "len"]+)+def test_text_that_claims_to_be_empty_is_still_redacted(kind):+ value = kind("password=" + "FalsySecret4242")+ out = redact_log_extra(+ {+ "detail": value,+ kind("token=" + "FalsySecret4242"): 1,+ "nested": [value],+ "password": kind("hunter2" + "FalsySecret4242"),+ }+ )+ assert "FalsySecret4242" not in repr(out)+ assert out["password"] == "[REDACTED]"+ assert "FalsySecret4242" not in redact_log_message(value)+ assert "FalsySecret4242" not in redact_sensitive_assignments(value)+++ "kind", [_FalsyText, _ZeroLengthText], ids=["bool", "len"]+)+def test_falsy_text_is_redacted_in_records(captured_records, kind):+ logger.bind(detail=kind("password=" + "FalsySecret4242")).info(+ kind("token=" + "FalsySecret4242")+ )+ record = captured_records[-1]+ assert "FalsySecret4242" not in repr(record["extra"])+ assert "FalsySecret4242" not in str.__str__(record["message"])+++ "kind", [_FalsyText, _ZeroLengthText], ids=["bool", "len"]+)+def test_falsy_group_message_is_redacted(rendered_sink, kind):+ _raise_and_log(+ ExceptionGroup(kind("password=" + "FalsySecret4242"), [ValueError()])+ )+ assert "FalsySecret4242" not in rendered_sink.getvalue()+++class _EmptyLookingDict(dict):+ def __len__(self):+ return 0+++def test_container_subclass_claiming_to_be_empty_is_masked():+ out = redact_log_extra(+ {"password": _EmptyLookingDict(note="hunter2" + "FalsySecret4242")}+ )+ assert out == {"password": "[REDACTED]"}+++class _ForgedRoutingKey(str):+ """Hashes and compares equal to ``"username"`` whatever its text."""++ def __hash__(self):+ return hash("username")++ def __eq__(self, other):+ return other == "username" or str.__eq__(self, other)+++class _HarmlessLookingKey(str):+ """Reports a harmless last segment to ``rsplit``-based name checks."""++ def rsplit(self, *args, **kwargs):+ return ["benign"]++ def lower(self):+ return "benign"+++_FORGED_KEY_TEXT = "token=ghp_" + "a" * 36+++ ("key", "value", "secrets"),+ [+ (+ _ForgedRoutingKey(_FORGED_KEY_TEXT),+ "password=hunter2plain",+ ("hunter2plain", "a" * 36),+ ),+ (_HarmlessLookingKey("db_password"), "hunter2plain", ("hunter2plain",)),+ ],+ ids=["forged_routing_key", "rsplit_override"],+)+def test_str_subclass_extra_key_is_checked_by_its_characters(+ captured_records, key, value, secrets+):+ """A ``str`` subclass key is no routing key and no harmless name."""+ logger.bind(**{key: value}).info("bound")+ extra = captured_records[-1]["extra"]+ assert all(type(k) is str for k in extra)+ assert "username" not in extra+ for secret in secrets:+ assert secret not in repr(extra)+++def test_fallback_extra_keeps_only_exact_routing_keys(+ captured_records, monkeypatch+):+ """The fail-closed path does not keep a key that only equals a route."""+ from local_deep_research.security import log_sanitizer++ def _fail(extra):+ raise RuntimeError("extra redaction failed")++ monkeypatch.setattr(log_sanitizer, "redact_log_extra", _fail)+ logger.bind(+ **{_ForgedRoutingKey(_FORGED_KEY_TEXT): "password=hunter2plain"},+ research_id=7,+ ).info("bound")+ assert captured_records[-1]["extra"] == {"research_id": 7}+++class _EmptyLookingSecret(metaclass=_AlwaysEqualMeta):+ """Claims (through its metaclass) to be a ``str``, and to be empty."""++ def __len__(self):+ return 0++ def __repr__(self):+ return "password=" + "MetaEqSecret741"++ __str__ = __repr__+++def test_metaclass_eq_cannot_pass_a_value_or_key_as_a_builtin(+ captured_records,+):+ """``type(x) in (str, ...)`` would be ``True`` for these; ``is`` is not."""+ logger.bind(+ password=_EmptyLookingSecret(), outer={_EmptyLookingSecret(): 1}+ ).info("bound")+ extra = captured_records[-1]["extra"]+ assert extra["password"] == "[REDACTED]"+ assert "MetaEqSecret741" not in repr(extra)+++def test_failed_redaction_redacts_the_type_name(captured_records, monkeypatch):+ """The placeholder and the DB prefix name the type, redacted."""+ from local_deep_research.security import log_sanitizer+ from local_deep_research.utilities.log_utils import _exception_context++ def _fail(*args, **kwargs):+ raise RuntimeError("rebuild failed")++ monkeypatch.setattr(log_sanitizer, "_build_redacted_exception", _fail)+ _raise_and_log(type(_LATER_SECRET, (ValueError,), {})("benign"))+ record = captured_records[-1]+ assert "LaterCallSecret739" not in str(record["exception"].value)+ assert "LaterCallSecret739" not in _exception_context(record)+++# ``enqueue=True`` stderr sinks (both processes) pickle every record before+# queueing it. When that fails, loguru's error handler writes ``str(record)``+# and the pickling traceback to ``sys.stderr``, and that traceback's+# ``__context__`` is the exception being handled -- the unredacted original.+_ENQUEUE_SECRET = "EnqueueDump" + "Secret739"+++def _local_class_with_secret_text():+ class ProviderError(Exception):+ pass++ return ProviderError(f"request failed: api_key=sk-live-{_ENQUEUE_SECRET}")+++def _clean_local_class_with_secret_cause():+ class LocalError(Exception):+ pass++ exc = LocalError("clean text")+ exc.__cause__ = ValueError(f"token=ghp_{_ENQUEUE_SECRET}")+ return exc+++def _secret_named_class():+ return type(f"password={_ENQUEUE_SECRET}", (ValueError,), {})("benign")+++def _builtin_with_secret_text():+ return ValueError(f"token=ghp_{_ENQUEUE_SECRET}")+++def enqueue_stderr(monkeypatch):+ """A real ``enqueue=True`` stderr sink, as ``config_logger`` adds it.++ ``sys.stderr`` is replaced first, so it captures both the sink's output+ and loguru's error handler, which writes to ``sys.stderr`` directly.+ The MCP process's sink (``configure_mcp_logging``) is tested the same+ way in tests/mcp/test_stderr_control_chars.py.+ """+ import io+ import sys++ from local_deep_research.utilities.log_utils import _sanitize_record++ stderr = io.StringIO()+ monkeypatch.setattr(sys, "stderr", stderr)+ with restored_loguru_state():+ logger.remove()+ logger.configure(patcher=_sanitize_record)+ # config_logger's stderr sink (utilities/log_utils.py).+ logger.add(sys.stderr, level="INFO", diagnose=False, enqueue=True)++ def read():+ logger.complete()+ return stderr.getvalue()++ yield read+++ "make, bind_lock, with_exception",+ [+ (_local_class_with_secret_text, False, True),+ (_clean_local_class_with_secret_cause, False, True),+ (_secret_named_class, False, True),+ (_builtin_with_secret_text, True, True),+ (_builtin_with_secret_text, True, False),+ ],+ ids=[+ "local_class",+ "local_class_cause",+ "secret_class_name",+ "unpicklable_extra",+ "unpicklable_extra_no_exception",+ ],+)+def test_enqueue_sink_never_dumps_the_unredacted_exception(+ enqueue_stderr, make, bind_lock, with_exception+):+ """Logged with or without the exception, while handling it."""+ import threading++ bound = {"lock": threading.Lock()} if bind_lock else {}+ exc = make()+ try:+ raise exc+ except BaseException:+ logger.bind(**bound).opt(exception=with_exception).error(+ "handled failure"+ )+ out = enqueue_stderr()+ assert "handled failure" in out+ assert "Logging error in Loguru Handler" not in out+ assert "EnqueueDumpSecret739" not in out+++def test_unpicklable_extra_value_is_replaced_by_its_type_name(+ captured_records,+):+ import threading++ logger.bind(lock=threading.Lock(), research_id=7).info("bound")+ extra = captured_records[-1]["extra"]+ assert extra == {"lock": "<unpicklable lock>", "research_id": 7}+++# Reads of ``_FlippingModuleError.__module__`` through its metaclass since+# the counter was last reset.+_MODULE_READS = [0]+++class _FlippingModuleMeta(type):+ """Names the real module on the first ``__module__`` read, then another.++ Pickling looks a class up by the ``__module__`` it reads with+ ``getattr``, which finds this property before the class's own entry: a+ trial pickle succeeds and the ``enqueue=True`` sink's pickle fails.+ """++ @property+ def __module__(cls):+ _MODULE_READS[0] += 1+ return __name__ if _MODULE_READS[0] == 1 else "builtins"+++class _FlippingModuleError(Exception, metaclass=_FlippingModuleMeta):+ """Module level, so pickle can find it while its metaclass allows."""+++def test_class_whose_pickling_can_change_is_not_kept_as_record_type(+ enqueue_stderr,+):+ """A rebuilt exception's class is replaced, not trusted after one trial."""+ _MODULE_READS[0] = 0+ try:+ raise _FlippingModuleError(+ f"request failed: api_key=sk-live-{_ENQUEUE_SECRET}"+ )+ except _FlippingModuleError:+ logger.exception("handled failure")+ out = enqueue_stderr()+ assert "handled failure" in out+ assert "_FlippingModuleError: request failed" in out+ assert "Logging error in Loguru Handler" not in out+ assert _ENQUEUE_SECRET not in out+++def test_flipping_metaclass_type_is_replaced_in_the_record(captured_records):+ _MODULE_READS[0] = 0+ _raise_and_log(_FlippingModuleError("benign"))+ record = captured_records[-1]+ assert record["exception"].type is RuntimeError+ assert str(record["exception"].value) == "_FlippingModuleError: benign"+++class _HookedOuterMeta(type):+ def __getattribute__(cls, name):+ return type.__getattribute__(cls, name)+++class _HookedOuter(metaclass=_HookedOuterMeta):+ class Error(Exception):+ """Found by pickle only through its enclosing class's metaclass."""+++class _PlainOuter:+ class Error(Exception):+ """Found by pickle through plain class dicts."""+++class _ModuleLevelError(Exception):+ """Found by pickle in this module's namespace."""+++ "kind, kept",+ [+ (ValueError, True),+ (_ModuleLevelError, True),+ (_PlainOuter.Error, True),+ (_FlippingModuleError, False),+ (_HookedOuter.Error, False),+ ],+ ids=["builtin", "module_level", "nested", "metaclass_hook", "outer_hook"],+)+def test_record_type_is_kept_only_when_pickling_it_runs_no_class_code(+ kind, kept+):+ from local_deep_research.security.log_sanitizer import (+ _record_type_is_safe,+ )++ _MODULE_READS[0] = 0+ assert _record_type_is_safe(kind) is kept+ # Deciding never ran the metaclass's code.+ assert _MODULE_READS[0] == 0+++def test_type_without_value_is_checked_too(enqueue_stderr):+ """``opt(exception=(Type, None, tb))``: the sink still pickles ``type``."""+ local = type("LocalError", (Exception,), {})+ try:+ raise _builtin_with_secret_text()+ except ValueError:+ logger.opt(exception=(local, None, None)).error("handled failure")+ out = enqueue_stderr()+ assert "handled failure" in out+ assert "RuntimeError: LocalError" in out+ assert "Logging error in Loguru Handler" not in out+ assert _ENQUEUE_SECRET not in out+++def test_type_without_value_keeps_a_safe_type(captured_records):+ try:+ raise _builtin_with_secret_text()+ except ValueError:+ logger.opt(exception=(KeyError, None, None)).error("handled failure")+ exception = captured_records[-1]["exception"]+ assert exception.type is KeyError+ assert exception.value is None+++class _ChangingWhenPickled:+ """Pickles on the first try and raises on every later one."""++ def __init__(self):+ self.calls = 0++ def __reduce_ex__(self, protocol):+ self.calls += 1+ if self.calls > 1:+ raise TypeError("not this time")+ return (str, ("benign",))+++def test_extra_value_whose_pickling_can_change_is_replaced(enqueue_stderr):+ """A trial pickle of an ``extra`` value says nothing about the next one."""+ value = _ChangingWhenPickled()+ try:+ raise _builtin_with_secret_text()+ except ValueError:+ logger.bind(value=value).error("handled failure")+ out = enqueue_stderr()+ assert "handled failure" in out+ assert "Logging error in Loguru Handler" not in out+ assert _ENQUEUE_SECRET not in out+ # Its pickling code never ran.+ assert value.calls == 0+++ "value, plain",+ [+ ({"a": [1, 2.0, None, b"x", (True, 3j)], "b": {1}}, True),+ (bytearray(b"x"), True),+ (frozenset({"x"}), True),+ (_ChangingWhenPickled(), False),+ (["fine", _ChangingWhenPickled()], False),+ ({_EmptyLookingSecret(): 1}, False),+ (_FalsyText("x"), False),+ ],+ ids=[+ "nested",+ "bytearray",+ "frozenset",+ "object",+ "in_list",+ "key",+ "str_subclass",+ ],+)+def test_plain_data_is_exact_builtin_values_only(value, plain):+ from local_deep_research.security.log_sanitizer import _is_plain_data++ assert _is_plain_data(value) is plain+++def test_plain_data_check_is_linear_on_shared_and_cyclic_containers():+ from local_deep_research.security.log_sanitizer import _is_plain_data++ shared = ["leaf"]+ for _ in range(20):+ shared = [shared, shared]+ assert _is_plain_data(shared) is True+ cycle = []+ cycle.append(cycle)+ assert _is_plain_data(cycle) is False+++class _RewritingMembers(list):+ """Rewrites its member's text when an ``enqueue=True`` sink pickles it."""++ def __reduce_ex__(self, protocol):+ for member in self:+ member.args = (f"rewritten: api_key=sk-live-{_ENQUEUE_SECRET}",)+ return (list, (list(self),))+++def _group_with_extra_member_in_args():+ members = [ValueError("a")]+ group = ExceptionGroup("plain", members)+ # The list the group was built from is the caller's; pickling the group+ # pickles it, not ``exceptions``.+ members.append(_ChangingWhenPickled())+ return group+++def test_group_member_container_cannot_rewrite_members_for_later_sinks(+ enqueue_stderr,+):+ """The group is pickled through ``args``, which hold the caller's list."""+ import io++ later = io.StringIO()+ sink = logger.add(later, format="{message}", diagnose=False)+ try:+ try:+ raise ExceptionGroup(+ "benign", _RewritingMembers([ValueError("benign")])+ )+ except ExceptionGroup:+ logger.exception("handled failure")+ out = enqueue_stderr()+ finally:+ logger.remove(sink)+ rendered = later.getvalue()+ assert "handled failure" in out+ assert "ValueError: benign" in rendered+ assert _ENQUEUE_SECRET not in out + rendered+++ "make, kept",+ [+ (lambda: ExceptionGroup("plain", [ValueError("a")]), True),+ (lambda: ExceptionGroup("plain", (ValueError("a"),)), True),+ (+ lambda: ExceptionGroup(+ "plain", _RewritingMembers([ValueError("a")])+ ),+ False,+ ),+ (_group_with_extra_member_in_args, False),+ ],+ ids=["list", "tuple", "list_subclass", "args_not_members"],+)+def test_group_is_kept_only_when_its_args_are_its_members(+ captured_records, make, kept+):+ group = make()+ _raise_and_log(group)+ assert (captured_records[-1]["exception"].value is group) is kept+++# The exception a pickling hook below rewrites, set by the test that logs it.+_PICKLE_VICTIM = []+# Names of the hooks that ran.+_PICKLE_HOOKS_RUN = []+++def _rewrite_victim(hook):+ """Give the victim a secret, as a pickling hook could between sinks."""+ _PICKLE_HOOKS_RUN.append(hook)+ if _PICKLE_VICTIM:+ _PICKLE_VICTIM[-1].args = (+ f"rewritten: api_key=sk-live-{_ENQUEUE_SECRET}",+ )+++class _LookupHookMeta(type):+ """Runs when pickle looks up ``_LookupHookOuter.Error`` by name."""++ def __getattribute__(cls, name):+ if name == "Error":+ _rewrite_victim("enclosing_getattribute")+ return type.__getattribute__(cls, name)+++class _LookupHookOuter(metaclass=_LookupHookMeta):+ class Error(Exception):+ """Its own metaclass is ``type``; its enclosing class's is not."""+++class _GetHookMeta(type):+ """Runs when ``getattr(_GetHookOuter, "Error")`` finds the class."""++ def __get__(cls, instance, owner=None):+ _rewrite_victim("own_metaclass_get")+ return cls+++class _GetHookOuter:+ class Error(Exception, metaclass=_GetHookMeta):+ """Nested in a plain class, with a ``__get__`` of its own."""+++class _HashHookMeta(type):+ """Runs when the pickler looks the class up in its dispatch tables."""++ def __hash__(cls):+ _rewrite_victim("metaclass_hash")+ return type.__hash__(cls)+++class _HashHookError(Exception, metaclass=_HashHookMeta):+ """Module level, so pickle finds it by name."""+++class _ReduceHookMeta(type):+ """Runs when ``object.__reduce_ex__`` reads ``type(obj).__reduce__``."""++ @property+ def __reduce__(cls):+ _rewrite_victim("metaclass_reduce")+ return BaseException.__reduce__+++class _ReduceHookError(Exception, metaclass=_ReduceHookMeta):+ """Module level, so pickle finds it by name."""+++class _ReducerRegisteredError(Exception):+ """A plain class, with a ``copyreg`` reducer registered by the test."""+++def _rewriting_reducer(error):+ _rewrite_victim("registered_reducer")+ return (_ReducerRegisteredError, error.args)+++class _RewritingSpec:+ """A module ``__spec__`` whose ``_initializing`` the import reads."""++ @property+ def _initializing(self):+ _rewrite_victim("module_spec")+ return False+++_SPEC_HOOK_MODULE = "_log_sink_spec_hook_module"+++class _SpecHookError(Exception):+ """Pickled by reference to a module whose ``__spec__`` runs code."""+++_SpecHookError.__module__ = _SPEC_HOOK_MODULE+_SpecHookError.__qualname__ = "_SpecHookError"+++def _install_pickling_hooks(monkeypatch):+ """Register the hooks that live outside the classes themselves."""+ import copyreg+ import sys+ import types++ monkeypatch.setitem(+ copyreg.dispatch_table, _ReducerRegisteredError, _rewriting_reducer+ )+ module = types.ModuleType(_SPEC_HOOK_MODULE)+ module._SpecHookError = _SpecHookError+ module.__spec__ = _RewritingSpec()+ monkeypatch.setitem(sys.modules, _SPEC_HOOK_MODULE, module)+ stock = copyreg.dispatch_table[complex]++ def complex_reducer(value):+ _rewrite_victim("complex_reducer")+ return stock(value)++ monkeypatch.setitem(copyreg.dispatch_table, complex, complex_reducer)+++# Read from the class dicts: ``_LookupHookOuter.Error`` and+# ``_GetHookOuter.Error`` would run the hooks.+_PICKLE_HOOKED_CLASSES = [+ vars(_LookupHookOuter)["Error"],+ vars(_GetHookOuter)["Error"],+ _HashHookError,+ _ReduceHookError,+ _ReducerRegisteredError,+ _SpecHookError,+]+_PICKLE_HOOKED_IDS = [+ "enclosing_getattribute",+ "own_metaclass_get",+ "metaclass_hash",+ "metaclass_reduce",+ "registered_reducer",+ "module_spec",+]+++def _hooked_member_group(kind):+ def make():+ victim = ValueError("benign sibling")+ _PICKLE_VICTIM.append(victim)+ return ExceptionGroup("benign", [victim, kind("benign member")])++ return make+++def _complex_argument_group():+ victim = ValueError("benign sibling")+ _PICKLE_VICTIM.append(victim)+ return ExceptionGroup("benign", [victim, ValueError("benign", 1j)])+++def _hooked_value_under_another_type():+ """``opt(exception=(Type, value, tb))``: the value's class is not ``type``."""+ victim = ValueError("benign sibling")+ _PICKLE_VICTIM.append(victim)+ value = vars(_GetHookOuter)["Error"]("benign")+ value.__context__ = victim+ return (ValueError, value, None)+++def pickling_hooks(monkeypatch):+ _install_pickling_hooks(monkeypatch)+ _PICKLE_VICTIM.clear()+ _PICKLE_HOOKS_RUN.clear()+ yield _PICKLE_HOOKS_RUN+ _PICKLE_VICTIM.clear()+ _PICKLE_HOOKS_RUN.clear()+++ "make",+ [_hooked_member_group(kind) for kind in _PICKLE_HOOKED_CLASSES]+ + [_complex_argument_group, _hooked_value_under_another_type],+ ids=[*_PICKLE_HOOKED_IDS, "complex_reducer", "value_not_record_type"],+)+def test_pickling_a_kept_exception_runs_no_code_before_later_sinks(+ enqueue_stderr, pickling_hooks, make+):+ """The ``enqueue=True`` sink pickles every kept node, not only ``type``.++ Pickling looks each kept node's class up by name, through the picklers'+ dispatch tables, its metaclass, the enclosing classes and its module's+ ``__spec__``; a hook there could rewrite a kept sibling's text after+ the first sink rendered it and before a later sink renders it.+ """+ import io++ later = io.StringIO()+ sink = logger.add(later, format="{message}", diagnose=False)+ try:+ exception = make()+ logger.opt(exception=exception).error("handled failure")+ out = enqueue_stderr()+ finally:+ logger.remove(sink)+ rendered = later.getvalue()+ assert "handled failure" in out+ assert "benign sibling" in rendered+ assert _ENQUEUE_SECRET not in out + rendered+ assert pickling_hooks == []++[email protected]("kind", _PICKLE_HOOKED_CLASSES, ids=_PICKLE_HOOKED_IDS)+def test_kept_nodes_and_record_type_share_one_pickling_check(+ pickling_hooks, kind+):+ """A class is either kept everywhere in the record or nowhere."""+ from local_deep_research.security.log_sanitizer import (+ _exception_text_is_stable,+ _pickled_by_reference_runs_no_code,+ _record_type_is_safe,+ )++ assert _pickled_by_reference_runs_no_code(kind) is False+ assert _record_type_is_safe(kind) is False+ assert _exception_text_is_stable(kind("benign"), False) is False+ # Deciding never ran the hooks.+ assert pickling_hooks == []+++ "kind",+ [ValueError, _ModuleLevelError, _PlainOuter.Error],+ ids=["builtin", "module_level", "nested"],+)+def test_plain_classes_pass_the_pickling_check(kind):+ from local_deep_research.security.log_sanitizer import (+ _exception_text_is_stable,+ _pickled_by_reference_runs_no_code,+ _record_type_is_safe,+ )++ assert _pickled_by_reference_runs_no_code(kind) is True+ assert _record_type_is_safe(kind) is True+ assert _exception_text_is_stable(kind("benign"), False) is True+++def test_local_class_member_is_still_kept(captured_records):+ """Pickle refuses a class defined in a function before any lookup."""++ class LocalError(Exception):+ pass++ group = ExceptionGroup("benign", [LocalError("benign")])+ _raise_and_log(group)+ assert captured_records[-1]["exception"].value is group+++ "make",+ [+ lambda: ValueError("benign", 1j),+ lambda: ExceptionGroup(+ "benign", [ValueError("a"), _ModuleLevelError("b")]+ ),+ lambda: ExceptionGroup("benign", [_PlainOuter.Error("c")]),+ *[_hooked_member_group(kind) for kind in _PICKLE_HOOKED_CLASSES],+ _complex_argument_group,+ ],+ ids=[+ "complex_argument",+ "plain_group",+ "nested_member",+ *_PICKLE_HOOKED_IDS,+ "hooked_complex",+ ],+)+def test_pickling_the_redacted_exception_calls_no_python_code(+ captured_records, pickling_hooks, make, request+):+ """The invariant itself: what the sinks get pickles in builtin code.++ ``copyreg``'s own reducer for ``complex`` is the one Python function+ the pickler may call, and only while it is the registered one.+ """+ import copyreg+ import pickle+ import sys++ if request.node.callspec.id == "complex_argument":+ # This case checks the stock reducer, not the test's hook.+ copyreg.dispatch_table[complex] = copyreg.pickle_complex+ _raise_and_log(make())+ value = captured_records[-1]["exception"].value+ calls = []++ def profile(frame, event, arg):+ if event == "call":+ calls.append(frame.f_code)++ sys.setprofile(profile)+ try:+ pickle.dumps(value)+ finally:+ sys.setprofile(None)+ assert [+ code for code in calls if code is not copyreg.pickle_complex.__code__+ ] == []+ assert pickling_hooks == []+++class InvalidAuthorization(Exception):+ """Its name ends in a credential header name."""+++_SPANNING_TOKEN = "SpanTok739" + "abcdef12"+++def test_credential_spanning_type_name_and_text_is_redacted(rendered_sink):+ """Name and text are each clean; ``Name: text`` is a credential."""+ from local_deep_research.utilities.log_utils import _exception_context++ records = []+ logger.add(lambda message: records.append(message.record), diagnose=False)+ _raise_and_log(InvalidAuthorization(_SPANNING_TOKEN))+ rendered = rendered_sink.getvalue()+ assert "raise exc" in rendered+ assert "InvalidAuthorization" in rendered+ assert "SpanTok739" not in rendered+ assert "SpanTok739" not in _exception_context(records[-1])+++def test_db_prefix_checks_the_joined_type_name_and_text():+ """The DB row joins name and text itself, whatever the patcher did."""+ from local_deep_research.utilities.log_utils import _exception_context++ exc = InvalidAuthorization(_SPANNING_TOKEN)+ prefix = _exception_context({"exception": (type(exc), exc, None)})+ assert prefix == "[InvalidAuthorization: [REDACTED]] "+++def test_builtin_exception_names_never_join_into_a_credential():+ """A rebuilt node renders ``BuiltinName: checked text``.++ The rebuild redacts its text without the builtin name in front, which is+ exact only while no builtin exception name completes a credential+ pattern with the text after it.+ """+ import builtins++ from local_deep_research.security.log_sanitizer import (+ _redact_exception_text,+ )++ names = [+ name+ for name, value in vars(builtins).items()+ if isinstance(value, type) and issubclass(value, BaseException)+ ]+ assert "RuntimeError" in names+ for name in names:+ for text in (_SPANNING_TOKEN, "dXNlcjpwYXNzd29yZA==", "x"):+ line = f"{name}: {text}"+ assert _redact_exception_text(line) == line+++def test_unsuppressed_context_beside_a_shared_cause_is_redacted(+ rendered_sink,+):+ """A cause rendered once already leaves the context to be rendered."""+ shared = KeyError("shared cause")+ first = ValueError("first member")+ second = ValueError("second member")+ first.__cause__ = shared+ second.__cause__ = shared+ second.__suppress_context__ = False+ second.__context__ = RuntimeError("password=" + "SharedCtxSecret739")+ _raise_and_log(ExceptionGroup("group", [first, second]))+ rendered = rendered_sink.getvalue()+ assert "raise exc" in rendered+ assert "second member" in rendered+ assert "password=[REDACTED]" in rendered+ assert "SharedCtxSecret739" not in rendered+++# The sinks render the ``TypeName: text`` line and then each note on a line+# of its own, so a credential label at the end of one and its value at the+# start of the next are adjacent text even when each piece is clean.+_NOTE_SPAN_SECRET = "NoteSpan" + "Secret739abcdef"+++def _label_in_message_value_in_note():+ exc = ValueError("config: password=")+ exc.add_note(_NOTE_SPAN_SECRET)+ return exc+++def _header_label_in_message_value_in_note():+ exc = ConnectionError("upstream rejected header Authorization:")+ exc.add_note("abc123def456" + _NOTE_SPAN_SECRET)+ return exc+++def _label_and_value_in_two_notes():+ exc = ValueError("benign")+ exc.add_note("db password =")+ exc.add_note(_NOTE_SPAN_SECRET)+ return exc+++def _split_note_in_a_group_member():+ return ExceptionGroup(+ "group", [_label_in_message_value_in_note(), KeyError("other")]+ )+++def _split_note_on_a_rebuilt_node():+ # The token makes the node rebuilt; the label after it is left as is.+ exc = ValueError("token=ghp_" + "a" * 36 + " password=")+ exc.add_note(_NOTE_SPAN_SECRET)+ return exc+++def _split_note_on_a_local_class():+ class LocalError(Exception):+ pass++ exc = LocalError("config: password=")+ exc.add_note(_NOTE_SPAN_SECRET)+ return exc+++# A ``SyntaxError``'s header line shows ``msg``, not ``str()``: the+# `` (file, line N)`` suffix ``str()`` adds is not printed between the+# message and the notes (``TracebackException._format_syntax_error``).+def _split_note_on_a_located_syntax_error():+ exc = SyntaxError(+ "upstream rejected header Authorization:", ("cfg.py", 3, None, None)+ )+ exc.add_note("abc123def456" + _NOTE_SPAN_SECRET)+ return exc+++def _split_note_on_a_syntax_error_with_source():+ exc = SyntaxError("config: password=", ("x.py", 1, 1, "a b\n", 1, 2))+ exc.add_note(_NOTE_SPAN_SECRET)+ return exc+++def _split_note_on_a_syntax_error_with_filename_only():+ # Printed as ``msg (f.py)``: the suffix ends up between the label and+ # the value, which is still the label's value.+ exc = SyntaxError("config: password=", ("f.py", None, None, None))+ exc.add_note(_NOTE_SPAN_SECRET)+ return exc+++class _MissingBearer(Exception):+ """Raised with no arguments, it renders as ``_MissingBearer`` alone."""+++def _split_note_after_an_empty_message():+ exc = _MissingBearer()+ exc.add_note(_NOTE_SPAN_SECRET)+ return exc+++ "make",+ [+ _label_in_message_value_in_note,+ _header_label_in_message_value_in_note,+ _label_and_value_in_two_notes,+ _split_note_in_a_group_member,+ _split_note_on_a_rebuilt_node,+ _split_note_on_a_local_class,+ _split_note_on_a_located_syntax_error,+ _split_note_on_a_syntax_error_with_source,+ _split_note_on_a_syntax_error_with_filename_only,+ ],+ ids=[+ "message_note",+ "header_note",+ "note_note",+ "group_member",+ "rebuilt_node",+ "local_class",+ "syntax_error_located",+ "syntax_error_source",+ "syntax_error_filename",+ ],+)+def test_credential_spanning_message_and_notes_is_redacted(rendered_sink, make):+ """Each piece is clean; the rendered block is a credential."""+ _raise_and_log(make())+ rendered = rendered_sink.getvalue()+ assert "raise exc" in rendered+ assert "[REDACTED]" in rendered+ assert "NoteSpanSecret739" not in rendered+++def test_credential_spanning_bare_type_name_and_notes_is_redacted(+ rendered_sink,+):+ """An empty message renders ``TypeName`` alone, then the notes."""+ _raise_and_log(_split_note_after_an_empty_message())+ rendered = rendered_sink.getvalue()+ assert "raise exc" in rendered+ assert "_MissingBearer\n<exception notes omitted" in rendered+ assert "NoteSpanSecret739" not in rendered+++def test_clean_notes_are_kept_beside_their_exception(captured_records):+ exc = ValueError("benign failure")+ exc.add_note("useful diagnostic note")+ _raise_and_log(exc)+ assert captured_records[-1]["exception"].value is exc+++def test_clean_syntax_error_with_notes_is_kept(captured_records):+ exc = SyntaxError("invalid syntax", ("cfg.py", 3, 1, "a b\n", 3, 2))+ exc.add_note("useful diagnostic note")+ _raise_and_log(exc)+ assert captured_records[-1]["exception"].value is exc+++def _header_cases():+ for msg in ("bad", "", None, 0, b"x"):+ for details in (+ ("f.py", 3, None, None),+ ("f.py", None, None, None),+ (b"f.py", None, None, None),+ (None, 2, None, None),+ (None, None, None, None),+ ("f.py", 3, 1, "a b\n", 3, 2),+ ):+ yield SyntaxError(msg, details)+ yield IndentationError(msg, details)+ yield SyntaxError(msg)+ yield ValueError()+ yield ValueError("")+ yield KeyError("key")+ yield OSError(2, "missing", "f.py")+ yield ExceptionGroup("group", [ValueError()])+++def test_checked_header_line_is_the_one_the_traceback_prints():+ """The checked header is ``format_exception_only``'s header line."""+ import traceback++ from local_deep_research.security.log_sanitizer import (+ _rendered_header_tails,+ )++ for exc in _header_cases():+ lines = traceback.format_exception_only(exc)+ printed = next(line for line in lines if not line.startswith(" "))+ tail = _rendered_header_tails(exc, str(exc))[0]+ assert printed == f"{type(exc).__qualname__}{tail}\n", exc+++def test_str_lineno_joined_with_source_line_is_redacted(rendered_sink):+ """``line <lineno>`` and the source line below it are adjacent text.++ A ``str`` line number ending in a label and source text holding its+ value are each clean alone; the traceback prints them as one block.+ """+ exc = SyntaxError(+ "m", ("f.py", "password=", None, "hunter2" + "LinenoJoin739")+ )+ _raise_and_log(exc)+ rendered = rendered_sink.getvalue()+ assert "raise exc" in rendered+ assert "LinenoJoin739" not in rendered+++ "details",+ [+ ("f.py", 1, 1, b"src\n"),+ ("f.py", 1, "1", "src\n"),+ ("f.py", "1", None, "src\n"),+ ("f.py", True, None, "src\n"),+ ("f.py", 1, 1, "src\n", 1, "2"),+ ("f.py", 1, 1, "src\n", 1.0, 2),+ (b"f.py", 1, None, None),+ ],+ ids=[+ "bytes_text",+ "str_offset",+ "str_lineno",+ "bool_lineno",+ "str_end_offset",+ "float_end_lineno",+ "bytes_filename",+ ],+)+def test_syntax_error_with_non_canonical_fields_is_rebuilt(+ captured_records, details+):+ """Only the field types the interpreter fills a ``SyntaxError`` with keep it.++ On Python 3.12 a ``bytes`` text or a ``str`` offset makes the traceback+ module raise inside loguru's formatter; loguru's error handler then+ prints that error's context -- the exception being handled -- to stderr+ unredacted. A rebuilt node carries no such field.+ """+ exc = SyntaxError("bad", details)+ try:+ raise ValueError("Authorization: Bearer " + "abc123def456ghi789XYZ0")+ except ValueError:+ logger.opt(exception=exc).error("syntax failure")+ value = captured_records[-1]["exception"].value+ assert value is not exc+ assert type(value) is SyntaxError+ for name in ("filename", "lineno", "offset", "text"):+ assert getattr(value, name) is None, name+++def test_syntax_error_with_canonical_fields_is_kept(captured_records):+ exc = SyntaxError("bad", ("f.py", 1, 1, "src\n", 1, 2))+ _raise_and_log(exc)+ assert captured_records[-1]["exception"].value is exc+++_OFFSET_SECRET = "abc123def456ghi789XYZ0" + "OffsetSecret739"++# ``int`` fields of the interpreter's type but outside its ranges. The+# traceback module draws the caret line with ``'^' * (end - start)``: on+# Python 3.12 (any source line) and 3.14 (an empty one) a huge offset makes+# it raise ``OverflowError`` or ``MemoryError`` inside loguru's formatter.+_OUT_OF_RANGE_SYNTAX_DETAILS = [+ ("f.py", 1, 1, "", 1, 10**20),+ ("f.py", 1, 1, "", 1, 2**62),+ ("f.py", 1, 1, "src\n", 1, 10**19),+ ("f.py", 1, 1, "src\n", 1, -(10**19)),+ ("f.py", 1, 10**19, "src\n", 1, None),+ ("f.py", 1, 1, "x", 2, 2**64),+ ("f.py", 1, 1, "", 1, 10**9),+]+_OUT_OF_RANGE_SYNTAX_IDS = [+ "empty_text_end_offset_1e20",+ "empty_text_end_offset_2e62",+ "end_offset_1e19",+ "end_offset_minus_1e19",+ "offset_1e19",+ "other_line_end_offset_2e64",+ "empty_text_end_offset_1e9",+]+++ "details", _OUT_OF_RANGE_SYNTAX_DETAILS, ids=_OUT_OF_RANGE_SYNTAX_IDS+)+def test_syntax_error_with_out_of_range_fields_never_dumps_the_handled_exception(+ enqueue_stderr, details+):+ """A crash rendering the caret line prints the exception being handled.++ Loguru's error handler prints the formatting error's traceback, whose+ context is the ``ValueError`` being handled here, unredacted to stderr.+ """+ exc = SyntaxError("bad", details)+ try:+ raise ValueError("Authorization: Bearer " + _OFFSET_SECRET)+ except ValueError:+ logger.opt(exception=exc).error("syntax failure")+ out = enqueue_stderr()+ assert "syntax failure" in out+ assert "Logging error in Loguru Handler" not in out+ assert "OffsetSecret739" not in out+ assert len(out) < 100_000+++ "details", _OUT_OF_RANGE_SYNTAX_DETAILS, ids=_OUT_OF_RANGE_SYNTAX_IDS+)+def test_syntax_error_with_out_of_range_fields_is_rebuilt(+ captured_records, details+):+ """Rebuilt from the range check, before any caret line is built."""+ import time++ exc = SyntaxError("bad", details)+ started = time.monotonic()+ _raise_and_log(exc)+ assert time.monotonic() - started < 5+ value = captured_records[-1]["exception"].value+ kept = value is exc+ assert not kept+ assert type(value) is SyntaxError+ for name in ("filename", "lineno", "offset", "text", "end_offset"):+ assert getattr(value, name) is None, name+++# The limit for ``offset`` and ``end_offset`` when ``text`` is a ``str``:+# its UTF-8 length plus one plus the later-line slack (2**16).+_SPAN = 2**16+++ "details, kept",+ [+ (("f.py", 1, 5, "src\n", 1, 5), True),+ (("f.py", 1, 5 + _SPAN, "src\n", 1, None), True),+ (("f.py", 1, 6 + _SPAN, "src\n", 1, None), False),+ (("f.py", 1, 1, "src\n", 2, 5 + _SPAN), True),+ (("f.py", 1, 1, "src\n", 2, 6 + _SPAN), False),+ # UTF-8 bytes, not characters: "\u00e9\u00e9\u00e9\n" is 7 bytes.+ (("f.py", 1, 1, "\u00e9\u00e9\u00e9\n", 1, 8 + _SPAN), True),+ (("f.py", 1, 1, "\u00e9\u00e9\u00e9\n", 1, 9 + _SPAN), False),+ (("f.py", 1, -1, "src\n", 1, -1), True),+ (("f.py", 1, -2, "src\n", 1, None), False),+ (("f.py", 1, 1, "src\n", 1, -2), False),+ (("f.py", 1, 1, "", 1, 1), True),+ (("f.py", 1, 1, "", 1, 1 + _SPAN), True),+ (("f.py", 1, 1, "", 1, 2 + _SPAN), False),+ (("f.py", 0, None, "src\n"), True),+ (("f.py", -1, None, "src\n"), False),+ (("f.py", 2**31 - 1, None, "src\n", 2**31 - 1, None), True),+ (("f.py", 2**31, None, "src\n"), False),+ (("f.py", 1, None, "src\n", 2**31, None), False),+ (("f.py", 1, 2**31 - 1, None, 1, 2**31 - 1), True),+ (("f.py", 1, 2**31, None, 1, None), False),+ ],+)+def test_syntax_error_int_field_range_bounds(captured_records, details, kept):+ """Offsets within -1..UTF-8 len(text)+1+2**16, lines within a C ``int``.++ A kept node at the upper limit is still rendered within bounds: Python+ 3.12 draws its ``end_offset - offset`` carets (none for an ``offset``+ below 1), at most the UTF-8 length of ``text`` plus ``2**16``+ (``end_offset`` at the limit, ``offset`` 1).+ """+ from local_deep_research.security.log_sanitizer import (+ _SYNTAX_ERROR_SPAN_END_SLACK,+ )++ assert _SYNTAX_ERROR_SPAN_END_SLACK == _SPAN+ exc = SyntaxError("bad", details)+ _raise_and_log(exc)+ assert (captured_records[-1]["exception"].value is exc) is kept+++_REAL_SYNTAX_ERROR_SOURCES = {+ "genexp_multiline": "f(x for x in\n y" + "y" * 80 + ", 1)",+ "assign_multiline": "x = (a\n+b" + "c" * 80 + ") = 3",+ "del_multiline": "del f(a,\n" + "b" * 80 + ")",+ "indent": " x = 1\n",+ "duplicate_argument": "def f(a, a):\n pass",+ "late_future_import": "from os import path\nfrom __future__ import annotations",+ "unterminated_nonascii": "x = '" + "\u00e9" * 10 + " $",+ "unterminated_string": "'abc",+ "invalid_syntax": "a b c",+ # Tokenizer errors report UTF-8 byte offsets: 21/22 and 34/35 against+ # 19 and 17 characters of text.+ "tokenizer_byte_offsets": "\u00e9" * 5 + " = 1; y = 0777\n",+ "tokenizer_byte_offsets_cjk": "\u5909\u6570" * 5 + " = 0777\n",+ # Compiler and symtable errors: byte offsets, and on import an+ # end_offset measured on the span's last line, not on ``text``.+ "return_span_on_later_line": "return f(\n 1) + some_long_function_name("+ + "a, " * 15+ + "b)\n",+ "yield_span_on_later_line": "yield (1,\n " + "x" * 70 + ")\n",+ "await_span_on_later_line": "await f(1,\n " + "y" * 70 + ")\n",+ "await_nonascii": "x = [\n " + "\u00e9" * 30 + ", await y]\n",+ "return_nonascii": 'x = "' + "\u00e9" * 30 + '"; return 1\n',+ "nonlocal_nonascii": "def g():\n \u00e9 = 1\n def h():\n print(\u00e9); nonlocal \u00e9\n",+ "return_emoji": "x = '\U0001f600\U0001f600\U0001f600'; return\n",+ "return_span_on_20000_char_line": "return f(\n" + "a" * 20_000 + ")\n",+}++[email protected]("how", ["compile", "import"])+ "case",+ list(_REAL_SYNTAX_ERROR_SOURCES),+ ids=list(_REAL_SYNTAX_ERROR_SOURCES),+)+def test_interpreter_syntax_errors_are_kept(+ captured_records, tmp_path, monkeypatch, case, how+):+ """Real interpreter errors (multi-line spans, ``-1`` offsets, no source+ line, UTF-8 byte offsets, and spans ending on a later line).++ The range check and the trial rendering must not drop the location+ details of an error the interpreter raised. Compiler and symtable errors+ only carry their source line (and so their offsets are only checked)+ when the file exists, so each source is also imported from a file.+ """+ import importlib+ import sys++ source = _REAL_SYNTAX_ERROR_SOURCES[case]+ error = None+ try:+ if how == "compile":+ compile(source, "f.py", "exec")+ else:+ name = "ldr_syntax_probe_" + case+ (tmp_path / (name + ".py")).write_text(+ source, encoding="utf-8", newline=""+ )+ monkeypatch.syspath_prepend(str(tmp_path))+ importlib.invalidate_caches()+ try:+ importlib.import_module(name)+ finally:+ sys.modules.pop(name, None)+ except SyntaxError as exc:+ error = exc+ if error is None:+ pytest.fail("source compiled")+ if how == "import":+ assert error.text is not None+ _raise_and_log(error)+ assert captured_records[-1]["exception"].value is error+++def test_syntax_error_whose_trial_rendering_fails_is_rebuilt(+ captured_records, monkeypatch+):+ """The keep decision renders the node as the sinks will, last."""+ import traceback++ real = traceback.format_exception_only++ def failing(exc, *args, **kwargs):+ # Only for a node with location details: the rebuilt node the sink+ # formats has none.+ if isinstance(exc, SyntaxError) and exc.lineno is not None:+ raise OverflowError("cannot fit 'int' into an index-sized integer")+ return real(exc, *args, **kwargs)++ exc = SyntaxError("bad", ("f.py", 1, 1, "src\n", 1, 2))+ monkeypatch.setattr(traceback, "format_exception_only", failing)+ _raise_and_log(exc)+ monkeypatch.setattr(traceback, "format_exception_only", real)+ value = captured_records[-1]["exception"].value+ assert value is not exc+ assert value.lineno is None and value.text is None+++def test_syntax_error_whose_trial_rendering_runs_long_is_rebuilt(+ captured_records, monkeypatch+):+ import traceback++ from local_deep_research.security.log_sanitizer import (+ _SYNTAX_ERROR_RENDER_SLACK,+ )++ real = traceback.format_exception_only++ def long(exc, *args, **kwargs):+ lines = real(exc, *args, **kwargs)+ if isinstance(exc, SyntaxError) and exc.lineno is not None:+ lines.append("^" * (_SYNTAX_ERROR_RENDER_SLACK + 100))+ return lines++ exc = SyntaxError("bad", ("f.py", 1, 1, "src\n", 1, 2))+ monkeypatch.setattr(traceback, "format_exception_only", long)+ _raise_and_log(exc)+ monkeypatch.setattr(traceback, "format_exception_only", real)+ assert captured_records[-1]["exception"].value is not exc+++def test_checked_location_block_is_the_one_the_traceback_prints():+ """The checked ``File``/source block is ``format_exception_only``'s."""+ import traceback++ from local_deep_research.security.log_sanitizer import (+ _syntax_error_location_block,+ )++ for details in (+ ("f.py", 3, None, None),+ ("", 3, None, " a b\n\n"),+ (None, 2, None, "\f x"),+ ("f.py", None, None, "a b\n"),+ (None, None, None, None),+ ("f.py", 3, None, "a b\n", 3, None),+ ):+ exc = SyntaxError("bad", details)+ lines = traceback.format_exception_only(exc)+ printed = "".join(+ line for line in lines if not line.startswith("SyntaxError")+ )+ assert _syntax_error_location_block(exc) == printed.rstrip("\n"), (+ details+ )+++class _ArglessApplicationError(Exception):+ """Module level and raised with no arguments: its ``str()`` is empty."""+++def test_empty_text_application_error_name_is_not_repeated_in_db_row(+ captured_records,+):+ from local_deep_research.utilities.log_utils import _exception_context++ exc = _ArglessApplicationError()+ exc.__cause__ = ValueError("token=" + "abcdef123456EmptyRow739")+ _raise_and_log(exc)+ record = captured_records[-1]+ assert record["exception"].value is not exc+ assert _exception_context(record) == "[_ArglessApplicationError] "+++def test_enqueue_sink_pickles_extra_with_the_queue_pickler(enqueue_stderr):+ """``SimpleQueue.put`` uses ``ForkingPickler``, not ``pickle.dumps``.++ Once ``multiprocessing.sharedctypes`` has created a value of a ``ctypes``+ type, ``ForkingPickler`` has a reducer for that type which raises+ outside process spawning, while ``pickle.dumps`` still succeeds.+ """+ import ctypes+ import pickle+ from multiprocessing import sharedctypes++ sharedctypes.RawValue(ctypes.c_ushort, 1)+ value = ctypes.c_ushort(3)+ pickle.dumps(value)+ try:+ raise _builtin_with_secret_text()+ except ValueError:+ logger.bind(value=value).info("bound ctypes value")+ out = enqueue_stderr()+ assert "bound ctypes value" in out+ assert "Logging error in Loguru Handler" not in out+ assert "EnqueueDumpSecret739" not in out+++# The redactor runs application code itself while it reads the graph (a+# parent's, a group subclass's or a note object's ``__str__``). That code+# can change a node read before it -- a cause, context or member whose text+# was clean -- or the record's exception class after its pickling was+# checked. Every decision must therefore come after all of that code.+_REWRITE_SECRET = "api_key=sk-live-" + "RewriteAfterCheck739"+++class _PlainValueError(ValueError):+ """Module level and plain, so it is kept when its text is clean."""+++class _SecretStrValueError(ValueError):+ def __str__(self):+ return _REWRITE_SECRET+++def _parent_rewrites(rewrite):+ victim = _PlainValueError("benign cause")++ class RewritingParent(Exception):+ def __str__(self):+ rewrite(victim)+ return "benign parent"++ exc = RewritingParent()+ exc.__cause__ = victim+ return exc+++def _rewrite_args(victim):+ victim.args = (_REWRITE_SECRET,)+++def _swap_class(victim):+ victim.__class__ = _SecretStrValueError+++def _relink_cause(victim):+ victim.__cause__ = ValueError(_REWRITE_SECRET)+++def _add_note(victim):+ victim.add_note(_REWRITE_SECRET)+++def _group_rewrites_member():+ victim = _PlainValueError("benign member")++ class RewritingGroup(ExceptionGroup):+ def __str__(self):+ _rewrite_args(victim)+ return "benign group"++ return RewritingGroup("benign", [victim])+++class _RewritingNote:+ def __init__(self, victim):+ self.victim = victim++ def __str__(self):+ _rewrite_args(self.victim)+ return "benign note"+++def _note_rewrites_context():+ victim = _PlainValueError("benign context")+ exc = RuntimeError("benign top")+ exc.__context__ = victim+ exc.__notes__ = [_RewritingNote(victim)]+ return exc+++_REWRITE_CASES = {+ "parent_str_rewrites_cause_args": lambda: _parent_rewrites(_rewrite_args),+ "parent_str_swaps_cause_class": lambda: _parent_rewrites(_swap_class),+ "parent_str_relinks_cause": lambda: _parent_rewrites(_relink_cause),+ "parent_str_adds_cause_note": lambda: _parent_rewrites(_add_note),+ "group_str_rewrites_member": _group_rewrites_member,+ "note_str_rewrites_context": _note_rewrites_context,+}+++ "make", list(_REWRITE_CASES.values()), ids=list(_REWRITE_CASES)+)+def test_node_changed_after_its_check_is_rendered_as_checked(+ rendered_sink, make+):+ """A node changed by code the redactor ran later is not kept as is.++ It is rebuilt from the text read and checked for it, so the sinks+ render that text, not what the application code made of the node.+ """+ import traceback++ records = []+ logger.add(lambda m: records.append(m.record), diagnose=False)+ _raise_and_log(make())+ rendered = rendered_sink.getvalue()+ assert "raise exc" in rendered+ assert "RewriteAfterCheck739" not in rendered+ assert "benign" in rendered+ value = records[-1]["exception"].value+ assert "RewriteAfterCheck739" not in "".join(+ traceback.format_exception(value)+ )+++class _RenamedLaterError(Exception):+ """Module level: pickled by name until its ``__qualname__`` changes."""+++def test_record_type_renamed_after_its_check_is_replaced(enqueue_stderr):+ """The record's type is checked after the code that could rename it.++ A cause's ``__str__`` renames the record's exception class, so pickle+ can no longer find it by name: had the type been checked before that+ code ran, the ``enqueue=True`` sink's pickle would fail and loguru's+ error handler would print the live chain, unredacted, to stderr.+ """+ calls = []++ class RenamingCause(Exception):+ def __str__(self):+ calls.append(None)+ if len(calls) == 1:+ _RenamedLaterError.__qualname__ = "_NoSuchName"+ return "benign cause"+ return _REWRITE_SECRET++ exc = _RenamedLaterError("benign top")+ exc.__cause__ = RenamingCause()+ try:+ _raise_and_log(exc)+ out = enqueue_stderr()+ finally:+ _RenamedLaterError.__qualname__ = "_RenamedLaterError"+ assert "unprintable failure" in out+ assert "Logging error in Loguru Handler" not in out+ assert "RewriteAfterCheck739" not in out+++class _StrRunningKey:+ """An ``extra`` key whose ``str()`` is application code."""++ def __str__(self):+ return "benign key"+++def test_application_code_runs_only_before_any_decision():+ """The invariant: no application code runs once a decision is made.++ Application code here is anything defined in this file. It runs while+ the patcher reads the record (an ``extra`` key's ``str()``, the+ exception graph's ``__str__`` and note objects) and never afterwards:+ not while the patcher decides what to keep, nor while the result is+ rendered and pickled the way the sinks do.+ """+ import pickle+ import sys+ import traceback+ from collections import namedtuple++ from local_deep_research.security import log_sanitizer++ decisions = {+ function.__code__+ for function in (+ log_sanitizer._build_redacted_exception,+ log_sanitizer._record_type_is_safe,+ log_sanitizer._exception_text_is_stable,+ log_sanitizer._pickled_by_reference_runs_no_code,+ log_sanitizer._type_header_changed,+ log_sanitizer._picklable_extra,+ )+ }+ exc = _note_rewrites_context()+ exc.__cause__ = _parent_rewrites(_rewrite_args)+ group = _group_rewrites_member()+ group.__context__ = exc+ record_exception = namedtuple("RecordException", "type value traceback")+ record = {+ "message": "benign message",+ "extra": {_StrRunningKey(): "benign value"},+ "exception": record_exception(type(group), group, None),+ }+ events = []++ def profile(frame, event, arg):+ if event != "call":+ return+ if frame.f_code.co_filename == __file__:+ events.append("application")+ elif frame.f_code in decisions:+ events.append("decision")++ sys.setprofile(profile)+ try:+ log_sanitizer.redact_log_record(record)+ value = record["exception"].value+ rendered = "".join(traceback.format_exception(value))+ pickle.dumps(value)+ finally:+ sys.setprofile(None)+ assert "RewriteAfterCheck739" not in rendered+ first_decision = events.index("decision")+ assert "application" in events[:first_decision]+ assert "application" not in events[first_decision:]+++class SwappedInAuthorization(ValueError):+ """Plain and stable, and its name ends in a credential header name."""+++_SWAP_TOKEN = "abc123def456ghi789jkl012mno345"+++def test_cause_swapped_to_a_stable_credential_named_class_is_rebuilt(+ rendered_sink,+):+ """A node whose class changed after it was read is not kept.++ A parent's ``__str__`` swaps a clean cause to a plain, stable class whose+ name joined with the cause's text forms a credential+ (``SwappedInAuthorization: <token>``). The header check is made with the+ class the text was read from, so only the class identity check stops+ the swapped node reaching the sinks as is.+ """+ import traceback++ victim = _PlainValueError(_SWAP_TOKEN)++ class SwappingParent(Exception):+ def __str__(self):+ victim.__class__ = SwappedInAuthorization+ return "benign parent"++ exc = SwappingParent()+ exc.__cause__ = victim+ records = []+ logger.add(lambda m: records.append(m.record), diagnose=False)+ _raise_and_log(exc)+ rendered = rendered_sink.getvalue()+ assert "raise exc" in rendered+ assert "benign parent" in rendered+ assert f"SwappedInAuthorization: {_SWAP_TOKEN}" not in rendered+ value = records[-1]["exception"].value+ assert f"SwappedInAuthorization: {_SWAP_TOKEN}" not in "".join(+ traceback.format_exception(value)+ )+++class _ClassPropertyName:+ """A ``name`` whose ``__class__`` property rewrites a kept node.++ ``isinstance(obj, str)`` falls back to ``obj.__class__`` and so runs it.+ """++ def __init__(self, victim):+ self.victim = victim++ @property+ def __class__(self):+ _rewrite_args(self.victim)+ return _ClassPropertyName+++class _RewritingDict(dict):+ """An instance ``__dict__`` whose own methods rewrite a kept node."""++ def _rewrite(self):+ _rewrite_args(vars(self)["victim"])++ def __len__(self):+ self._rewrite()+ return dict.__len__(self)++ def __iter__(self):+ self._rewrite()+ return dict.__iter__(self)++ def items(self):+ self._rewrite()+ return dict.items(self)+++def _rewriting_state(victim):+ state = _RewritingDict(note="benign")+ vars(state)["victim"] = victim+ return state+++def _name_rewrites_cause(kind, field):+ victim = _PlainValueError("benign cause")+ exc = kind("benign")+ setattr(exc, field, _ClassPropertyName(victim))+ exc.__cause__ = victim+ return exc+++def _name_rewrites_group_sibling():+ victim = _PlainValueError("benign member")+ member = NameError("benign")+ member.name = _ClassPropertyName(victim)+ return ExceptionGroup("benign", [victim, member])+++def _state_rewrites_cause():+ victim = _PlainValueError("benign cause")+ middle = _PlainValueError("benign middle")+ middle.__dict__ = _rewriting_state(victim)+ middle.__cause__ = victim+ exc = RuntimeError("benign top")+ exc.__cause__ = middle+ return exc+++def _state_rewrites_group_sibling():+ victim = _PlainValueError("benign member")+ member = _PlainValueError("benign member two")+ member.__dict__ = _rewriting_state(victim)+ return ExceptionGroup("benign", [victim, member])+++_DECISION_HOOK_CASES = {+ "attribute_error_name_class_property": lambda: _name_rewrites_cause(+ AttributeError, "name"+ ),+ "import_error_name_from_class_property": lambda: _name_rewrites_cause(+ ImportError, "name_from"+ ),+ "name_error_name_rewrites_group_sibling": _name_rewrites_group_sibling,+ "dict_subclass_state_rewrites_cause": _state_rewrites_cause,+ "dict_subclass_state_rewrites_group_sibling": _state_rewrites_group_sibling,+}+++ "make", list(_DECISION_HOOK_CASES.values()), ids=list(_DECISION_HOOK_CASES)+)+def test_decisions_run_no_hook_of_a_field_value_or_instance_dict(make):+ """Deciding what to keep runs no code of a field value or ``__dict__``.++ A non-``str`` ``name``/``name_from`` (whose ``__class__`` an+ ``isinstance`` check would run) or an instance ``__dict__`` that is a+ ``dict`` subclass (whose ``__len__``/``items`` iterating it would run)+ could otherwise rewrite a cause or group sibling already decided to be+ kept, and every sink would render the rewritten text. Such a node is+ rebuilt instead, and no application code runs once a decision is made.+ """+ import pickle+ import sys+ import traceback+ from collections import namedtuple++ from local_deep_research.security import log_sanitizer++ decisions = {+ function.__code__+ for function in (+ log_sanitizer._build_redacted_exception,+ log_sanitizer._record_type_is_safe,+ log_sanitizer._exception_text_is_stable,+ log_sanitizer._pickled_by_reference_runs_no_code,+ log_sanitizer._type_header_changed,+ log_sanitizer._picklable_extra,+ )+ }+ exc = make()+ record_exception = namedtuple("RecordException", "type value traceback")+ record = {+ "message": "benign message",+ "extra": {},+ "exception": record_exception(type(exc), exc, None),+ }+ events = []++ def profile(frame, event, arg):+ if event != "call":+ return+ if frame.f_code.co_filename == __file__:+ events.append("application")+ elif frame.f_code in decisions:+ events.append("decision")++ sys.setprofile(profile)+ try:+ log_sanitizer.redact_log_record(record)+ value = record["exception"].value+ rendered = "".join(traceback.format_exception(value))+ pickled = pickle.dumps(value)+ rendered_again = "".join(traceback.format_exception(value))+ finally:+ sys.setprofile(None)+ assert "benign" in rendered+ assert "RewriteAfterCheck739" not in rendered+ assert "RewriteAfterCheck739" not in rendered_again+ assert b"RewriteAfterCheck739" not in pickled+ first_decision = events.index("decision")+ assert "application" not in events[first_decision:]+++def test_module_spec_dict_subclass_is_not_iterated(monkeypatch):+ """A module ``__spec__`` whose ``__dict__`` is a subclass is rejected.++ Pickle's lookup of a class goes through its module's ``__spec__``; its+ instance dict is checked as an exact ``dict``, so a subclass's+ ``__iter__``/``__contains__`` never runs during the check.+ """+ import sys+ import types+ from importlib.machinery import ModuleSpec++ from local_deep_research.security.log_sanitizer import (+ _pickled_by_reference_runs_no_code,+ )++ calls = []++ class SpyDict(dict):+ def __iter__(self):+ calls.append("__iter__")+ return dict.__iter__(self)++ def __contains__(self, key):+ calls.append("__contains__")+ return dict.__contains__(self, key)++ name = "_log_sink_spec_dict_subclass_module"+ module = types.ModuleType(name)+ spec = ModuleSpec(name, None)+ spec.__dict__ = SpyDict(vars(spec))+ module.__spec__ = spec+ kind = type("SpecDictError", (Exception,), {"__module__": name})+ module.SpecDictError = kind+ monkeypatch.setitem(sys.modules, name, module)+ assert _pickled_by_reference_runs_no_code(kind) is False+ assert calls == []+++def test_pickling_a_class_never_calls_its_module_getattr(monkeypatch):+ """Pickle imports a class's module without reading ``__path__``.++ ``_module_import_runs_no_code`` does not look at a module-level+ (PEP 562) ``__getattr__``: CPython 3.12 to 3.14 import the module with+ an empty ``fromlist`` (``PyImport_Import``), so the import never reads+ ``__path__`` (or any other missing name) on it. This pins that.+ """+ import pickle+ import sys+ import types+ from multiprocessing.reduction import ForkingPickler++ from local_deep_research.security.log_sanitizer import (+ _pickled_by_reference_runs_no_code,+ )++ name = "_log_sink_module_getattr_module"+ module = types.ModuleType(name)+ module.__spec__ = None+ calls = []++ def module_getattr(attribute):+ calls.append(attribute)+ raise AttributeError(attribute)++ module.__getattr__ = module_getattr+ kind = type("ModuleGetattrError", (Exception,), {"__module__": name})+ module.ModuleGetattrError = kind+ monkeypatch.setitem(sys.modules, name, module)+ assert _pickled_by_reference_runs_no_code(kind) is True+ pickle.dumps(kind("benign"))+ ForkingPickler.dumps(kind("benign"))+ pickle.dumps(kind)+ assert calls == []+++def _plain_module_error(monkeypatch, name):+ """An exception class defined at the top level of a plain module."""+ import sys+ import types++ module = types.ModuleType(name)+ module.__spec__ = None+ kind = type("PlainModuleError", (Exception,), {"__module__": name})+ module.PlainModuleError = kind+ monkeypatch.setitem(sys.modules, name, module)+ return kind+++def _group_record(members):+ try:+ raise ExceptionGroup("group", members)+ except ExceptionGroup as group:+ return {+ "message": "m",+ "extra": {},+ "exception": (type(group), group, group.__traceback__),+ }+++def test_sys_modules_is_scanned_once_per_record(monkeypatch):+ """A large exception group scans ``sys.modules`` once, not per member.++ Every kept member's pickling check reads ``sys.modules``, which holds+ thousands of entries in the web process; scanning its keys once per+ member made one record with a 150-member group cost tens of+ milliseconds on the logging thread.+ """+ import sys++ from local_deep_research.security import log_sanitizer+ from local_deep_research.security.log_sanitizer import redact_log_record++ kind = _plain_module_error(monkeypatch, "_log_sink_scan_once_module")+ scans = []+ plain_names = log_sanitizer._plain_names++ def counting(namespace):+ if namespace is sys.modules:+ scans.append(1)+ return plain_names(namespace)++ monkeypatch.setattr(log_sanitizer, "_plain_names", counting)+ record = _group_record([kind(f"member {i}") for i in range(150)])+ group = record["exception"][1]+ redact_log_record(record)+ # Every member is still checked and kept as the original object.+ assert record["exception"][1] is group+ assert len(scans) == 1+ # The once-per-record answer does not outlive the record.+ assert log_sanitizer._DECISION_MEMO.get() is None+ redact_log_record(_group_record([kind("again")]))+ assert len(scans) == 2+++def test_non_str_sys_modules_key_added_while_reading_is_seen(monkeypatch):+ """The once-per-record scan is made after the graph is read.++ A ``__str__`` the read phase runs can add a key to ``sys.modules``; the+ pickling checks made afterwards must see it, so a member whose class+ would be kept is rebuilt instead, as when the key was there from the+ start.+ """+ import sys++ from local_deep_research.security.log_sanitizer import redact_log_record++ kind = _plain_module_error(monkeypatch, "_log_sink_scan_late_module")+ module = sys.modules["_log_sink_scan_late_module"]++ class AddsModuleKeyError(Exception):+ def __str__(self):+ sys.modules[_NON_STR_MODULE_KEY] = module+ return "benign"++ monkeypatch.delitem(sys.modules, _NON_STR_MODULE_KEY, raising=False)+ try:+ member = kind("benign member")+ record = _group_record([AddsModuleKeyError(), member])+ redact_log_record(record)+ assert _NON_STR_MODULE_KEY in sys.modules+ rendered = record["exception"][1]+ assert str(rendered.exceptions[1]) == "PlainModuleError: benign member"+ assert rendered.exceptions[1] is not member+ finally:+ sys.modules.pop(_NON_STR_MODULE_KEY, None)++ # Without the key, the same member is kept as the original object.+ member = kind("benign member")+ record = _group_record([kind("other"), member])+ redact_log_record(record)+ assert record["exception"][1].exceptions[1] is member+++# A ``sys.modules`` key that is not a ``str``: one whose comparison could+# run code, so the pickling checks keep no application class while it is+# there.+_NON_STR_MODULE_KEY = ("_log_sink_non_str_module_key",)+++def test_class_level_checks_run_once_per_class_per_record(monkeypatch):+ """A group of one class pays for that class's pickling check once.++ Whether pickling a class runs code depends on the class and global+ tables only, so a record answers it once per class, not once per+ member: a 150-member group cost about ten times what the patcher cost+ before these checks while it repeated them for every member.+ """+ from local_deep_research.security import log_sanitizer+ from local_deep_research.security.log_sanitizer import redact_log_record++ kind = _plain_module_error(monkeypatch, "_log_sink_class_once_module")+ lookups = []+ lookup = log_sanitizer._pickle_lookup_runs_no_code++ def counting(checked, module, qualname):+ lookups.append(checked)+ return lookup(checked, module, qualname)++ monkeypatch.setattr(log_sanitizer, "_pickle_lookup_runs_no_code", counting)+ record = _group_record([kind(f"member {i}") for i in range(150)])+ group = record["exception"][1]+ redact_log_record(record)+ # Every member is still checked and kept as the original object.+ assert record["exception"][1] is group+ # Once for the members' class and once for the group's.+ assert sorted(map(id, lookups)) == sorted({id(kind), id(ExceptionGroup)})+ assert log_sanitizer._DECISION_MEMO.get() is None+ # The answers do not outlive the record: the next one checks again.+ redact_log_record(_group_record([kind("again")]))+ assert len(lookups) == 4+++def test_clean_kept_exception_text_is_scanned_twice(monkeypatch):+ """A kept exception's text costs two redaction passes, as on main.++ Main scanned a node's text twice (its message and its ``str()``). The+ header check (``TypeName: text``) and the read-phase check are the two+ passes here: the second pass of :func:`_redact_exception_text` is+ skipped when it would scan the same text again, and the type is+ joined with the text only in the forms a sink renders (``ValueError``,+ not ``builtins.ValueError``). Before, a kept ``ValueError`` holding a+ long message cost three times what main did.+ """+ from local_deep_research.security import log_sanitizer+ from local_deep_research.security.log_sanitizer import redact_log_record++ text = "the upstream service returned an unexpected payload " * 40+ scans = []+ redact = log_sanitizer._redact_bounded_log_text++ def counting(value):+ if text.strip() in value:+ scans.append(value)+ return redact(value)++ monkeypatch.setattr(log_sanitizer, "_redact_bounded_log_text", counting)+ try:+ raise ValueError(text)+ except ValueError as exc:+ value = exc+ record = {+ "message": "m",+ "extra": {},+ "exception": (ValueError, exc, exc.__traceback__),+ }+ redact_log_record(record)+ assert record["exception"][1] is value+ assert scans == [text, f"ValueError: {text}"]+++ "text",+ [+ "plain text with no credential",+ "token=abc123def456ghi789",+ "api_\u200bkey=abc123def456ghi789",+ "tok\x1fen=abc123def456ghi789",+ "line one\nline two\tpassword=hunter2hunter2",+ "https://user:pa\[email protected]/path",+ "\x85\u2028\u200b",+ "Bearer \u200bsk-abcdefghijklmnopqrstuvwxyz012345",+ "word " * 7000 + "password=hunter2hunter2",+ "x" * 40_000,+ ],+ ids=[+ "plain",+ "token",+ "invisible-api-key",+ "control-character-token",+ "multiline-password",+ "url-password",+ "invisible-only",+ "bearer-token",+ "long-password",+ "long-plain",+ ],+)+def test_skipped_second_pass_returns_what_both_passes_return(text):+ """Skipping the second pass on unchanged text never changes the result.++ Reference: both passes run unconditionally, as before the skip.+ """+ from local_deep_research.security import log_sanitizer++ def two_passes(value, strip):+ head, marker = log_sanitizer._truncate_for_log_redaction(value)+ first = log_sanitizer._redact_bounded_log_text(head)+ visible = strip(first)+ second = log_sanitizer._redact_bounded_log_text(visible)+ return first, visible, second, marker++ first, visible, second, marker = two_passes(+ text, lambda value: log_sanitizer._EXCEPTION_INVISIBLE_RE.sub("", value)+ )+ expected = (first if second == visible else second) + marker+ assert log_sanitizer._redact_exception_text(text) == expected++ _, _, second, marker = two_passes(text, log_sanitizer.strip_control_chars)+ assert log_sanitizer._redact_log_text(text) == second + marker+++ "shape",+ [+ "Api-Key: {secret}",+ "postgresql://ldr:ab/cd{secret}@db:5432/ldr",+ '{{"password": "{secret}"}}',+ ],+ ids=["api-key-header", "slash-dsn-password", "quoted-key"],+)+def test_additional_credential_shapes_are_scrubbed_from_exception_values(shape):+ """The shapes added to record text also stay out of rendered tracebacks."""+ import traceback++ from local_deep_research.security.log_sanitizer import redact_log_record++ secret = "ZZZTESTCREDENTIAL123456"+ try:+ raise ValueError(shape.format(secret=secret))+ except ValueError as error:+ record = {+ "message": "logging failed",+ "extra": {},+ "exception": (ValueError, error, error.__traceback__),+ }++ redact_log_record(record)+ assert secret not in str(record["exception"][1])+ assert secret not in "".join(+ traceback.format_exception(*record["exception"])+ )+++ "scheme", ["Basic", "Bearer", "Digest", "Negotiate", "ApiKey", "Token"]+)+ "placement", ["message", "extra", "exception", "note", "group-member"]+)+def test_unquoted_authorization_is_redacted_before_each_sink(+ enqueue_stderr, scheme, placement+):+ """The credential, not only its scheme word, is removed at real sinks."""+ from local_deep_research.utilities.log_utils import _exception_context++ secret = "BoundarySinkCanary0123456789"+ payload = "{'Authorization': " + scheme + " " + secret + "==}"+ records = []+ logger.add(lambda message: records.append(message.record), diagnose=False)+ error = None+ if placement == "exception":+ error = ValueError(payload)+ elif placement == "note":+ error = ValueError("upstream rejected request")+ error.add_note(payload)+ elif placement == "group-member":+ error = ExceptionGroup("upstream failures", [ValueError(payload)])+ bound = logger.bind(+ username="review-owner",+ research_id="review-research",+ detail=payload if placement == "extra" else "ordinary detail",+ )+ bound.opt(exception=error).error(+ payload if placement == "message" else "provider failed"+ )+ output = enqueue_stderr()+ assert "Logging error in Loguru Handler" not in output+ assert len(records) == 1+ record = records[0]+ assert record["extra"]["username"] == "review-owner"+ assert record["extra"]["research_id"] == "review-research"+ for shown in (+ output,+ record["message"],+ repr(record["extra"]),+ _exception_context(record),+ ):+ assert secret not in shown, shown+++# --- #5768 follow-ups -------------------------------------------------------+++ "name",+ [+ "OPENAI_API_KEY",+ "LDR_LLM_OPENAI_API_KEY",+ "llm.openai.api_key",+ "db_password",+ "search.engine.web.serper.api_key",+ "MILVUS_TOKEN",+ "app.client_secret",+ ],+)+def test_prefixed_env_and_dotted_names_redacted_in_message_text(name):+ """Message text uses the same exact-or-suffix name rule as extra keys."""+ message = f"loaded {name}=NameMarker987plain and more"+ assert redact_log_message(message) == (f"loaded {name}=[REDACTED] and more")+++ "message",+ [+ "max tokens = 4096",+ "token count: 5",+ "max_tokens=4096 context_tokens=8192",+ "requires_api_key=True",+ "search.engine.web.brave.requires_api_key=False",+ "mytoken=keepme",+ "x-token=keepme",+ "api_keys=3",+ "OLDPWD=/home/user",+ "token_count=5",+ ],+)+def test_prefixed_name_rule_leaves_non_credentials_readable(message):+ assert redact_log_message(message) == message+++def test_trailing_list_delimiter_is_not_consumed():+ """``max token = 4096,`` keeps its comma; the value is still redacted."""+ assert redact_log_message(+ "LLM config: max token = 4096, temperature = 0.7"+ ) == ("LLM config: max token = [REDACTED], temperature = 0.7")+ assert redact_log_message("token=abc; next") == "token=[REDACTED]; next"+ # Commas INSIDE a value are still part of it.+ assert redact_log_message("password=a,b,Marker987 x") == (+ "password=[REDACTED] x"+ )+++ "message, secret",+ [+ ("Engine requires_api_key=True,api_key=Hide987a", "Hide987a"),+ ("requires_api_key=true;password=Hide987b", "Hide987b"),+ ("requires_api_key=False|token=Hide987c", "Hide987c"),+ # An unterminated quote after the flag runs to the end of the text.+ ('requires_api_key=" api_key=Hide987d', "Hide987d"),+ ("cfg requires_api_key='yes token=Hide987e", "Hide987e"),+ ('requires_api_key="true password=Hide987f"', "Hide987f"),+ ("requires_api_key=password = Hide987g", "Hide987g"),+ ("requires_api_key = password=Hide987h", "Hide987h"),+ ("requires_api_key=True\u200bapi_key=Hide987i", "Hide987i"),+ ("query=requires_api_key=1,api_key=Hide987j", "Hide987j"),+ ("requires_api_key =\napi_key = Hide987k", "Hide987k"),+ ("REQUIRES_API_KEY=\nDB_PASSWORD=Hide987l", "Hide987l"),+ (+ "search.engine.web.brave.requires_api_key=False,api_key=Hide987m",+ "Hide987m",+ ),+ (+ "search.engine.web.brave.requires_api_key=\n"+ "search.engine.web.brave.api_key=Hide987n",+ "Hide987n",+ ),+ ("requires_api_key=True,OPENAI_API_KEY=Hide987o", "Hide987o"),+ ],+)+def test_exempt_flag_does_not_hide_the_assignment_after_it(message, secret):+ """The readable ``requires_api_key`` flag must not consume its value.++ Had the match consumed the flag's value and handed it back unchanged,+ ``re.sub`` would resume after it and never scan the credential inside.+ """+ from local_deep_research.security.log_sanitizer import _redact_log_text++ for redact in (redact_log_message, _redact_log_text):+ redacted = redact(message)+ assert secret not in redacted, (redact.__name__, redacted)+ assert "requires_api" in redacted.lower()+ assert redact_log_message("Engine requires_api_key=True,api_key=x") == (+ "Engine requires_api_key=True,api_key=[REDACTED]"+ )+++ "message, secret",+ [+ # A prefixed name's value runs on into an exact-name assignment.+ ("OPENAI_API_KEY=abc,password = Hide987p", "Hide987p"),+ ("OPENAI_API_KEY=api_key = Hide987q", "Hide987q"),+ ("OPENAI_password\x1c=x;secret= Hide987r", "Hide987r"),+ ('db_password="a token="b Hide987s"', "Hide987s"),+ # ... or a first-pass replacement changes what the second pass,+ # after stripping control characters, reads around it.+ ('s_apikey=s\npasswd=""apikey =""Hide987t', "Hide987t"),+ (+ "tok\u200ben='a OPENAI_API_KEY='bc' pass\u200bword='d Hide987u' x'",+ "Hide987u",+ ),+ # A prefixed value after a redacted line, glued to it once the+ # newline is stripped.+ ('password=abc\nOPENAI_API_KEY="def Hide987v"', "Hide987v"),+ ("client_secret='x'\nllm.api_key='y Hide987w'", "Hide987w"),+ ],+)+def test_prefixed_names_never_hide_an_exact_name_assignment(message, secret):+ from local_deep_research.security.log_sanitizer import _redact_log_text++ redacted = _redact_log_text(message)+ assert secret not in redacted, redacted+ # ``redact_log_message`` (exception text) strips nothing, so a name an+ # invisible character splits stays unrecognised there.+ if "\u200b" not in message:+ assert secret not in redact_log_message(message)+++ "message, secret",+ [+ # A name on its own line, after a line the strip glues it to: a+ # name after ``-``, ``?``, ``&``, ``.`` or a non-ASCII letter is+ # not recognised in the stripped text.+ ("-----\nDB_PASSWORD=Line987a\n-----", "Line987a"),+ (+ "Loaded .env:\n# ---\nANTHROPIC_API_KEY=Line987b\nLDR_DEBUG=1",+ "Line987b",+ ),+ ("Are you sure?\nDB_PASSWORD=Line987c\nok", "Line987c"),+ (+ "Konfiguration f\u00fcr Gr\u00f6\u00dfe\nOPENAI_API_KEY=Line987d\n",+ "Line987d",+ ),+ ("-----\r\nDB_PASSWORD=Line987e\r\n", "Line987e"),+ ("x-\tSMTP_PASSWORD=Line987f\tdone", "Line987f"),+ ("a&\nllm.openai.api_key=Line987g\nend", "Line987g"),+ ("Loading...\tOPENAI_API_KEY=Line987h\tok", "Line987h"),+ (+ "name=caf\u00e9\nLDR_SEARCH_ENGINE_WEB_BRAVE_API_KEY=Line987i\nx=1",+ "Line987i",+ ),+ ("HOST=web-1\x1cDB_PASSWORD=Line987j\u2028PORT=5432", "Line987j"),+ ("requires_api_key- OPENAI_API_KEY=Line987k", "Line987k"),+ # ... or the previous line's value runs on into it.+ (+ "SERPER_API_KEY = abc123\nOPENAI_API_KEY = Line987l\nTIMEOUT = 30",+ "Line987l",+ ),+ ("db_password = abc\nredis_password = Line987m\nport = 1", "Line987m"),+ (+ "search.engine.web.brave.api_key = xyz\n"+ "llm.openai.api_key = Line987n\nllm.model = gpt",+ "Line987n",+ ),+ # An empty assignment does not take the next line's name as value.+ ("DB_PASSWORD=\nOPENAI_API_KEY = Line987o\n", "Line987o"),+ ("password=\napi_key = Line987p", "Line987p"),+ ],+)+def test_prefixed_name_on_its_own_line_is_redacted(message, secret):+ from local_deep_research.security.log_sanitizer import _redact_log_text++ redacted = _redact_log_text(message)+ assert secret not in redacted, redacted+ assert "[REDACTED]" in redacted+ # Exception text keeps its newlines; it is read line by line the same.+ assert secret not in redact_log_message(message)+++# Whitespace (and invisible characters) between an empty assignment and+# the next line's name: the indentation of a pretty-printed dump, on the+# next line or after a blank one, with CRLF, a tab, NBSP, U+3000 or a+# zero-width character before the name.+_NEXT_LINE_GAPS = [+ "\n ",+ "\n ",+ "\n ",+ "\n\t ",+ "\r\n ",+ " \n ",+ "\n\n ",+ "\n\u00a0",+ "\n\u3000",+ "\n\u200b",+ "\n \u200b",+ "\x1c ",+ "\u2028 ",+]++[email protected]("gap", _NEXT_LINE_GAPS)+ "empty", ["DB_PASSWORD=", "DB_PASSWORD =", "password=", "llm.api_key ="]+)[email protected]("next_name", ["OPENAI_API_KEY", "api_key"])+def test_empty_assignment_does_not_take_an_indented_next_name(+ gap, empty, next_name+):+ """The next line's name is not the empty assignment's value, however+ the next line is indented, and its value -- followed by a newline, as+ every line of a dump is -- is redacted."""+ from local_deep_research.security.log_sanitizer import _redact_log_text++ message = (+ "Settings:\n "+ + empty+ + gap+ + next_name+ + " = Indent987\n TIMEOUT = 30\n"+ )+ for redact in (redact_log_message, _redact_log_text):+ out = redact(message)+ assert "Indent987" not in out, (redact.__name__, out)+ assert "TIMEOUT = 30" in out, (redact.__name__, out)+++ "message",+ [+ # An indented .env-style block.+ "Loaded config:\n HOST = web-1\n DB_PASSWORD =\n"+ " OPENAI_API_KEY = Indent987a\n TIMEOUT = 30\n",+ # A YAML-style block (two-space indent, an empty value first).+ "settings:\n llm:\n password=\n api_key = Indent987b\n"+ " model = gpt\n",+ # Tab-and-space indentation with CRLF line endings.+ "[db]\r\n\tDB_PASSWORD=\r\n\t REDIS_PASSWORD = Indent987c\r\n",+ ],+)+def test_indented_config_block_is_redacted(message):+ from local_deep_research.security.log_sanitizer import _redact_log_text++ for redact in (redact_log_message, _redact_log_text):+ out = redact(message)+ assert "Indent987" not in out, (redact.__name__, out)+++def _exact_names_only_log_text(value):+ """The log redaction with only the exact names (no prefix rule).++ One reference for the "never less" property: the assignment pattern+ that recognised only the exact names, as it was before the prefix rule.+ """+ import re++ from local_deep_research.security import log_sanitizer as ls++ exact_only = re.compile(+ r"(?i)(?<![\w.?&-])(" + ls._LOG_SENSITIVE_NAME_PATTERN + r")"+ r"(\s*=\s*)"+ r"(?:\"(?:\\.|[^\"\\])*(?:\"|\\?$)|'(?:\\.|[^'\\])*(?:'|\\?$)"+ r"|[^\s]+)"+ )++ def one_pass(text):+ shaped = ls.sanitize_error_message(text)+ queried = ls._SENSITIVE_QUERY_RE.sub(r"\1[REDACTED]", shaped)+ return exact_only.sub(r"\1\2[REDACTED]", queried)++ return one_pass(ls.strip_control_chars(one_pass(value)))+++def _prefixed_names_log_text(value):+ """The log redaction with prefixed names, in one pattern.++ The other reference: exact and prefixed names (``OPENAI_API_KEY``,+ ``db_password``, ``llm.openai.api_key``) matched in start order on the+ original separators and again on the stripped text, the+ ``requires_api_key`` flag's assignment kept as it is.+ """+ import re++ from local_deep_research.security import log_sanitizer as ls++ names = re.compile(+ r"(?i)(?<![\w.?&-])((?:[a-z0-9]+[._])*(?:"+ + ls._LOG_SENSITIVE_NAME_PATTERN+ + r"))(\s*=\s*)"+ r"(?:\"(?:\\.|[^\"\\])*(?:\"|\\?$)|'(?:\\.|[^'\\])*(?:'|\\?$)"+ r"|\S+?(?=[,;]?(?:\s|$)))"+ )++ def replace(match):+ leaf = match.group(1).rsplit(".", 1)[-1].lower().replace("-", "_")+ if leaf == "requires_api_key":+ return match.group(0)+ return match.group(1) + match.group(2) + "[REDACTED]"++ def one_pass(text):+ shaped = ls.sanitize_error_message(text)+ queried = ls._SENSITIVE_QUERY_RE.sub(r"\1[REDACTED]", shaped)+ return names.sub(replace, queried)++ return one_pass(ls.strip_control_chars(one_pass(value)))+++def _seeded_log_messages(rng, case):+ """One seeded message and the secrets in it (values of credentials)."""+ exempt = [+ "requires_api_key",+ "REQUIRES_API_KEY",+ "x.requires_api_key",+ "requires_api-key",+ ]+ names = [+ "token",+ "password",+ "api_key",+ "api-key",+ "pwd",+ "client_secret",+ "OPENAI_API_KEY",+ "DB_PASSWORD",+ "db_password",+ "llm.openai.api_key",+ "LDR_SEARCH_ENGINE_WEB_BRAVE_API_KEY",+ "s_apikey",+ ]+ secrets = []+ if case % 2:+ # Lines of ``NAME=value`` / ``NAME = value``, between lines that+ # end in characters the stripped text glues a name onto.+ prose = [+ "-----",+ "# ---",+ "Are you sure?",+ "a&",+ "ok.",+ "caf\u00e9",+ "",+ ]+ lines = []+ for _ in range(rng.randint(1, 6)):+ kind = rng.random()+ if kind < 0.6:+ secret = f"Sk{case}x{len(secrets)}Q"+ secrets.append(secret)+ quote = rng.choice(['"', "'", "", ""])+ lines.append(+ rng.choice(names)+ + rng.choice(["=", " = "])+ + quote+ + secret+ + quote+ )+ elif kind < 0.75:+ lines.append(+ rng.choice(exempt)+ + rng.choice(["=", " = "])+ + rng.choice(["True", "", "1"])+ )+ else:+ lines.append(rng.choice(prose))+ message = lines[0]+ for line in lines[1:]:+ message += (+ rng.choice(["\n", "\r\n", "\t", "\x1c", "\u2028", "\n\n"])+ + line+ )+ return message, secrets+ seps = ["=", " = ", "=\n", " =", "\n=\n"]+ glue = [",", ";", "|", " ", "\n", "\u200b", "\x1c", "", " and ", "'", '"']+ parts = []+ for _ in range(rng.randint(1, 4)):+ quote = rng.choice(['"', "'", ""])+ parts.append(+ rng.choice(exempt)+ + rng.choice(seps)+ + quote+ + rng.choice(["True", "1", "yes", "", "a b"])+ + rng.choice([quote, ""])+ + rng.choice(glue)+ )+ for _ in range(rng.randint(1, 2)):+ secret = f"Sk{case}x{len(secrets)}Q"+ secrets.append(secret)+ quote = rng.choice(['"', "'", ""])+ parts.append(+ rng.choice(names)+ + rng.choice(seps)+ + quote+ + rng.choice(["", "a b ", "x,"])+ + secret+ + rng.choice([quote, ""])+ + rng.choice(glue)+ )+ return "".join(parts), secrets+++def test_log_text_never_redacts_less_than_either_reference():+ """Seeded differential: no secret either reference redacts survives.++ The references are the exact names alone and the prefixed names in one+ pattern (see :func:`_prefixed_names_log_text`), so a prefixed value+ the log redaction leaves while the one-pattern reading redacts it --+ a name on its own line after ``-`` or ``?``, a value the previous+ line's runs on into -- is a failure here too.+ """+ import random++ from local_deep_research.security.log_sanitizer import _redact_log_text++ rng = random.Random(5768)+ failures = []+ for case in range(2000):+ message, secrets = _seeded_log_messages(rng, case)+ redacted = _redact_log_text(message)+ present = [s for s in secrets if s in redacted]+ if not present:+ continue+ for reference in (_exact_names_only_log_text, _prefixed_names_log_text):+ expected = reference(message)+ leaked = [s for s in present if s not in expected]+ if leaked:+ failures.append((reference.__name__, message, redacted))+ assert not failures, failures[:3]+++def test_log_text_pipelines_track_every_character():+ """Each pipeline's tracked run gives its untracked text, and each kept+ character's origin is the character it was in the original."""+ import random++ from local_deep_research.security import log_sanitizer as ls++ rng = random.Random(6879)+ for case in range(300):+ message, _ = _seeded_log_messages(rng, case)+ plain = ls._PipelineRun(message, tracked=False)+ tracked = ls._PipelineRun(+ message, tracked=True, unmatched=plain.unmatched+ )+ for index in ls._LOG_TEXT_PIPELINE_INDEXES:+ text, origins = tracked.result(index)+ assert text == plain.result(index)[0], (index, message)+ assert len(origins) == len(text)+ assert all(+ origin < 0 or message[origin] == character+ for character, origin in zip(text, origins)+ ), (index, message)+++ "message",+ [+ "Engine requires_api_key=True,api_key=hunter2 next",+ "OPENAI_API_KEY=\"a b\"tail and db_password='x'y",+ 'password=abc\nOPENAI_API_KEY="def ghi"',+ 'b_passwd=""e',+ "requires_api_key=True",+ "-----\nDB_PASSWORD=hunter2abc\n-----",+ "SERPER_API_KEY = abc\nOPENAI_API_KEY = def\nTIMEOUT = 30",+ "DB_PASSWORD=\nOPENAI_API_KEY = x\n",+ 'password="a"Secret9',+ 'pwd\u200b=""Secret1',+ ],+)+def test_log_text_redaction_is_idempotent(message):+ from local_deep_research.security.log_sanitizer import _redact_log_text++ once = _redact_log_text(message)+ assert _redact_log_text(once) == once+++ "message",+ [+ "A_" * 16_000 + "API_KEY=x",+ "a." * 16_000,+ "a_api_key_password_" * 1_700,+ "token=" + "a," * 16_000,+ "db_password = a, " * 1_900,+ "requires_api_key=" * 1_900,+ 'requires_api_key="' * 1_800,+ "=a_a" * 8_000,+ "a_password=" * 2_900,+ 'a_token="' * 3_600,+ "requires_api_key=password=" * 1_200,+ "OPENAI_API_KEY=a," * 1_900,+ # The pipelines disagree on every line, so the origins are tracked.+ "-\nDB_PASSWORD=x\n" * 2_000,+ "DB_PASSWORD=\nOPENAI_API_KEY = x\n" * 900,+ "requires_api_key=a,b,db_password\x1c=x;" * 700,+ 'password="a"x ' * 2_300,+ 'DB_PASSWORD=\nOPENAI_API_KEY = "x"t\n' * 800,+ 'OPENAI_API_KEY=abc,DB_PASSWORD="a b c" ' * 800,+ ],+ ids=[+ "upper-snake",+ "dotted",+ "name-runs",+ "comma-value",+ "list",+ "exempt-runs",+ "exempt-quote-runs",+ "word-starts",+ "prefixed-runs",+ "prefixed-quote-runs",+ "exempt-then-exact",+ "prefixed-comma-runs",+ "env-lines-after-dashes",+ "empty-then-name-lines",+ "flag-value-runs",+ "glued-quote-runs",+ "next-line-quoted-runs",+ "read-on-quoted-runs",+ ],+)+def test_prefixed_name_rule_is_linear(message):+ import time++ # Measure redaction's CPU work without counting xdist/runner preemption.+ # The same one-second budget still rejects pathological backtracking.++ from local_deep_research.security.log_sanitizer import _redact_log_text++ for redact in (redact_log_message, _redact_log_text):+ started = time.thread_time()+ redact(message)+ elapsed = time.thread_time() - started+ assert elapsed < _QUADRATIC_BUDGET_SECONDS, (redact.__name__, elapsed)+++ ("message", "secret"),+ [+ ('password="a"Glued987', "Glued987"),+ ("pwd='x'Glued987 next", "Glued987"),+ ('pwd=""Glued987', "Glued987"),+ ('password\x7f="a"Glued987', "Glued987"),+ ("pass\x00word='x'Glued987", "Glued987"),+ ('DB_PASSWORD=\nOPENAI_API_KEY = "x"Glued987', "Glued987"),+ ],+)+def test_exact_name_glued_quote_tail_is_redacted_once(message, secret):+ """A quoted value glued to the next text leaves no readable tail on+ either log path, and scrubbing the result again changes nothing."""+ from local_deep_research.security.log_sanitizer import _redact_log_text++ redacts = [_redact_log_text]+ # ``redact_log_message`` (exception text) strips nothing, so a name an+ # invisible character splits stays unrecognised there.+ if not any(character in message for character in "\u200b\x7f\x00"):+ redacts.append(redact_log_message)+ for redact in redacts:+ once = redact(message)+ assert secret not in once, (redact.__name__, once)+ assert redact(once) == once, (redact.__name__, once)+++def test_full_pass_name_steps_are_a_fixpoint():+ """Seeded: the "exact names first" name steps, run again on their own+ result, change nothing (the claim at ``_FULL_PASS_NAME_STEPS``)."""+ import random++ from local_deep_research.security import log_sanitizer as ls++ rng = random.Random(6879)+ failures = []+ for case in range(1500):+ message, _ = _seeded_log_messages(rng, case)+ for text in (message, ls.strip_control_chars(message)):+ once = ls._run_steps(text, ls._FULL_PASS_NAME_STEPS)+ if ls._run_steps(once, ls._FULL_PASS_NAME_STEPS) != once:+ failures.append(text)+ assert not failures, failures[:3]+++ "message",+ [+ 'OPENAI_API_KEY=abc,DB_PASSWORD="a b Restricted987"',+ 'OPENAI_API_KEY=abc,DB_PASSWORD="hunter two Restricted987" next',+ 'OPENAI_API_KEY=abc,DB_PASSWORD="a b Restricted987", next',+ 'OPENAI_API_KEY=abc,DB_PASSWORD="a b Restricted987";',+ # A quoted EXACT name is closed whatever follows the quote.+ 'OPENAI_API_KEY=abc,password="a b Restricted987"\n',+ 'OPENAI_API_KEY=abc,password="a b Restricted987"\tnext',+ '-----\nOPENAI_API_KEY = abc,DB_PASSWORD = "a b Restricted987"',+ ],+)+def test_value_read_on_into_a_quoted_assignment_is_redacted(message):+ """``abc,DB_PASSWORD="a`` read as one unquoted value would leave the+ rest of the quoted password readable; for a prefixed quoted name, only+ the "restricted first pass" reading, which redacts the quoted value+ first, hides it (an exact one the bare-name step reads first)."""+ from local_deep_research.security.log_sanitizer import _redact_log_text++ for redact in (redact_log_message, _redact_log_text):+ out = redact(message)+ assert "Restricted987" not in out, (redact.__name__, out)+ assert " b " not in out and "two" not in out, (redact.__name__, out)+++def test_second_pass_disagreement_is_not_skipped():+ """First passes that agree do not make the second passes agree: only+ a pipeline other than the kept one hides the value here."""+ from local_deep_research.security.log_sanitizer import _redact_log_text++ message = (+ "requires_api_key = x,a1,;\tapi_key = x,,\r\nb2,"+ 'p\x7fwd\n=\n"a b xSecond987='+ )+ assert "Second987" not in _redact_log_text(message)+++ ("text", "secret"),+ [+ ("Config:\npassword=\napi_key = NextLine987", "NextLine987"),+ (+ "DB_PASSWORD=\nOPENAI_API_KEY = NextLine987\nTIMEOUT=3",+ "NextLine987",+ ),+ ('DB_PASSWORD=\nOPENAI_API_KEY = "x"NextLine987', "NextLine987"),+ ('OPENAI_API_KEY=abc,DB_PASSWORD="a b NextLine987"', "NextLine987"),+ ('password="a"NextLine987', "NextLine987"),+ (+ "Config:\n DB_PASSWORD =\n OPENAI_API_KEY = NextLine987\n",+ "NextLine987",+ ),+ ("password=\n\t api_key = NextLine987\r\n", "NextLine987"),+ ],+)+def test_exception_text_gets_the_log_message_readings(+ rendered_sink, text, secret+):+ """Exception ``str()`` and notes go through ``redact_log_message``,+ which keeps their newlines; it must read them as a log message is+ read, so the next line's name is not taken as an empty value."""+ exc = ValueError(text)+ exc.add_note("note: " + text)+ logger.opt(exception=exc).error("config load failed")+ rendered = rendered_sink.getvalue()+ assert "Traceback" in rendered or "ValueError" in rendered+ assert secret not in rendered+++def test_log_message_pipelines_track_every_character():+ """``redact_log_message``'s pipelines (no second pass) track origins+ as the log-text ones do."""+ import random++ from local_deep_research.security import log_sanitizer as ls++ rng = random.Random(7068)+ pipelines = ls._LOG_MESSAGE_PIPELINES+ for case in range(300):+ message, _ = _seeded_log_messages(rng, case)+ plain = ls._PipelineRun(message, tracked=False, pipelines=pipelines)+ tracked = ls._PipelineRun(+ message,+ tracked=True,+ unmatched=plain.unmatched,+ pipelines=pipelines,+ )+ for index in range(len(pipelines)):+ text, origins = tracked.result(index)+ assert text == plain.result(index)[0], (index, message)+ assert len(origins) == len(text)+ assert all(+ origin < 0 or message[origin] == character+ for character, origin in zip(text, origins)+ ), (index, message)+++def _redact_without_fast_path(monkeypatch, redact, text):+ from local_deep_research.security import log_sanitizer as ls++ with monkeypatch.context() as patched:+ patched.setattr(+ ls, "_result_without_name_assignments", lambda *_args: None+ )+ return redact(text)+++ "text",+ [+ "Starting research",+ "LLM call completed in 1.24s (tokens=512, max_tokens=4096)",+ "Fetching https://user:FastPathPw1@h/x?q=1&limit=10",+ "Authorization: Bearer abcdefghijklmnopqrstuvwxyz0123",+ "max_tokens=5 tokens\x1c=7 x-tokens = 2",+ "password is not set\x1c",+ ],+)+def test_text_without_a_name_assignment_skips_the_name_steps(monkeypatch, text):+ """A record with no credential name followed by ``=`` gets only the+ shape redaction, without running every pipeline's name steps (most+ records), and the same text the pipelines give."""+ from local_deep_research.security import log_sanitizer as ls++ def _no_name_steps(*_args):+ raise AssertionError("name steps ran")++ for redact in (redact_log_message, ls._redact_log_text):+ expected = _redact_without_fast_path(monkeypatch, redact, text)+ with monkeypatch.context() as patched:+ patched.setattr(ls._PipelineRun, "first_pass", _no_name_steps)+ assert redact(text) == expected, (redact.__name__, text)+++ ("text", "secret"),+ [+ ("apikey=HintAfterStrip987", "HintAfterStrip987"),+ ("pass\x1cword = HintAfterStrip987", "HintAfterStrip987"),+ ("OPENAI_API_KEY\n=\nHintAfterStrip987", "HintAfterStrip987"),+ ("paſſword=HintCaseFold987", "HintCaseFold987"),+ ],+)+def test_name_assignment_hint_sees_what_the_name_steps_see(text, secret):+ """The fast path never skips a name the steps would read: one that+ only appears once control characters are stripped, or one matched by+ ``(?i)`` case folding (U+017F folds to ``s``)."""+ from local_deep_research.security.log_sanitizer import _redact_log_text++ assert secret not in _redact_log_text(text)+++def test_fast_path_gives_the_pipelines_result(monkeypatch):+ """Seeded differential: with and without the fast path, both+ redactions give the same text, also for messages with the ``=`` or+ the name broken up so that the fast path applies."""+ import random++ from local_deep_research.security import log_sanitizer as ls++ rng = random.Random(6879)+ mismatches = []+ for case in range(300):+ message, _ = _seeded_log_messages(rng, case)+ for text in (+ message,+ message.replace("=", " "),+ message.replace("=", ":"),+ message.replace("_", ""),+ ):+ for redact in (redact_log_message, ls._redact_log_text):+ slow = _redact_without_fast_path(monkeypatch, redact, text)+ if redact(text) != slow:+ mismatches.append((redact.__name__, text))+ assert not mismatches, mismatches[:3]+++def test_prefixed_name_and_header_are_scrubbed_from_exception_sink(+ rendered_sink,+):+ """The three logging fixes compose on the rendered traceback path."""+ name_secret = "NamedCredential987654"+ header_secret = "HeaderCredential987654"+ try:+ raise ValueError(+ f"OPENAI_API_KEY={name_secret} Api-Key: {header_secret}"+ )+ except ValueError:+ logger.exception("provider failed")++ rendered = rendered_sink.getvalue()+ assert "Traceback" in rendered+ assert "ValueError" in rendered+ assert name_secret not in rendered+ assert header_secret not in rendereddiff --git a/tests/security/test_sanitize_error_message.py b/tests/security/test_sanitize_error_message.pyindex c3c0a546ee..c66cb03981 100644--- a/tests/security/test_sanitize_error_message.py+++ b/tests/security/test_sanitize_error_message.py@@ -386,6 +386,24 @@ class TestSanitizeErrorDetails:"username": "bob"}+ def test_colliding_redacted_keys_keep_every_entry(self):+ from local_deep_research.security.log_sanitizer import (+ sanitize_error_details,+ )++ out = sanitize_error_details(+ {+ "https://alice:[email protected]/": 1,+ "https://alice:[email protected]/": 2,+ "plain": 3,+ }+ )+ assert "Collide" not in repr(out)+ first, second, plain = list(out)+ assert second == f"{first}#2"+ assert plain == "plain"+ assert list(out.values()) == [1, 2, 3]+def test_set_leaf_passes_through(self):# A set is not JSON-serializable, so it is left as-is (fails closed at# jsonify rather than leaking) — pin the passthrough behavior.diff --git a/tests/security/test_scrub_error_query_work_bound.py b/tests/security/test_scrub_error_query_work_bound.pynew file mode 100644index 0000000000..c5b6b75895--- /dev/null+++ b/tests/security/test_scrub_error_query_work_bound.py@@ -0,0 +1,165 @@+"""Bound expensive query composition without losing useful plain diagnostics."""++import asyncio+from types import SimpleNamespace++import pytest++from local_deep_research.security import log_sanitizer as ls+++def _track_guard_sizes(monkeypatch):+ original = ls._pipeline_credential_spans+ sizes = []++ def collect(text):+ sizes.append(len(text))+ assert len(text) <= ls._LOG_REDACTION_MAX_CHARS+ return original(text)++ monkeypatch.setattr(ls, "_pipeline_credential_spans", collect)+ return sizes+++def _sparse_message(size, assignment="password=value"):+ prefix = (+ f"Request failed https://host/path?query=value {assignment} details: "+ )+ prose = (+ "The provider supplied additional explanation of the upstream problem. "+ )+ return (prefix + prose * (size // len(prose) + 1))[:size]++[email protected]("dense", [False, True])[email protected]("size", [32_767, 32_768, 32_769, 131_072])+def test_query_guard_analysis_is_bounded(monkeypatch, dense, size):+ sizes = _track_guard_sizes(monkeypatch)+ unit = "https://host/path?query=value password=value details "+ message = (+ (unit * (size // len(unit) + 1))[:size]+ if dense+ else _sparse_message(size)+ )+ result = ls.scrub_error(message)+ assert sizes+ assert "https://host/path?<redacted>" in result+ if size > ls._LOG_REDACTION_MAX_CHARS:+ assert result.count("characters omitted from log output]") == 1+ assert result.endswith("characters omitted from log output]")+ else:+ assert "characters omitted" not in result++[email protected]("control", ["\u200b", "\r", "\n"])+def test_control_split_assignment_uses_the_same_work_bound(+ monkeypatch, control+):+ sizes = _track_guard_sizes(monkeypatch)+ message = _sparse_message(131_072, f"pass{control}word=value")+ result = ls.scrub_error(message)+ assert sizes+ assert "https://host/path?<redacted>" in result+ assert result.endswith("characters omitted from log output]")+++ "prefix",+ [+ "Plain failure: ",+ "Request failed https://host/path?query=value details: ",+ "password=value without a URL query: ",+ ],+)+def test_long_diagnostics_without_query_guards_keep_the_tail(prefix):+ message = prefix + "ordinary detail " * 8_000 + "diagnostic-end"+ result = ls.scrub_error(message)+ assert len(result) > ls._LOG_REDACTION_MAX_CHARS+ assert result.endswith("diagnostic-end")+ assert "characters omitted" not in result+++def _padded_prefix(prefix, size):+ remaining = size - len(prefix)+ return prefix + "x " * (remaining // 2) + " " * (remaining % 2)++[email protected]("separator", [" ", "\n", "\u200b "])+def test_known_literal_crossing_cut_is_scrubbed_before_truncation(+ monkeypatch, separator+):+ sizes = _track_guard_sizes(monkeypatch)+ first = "KnownAlphaCanary731xy"+ second = "KnownOmegaCanary982xy"+ secret = first + separator + second+ prefix = _padded_prefix(+ "Request https://host/path?query=value password=value ",+ ls._LOG_REDACTION_MAX_CHARS - 30,+ )+ result = ls.scrub_error(prefix + secret + " extra detail" * 4_000, secret)+ assert sizes+ assert first not in result+ assert second not in result+ assert "***REDACTED***" in result+ assert result.endswith("characters omitted from log output]")++[email protected]("quote", ["'", '"'])[email protected]("separator", [" ", "\r\n", "\u200b "])+def test_quoted_credential_cut_keeps_no_value_in_log_output(+ monkeypatch, quote, separator+):+ _track_guard_sizes(monkeypatch)+ first = "FirstCanary731xy"+ second = "SecondCanary982xy"+ prefix = _padded_prefix(+ "Request https://host/path?query=value details: ",+ ls._LOG_REDACTION_MAX_CHARS - 38,+ )+ message = (+ prefix+ + f" password={quote}{first}{separator}{second} trailing value{quote}"+ + " additional details" * 4_000+ )+ scrubbed = ls.scrub_error(message)+ record = {"message": scrubbed, "extra": {}, "exception": None}+ ls.redact_log_record(record)+ assert first not in record["message"]+ assert second not in record["message"]+ assert "characters omitted" in scrubbed+++def test_async_provider_error_bounds_query_work_before_logging(monkeypatch):+ import httpx+ import openai++ from local_deep_research.config import llm_config++ sizes = _track_guard_sizes(monkeypatch)+ logged = []+ monkeypatch.setattr(llm_config, "scrub_error", ls.scrub_error)+ monkeypatch.setattr(+ llm_config, "logger", SimpleNamespace(warning=logged.append)+ )+ response = httpx.Response(+ 500,+ text=_sparse_message(131_072),+ request=httpx.Request(+ "POST", "https://provider.invalid/v1/chat/completions"+ ),+ )+ with openai.OpenAI(api_key="synthetic-test-value", max_retries=0) as client:+ upstream_error = client._make_status_error_from_response(response)++ class Model:+ async def ainvoke(self, *args, **kwargs):+ raise upstream_error++ wrapper = llm_config.ProcessingLLMWrapper(Model(), owns_llm=False)+ with pytest.raises(openai.InternalServerError) as captured:+ asyncio.run(wrapper.ainvoke("Return selected indices"))+ assert captured.value is upstream_error+ assert sizes+ assert len(logged) == 1+ assert "https://host/path?<redacted>" in logged[0]+ assert logged[0].endswith("characters omitted from log output]")diff --git a/tests/security/test_user_db_error_parameter_redaction.py b/tests/security/test_user_db_error_parameter_redaction.pynew file mode 100644index 0000000000..68bcd9007b--- /dev/null+++ b/tests/security/test_user_db_error_parameter_redaction.py@@ -0,0 +1,154 @@+"""User-database errors must not echo bound document URLs into logs (#6829)."""++import pytest+from loguru import logger+from sqlalchemy import text+from sqlalchemy.exc import StatementError+from unittest.mock import MagicMock, patch++from local_deep_research.database.encrypted_db import DatabaseManager++[email protected](params=(True, False), ids=("encrypted", "plaintext"))+def manager(tmp_path, monkeypatch, request):+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ monkeypatch.setenv("LDR_DB_CONFIG_KDF_ITERATIONS", "1000")+ if request.param:+ pytest.importorskip("sqlcipher3")+ else:+ monkeypatch.setattr(+ DatabaseManager, "_check_encryption_available", lambda self: False+ )+ db_manager = DatabaseManager()+ assert db_manager.has_encryption is request.param+ db_manager.data_dir = tmp_path+ yield db_manager+ db_manager.close_all_databases()+++def _assert_duplicate_url_is_hidden(engine, url):+ # Plain SQLite is wrapped as SQLAlchemy IntegrityError; SQLCipher's+ # driver raises its own IntegrityError directly in this path.+ with pytest.raises(Exception, match="UNIQUE constraint failed") as failure:+ with engine.begin() as connection:+ connection.execute(+ text("INSERT INTO url_canary (url) VALUES (:url)"),+ {"url": url},+ )++ rendered = str(failure.value)+ assert type(failure.value).__name__ == "IntegrityError"+ assert "user:private-password" not in rendered+ assert "private-path" not in rendered+ assert "private-token" not in rendered+++def test_user_db_create_and_reopen_hide_url_parameters(manager):+ """Both engine constructors hide bound values in real SQL errors."""+ username = "url_error_mask"+ password = "ParamMaskPw1!" # noqa: S105+ url = (+ "https://user:[email protected]/private-path"+ "?token=private-token"+ )++ engine = manager.create_user_database(username, password)+ assert engine.hide_parameters is True+ with engine.begin() as connection:+ connection.execute(text("CREATE TABLE url_canary (url TEXT UNIQUE)"))+ connection.execute(+ text("INSERT INTO url_canary (url) VALUES (:url)"),+ {"url": url},+ )+ _assert_duplicate_url_is_hidden(engine, url)++ manager.close_user_database(username)+ reopened = manager.open_user_database(username, password)+ assert reopened is not None+ assert reopened.hide_parameters is True+ _assert_duplicate_url_is_hidden(reopened, url)+++def test_failed_document_record_logs_only_exception_class_with_diagnose():+ """A debug sink must not render SQLAlchemy's bound URL from frame locals."""+ from local_deep_research.research_library.services import (+ download_service as ds,+ )++ url = (+ "https://user:[email protected]/private-path"+ "?token=private-token"+ )+ failure = StatementError(+ "insert failed",+ "INSERT INTO documents (original_url) VALUES (:original_url)",+ {"original_url": url},+ RuntimeError("duplicate document"),+ )+ service = ds.DownloadService.__new__(ds.DownloadService)+ service.username = "alice"+ service.password = "pw" # noqa: S105+ resource = MagicMock(id=7, url=url, research_id="r1")+ session = MagicMock()+ session.add.side_effect = failure+ records = []+ sink = logger.add(+ lambda message: records.append(str(message)),+ format="{message}",+ level="ERROR",+ diagnose=True,+ )+ logger.enable("local_deep_research")+ try:+ with (+ patch.object(ds, "get_document_for_resource", return_value=None),+ patch.object(ds, "get_source_type_id", return_value="st"),+ patch.object(ds, "Document"),+ ):+ service._record_failed_text_extraction(+ session, resource, "extraction failed"+ )+ finally:+ logger.disable("local_deep_research")+ logger.remove(sink)++ rendered = "\n".join(records)+ assert "Error recording failed text extraction (StatementError)" in rendered+ assert "private-password" not in rendered+ assert "private-path" not in rendered+ assert "private-token" not in rendered+++def test_cached_arxiv_save_failure_returns_fixed_error_token():+ """A SQL error from an offline arXiv save must not enter the SSE result."""+ from local_deep_research.research_library.services import (+ download_service as ds,+ )++ url = (+ "https://user:[email protected]/private-path"+ "?token=private-token"+ )+ failure = StatementError(+ "insert failed",+ "INSERT INTO documents (original_url) VALUES (:original_url)",+ {"original_url": url},+ RuntimeError("duplicate document"),+ )+ service = ds.DownloadService.__new__(ds.DownloadService)+ session = MagicMock()+ resource = MagicMock(url="https://arxiv.org/abs/2401.12345")+ with (+ patch.object(+ service, "_load_cached_arxiv_pdf", return_value=(b"%PDF", "doc1")+ ),+ patch.object(+ ds.ArxivDownloader,+ "extract_text_from_pdf",+ return_value="Paper text",+ ),+ patch.object(service, "_save_text_with_db", side_effect=failure),+ ):+ result = service._text_from_cached_pdf(session, resource)++ assert result == (False, "download_error:StatementError")diff --git a/tests/test_known_defect_pattern_sweep.py b/tests/test_known_defect_pattern_sweep.pyindex 170ea5f6e6..27249c99c8 100644--- a/tests/test_known_defect_pattern_sweep.py+++ b/tests/test_known_defect_pattern_sweep.py@@ -1879,8 +1879,11 @@ def test_p5_inventory_is_pinned():# sanitiser its siblings use## ``sanitize_for_log`` strips control characters and caps length.-# ``scrub_error``/``sanitize_error_message`` only mask credential *shapes*.-# Substituting the second for the first leaves the record forgeable.+# ``scrub_error``/``sanitize_error_message`` do not guarantee control-free+# output. This inventories call sites relying on a later sink backstop.+# The runtime premise for ``scrub_error`` is checked in+# tests/security/test_log_sanitizer.py: inspecting a stripped view for+# redaction analysis does not mean the returned text has been stripped.# ===========================================================================READER_CONTROLLED_RE = re.compile(@@ -2053,7 +2056,7 @@ def scan_pattern_6_credential_only(mods):f"{sink}() interpolates a credential-scrubbed "f"value; scrub_error()/"f"sanitize_error_message() mask credential "- f"shapes but never strip control characters",+ f"shapes but do not guarantee control-free output",))return ordered(sites)@@ -2122,22 +2125,6 @@ def scan_pattern_6_headers(mods):return ordered(sites), {"header_writes": examined}-def scrub_error_strips_control_chars(mods) -> bool:- for path, tree in mods:- if not path.endswith("security/log_sanitizer.py"):- continue- for fn in functions(tree):- if fn.name != "scrub_error":- continue- called = {- (call_name(n) or "").split(".")[-1]- for n in ast.walk(fn)- if isinstance(n, ast.Call)- }- return bool(called & {"strip_control_chars", "sanitize_for_log"})- raise AssertionError("scrub_error() not found in log_sanitizer.py")--P6_POSITIVE = """from fastapi import Requestfrom loguru import logger@@ -2213,12 +2200,6 @@ def test_p6_examines_a_floor_of_sites():assert header_stats["header_writes"] >= 20, header_stats-def test_p6_premise_scrub_error_does_not_strip_control_chars():- """The credential-only arm is a real gap only if scrub_error really does- not neutralise CR/LF. Pin the premise rather than assume it."""- assert scrub_error_strips_control_chars(modules()) is False--def test_p6_known_live_instances_are_refound():cred = scan_pattern_6_credential_only(modules())assert P6_CREDENTIAL_KNOWN in keys(cred), report(diff --git a/tests/web/routers/test_research_model_log_preview_bound.py b/tests/web/routers/test_research_model_log_preview_bound.pyindex 6e9f3f43f9..5a9c8c7140 100644--- a/tests/web/routers/test_research_model_log_preview_bound.py+++ b/tests/web/routers/test_research_model_log_preview_bound.py@@ -1462,9 +1462,12 @@ class TestLogValueWorkIsBounded:assert _is_sensitive_log_key("model") is Falseassert _is_sensitive_log_key("k" * 32_768) is Falseassert _is_sensitive_log_key("k" * 32_769) is True- assert redact_log_extra({"k" * 40_000: "v"}) == {- "k" * 40_000: "[REDACTED]"- }+ redacted = redact_log_extra({"k" * 40_000: "v"})+ assert list(redacted.values()) == ["[REDACTED]"]+ # The integrated sink also bounds structured keys before logging.+ key = next(iter(redacted))+ assert len(key) < 100+ assert "40000 characters omitted" in keydef test_validate_safe_path_redacts_only_to_log_a_rejection(self, tmp_path):from local_deep_research.security import path_validator