~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(logs): bound the remaining request-derived log sites through the value preview (#6947)
LearningCircuit6c0d974e5373
diff --git a/changelog.d/6938.security.md b/changelog.d/6938.security.mdnew file mode 100644index 0000000000..f76f1fcb31--- /dev/null+++ b/changelog.d/6938.security.md@@ -0,0 +1 @@+The log lines listed here no longer interpolate request-derived values unbounded (other lines, such as a research strategy's own query log, still log the full value, capped only by the log patcher's 32 KiB bound). The research thread's strategy/parameter lines, the follow-up router and service lines that log the request's question and `parent_research_id` (including the not-found paths, which run before any other check), the api router's SSRF URL-refusal warning, the config-write blocked-keys warning, and the sibling sites that log body, form, query, path or header values (registration username and the username on the login, post-login, logout and password-change lines, setting keys, collection/document/research ids, Socket.IO subscribe ids and handshake origins, news card ids, CSRF and error-handler request paths, `/api/v1` queries) now pass them through the bounded log-value preview or `redact_and_bound_for_log`. Every bounded value is run through the log patcher's credential redaction before it is cut, so a cut can never drop a credential's label (`?key=`, `api_key=`, the `user:` before `@`) and keep part of the secret; the research thread logs only the `scheme://host:port` of `custom_endpoint`, and the preview masks values under sensitive dict keys. `redact_url_for_log` now caps the scheme and host it returns at 256 characters, `validate_url` logs only that redacted form instead of the raw scheme or hostname, the notification validator bounds the hostname and scheme inside the rejection messages its callers log, and the Socket.IO origin-rejection hook hands engine.io's own logger the bounded message whenever that logger will emit it. The bounded preview's own work is capped too: it redacts only the first 512 characters of each string (cut, like the log patcher's own 32 KiB bound, only at whitespace, with the rest replaced by an omitted-length marker), runs at most 32 redactions (each charged at least 32 of its 1,024-character budget) and at most 512 sensitive-key checks over at most 32 KiB of keys, masking the value under any key that budget cannot cover, and the log patcher treats a key longer than 32 KiB as sensitive instead of scanning it. `redact_and_bound_for_log` likewise redacts only the first 1,024 characters (or four times its output cap, if more) by the same rule. `validate_safe_path` redacts the path only when it logs a rejection, not on every static-file lookup. Likewise the Socket.IO origin-rejection hook redacts the origin only for a warning it emits (at most one per distinct origin, up to 100) or a line engine.io's logger emits, deduplicating on a SHA-256 digest of the raw message, so a flood of rejected handshakes costs no redaction once the cap is reached. The news feed's per-row query and headline lines are now DEBUG and evaluated lazily, so their redaction runs only when a DEBUG sink is enabled, and so are the DEBUG lines that preview or redact a request-derived value in the research router and service, the history, RAG, auth and library routers, the news topic generator, DNS pinning and the notification validator. The log lines that still cut a query, URL, headline, chat title, subscription label, rejection message or login username before redacting it (`value[:N]` or `sanitize_for_log`) in the research service and router, `url_validator`, the news API, the library and news routers, the chat service, the notification validator and the login route now redact it first.diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.pyindex eafeb58731..c17ec6465a 100644--- a/src/local_deep_research/api/research_functions.py+++ b/src/local_deep_research/api/research_functions.py@@ -19,6 +19,7 @@ from ..utilities.thread_context import clear_search_context, set_search_contextfrom ..utilities.type_utils import overlay_runtime_settingsfrom .settings_utils import create_settings_snapshotfrom ..utilities.llm_utils import invoke_llm_sync+from ..security.log_sanitizer import redact_and_bound_for_logdef _close_system(system):@@ -151,11 +152,15 @@ def _init_search_system()if search_engine is None:logger.warning(- f"Could not create search engine '{search_tool}', using default."+ "Could not create search engine '{}', using default.",+ redact_and_bound_for_log(str(search_tool), 200),)# Create search system with custom parameters- logger.info("Search strategy: {}", search_strategy)+ logger.info(+ "Search strategy: {}",+ redact_and_bound_for_log(str(search_strategy), 200),+ )system = AdvancedSearchSystem(llm=llm,search=search_engine,@@ -242,7 +247,11 @@ def quick_summary(settings_override={"search.engines.arxiv.enabled": True})"""- logger.info("Generating quick summary for query: {}", query)+ # (#6938: the /api/v1 routes pass the body's query unbounded.)+ logger.info(+ "Generating quick summary for query: {}",+ redact_and_bound_for_log(str(query), 200),+ )if "settings_snapshot" not in kwargs:snapshot_kwargs = {}@@ -418,7 +427,10 @@ def generate_report(settings_snapshot=settings)"""- logger.info("Generating comprehensive research report for query: {}", query)+ logger.info(+ "Generating comprehensive research report for query: {}",+ redact_and_bound_for_log(str(query), 200),+ )if "settings_snapshot" not in kwargs:snapshot_kwargs = {}@@ -684,7 +696,9 @@ def analyze_documents(settings_snapshot = create_settings_snapshot()logger.info(- f"Analyzing documents in collection '{collection_name}' for query: {query}"+ "Analyzing documents in collection '{}' for query: {}",+ redact_and_bound_for_log(str(collection_name), 200),+ redact_and_bound_for_log(str(query), 200),)llm = Nonediff --git a/src/local_deep_research/chat/service.py b/src/local_deep_research/chat/service.pyindex 4e201da67e..6508e87557 100644--- a/src/local_deep_research/chat/service.py+++ b/src/local_deep_research/chat/service.py@@ -28,6 +28,7 @@ from ..database.models import (UserActiveResearch,)from ..database.session_context import get_user_db_session+from ..security.log_sanitizer import redact_and_bound_for_logfrom ..web.routes.globals import (cleanup_research,is_research_thread_alive,@@ -229,8 +230,10 @@ class ChatService:fallback = self._fallback_title(query)if current_title and current_title != fallback:logger.info(- f"Skipping LLM title gen for {session_id[:8]}...: title "- f"already set ('{current_title[:30]}...')"+ "Skipping LLM title gen for {}...: title already set ('{}')",+ session_id[:8],+ # (#6938: redacted before it is cut.)+ redact_and_bound_for_log(str(current_title), 30),)return Nonenew_title = self._generate_title(query, settings_snapshot)@@ -545,9 +548,12 @@ class ChatService:before_created_at.replace("Z", "+00:00"))except ValueError:+ # (#6938: the cursor is a raw query param.)+ from ..web.routers.notes import _log_value_preview+logger.warning(- "Invalid before_created_at cursor: "- f"{before_created_at!r} — ignoring."+ "Invalid before_created_at cursor: {} — ignoring.",+ _log_value_preview(before_created_at),)else:# Composite cursor: when `before_id` is alsodiff --git a/src/local_deep_research/config/search_config.py b/src/local_deep_research/config/search_config.pyindex 6d327244f4..c3d7438164 100644--- a/src/local_deep_research/config/search_config.py+++ b/src/local_deep_research/config/search_config.py@@ -7,6 +7,7 @@ from ..web_search_engines.search_engine_factory import (from .constants import DEFAULT_MAX_FILTERED_RESULTSfrom .llm_config import get_llmfrom .thread_settings import get_setting_from_snapshot+from ..security.log_sanitizer import redact_and_bound_for_log# Whether to check the quality search results using the LLM.QUALITY_CHECK_DDG_URLS = True@@ -50,8 +51,11 @@ def get_search(if "value" in tool:tool = tool["value"]+ # (#6938: the tool name can be a request-supplied string.)logger.info(- f"Creating search engine with tool: {tool} (type: {type(tool)})"+ "Creating search engine with tool: {} (type: {})",+ redact_and_bound_for_log(str(tool), 200),+ type(tool),)# Get LLM instance (use provided or get fresh one). Pass usernamediff --git a/src/local_deep_research/followup_research/service.py b/src/local_deep_research/followup_research/service.pyindex e424fcc575..4115ce1f2b 100644--- a/src/local_deep_research/followup_research/service.py+++ b/src/local_deep_research/followup_research/service.py@@ -50,8 +50,16 @@ class FollowUpResearchService:)if not research:+ # (#6938: on this not-found path the id is raw,+ # unchecked request input — both followup routes call+ # here with the body's parent_research_id before any+ # other check — so it previews instead of f-stringing.+ # Imported at call time like perform_followup below.)+ from ..web.routers.notes import _log_value_preview+logger.warning(- f"Parent research not found: {parent_research_id}"+ "Parent research not found: {}",+ _log_value_preview(parent_research_id),)return {}@@ -190,9 +198,18 @@ class FollowUpResearchService:request.parent_research_id)+ # (#6938: the question and parent id are raw request input, so+ # every line below that logs them previews instead of+ # f-stringing — same conversion as the followup router's+ # params/query lines. Imported at call time like the research+ # thread's sites, so this service module never imports the notes+ # router at import time.)+ from ..web.routers.notes import _log_value_preview+if not research_context:logger.warning(- f"Parent research not found: {request.parent_research_id}, using empty context"+ "Parent research not found: {}, using empty context",+ _log_value_preview(request.parent_research_id),)# Use empty context to allow follow-up without parentresearch_context = {@@ -217,8 +234,10 @@ class FollowUpResearchService:}logger.info(- f"Prepared follow-up research for question: '{request.question}' "- f"based on parent: {request.parent_research_id}"+ "Prepared follow-up research for question: '{}' "+ "based on parent: {}",+ _log_value_preview(request.question),+ _log_value_preview(request.parent_research_id),)return research_paramsdiff --git a/src/local_deep_research/news/api.py b/src/local_deep_research/news/api.pyindex bbe11d4420..ac7f3a90b3 100644--- a/src/local_deep_research/news/api.py+++ b/src/local_deep_research/news/api.py@@ -3,7 +3,7 @@ Direct API functions for news system.These functions can be called directly by scheduler or wrapped by Flask endpoints."""-from typing import Dict, Any, Optional+from typing import Any, Callable, Dict, Optionalfrom datetime import datetime, timezone, UTCfrom loguru import loggerfrom sqlalchemy.orm import Session@@ -12,6 +12,7 @@ import jsonfrom ..constants import ResearchStatusfrom ..llm.providers.base import normalize_providerfrom ..utilities.sql_utils import escape_like+from ..security.log_sanitizer import redact_and_bound_for_logfrom .exceptions import (InvalidLimitException,SubscriptionNotFoundException,@@ -39,6 +40,16 @@ from ..constants import DEFAULT_SEARCH_TOOL_GENERIC_ERROR_DETAIL = "an internal error occurred"+def _lazy_log_preview(value: Any, max_length: int) -> Callable[[], str]:+ """A ``logger.opt(lazy=True)`` argument: the redacted, bounded value.++ Redaction runs before the cut (#6938), and it only runs when a sink+ takes the record's level, so a per-row DEBUG line costs nothing at the+ default INFO level however long the stored value is.+ """+ return lambda: redact_and_bound_for_log(str(value), max_length)++def _notify_scheduler_about_subscription_change(action: str, user_id: Optional[str] = None):@@ -210,8 +221,16 @@ def get_news_feed(logger.info(f"First row keys: {list(results[0].keys())}")# Log first few items' metadatafor i, row in enumerate(results[:3]):- logger.info(- f"Item {i}: query='{row['query'][:50]}...', has meta={bool(row.get('research_meta'))}"+ # (#6938: the query is redacted before it is cut. A+ # stored query can be tens of KiB and redaction costs+ # about 1 us per character, so these per-row lines are+ # DEBUG and lazy: nothing is computed unless a sink+ # takes DEBUG records.)+ logger.opt(lazy=True).debug(+ "Item {}: query='{}', has meta={}",+ lambda i=i: i,+ _lazy_log_preview(row["query"], 50),+ lambda row=row: bool(row.get("research_meta")),)# Process results to find news items@@ -258,17 +277,27 @@ def get_news_feed()# Log the decision for first few items+ # (#6938: DEBUG and lazy, see the first-rows log above;+ # error_count is usually 0, so this runs on every row.)if processed_count < 3 or error_count < 3:- logger.info(- f"Item check: query='{row['query'][:30]}...', is_news_search={metadata.get('is_news_search')}, "- f"has_news_metadata={has_news_metadata}, is_news_query={is_news_query}"+ logger.opt(lazy=True).debug(+ "Item check: query='{}', is_news_search={}, "+ "has_news_metadata={}, is_news_query={}",+ _lazy_log_preview(row["query"], 30),+ lambda metadata=metadata: metadata.get(+ "is_news_search"+ ),+ lambda v=has_news_metadata: v,+ lambda v=is_news_query: v,)# Only show items that have news metadata or are news queriesif is_news_query:processed_count += 1- logger.info(- f"Processing research item #{processed_count}: {row['query'][:50]}..."+ logger.opt(lazy=True).debug(+ "Processing research item #{}: {}",+ lambda n=processed_count: n,+ _lazy_log_preview(row["query"], 50),)# Always use database content@@ -309,6 +338,10 @@ def get_news_feed(original_query = row["query"]# Check for headline - first try database title, then metadata+ # What the "Added news item" line logs: the headline,+ # or the whole query when the headline is cut from+ # it (#6938: redacted before it is cut).+ headline_from_query = Falseheadline = row.get("title") or metadata.get("generated_headline")@@ -324,6 +357,7 @@ def get_news_feed(else:# Generate headline from queryheadline = f"News: {row['query'][:60]}..."+ headline_from_query = True# Skip items without meaningful headlines or that are incompleteif (@@ -405,7 +439,16 @@ def get_news_feed(}news_items.append(news_item)- logger.info(f"Added news item: {headline[:50]}...")+ # (#6938: DEBUG and lazy, see the first-rows log.)+ logger.opt(lazy=True).debug(+ "Added news item: {}",+ _lazy_log_preview(+ "News: " + str(row["query"])+ if headline_from_query+ else headline,+ 50,+ ),+ )if len(news_items) >= limit:break@@ -413,7 +456,10 @@ def get_news_feed(except Exception:error_count += 1logger.exception(- f"Error processing research item with query: {row.get('query', 'UNKNOWN')[:100]}"+ "Error processing research item with query: {}",+ redact_and_bound_for_log(+ str(row.get("query", "UNKNOWN")), 100+ ),)continue@@ -745,7 +791,11 @@ def get_subscription(# Re-raise our custom exceptionsraiseexcept Exception:- logger.exception(f"Error getting subscription {subscription_id}")+ from ..web.routers.notes import _log_value_preview++ logger.exception(+ "Error getting subscription {}", _log_value_preview(subscription_id)+ )raise DatabaseAccessException("get_subscription", _GENERIC_ERROR_DETAIL)@@ -1306,7 +1356,11 @@ def submit_feedback(card_id: str, user_id: str, vote: str) -> Dict[str, Any]:# Validate vote valueif vote not in ["up", "down"]:- raise ValueError(f"Invalid vote type: {vote}")+ # (#6938: the vote is raw request input and this message reaches+ # the router's logged traceback, so it carries the bounded preview.)+ from ..web.routers.notes import _log_value_preview++ raise ValueError(f"Invalid vote type: {_log_value_preview(vote)}")# Prefer the request's authenticated username (FastAPI contextvar),# fall back to the explicit `user_id` arg for off-request callers.@@ -1365,8 +1419,15 @@ def submit_feedback(card_id: str, user_id: str, vote: str) -> Dict[str, Any]:.count())+ # (#6938: card_id is the raw body/path value.)+ from ..web.routers.notes import _log_value_preview+logger.info(- f"Feedback submitted for card {card_id}: {vote} (up: {upvotes}, down: {downvotes})"+ "Feedback submitted for card {}: {} (up: {}, down: {})",+ _log_value_preview(card_id),+ vote,+ upvotes,+ downvotes,)return {@@ -1378,7 +1439,12 @@ def submit_feedback(card_id: str, user_id: str, vote: str) -> Dict[str, Any]:}except Exception:- logger.exception(f"Error submitting feedback for card {card_id}")+ from ..web.routers.notes import _log_value_preview++ logger.exception(+ "Error submitting feedback for card {}",+ _log_value_preview(card_id),+ )raisediff --git a/src/local_deep_research/news/utils/topic_generator.py b/src/local_deep_research/news/utils/topic_generator.pyindex dc95ba3673..65058e6916 100644--- a/src/local_deep_research/news/utils/topic_generator.py+++ b/src/local_deep_research/news/utils/topic_generator.py@@ -146,8 +146,15 @@ def _generate_with_llm(try:from ...config.llm_config import get_llm- logger.debug(- f"Topic generation - findings length: {len(findings) if findings else 0}, category: {category}"+ # (#6938: the category can come from a research request's+ # metadata, so it is previewed rather than f-stringed, and only+ # when a DEBUG sink takes the line.)+ from ...web.routers.notes import _log_value_preview++ logger.opt(lazy=True).debug(+ "Topic generation - findings length: {}, category: {}",+ lambda: len(findings) if findings else 0,+ lambda: _log_value_preview(category),)# Use the configured model for topic generation@@ -187,8 +194,15 @@ async def _generate_with_llm_async(try:from ...config.llm_config import get_llm- logger.debug(- f"Topic generation - findings length: {len(findings) if findings else 0}, category: {category}"+ # (#6938: the category can come from a research request's+ # metadata, so it is previewed rather than f-stringed, and only+ # when a DEBUG sink takes the line.)+ from ...web.routers.notes import _log_value_preview++ logger.opt(lazy=True).debug(+ "Topic generation - findings length: {}, category: {}",+ lambda: len(findings) if findings else 0,+ lambda: _log_value_preview(category),)# Use the configured model for topic generationdiff --git a/src/local_deep_research/security/dns_pinning.py b/src/local_deep_research/security/dns_pinning.pyindex 1887949218..a491f2800e 100644--- a/src/local_deep_research/security/dns_pinning.py+++ b/src/local_deep_research/security/dns_pinning.py@@ -78,6 +78,7 @@ from urllib3.exceptions import LocationParseErrorfrom urllib3.util import parse_urlfrom . import ssrf_validator+from .log_sanitizer import redact_and_bound_for_log# Attribute stamped on our shim (see below) so any later capture of the# "real" resolver can recognize it and refuse to capture the shim as if it@@ -795,8 +796,11 @@ def pin_hosts(# ``add()`` rejects such a host first. The reachable# IDNA route into ``_resolve_maybe_block`` is a scheme# skipped by the ``_PINNABLE_SCHEMES`` check above.- logger.debug(- "Skipping pin for currently-unresolvable host {}", host+ logger.opt(lazy=True).debug(+ "Skipping pin for currently-unresolvable host {}",+ # (#6938: a request-supplied host is unbounded;+ # redacted only when a DEBUG sink takes the line.)+ lambda: redact_and_bound_for_log(host, 256),)continuesaved.append((host, host in pins, pins.get(host)))diff --git a/src/local_deep_research/security/log_sanitizer.py b/src/local_deep_research/security/log_sanitizer.pyindex 812f503137..d53ab28eb8 100644--- a/src/local_deep_research/security/log_sanitizer.py+++ b/src/local_deep_research/security/log_sanitizer.py@@ -7,6 +7,9 @@ concerns:* :func:`strip_control_chars` / :func:`sanitize_for_log` \u2014 make a singlestring value safe to include in a log line by removing non-printablecharacters and truncating to a reasonable length.+ :func:`redact_and_bound_for_log` redacts credential shapes before it+ truncates, for a value whose cut could otherwise hide a credential from+ the log patcher's redaction.* :func:`redact_secrets` \u2014 scrub known sensitive *values* (API keys,passwords, session tokens) from an arbitrary string before it islogged, returned in an error message, or persisted.@@ -724,9 +727,16 @@ _LOG_OMISSION_MARKER_RE = re.compile()-def _truncate_for_log_redaction(message: str) -> tuple[str, str]:+def _truncate_for_log_redaction(+ message: str, max_chars: int = _LOG_REDACTION_MAX_CHARS+) -> tuple[str, str]:"""Split *message* into the part to scan and a marker for the rest.+ *max_chars* is the bound (the patcher's ``_LOG_REDACTION_MAX_CHARS``+ unless a caller that shows only a short prefix of the result passes a+ smaller one, see :func:`redact_and_bound_for_log`); the rule below is+ the same for any bound.+The cut only lands at a boundary: a whitespace character that:func:`strip_control_chars` keeps (a space, U+00A0, U+3000, ...). Acontrol or separator whitespace character (``\n``, ``\t``, ``\x1c``,@@ -735,7 +745,7 @@ def _truncate_for_log_redaction(message: str) -> tuple[str, str]:Unless the character at the bound is a boundary, the cut moves back tojust after the last boundary before the bound, dropping the whole runthe bound falls in -- however long, so a string with no boundary in its- first ``_LOG_REDACTION_MAX_CHARS`` characters keeps nothing but the+ first *max_chars* characters keeps nothing but themarker. A partial run could be a credential fragment its shape patternno longer recognises (a key cut below its minimum length, URL userinfocut before its ``@``, a password cut at a ``&``). A credential token@@ -746,9 +756,9 @@ def _truncate_for_log_redaction(message: str) -> tuple[str, str]:quote, which the assignment pass redacts to the end of the head, so aquoted value with spaces in it is covered too)."""- if len(message) <= _LOG_REDACTION_MAX_CHARS:+ if len(message) <= max_chars:return message, ""- cut = _LOG_REDACTION_MAX_CHARS+ cut = max_charsat_bound = message[cut]if not at_bound.isspace() or _UNSAFE_CHAR_RE.match(at_bound):# ``\S`` is exactly ``not str.isspace()``; matching the reversed head@@ -821,6 +831,77 @@ def _redact_log_text(value: str) -> str:return _redact_bounded_log_text(strip_control_chars(first)) + 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.@@ -829,9 +910,16 @@ def _is_sensitive_log_key(key: Any) -> bool:or as an underscore-delimited suffix (``openai_api_key``,``db_password``), after invisible characters are removed from it. Keysonly -- 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."""if not isinstance(key, str):return False+ if len(key) > _LOG_REDACTION_MAX_CHARS:+ return Truereturn DataSanitizer.is_sensitive_setting(key, sensitive_keys=LOG_SENSITIVE_KEYS)diff --git a/src/local_deep_research/security/notification_validator.py b/src/local_deep_research/security/notification_validator.pyindex 54181a04a9..10fd48edae 100644--- a/src/local_deep_research/security/notification_validator.py+++ b/src/local_deep_research/security/notification_validator.py@@ -29,8 +29,17 @@ from .legacy_ipv4 import (is_ambiguous_numeric_ipv4_host,is_percent_encoded_numeric_ipv4_host,)+from .log_sanitizer import redact_and_bound_for_logfrom .ssrf_validator import RFC_FORBIDDEN_URL_CHARS_RE, redact_url_for_log+# (#6938) Cap for a request-supplied hostname or scheme in a log line, and+# in the rejection messages this module returns, which callers log+# (``NotificationService.test_service``) — a scoped IPv6 literal such as+# ``[fe80::1%25<100k chars>]`` is accepted by the parser and rejected here+# with its full host. 256 keeps every name within the 253-char DNS limit+# intact. Each value is redacted before it is cut (``redact_and_bound_for_log``).+_LOG_HOST_MAX_CHARS = 256+# Type alias for resolved IP addresses (avoids referencing the private# ipaddress._BaseAddress API).ResolvedIP = Union[ipaddress.IPv4Address, ipaddress.IPv6Address]@@ -595,7 +604,7 @@ class NotificationURLValidator:logger.warning("DNS resolution failed for hostname {} — ""allowing request (unable to determine if private)",- hostname,+ redact_and_bound_for_log(hostname, _LOG_HOST_MAX_CHARS),)return None@@ -931,9 +940,15 @@ class NotificationURLValidator:# Check for blocked schemesif scheme in NotificationURLValidator.BLOCKED_SCHEMES:logger.warning(- f"Blocked unsafe notification protocol: {scheme} in URL: {redact_url_for_log(url)}"+ "Blocked unsafe notification protocol: {} in URL: {}",+ redact_and_bound_for_log(scheme, _LOG_HOST_MAX_CHARS),+ redact_url_for_log(url),+ )+ return (+ False,+ "Blocked unsafe protocol: "+ f"{redact_and_bound_for_log(scheme, _LOG_HOST_MAX_CHARS)}",)- return False, f"Blocked unsafe protocol: {scheme}"# Check for allowed schemesif scheme not in NotificationURLValidator.ALLOWED_SCHEMES:@@ -949,11 +964,14 @@ class NotificationURLValidator:"(e.g. tgram://123456789:AAexample_token/123456789)",)logger.warning(- f"Unknown notification protocol: {scheme} in URL: {redact_url_for_log(url)}"+ "Unknown notification protocol: {} in URL: {}",+ redact_and_bound_for_log(scheme, _LOG_HOST_MAX_CHARS),+ redact_url_for_log(url),)return (False,- f"Unsupported protocol: {scheme}. "+ "Unsupported protocol: "+ f"{redact_and_bound_for_log(scheme, _LOG_HOST_MAX_CHARS)}. "f"Allowed: {', '.join(NotificationURLValidator.ALLOWED_SCHEMES[:5])}...",)@@ -1189,12 +1207,14 @@ class NotificationURLValidator:)return (False,- f"Blocked cloud-metadata / link-local IP address: {effective_host}",+ "Blocked cloud-metadata / link-local IP address: "+ f"{redact_and_bound_for_log(effective_host, _LOG_HOST_MAX_CHARS)}",)logger.warning("Blocked private/internal notification host")return (False,- f"{NotificationURLValidator.PRIVATE_IP_REJECTION_PREFIX} {effective_host}",+ f"{NotificationURLValidator.PRIVATE_IP_REJECTION_PREFIX} "+ f"{redact_and_bound_for_log(effective_host, _LOG_HOST_MAX_CHARS)}",)# Passed all security checks@@ -1224,12 +1244,12 @@ class NotificationURLValidator:block_link_local=block_link_local,)if not hint:- logger.debug(+ logger.opt(lazy=True).debug("hint suppressed: {} targets an always-blocked ""category (metadata / 6to4 / Teredo / discard / ""IPv4-Compatible / IPv4-Translated-SIIT / ""NAT64-wrapped metadata)",- hostname,+ lambda: redact_and_bound_for_log(hostname, _LOG_HOST_MAX_CHARS),)return hint@@ -1347,6 +1367,11 @@ class NotificationURLValidator:block_link_local = Trueif not is_valid:+ if error_msg in (+ AMBIGUOUS_NUMERIC_IPV4_HOST_ERROR,+ ENCODED_NUMERIC_IPV4_HOST_ERROR,+ ):+ return False, error_msg, Falseif (not error_msgor not error_msg.startswith(@@ -1354,6 +1379,16 @@ class NotificationURLValidator:)or not hostname):+ logger.opt(lazy=True).debug(+ "hint suppressed: non-private-IP rejection ({})",+ # (#6938: redacted before it is cut, and only when a+ # DEBUG sink takes the line.)+ lambda: (+ redact_and_bound_for_log(error_msg, 60)+ if error_msg+ else "<none>"+ ),+ )return False, error_msg, Falsereturn (False,diff --git a/src/local_deep_research/security/path_validator.py b/src/local_deep_research/security/path_validator.pyindex c990fbd942..654877b891 100644--- a/src/local_deep_research/security/path_validator.py+++ b/src/local_deep_research/security/path_validator.py@@ -16,6 +16,7 @@ from loguru import loggerfrom werkzeug.security import safe_joinfrom ..config.paths import get_models_directory+from .log_sanitizer import redact_and_bound_for_log# Encoded forms of ".." and "." that path traversal attacks use to bypass@@ -114,13 +115,19 @@ class PathValidator:# Strip whitespaceuser_input = user_input.strip()+ # (#6938: the input is a client-chosen path — e.g. the+ # unauthenticated /static route — so the rejection log lines+ # below interpolate a redacted, bounded form, never the raw value.+ # It is built only in those rejection branches: this runs on every+ # static-file lookup, and redaction costs up to tens of+ # milliseconds on a long adversarial path.)# Reject URL-encoded traversal tokens (single or double encoded).# safe_join's literal-".."-check doesn't catch %2e%2e or %252e%252e,# so do it explicitly here before any decoding takes place.if _has_encoded_traversal(user_input):logger.warning(- f"Encoded path-traversal attempt blocked: {user_input!r}"+ f"Encoded path-traversal attempt blocked: {redact_and_bound_for_log(user_input, 200)!r}")raise ValueError("Invalid path - encoded traversal pattern detected"@@ -132,7 +139,7 @@ class PathValidator:# disguised traversal attempt.if _has_unicode_traversal(user_input):logger.warning(- f"Unicode path-traversal attempt blocked: {user_input!r}"+ f"Unicode path-traversal attempt blocked: {redact_and_bound_for_log(user_input, 200)!r}")raise ValueError("Invalid path - unicode traversal pattern detected"@@ -148,11 +155,15 @@ class PathValidator:except ValueError:raiseexcept Exception as e:- logger.warning(f"Path validation failed for input '{user_input}'")+ logger.warning(+ f"Path validation failed for input '{redact_and_bound_for_log(user_input, 200)}'"+ )raise ValueError(f"Invalid path: {e}") from eif safe_path is None:- logger.warning(f"Path traversal attempt blocked: {user_input}")+ logger.warning(+ f"Path traversal attempt blocked: {redact_and_bound_for_log(user_input, 200)}"+ )raise ValueError("Invalid path - potential traversal attempt")result_path = Path(safe_path)diff --git a/src/local_deep_research/security/ssrf_validator.py b/src/local_deep_research/security/ssrf_validator.pyindex 020809abdc..116dc67224 100644--- a/src/local_deep_research/security/ssrf_validator.py+++ b/src/local_deep_research/security/ssrf_validator.py@@ -15,6 +15,7 @@ from urllib3.exceptions import LocationParseErrorfrom urllib3.util import parse_urlfrom .ip_ranges import PRIVATE_IP_RANGES as BLOCKED_IP_RANGES+from .log_sanitizer import redact_and_bound_for_logfrom .ip_ranges import NAT64_PREFIXESfrom .legacy_ipv4 import (is_ambiguous_numeric_ipv4_host,@@ -67,6 +68,15 @@ LINK_LOCAL_RANGES = [# Allowed URL schemesALLOWED_SCHEMES = {"http", "https"}+# Per-component cap for URL parts that reach a log line (#6938). The URLs+# this module logs are often request-supplied (e.g. the api router's+# add-resource body), and neither ``urlparse`` nor urllib3 bounds the+# scheme or host length, so a 100,000-char scheme or host would otherwise+# be written in full to every sink. ``redact_and_bound_for_log`` keeps+# ``max_length - 3`` chars plus ``...``, so a 256 cap never shortens a+# hostname within the 253-char DNS name limit.+_LOG_COMPONENT_MAX_CHARS = 256+# RFC 6052 §2.2 places the embedded IPv4 at prefix-length-specific byte# positions — NOT always the trailing 32 bits. Only /96 puts the IPv4 in the@@ -421,7 +431,7 @@ def validate_url(# Check schemeif parsed.scheme.lower() not in ALLOWED_SCHEMES:logger.warning(- f"Blocked URL with invalid scheme: {parsed.scheme} - {redact_url_for_log(url)}"+ f"Blocked URL with invalid scheme: {redact_url_for_log(url)}")return False@@ -476,7 +486,7 @@ def validate_url(block_link_local=block_link_local,):logger.warning(- f"Blocked URL with internal/private IP: {hostname} - {redact_url_for_log(url)}"+ f"Blocked URL with internal/private IP: {redact_url_for_log(url)}")return Falseexcept ValueError:@@ -516,13 +526,15 @@ def validate_url(block_link_local=block_link_local,):logger.warning(- f"Blocked URL - hostname {hostname} resolves to "- f"internal/private IP: {ip_str} - {redact_url_for_log(url)}"+ f"Blocked URL - host resolves to internal/private "+ f"IP: {ip_str} - {redact_url_for_log(url)}")return Falseexcept socket.gaierror:- logger.warning(f"Failed to resolve hostname {hostname}")+ logger.warning(+ f"Failed to resolve hostname: {redact_url_for_log(url)}"+ )return Falseexcept Exception:logger.exception("Error during hostname resolution")@@ -604,6 +616,14 @@ def redact_url_for_log(url: str) -> str:+ port to minimise the chance of leaking credentials, tokens, orsensitive paths into logs while still giving operators enough todistinguish ``http://10.0.0.1:80`` from ``https://10.0.0.1:443``.+ The scheme and the host each pass through ``redact_and_bound_for_log``+ capped at ``_LOG_COMPONENT_MAX_CHARS``: the log patcher's credential+ redaction runs first, then control characters are stripped and an+ over-long component is cut with a ``...`` marker, so the result stays+ bounded for any input. A component whose first whitespace-free run+ reaches past the 1,024 characters ``redact_and_bound_for_log`` scans+ is replaced by the patcher's omitted-length marker, as a run past the+ patcher's own 32 KiB bound would be in any log line.RFC 3986 §3.2.1 allows credentials in URL userinfo(``http://user:pass@host/``). A rejected URL is by definition@@ -616,6 +636,10 @@ def redact_url_for_log(url: str) -> str:u = parse_url(url.lstrip() if isinstance(url, str) else url)scheme = u.scheme or "?"host = u.host or "<no-host>"+ # (#6938: scheme and host are unbounded in a request-supplied URL,+ # so each is capped — every caller's log line stays bounded.)+ 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 hostreturn f"{scheme}://{host_port}"except (LocationParseError, ValueError):diff --git a/src/local_deep_research/security/url_validator.py b/src/local_deep_research/security/url_validator.pyindex 01094b43ba..000f97f5cb 100644--- a/src/local_deep_research/security/url_validator.py+++ b/src/local_deep_research/security/url_validator.py@@ -10,6 +10,8 @@ from typing import Optional, Listfrom urllib.parse import urlparse, urljoin, unquotefrom loguru import logger+from .log_sanitizer import redact_and_bound_for_log+class URLValidationError(ValueError):"""Raised when URL construction or validation fails."""@@ -76,7 +78,11 @@ class URLValidator:for scheme in URLValidator.UNSAFE_SCHEMES:if normalized_url.startswith(f"{scheme}:"):logger.warning(- f"Unsafe URL scheme detected: {scheme} in URL: {url[:100]}"+ "Unsafe URL scheme detected: {} in URL: {}",+ scheme,+ # (#6938: redacted before it is cut, so the cut cannot+ # drop the ``@`` after URL userinfo.)+ redact_and_bound_for_log(url, 100),)return True@@ -118,7 +124,10 @@ class URLValidator:try:parsed = urlparse(url)except Exception:- logger.warning(f"Failed to parse URL '{url[:100]}'")+ logger.warning(+ "Failed to parse URL '{}'",+ redact_and_bound_for_log(str(url), 100),+ )return False# Check scheme@@ -223,7 +232,10 @@ class URLValidator:return urlexcept Exception:- logger.warning(f"Failed to sanitize URL '{url[:100]}'")+ logger.warning(+ "Failed to sanitize URL '{}'",+ redact_and_bound_for_log(str(url), 100),+ )return None@@ -436,7 +448,9 @@ class URLValidator:# Block path traversal patterns (/../, /.. at end, ../ at start)if re.search(r"(^|/)\.\.(/|$|\?|#)", decoded_target):logger.warning(- "Path traversal detected in redirect URL: {}", target+ "Path traversal detected in redirect URL: {}",+ # (#6938: the ``next`` target is a raw query param.)+ redact_and_bound_for_log(target, 200),)return False@@ -444,7 +458,10 @@ class URLValidator:test_url = urlparse(urljoin(host_url, target))if test_url.path.startswith("//"):- logger.warning("Double-slash path in redirect URL: {}", target)+ logger.warning(+ "Double-slash path in redirect URL: {}",+ redact_and_bound_for_log(target, 200),+ )return Falsereturn (diff --git a/src/local_deep_research/web/dependencies/csrf.py b/src/local_deep_research/web/dependencies/csrf.pyindex f5201debd7..6a933c789a 100644--- a/src/local_deep_research/web/dependencies/csrf.py+++ b/src/local_deep_research/web/dependencies/csrf.py@@ -123,6 +123,18 @@ from starlette.responses import JSONResponsefrom starlette.types import ASGIApp, Receive, Scope, Send+def _log_path_preview(path: str) -> str:+ """Bounded preview of the request path for the rejection log lines.++ (#6938: the path is client-chosen and logged before authentication,+ so it goes through the shared value preview. Imported at call time so+ this middleware never imports the routers package at import time.)+ """+ from ..routers.notes import _log_value_preview++ return _log_value_preview(path)++def generate_csrf_token(request: Request) -> str:"""Generate or retrieve CSRF token for the current session.@@ -328,7 +340,7 @@ class CSRFMiddleware:logger.warning("CSRF rejected: request lacks session _csrf_token ({} {})",method,- path,+ _log_path_preview(path),)response = JSONResponse({"error": "CSRF token missing: fetch /auth/csrf-token first"},@@ -390,7 +402,7 @@ class CSRFMiddleware:"CSRF rejected: urlencoded body over the form-parse cap ""with no X-CSRFToken header ({} {})",method,- path,+ _log_path_preview(path),)response = JSONResponse({@@ -422,7 +434,7 @@ class CSRFMiddleware:logger.warning("CSRF validation failed: {} {} (token present: {})",method,- path,+ _log_path_preview(path),bool(provided),)response = JSONResponse(diff --git a/src/local_deep_research/web/fastapi_app.py b/src/local_deep_research/web/fastapi_app.pyindex 7748aba137..bd563dc49a 100644--- a/src/local_deep_research/web/fastapi_app.py+++ b/src/local_deep_research/web/fastapi_app.py@@ -998,9 +998,14 @@ class BodySizeLimitMiddleware:# Too late for a 413 — let the server tear the# connection down.raise+ from .routers.notes import _log_value_preview++ # (#6938: the path is client-chosen and this runs before+ # authentication, so it is bounded.)logger.warning(- f"Rejected over-limit request body on {scope.get('path', '')} "- f"(> {effective_max} bytes)"+ "Rejected over-limit request body on {} (> {} bytes)",+ _log_value_preview(scope.get("path", "")),+ effective_max,)await self._send_413(scope, receive, send)@@ -1075,12 +1080,19 @@ class SecureCookieMiddleware:returnif remote_addr and not _is_private_ip(remote_addr):self._warned_insecure_public = True+ from ..security.log_sanitizer import redact_and_bound_for_log+logger.warning("Serving HTTP to a public client ({}). Session/CSRF cookies ""are NOT marked Secure (marking them Secure over HTTP would ""make the browser drop them). Put LDR behind HTTPS, and if ""using a TLS proxy set TRUST_PROXY_HEADERS=true.",- remote_addr,+ # (#6938: under TRUST_PROXY_HEADERS this is the client's+ # unvalidated X-Forwarded-For entry, so it is bounded. A+ # plain string cap, not the quoted value preview, so a real+ # address logs exactly as before, like the ``ip=`` field of+ # the rate-limit-exceeded line below.)+ redact_and_bound_for_log(remote_addr, 64),)async def __call__(self, scope, receive, send):@@ -1429,8 +1441,13 @@ def _register_exception_handlers(app: FastAPI) -> None:# Let HTTPException pass through to FastAPI's default handler.if isinstance(exc, HTTPException):raise exc from None+ from .routers.notes import _log_value_preview++ # (#6938: the path is client-chosen, so it is bounded.)logger.opt(exception=exc).error(- "Unhandled exception: {} {}", request.method, request.url.path+ "Unhandled exception: {} {}",+ request.method,+ _log_value_preview(request.url.path),)# Stamp the security headers here rather than relying on# SecurityHeadersMiddleware. Registering a handler for the bare@@ -1481,10 +1498,13 @@ def _register_exception_handlers(app: FastAPI) -> None:# a real blind spot in check-sensitive-logging, which tracks# exception variables via `except ... as e` and therefore cannot# see one arriving as an exception-handler parameter.+ from .routers.notes import _log_value_preview++ # (#6938: the path is client-chosen, so it is bounded.)logger.warning("JSON decode error handling {} {}: {} (line {} column {})",request.method,- request.url.path,+ _log_value_preview(request.url.path),getattr(exc, "msg", "invalid JSON"),getattr(exc, "lineno", "?"),getattr(exc, "colno", "?"),diff --git a/src/local_deep_research/web/routers/api.py b/src/local_deep_research/web/routers/api.pyindex 9165f16caa..ace80a288d 100644--- a/src/local_deep_research/web/routers/api.py+++ b/src/local_deep_research/web/routers/api.py@@ -12,8 +12,10 @@ from ...constants import ResearchStatusfrom ...database.models import QueuedResearch, ResearchHistoryfrom ...database.session_context import get_user_db_sessionfrom ...config.constants import DEFAULT_OLLAMA_URL+from ...security.ssrf_validator import redact_url_for_logfrom ...utilities.url_utils import normalize_url+from .notes import _log_value_previewfrom .research import _research_not_foundfrom ..services.research_service import (cancel_research,@@ -244,7 +246,13 @@ async def api_add_resource(is_valid = validate_url(url)if not is_valid:- logger.warning(f"SSRF protection: Rejected URL {url}")+ if isinstance(url, str):+ logger.warning(+ "SSRF protection: Rejected URL {}",+ _log_value_preview(redact_url_for_log(url)),+ )+ else:+ logger.warning("SSRF protection: Rejected URL (non-string)")return JSONResponse({"status": "error", "message": "Invalid URL"},status_code=400,@@ -512,7 +520,9 @@ def check_ollama_model()# Log which model we're checking for debugging- logger.info(f"Checking availability of Ollama model: {model_name}")+ logger.info(+ f"Checking availability of Ollama model: {_log_value_preview(model_name)}"+ )ollama_base_url = _ollama_base_url_from_config(raw_ollama_base_url)@@ -585,7 +595,7 @@ def check_ollama_model(message = "No models found in Ollama. Please pull models first."else:logger.warning(- f"Model {model_name} not found among {len(models)} available models"+ f"Model {_log_value_preview(model_name)} not found among {len(models)} available models")# Don't expose available models for security reasonsmessage = f"Model {model_name} is not available"diff --git a/src/local_deep_research/web/routers/auth.py b/src/local_deep_research/web/routers/auth.pyindex bee7fdb178..5927a64c50 100644--- a/src/local_deep_research/web/routers/auth.py+++ b/src/local_deep_research/web/routers/auth.py@@ -40,7 +40,8 @@ from urllib.parse import urlparsefrom ...security.url_validator import URLValidatorfrom ...security.account_lockout import get_account_lockout_managerfrom ...security.password_validator import PasswordValidator-from ...security.log_sanitizer import sanitize_for_log+from ...security.log_sanitizer import redact_and_bound_for_log+from .notes import _log_value_previewfrom typing import Annotatedrouter = APIRouter(prefix="/auth", tags=["auth"])@@ -118,7 +119,9 @@ def _disconnect_user_sockets(username: str) -> None:disconnect_user(username)except Exception:- logger.exception(f"Failed to disconnect sockets for {username}")+ logger.exception(+ f"Failed to disconnect sockets for {_log_value_preview(username)}"+ )def _disconnect_session_sockets(session_id: str) -> None:@@ -184,7 +187,7 @@ def login(lockout_mgr = get_account_lockout_manager()if lockout_mgr.is_locked(username):logger.warning(- f"Login attempt for locked account: {sanitize_for_log(username)}"+ f"Login attempt for locked account: {redact_and_bound_for_log(username, 50)}")flash(request,@@ -216,7 +219,7 @@ def login(engine = db_manager.open_user_database(username, password)except DatabaseInitializationError:logger.warning(- f"Login refused for {sanitize_for_log(username)}: "+ f"Login refused for {redact_and_bound_for_log(username, 50)}: ""database initialisation failed (see traceback above). ""Lockout counter NOT incremented — credentials are valid.")@@ -239,7 +242,7 @@ def login(if engine is None:lockout_mgr.record_failure(username)logger.warning(- f"Failed login attempt for username: {sanitize_for_log(username)}"+ f"Failed login attempt for username: {redact_and_bound_for_log(username, 50)}")flash(request, "Invalid username or password", "error")return render_template(@@ -287,7 +290,7 @@ def login(_rollback_partial_session(request, username)raise- logger.info(f"User {username} logged in successfully")+ logger.info(f"User {_log_value_preview(username)} logged in successfully")# Defer non-critical post-login work to a background thread so the# redirect returns immediately (settings migration, library init,@@ -332,7 +335,7 @@ def _perform_post_login_tasks(_perform_post_login_tasks_body(username, password, session_id)except Exception:logger.exception(- f"Post-login background thread crashed for user {username}"+ f"Post-login background thread crashed for user {_log_value_preview(username)}")@@ -367,7 +370,7 @@ def _perform_post_login_tasks_body(settings_manager = SettingsManager(db_session)if not settings_manager.db_version_matches_package():logger.info(- f"Database version mismatch for {username} "+ f"Database version mismatch for {_log_value_preview(username)} ""- loading missing default settings")# override_locked: this only adds keys the upgrade@@ -385,10 +388,12 @@ def _perform_post_login_tasks_body(db_session.commit()logger.info(f"Missing default settings loaded and version "- f"updated for user {username}"+ f"updated for user {_log_value_preview(username)}")except Exception:- logger.exception(f"Post-login settings migration failed for {username}")+ logger.exception(+ f"Post-login settings migration failed for {_log_value_preview(username)}"+ )_log_step_duration("step 1 (settings version check)", step_start, username)# 2. Initialize library system (source types and default collection)@@ -398,14 +403,18 @@ def _perform_post_login_tasks_body(init_results = initialize_library_for_user(username, password)if init_results.get("success"):- logger.info(f"Library system initialized for user {username}")+ logger.info(+ f"Library system initialized for user {_log_value_preview(username)}"+ )else:logger.warning(- f"Library initialization issue for {username}: "+ f"Library initialization issue for {_log_value_preview(username)}: "f"{init_results.get('error', 'Unknown error')}")except Exception:- logger.exception(f"Post-login library init failed for {username}")+ logger.exception(+ f"Post-login library init failed for {_log_value_preview(username)}"+ )_log_step_duration("step 2 (library init)", step_start, username)# 3. Update last_login in auth DB + notify news scheduler@@ -425,14 +434,16 @@ def _perform_post_login_tasks_body(if scheduler.is_running:scheduler.update_user_info(username, password)logger.info(- f"Updated scheduler with user info for {username}"+ f"Updated scheduler with user info for {_log_value_preview(username)}")except Exception:logger.exception("Could not update scheduler on login")auth_db.commit()except Exception:- logger.exception(f"Post-login auth DB update failed for {username}")+ logger.exception(+ f"Post-login auth DB update failed for {_log_value_preview(username)}"+ )_log_step_duration("step 3 (auth DB + scheduler notify)", step_start, username)@@ -458,9 +469,13 @@ def _perform_post_login_tasks_body(get_backup_executor().submit_backup(username, password, max_backups, max_age_days)- logger.info(f"Background backup scheduled for user {username}")+ logger.info(+ f"Background backup scheduled for user {_log_value_preview(username)}"+ )except Exception:- logger.exception(f"Post-login backup scheduling failed for {username}")+ logger.exception(+ f"Post-login backup scheduling failed for {_log_value_preview(username)}"+ )_log_step_duration("step 4 (schedule backup)", step_start, username)# 6. Reconcile orphan IN_PROGRESS research records. If the server was@@ -477,7 +492,7 @@ def _perform_post_login_tasks_body()except Exception:logger.exception(- f"Post-login research reconciliation failed for {username}"+ f"Post-login research reconciliation failed for {_log_value_preview(username)}")_log_step_duration("step 6 (reconcile orphan research)", step_start, username@@ -498,19 +513,19 @@ def _perform_post_login_tasks_body(queue_processor.notify_user_activity(username, session_id)except Exception:logger.exception(- f"Post-login queue-resume registration failed for {username}"+ f"Post-login queue-resume registration failed for {_log_value_preview(username)}")_log_step_duration("step 7 (resume queued research)", step_start, username)total_ms = (time.perf_counter() - total_start) * 1000if total_ms > 1000:logger.info(- f"Post-login tasks completed for user {username} "+ f"Post-login tasks completed for user {_log_value_preview(username)} "f"(total: {total_ms:.0f}ms)")else:logger.info(- f"Post-login tasks completed for user {username} ({total_ms:.0f}ms)"+ f"Post-login tasks completed for user {_log_value_preview(username)} ({total_ms:.0f}ms)")@@ -519,11 +534,14 @@ def _log_step_duration(step_label: str, start: float, username: str) -> None:elapsed_ms = (time.perf_counter() - start) * 1000if elapsed_ms > 100:logger.info(- f"Post-login {step_label} for {username} took {elapsed_ms:.0f}ms"+ f"Post-login {step_label} for {_log_value_preview(username)} took {elapsed_ms:.0f}ms")else:- logger.debug(- f"Post-login {step_label} for {username} took {elapsed_ms:.0f}ms"+ logger.opt(lazy=True).debug(+ "Post-login {} for {} took {:.0f}ms",+ lambda: step_label,+ lambda: _log_value_preview(username),+ lambda: elapsed_ms,)@@ -634,6 +652,11 @@ def register(status_code=400,)+ # (#6938: the form username has a minimum length but no maximum, so+ # every registration log line below interpolates this bounded preview,+ # never the raw value.)+ log_username = _log_value_preview(username)+# Create user in auth databasewith auth_db_session() as auth_db:try:@@ -652,7 +675,7 @@ def register(# Catch duplicate username specifically (race condition case)# This handles the edge case where two requests for the same username# pass the user_exists() check simultaneously- logger.warning(f"Duplicate username attempted: {username}")+ logger.warning(f"Duplicate username attempted: {log_username}")auth_db.rollback()flash(request,@@ -670,7 +693,7 @@ def register()except Exception:logger.exception(- f"Registration failed for {username} while creating the "+ f"Registration failed for {log_username} while creating the "f"auth record")auth_db.rollback()@@ -698,7 +721,7 @@ def register(db_manager.create_user_database(username, password)except Exception:logger.exception(- f"Registration failed for {username} while creating the "+ f"Registration failed for {log_username} while creating the "f"encrypted database")# Delete the orphaned auth row by primary key in a fresh session@@ -713,13 +736,13 @@ def register(cleanup_db.delete(orphaned_user)cleanup_db.commit()logger.info(- f"Cleaned up orphaned auth entry for {username}"+ f"Cleaned up orphaned auth entry for {log_username}")except Exception:# Surface a stuck orphan so it's diagnosable, but don't mask the# original registration failure returned to the user.logger.exception(- f"Failed to clean up orphaned auth entry for {username}"+ f"Failed to clean up orphaned auth entry for {log_username}")flash(request, "Registration failed. Please try again.", "error")return render_template(@@ -770,12 +793,12 @@ def register(if scheduler.is_running:scheduler.update_user_info(username, password)logger.info(- f"Updated scheduler with new user info for {username}"+ f"Updated scheduler with new user info for {log_username}")except Exception:logger.exception("Could not update scheduler on registration")- logger.info(f"New user registered: {username}")+ logger.info(f"New user registered: {log_username}")# Initialize library system (source types and default collection)from ...database.library_init import initialize_library_for_user@@ -784,15 +807,15 @@ def register(init_results = initialize_library_for_user(username, password)if init_results.get("success"):logger.info(- f"Library system initialized for new user {username}"+ f"Library system initialized for new user {log_username}")else:logger.warning(- f"Library initialization issue for {username}: {init_results.get('error', 'Unknown error')}"+ f"Library initialization issue for {log_username}: {init_results.get('error', 'Unknown error')}")except Exception:logger.exception(- f"Error initializing library for new user {username}"+ f"Error initializing library for new user {log_username}")# Don't block registration on library init failure@@ -807,7 +830,7 @@ def register(# the partially-set cookie on this response — see #5006)._rollback_partial_session(request, username)logger.exception(- f"Registration failed for {username} after database creation "+ f"Registration failed for {log_username} after database creation "f"(post-creation session/login setup)")flash(request, "Registration failed. Please try again.", "error")@@ -971,7 +994,7 @@ def logout(request: Request):# logged out even if earlier cleanup raised.request.session.clear()- logger.info(f"User {username} logged out")+ logger.info(f"User {_log_value_preview(username)} logged out")flash(request, "You have been logged out successfully", "info")if "application/json" in request.headers.get("accept", ""):@@ -1152,7 +1175,7 @@ def change_password(# operator needs; the reason is one of the two guards in# change_password.logger.warning(- f"Password change rejected for {username}: the rekey path "+ f"Password change rejected for {_log_value_preview(username)}: the rekey path ""refused one of the submitted password fields")flash(@@ -1215,17 +1238,17 @@ def change_password(result = svc.purge_and_refresh()if result.success:logger.info(- f"Backups refreshed after password change for {username}"+ f"Backups refreshed after password change for {_log_value_preview(username)}")else:logger.error(- f"Post-password-change backup failed for {username}: "+ f"Post-password-change backup failed for {_log_value_preview(username)}: "f"{result.error}. Old backups were purged.")except Exception:logger.exception(f"Could not refresh backups after password change "- f"for {username}"+ f"for {_log_value_preview(username)}")# 3. Destroy ALL sessions for this user + clear password store@@ -1255,7 +1278,7 @@ def change_password(# 4. Clear Flask session dictrequest.session.clear()- logger.info(f"Password changed for user {username}")+ logger.info(f"Password changed for user {_log_value_preview(username)}")flash(request,"Password changed successfully. Please login with your new password.",diff --git a/src/local_deep_research/web/routers/followup.py b/src/local_deep_research/web/routers/followup.pyindex 520d4f5141..fc1316ff32 100644--- a/src/local_deep_research/web/routers/followup.py+++ b/src/local_deep_research/web/routers/followup.py@@ -15,6 +15,7 @@ from ...llm.providers.base import normalize_providerfrom ...followup_research.service import FollowUpResearchServicefrom ...followup_research.models import FollowUpRequestfrom ...utilities.url_utils import is_safe_custom_llm_endpoint+from .notes import _log_value_previewfrom ..auth.password_utils import resolve_user_passwordfrom typing import Annotated@@ -108,8 +109,11 @@ async def prepare_followup(# Parent research doesn't exist (wrong ID, deleted, or belongs# to another user whose DB we can't read). Return 404 so the# caller doesn't submit a follow-up against a ghost parent.+ # (#6938: parent_id is the raw, unchecked body value here.)logger.warning(- f"Parent research {parent_id} not found for user {username}"+ "Parent research {} not found for user {}",+ _log_value_preview(parent_id),+ username,)return JSONResponse({"success": False, "error": "Parent research not found"},@@ -259,16 +263,23 @@ def _start_followup_sync(data, username):# Prepare research parametersresearch_params = service.perform_followup(followup_request)- logger.info(f"Research params type: {type(research_params)}")- logger.info(- f"Research params keys: {research_params.keys() if isinstance(research_params, dict) else 'Not a dict'}"+ # (#6938: the query is raw request input and a wide params dict has+ # unbounded keys, so both go through the bounded preview instead of+ # eager f-strings.)+ params_keys = (+ list(research_params.keys())+ if isinstance(research_params, dict)+ else "Not a dict")- logger.info(- f"Query value: {research_params.get('query') if isinstance(research_params, dict) else 'N/A'}"- )- logger.info(- f"Query type: {type(research_params.get('query')) if isinstance(research_params, dict) else 'N/A'}"+ query_value = (+ research_params.get("query")+ if isinstance(research_params, dict)+ else "N/A")+ logger.info("Research params type: {}", type(research_params))+ logger.info("Research params keys: {}", _log_value_preview(params_keys))+ logger.info("Query value: {}", _log_value_preview(query_value))+ logger.info("Query type: {}", type(query_value))# (user_password / session-expired 401 are resolved above, before the# parent-ownership check, so auth precedes authz.)diff --git a/src/local_deep_research/web/routers/history.py b/src/local_deep_research/web/routers/history.pyindex 8cc01b4436..2946e5694b 100644--- a/src/local_deep_research/web/routers/history.py+++ b/src/local_deep_research/web/routers/history.py@@ -7,6 +7,7 @@ from ..template_config import templatesimport jsonfrom loguru import logger+from .notes import _log_value_previewfrom sqlalchemy import funcfrom ...constants import (@@ -266,7 +267,10 @@ def get_research_details():"""Get detailed progress log for a specific research"""- logger.debug(f"Details route accessed for research_id: {research_id}")+ logger.opt(lazy=True).debug(+ "Details route accessed for research_id: {}",+ lambda: _log_value_preview(research_id),+ )try:with get_user_db_session(username) as db_session:@@ -278,7 +282,9 @@ def get_research_details(logger.debug(f"Research found: {research.id if research else None}")if not research:- logger.error(f"Research not found for id: {research_id}")+ logger.error(+ f"Research not found for id: {_log_value_preview(research_id)}"+ )return _research_not_found(research_id)# Extract all needed attributes while session is activediff --git a/src/local_deep_research/web/routers/library.py b/src/local_deep_research/web/routers/library.pyindex bb98ec148e..cbcb6b8002 100644--- a/src/local_deep_research/web/routers/library.py+++ b/src/local_deep_research/web/routers/library.py@@ -49,8 +49,10 @@ from ...research_library.utils import ()from ...utilities.db_utils import get_settings_managerfrom ...config.paths import get_library_directory+from ...security.log_sanitizer import redact_and_bound_for_logfrom ...web.exceptions import AuthenticationRequiredErrorfrom ..dependencies.json_body import json_body_error+from .notes import _log_value_previewfrom typing import Annotated# Create the router@@ -526,7 +528,7 @@ def _serve_pdf(if not document:logger.warning(- f"Document ID {document_id} not found in database for user {username}"+ f"Document ID {_log_value_preview(document_id)} not found in database for user {username}")# Browser navigation: return text/html, not JSON. These four page# routes are reached from library.html as ordinary <a href> links, so a@@ -659,7 +661,9 @@ def view_text_page(document = db_session.query(Document).filter_by(id=document_id).first()if not document:- logger.warning(f"Document not found for document ID {document_id}")+ logger.warning(+ f"Document not found for document ID {_log_value_preview(document_id)}"+ )# Browser navigation: return text/html, not JSON. These four page# routes are reached from library.html as ordinary <a href> links, so a# stale link showed the user a raw {"error": ...} body in the browser's@@ -705,7 +709,9 @@ def serve_text_api(document = db_session.query(Document).filter_by(id=document_id).first()if not document:- logger.warning(f"Document not found for document ID {document_id}")+ logger.warning(+ f"Document not found for document ID {_log_value_preview(document_id)}"+ )return JSONResponse({"error": "Document not found"}, status_code=404)@@ -1164,9 +1170,11 @@ async def download_bulk(except Exception:queue_failures += 1logger.exception(- f"Error queueing downloads for "- f"user={username} research={research_id} "- f"collection={collection_id}"+ "Error queueing downloads for "+ "user={} research={} collection={}",+ username,+ research_id,+ _log_value_preview(collection_id),)with get_user_db_session(username) as session:@@ -1557,12 +1565,21 @@ def queue_all_undownloaded(# Log what we're checkingif resource.url and "pubmed" in resource.url.lower():- logger.info(f"Found PubMed URL: {resource.url[:100]}")+ logger.info(+ "Found PubMed URL: {}",+ # (#6938: redacted before it is cut.)+ redact_and_bound_for_log(resource.url, 100),+ )if not is_downloadable:skipped_count += 1- logger.debug(- f"Skipping non-downloadable URL: {resource.url[:100] if resource.url else 'None'}"+ logger.opt(lazy=True).debug(+ "Skipping non-downloadable URL: {}",+ lambda: (+ redact_and_bound_for_log(resource.url, 100)+ if resource.url+ else "None"+ ),)continuediff --git a/src/local_deep_research/web/routers/metrics.py b/src/local_deep_research/web/routers/metrics.pyindex 6e7b6ce908..287d8cf05e 100644--- a/src/local_deep_research/web/routers/metrics.py+++ b/src/local_deep_research/web/routers/metrics.py@@ -40,6 +40,7 @@ from ...metrics.query_utils import ()from ...metrics.search_tracker import get_search_trackerfrom ..dependencies.json_body import json_body_error+from .notes import _log_value_preview# Create the router for metricsrouter = APIRouter(prefix="/metrics", tags=["metrics"])@@ -1897,8 +1898,12 @@ def api_model_pricing("last_updated": datetime.now(UTC).isoformat(),}- except Exception:- logger.exception(f"Error getting pricing for model: {model_name}")+ except Exception as exc:+ logger.opt(exception=False).error(+ "Error getting pricing for model: {} ({})",+ _log_value_preview(model_name),+ type(exc).__name__,+ )return JSONResponse({"error": "An internal error occurred"}, status_code=500)@@ -2030,7 +2035,7 @@ def api_research_costs(except Exception:logger.exception(- f"Error getting research costs for research: {research_id}"+ f"Error getting research costs for research: {_log_value_preview(research_id)}")return JSONResponse({"error": "An internal error occurred"}, status_code=500@@ -2324,7 +2329,9 @@ async def api_classify_domains()if domain and not batch_mode:- logger.info(f"Classifying single domain: {domain}")+ logger.info(+ "Classifying single domain: {}", _log_value_preview(domain)+ )classification = classifier.classify_domain(domain, force_update)diff --git a/src/local_deep_research/web/routers/news_flask_api.py b/src/local_deep_research/web/routers/news_flask_api.pyindex 4529ef9011..01510cca47 100644--- a/src/local_deep_research/web/routers/news_flask_api.py+++ b/src/local_deep_research/web/routers/news_flask_api.py@@ -20,6 +20,8 @@ from typing import Any, Annotatedfrom loguru import logger+from .notes import _log_value_preview+from ...llm.providers.base import normalize_providerfrom ...news import apifrom ...news.constants import (@@ -37,6 +39,7 @@ from ...database.session_context import get_user_db_sessionfrom ...settings.env_registry import get_env_settingfrom ...utilities.db_utils import get_settings_managerfrom ...utilities.url_utils import is_safe_custom_llm_endpoint+from ...security.log_sanitizer import redact_and_bound_for_logfrom ..dependencies.json_body import json_body_error, read_json_dict# Hard ceiling for user-supplied ``limit`` query params on the news@@ -164,8 +167,8 @@ def require_scheduler_control(request: Request) -> None:remote_addr = request.client.host if request.client else "unknown"logger.warning("Scheduler API control blocked (user={}, ip={})",- username,- remote_addr,+ _log_value_preview(username),+ _log_value_preview(remote_addr),)raise HTTPException(status_code=403,@@ -412,7 +415,7 @@ def get_news_feed()logger.info(- f"News feed params: limit={limit}, subscription_id={subscription_id}, focus={focus}"+ f"News feed params: limit={limit}, subscription_id={subscription_id}, focus={_log_value_preview(focus)}")# Call the direct API function (now synchronous)@@ -1599,7 +1602,12 @@ def check_overdue_subscriptions(try:# Run the subscription using the same pattern as run_subscription_nowlogger.info(- f"Running overdue subscription: {sub_label[:30]}"+ "Running overdue subscription: {}",+ # (#6938: redacted before it is cut; ``sub_label``+ # is already a cut of the query.)+ redact_and_bound_for_log(+ str(sub.name or sub.query_or_topic), 30+ ),)# Snapshot for the post-run compare-and-set (see below).@@ -1933,7 +1941,9 @@ def _update_subscription_folder_sync(data, subscription_id, username):update_data = normalize_compact_subscription_update(data)logger.info(- f"Updating subscription {subscription_id} with data: {update_data}"+ "Updating subscription {} with data: {}",+ _log_value_preview(subscription_id),+ _log_value_preview(update_data),)with get_user_db_session(username) as session:@@ -2073,7 +2083,9 @@ async def add_search_history(# get.logger.info("add_search_history received data keys: {}",- list(data.keys()) if isinstance(data, dict) else "None",+ _log_value_preview(list(data.keys()))+ if isinstance(data, dict)+ else "None",)if not isinstance(data, dict) or not data.get("query"):logger.warning("Invalid search history data: missing query")diff --git a/src/local_deep_research/web/routers/news_pages.py b/src/local_deep_research/web/routers/news_pages.pyindex 8792c44a56..51e66071b0 100644--- a/src/local_deep_research/web/routers/news_pages.py+++ b/src/local_deep_research/web/routers/news_pages.py@@ -6,6 +6,7 @@ Ported from news/web.py Flask blueprint factory.from fastapi import APIRouter, Depends, Requestfrom fastapi.responses import JSONResponsefrom loguru import logger+from .notes import _log_value_previewfrom ...constants import DEFAULT_SEARCH_TOOL, get_available_strategiesfrom ..dependencies.auth import require_auth@@ -143,7 +144,9 @@ def edit_subscription_page(_load_user_settings(default_settings, db_session, username)except Exception:- logger.exception(f"Error loading subscription {subscription_id}")+ logger.exception(+ f"Error loading subscription {_log_value_preview(subscription_id)}"+ )return templates.TemplateResponse(request=request,name="pages/news-subscription-form.html",diff --git a/src/local_deep_research/web/routers/notes.py b/src/local_deep_research/web/routers/notes.pyindex b5f827ce35..d2ca06f830 100644--- a/src/local_deep_research/web/routers/notes.py+++ b/src/local_deep_research/web/routers/notes.py@@ -34,6 +34,7 @@ Notes on the port:"""import asyncio+import builtinsimport itertoolsimport jsonimport math@@ -59,6 +60,14 @@ from ...research_library.notes.services.note_service import (escape_markdown_link_label,)from ...research_library.utils import handle_api_error+from ...security.data_sanitizer import REDACTION_TEXT+from ...security.log_sanitizer import (+ _LOG_REDACTION_MAX_CHARS,+ _is_empty_log_value,+ _is_sensitive_log_key,+ _truncate_for_log_redaction,+ redact_for_log,+)from ..dependencies.auth import require_authfrom ..dependencies.rate_limit import async_shared_limit, limiter, _user_keyfrom ..dependencies.threadpool import run_db_sync@@ -143,17 +152,110 @@ def _clamp_text_query(value, name, max_len=MAX_SEARCH_LEN):# afterwards. That is why values reach ``reprlib`` here only through the# bounded walk in ``_bound_dict_shaped_walk`` below. ``maxlevel`` also caps# recursion depth for a deeply nested dict.-_log_value_repr = reprlib.Repr(- maxlevel=4,- maxtuple=10,- maxlist=10,- maxdict=10,- maxset=10,- maxfrozenset=10,- maxstring=100,- maxlong=100,- maxother=100,-)+#+# Redaction runs BEFORE any cut. ``repr_str`` keeps a long string's first+# and last ~48 characters and drops the middle; the final ``[:100]``+# backstop below keeps only a prefix. Either cut can drop a credential's+# label (``?key=``, ``api_key=``, the ``user:`` ... ``@`` around URL+# userinfo) while keeping part of the secret, and the loguru patcher's+# redaction — the backstop for every sink — then has nothing to match. The+# value was often logged in full before it went through this preview, so+# the patcher used to see the whole thing. ``_RedactingRepr`` therefore runs+# the patcher's own redaction (``redact_for_log``) on every string, and on+# every ``builtins.repr`` text ``repr_instance`` falls back to, before+# reprlib shortens it; ``_bound_dict_shaped_walk`` masks a value under a+# sensitive key name (``api_key``, ``password``, ...), as the patcher's+# ``extra`` redaction does, because per-string redaction cannot see a label+# that lives in the dict key (and masks the value under any key its+# key-check budget cannot cover, see ``_PREVIEW_KEY_CHECK_BUDGET``).+#+# Redaction costs about 2 microseconds per character on adversarial input+# (a run of spaces, or of ``https://a:b@ ``): ~70-120 ms for a 32 KiB+# string, where the unredacted preview cost well under 0.1 ms. The preview+# shows at most 100 characters, so each string is redacted only up to+# ``_PREVIEW_STRING_REDACTION_MAX_CHARS``: it is cut first by the+# patcher's own rule (``_truncate_for_log_redaction`` with that bound,+# only at a whitespace boundary, dropping the whole run the bound falls+# in), the kept head is redacted, and the rest is replaced by the+# omitted-length marker. A credential token holds no boundary character,+# so the head never keeps part of a token whose label or ``@`` lies past+# the cut, and nothing past the cut is shown. A bounded container can+# still hold over twenty thousand strings (reprlib renders up to ten keys+# and ten values per dict at each of four levels), so each preview also+# has a total redaction budget of ``_PREVIEW_REDACTION_BUDGET``+# characters. Each redaction also has a fixed cost of about 25+# microseconds however short the string, so every call is charged at+# least ``_PREVIEW_REDACTION_MIN_CHARGE`` characters: a preview runs at+# most ``_PREVIEW_REDACTION_BUDGET // _PREVIEW_REDACTION_MIN_CHARGE``+# (32) redactions over at most ``_PREVIEW_REDACTION_BUDGET`` characters+# in total, a few milliseconds at worst. The 100-character preview shows+# only the first few strings reprlib renders, and those are the ones+# redacted first. A string that does not fit the remaining budget is+# shown as ``<N-char string not shown>``, never raw.+_PREVIEW_STRING_REDACTION_MAX_CHARS = 512+_PREVIEW_REDACTION_BUDGET = 1_024+_PREVIEW_REDACTION_MIN_CHARGE = 32+++class _RedactingRepr(reprlib.Repr):+ """``reprlib.Repr`` that redacts each string before shortening it.++ Stateful (the remaining budget), so ``_log_value_preview`` builds a new+ one per call; the module-level ``_log_value_repr`` instance only holds+ the shared limits.+ """++ def __init__(self) -> None:+ super().__init__(+ maxlevel=4,+ maxtuple=10,+ maxlist=10,+ maxdict=10,+ maxset=10,+ maxfrozenset=10,+ maxstring=100,+ maxlong=100,+ maxother=100,+ )+ self._budget = _PREVIEW_REDACTION_BUDGET++ def _redacted(self, text: str):+ cost = max(+ min(len(text), _PREVIEW_STRING_REDACTION_MAX_CHARS),+ _PREVIEW_REDACTION_MIN_CHARGE,+ )+ if cost > self._budget:+ return None+ self._budget -= cost+ head, marker = _truncate_for_log_redaction(+ text, _PREVIEW_STRING_REDACTION_MAX_CHARS+ )+ return redact_for_log(head) + marker++ def repr_str(self, x, level):+ redacted = self._redacted(x)+ if redacted is None:+ return f"<{len(x)}-char string not shown>"+ return super().repr_str(redacted, level)++ def repr_instance(self, x, level):+ try:+ text = builtins.repr(x)+ except Exception:+ return f"<{x.__class__.__name__} instance at {id(x):#x}>"+ redacted = self._redacted(text)+ if redacted is None:+ return f"<{x.__class__.__name__} repr not shown>"+ if len(redacted) > self.maxother:+ i = max(0, (self.maxother - 3) // 2)+ j = max(0, self.maxother - 3 - i)+ redacted = (+ redacted[:i] + self.fillvalue + redacted[len(redacted) - j :]+ )+ return redacted+++_log_value_repr = _RedactingRepr()def _log_value_preview(value: Any) -> str:@@ -196,9 +298,18 @@ def _log_value_preview(value: Any) -> str:pre-bounding walk visits always previews differently from thecorresponding all-≤10-key payload. Reprs that fit the cap arereturned untouched, and the preview never exceeds the cap.++ Every string (and every ``repr`` text of a non-container object) has+ already been through the log patcher's credential redaction before+ ``reprlib`` or the backstop shortens it, and a value under a sensitive+ dict key (or under a key the key-check budget could not cover) is+ masked whole — see ``_RedactingRepr`` above. A cut+ therefore only removes text the patcher already redacted or would+ leave as is: it cannot strip a recognised credential's label while+ keeping part of the secret."""bounded, items_omitted = _bound_dict_shaped_walk(value, 0)- text = _log_value_repr.repr(bounded)+ text = _RedactingRepr().repr(bounded)if len(text) <= _PREVIEW_MAX_CHARS:return textfor tail in _PREVIEW_CONTAINER_TAILS:@@ -250,9 +361,23 @@ _PREVIEW_CONTAINER_TAILS = (", ...}", ", ...]", ", ...)")# ends in a bare ``...``. Deliberately identical to the dict tail: both# spell "entries were omitted"._PREVIEW_ITEMS_OMITTED_TAIL = ", ...}"---def _bound_dict_shaped_walk(value: Any, _depth: int) -> tuple[Any, bool]:+# Budget for the sensitive-key check in ``_bound_dict_shaped_walk``. The+# check walks the whole key (``DataSanitizer.is_sensitive_setting``+# normalises it character by character), JSON keys have no length limit,+# and the walk can visit over sixteen thousand keys (up to 11 per dict in+# up to 1,464 dicts). Each check of a str key is charged the key's length,+# at least ``_PREVIEW_KEY_CHECK_MIN_CHARGE`` (a non-str key is never+# sensitive, and its check is free), so one preview checks at most+# ``_PREVIEW_KEY_CHECK_BUDGET`` characters of keys in at most 512 checks.+# A key the remaining budget cannot cover is not checked, and its value is+# masked as if the key were sensitive (fail closed).+_PREVIEW_KEY_CHECK_BUDGET = _LOG_REDACTION_MAX_CHARS+_PREVIEW_KEY_CHECK_MIN_CHARGE = 64+++def _bound_dict_shaped_walk(+ value: Any, _depth: int, _key_budget: list[int] | None = None+) -> tuple[Any, bool]:"""Return a size-bounded copy of ``value``, safe to hand to``_log_value_repr.repr()``, plus an "entries were dropped" flag.@@ -287,9 +412,15 @@ def _bound_dict_shaped_walk(value: Any, _depth: int) -> tuple[Any, bool]:``1 + M + M**2 + M**3`` for ``M = _PREVIEW_MAX_ITEMS`` (1,464 at thecurrent limits), NOT ``M ** _PREVIEW_MAX_DEPTH``, regardless of the realstructure's size. Dict/set *keys* are returned unbounded: JSON object- keys are always strings, and a huge individual string key is already- handled cheaply by reprlib's own ``repr_str`` slicing, so there is- nothing to pre-bound there.+ keys are always strings, and rendering a huge key is bounded by+ ``_RedactingRepr``'s redaction budget and ``repr_str`` slicing. The+ sensitive-key check on each visited dict key is NOT free — it walks the+ whole key — so it draws on a per-preview budget,+ ``_PREVIEW_KEY_CHECK_BUDGET`` (``_key_budget`` holds what remains; the+ outermost call creates it). A key the remaining budget cannot cover is+ not checked and its value is masked whole, as for a sensitive key. The+ walk still descends into that masked value (with no budget, so every+ key under it is masked unchecked) to compute the items-omitted flag.Past ``_PREVIEW_MAX_DEPTH`` the walk stops and the sub-value is handedto reprlib untouched. For a **dict** that costs nothing: ``repr_dict``@@ -341,11 +472,40 @@ def _bound_dict_shaped_walk(value: Any, _depth: int) -> tuple[Any, bool]:"""if _depth >= _PREVIEW_MAX_DEPTH:return value, False+ if _key_budget is None:+ _key_budget = [_PREVIEW_KEY_CHECK_BUDGET]if isinstance(value, dict):bounded: dict[Any, Any] = {}omitted = len(value) >= _PREVIEW_MAX_ITEMSfor k, v in itertools.islice(value.items(), _PREVIEW_MAX_ITEMS):- bounded[k], child_omitted = _bound_dict_shaped_walk(v, _depth + 1)+ # A non-str key is never sensitive and costs nothing to check.+ cost = (+ max(len(k), _PREVIEW_KEY_CHECK_MIN_CHARGE)+ if isinstance(k, str)+ else 0+ )+ if cost > _key_budget[0]:+ # Not checked (see ``_PREVIEW_KEY_CHECK_BUDGET``), so+ # masked unless empty. The walk below only computes the+ # flag: with no budget, everything under it is masked too.+ if not _is_empty_log_value(v):+ bounded[k] = REDACTION_TEXT+ _, child_omitted = _bound_dict_shaped_walk(+ v, _depth + 1, [0]+ )+ omitted = omitted or child_omitted+ continue+ else:+ _key_budget[0] -= cost+ if _is_sensitive_log_key(k) and not _is_empty_log_value(v):+ # Masked whole, as the log patcher masks a sensitive+ # ``extra`` key: string redaction cannot see a label+ # that lives in the key (see ``_RedactingRepr``).+ bounded[k] = REDACTION_TEXT+ continue+ bounded[k], child_omitted = _bound_dict_shaped_walk(+ v, _depth + 1, _key_budget+ )omitted = omitted or child_omittedreturn bounded, omittedif isinstance(value, (set, frozenset)):@@ -364,7 +524,9 @@ def _bound_dict_shaped_walk(value: Any, _depth: int) -> tuple[Any, bool]:bounded = []omitted = len(value) >= _PREVIEW_MAX_ITEMSfor v in itertools.islice(value, _PREVIEW_MAX_ITEMS):- bounded_item, child_omitted = _bound_dict_shaped_walk(v, _depth + 1)+ bounded_item, child_omitted = _bound_dict_shaped_walk(+ v, _depth + 1, _key_budget+ )bounded.append(bounded_item)omitted = omitted or child_omitted# Rebuilt as a plain ``tuple``, so a namedtuple degrades to adiff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.pyindex 3d3b95473b..cc7d950844 100644--- a/src/local_deep_research/web/routers/rag.py+++ b/src/local_deep_research/web/routers/rag.py@@ -88,6 +88,7 @@ from ...database.thread_local_session import thread_cleanupfrom ...config.paths import get_library_directoryfrom ...constants import DEFAULT_SEARCH_TOOLfrom ..dependencies.json_body import json_body_error+from .notes import _log_value_preview#: Upper bound on ``page`` -- see context_overflow_api for the rationale._MAX_PAGE = 10_000@@ -626,7 +627,9 @@ def _validated_collection_id(collection_id: str) -> str:try:uuid.UUID(str(collection_id))except (ValueError, AttributeError, TypeError):- logger.warning(f"Rejected malformed collection_id: {collection_id!r}")+ logger.warning(+ f"Rejected malformed collection_id: {_log_value_preview(collection_id)}"+ )raise HTTPException(status_code=404, detail="Collection not found")return str(collection_id)@@ -773,7 +776,9 @@ async def test_embedding()logger.info(- f"Testing embedding with provider={provider}, model={model}"+ "Testing embedding with provider={}, model={}",+ _log_value_preview(provider),+ _log_value_preview(model),)# Get user's settings so provider URLs (e.g. Ollama) are resolved correctly.@@ -1072,7 +1077,7 @@ def get_index_info(collection_id = get_default_library_id(username)logger.info(- f"Getting RAG index info for collection_id: {collection_id}"+ f"Getting RAG index info for collection_id: {_log_value_preview(collection_id)}")# `with`: LocalEmbeddingManager eagerly opens httpx client pairs for@@ -1084,11 +1089,13 @@ def get_index_info(if info is None:logger.info(- f"No RAG index found for collection_id: {collection_id}"+ f"No RAG index found for collection_id: {_log_value_preview(collection_id)}")return {"success": True, "info": None, "message": "No index found"}- logger.info(f"Found RAG index for collection_id: {collection_id}")+ logger.info(+ f"Found RAG index for collection_id: {_log_value_preview(collection_id)}"+ )return {"success": True, "info": info}except Exception as e:return handle_api_error("getting index info", e)@@ -1259,7 +1266,7 @@ def index_all(collection_id = get_default_library_id(username)logger.info(- f"Starting index-all for collection_id: {collection_id}, force_reindex: {force_reindex}"+ f"Starting index-all for collection_id: {_log_value_preview(collection_id)}, force_reindex: {force_reindex}")# Create RAG service in request context before generator runs.@@ -1784,7 +1791,7 @@ def get_documents(collection_id = get_default_library_id(username)logger.info(- f"Getting documents for collection_id: {collection_id}, filter: {filter_type}, page: {page}"+ f"Getting documents for collection_id: {_log_value_preview(collection_id)}, filter: {_log_value_preview(filter_type)}, page: {page}")with get_user_db_session(username) as db_session:@@ -1812,7 +1819,11 @@ def get_documents())- logger.debug(f"Base query for collection {collection_id}: {query}")+ logger.opt(lazy=True).debug(+ "Base query for collection {}: {}",+ lambda: _log_value_preview(collection_id),+ lambda: query,+ )# Apply filters based on rag_document_status existenceif filter_type == "indexed":@@ -1824,7 +1835,7 @@ def get_documents(# Get total count before paginationtotal_count = query.count()logger.info(- f"Found {total_count} total documents for collection {collection_id} with filter {filter_type}"+ f"Found {total_count} total documents for collection {_log_value_preview(collection_id)} with filter {_log_value_preview(filter_type)}")# Apply pagination@@ -1859,7 +1870,7 @@ def get_documents(.all())logger.info(- f"rag_document_status table shows: {len(all_indexed_statuses)} documents indexed for collection {collection_id}"+ f"rag_document_status table shows: {len(all_indexed_statuses)} documents indexed for collection {_log_value_preview(collection_id)}")logger.info(@@ -4567,7 +4578,7 @@ def _start_background_index_sync(thread.start()logger.info(- f"Started background indexing task {task_id} for collection {collection_id}"+ f"Started background indexing task {task_id} for collection {_log_value_preview(collection_id)}")return {diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.pyindex 1313781261..d0ba18cd32 100644--- a/src/local_deep_research/web/routers/research.py+++ b/src/local_deep_research/web/routers/research.py@@ -45,6 +45,7 @@ from ...security import (sanitize_filename,strip_settings_snapshot,)+from ...security.log_sanitizer import redact_and_bound_for_logfrom ...utilities.type_utils import overlay_runtime_settings, to_boolfrom ...utilities.url_utils import is_safe_custom_llm_endpoint@@ -217,9 +218,9 @@ def _extract_research_params(data, settings_manager):# Raw request-body value: log it through the bounded preview so a# wide dict/list posted for it does not cost a full repr per# request (#6305, same shape as #6191). Same for ``model`` below.- logger.debug(+ logger.opt(lazy=True).debug("Using model_provider from request: {}",- _log_value_preview(model_provider),+ lambda: _log_value_preview(model_provider),)# Normalize provider to lowercase canonical form (main fix #3348) —# the uppercase comparisons below would otherwise never match the@@ -232,7 +233,9 @@ def _extract_research_params(data, settings_manager):model = settings_manager.get_setting("llm.model", None)logger.debug(f"No model in request, using database setting: {model}")else:- logger.debug("Using model from request: {}", _log_value_preview(model))+ logger.opt(lazy=True).debug(+ "Using model from request: {}", lambda: _log_value_preview(model)+ )custom_endpoint = Noneif model_provider == "openai_endpoint":@@ -728,7 +731,11 @@ def _research_not_found(research_id, message="Research not found"):``research_id`` is used only for a debug log identifying which researchwas missing; it is intentionally never echoed in the response body."""- logger.debug(f"404 for research {research_id}: {message}")+ logger.opt(lazy=True).debug(+ "404 for research {}: {}",+ lambda: _log_value_preview(research_id),+ lambda: message,+ )return JSONResponse({"status": "error", "error": message, "message": message},status_code=404,@@ -883,7 +890,9 @@ def _start_research_sync(# Debug logging to trace model parameter. The key list is request# input too (a body may carry any number of keys of any length), so# it goes through the same bounded preview as the values below.- logger.debug("Request data keys: {}", _log_value_preview(list(data.keys())))+ logger.opt(lazy=True).debug(+ "Request data keys: {}", lambda: _log_value_preview(list(data.keys()))+ )# Check if this is a news searchmetadata = data.get("metadata", {})@@ -916,7 +925,10 @@ def _start_research_sync(original_query = queryquery = query.replace("YYYY-MM-DD", current_date)logger.info(- f"Replaced date placeholder in query: {original_query[:100]}... -> {query[:100]}..."+ "Replaced date placeholder in query: {} -> {}",+ # (#6938: redacted before it is cut.)+ redact_and_bound_for_log(original_query, 100),+ redact_and_bound_for_log(query, 100),)logger.info(f"Using date: {current_date}")@@ -1000,10 +1012,10 @@ def _start_research_sync(# eagerly: an f-string builds the full repr on every request# regardless of log level. The bounded preview keeps the cost and# the logged size capped (#6305, same shape as #6191).- logger.debug(+ logger.opt(lazy=True).debug("Extracted model value: {} (type: {})",- _log_value_preview(model),- type(model).__name__,+ lambda: _log_value_preview(model),+ lambda: type(model).__name__,)# Log the selections for troubleshooting. These two lines are emitted@@ -2533,7 +2545,8 @@ async def save_raw_config(blocked_keys = find_blocked_keys(parsed_config)if blocked_keys:logger.warning(- f"Security: Blocked attempt to write config with dangerous keys: {blocked_keys}"+ "Security: Blocked attempt to write config with dangerous keys: {}",+ _log_value_preview(blocked_keys),)return JSONResponse({diff --git a/src/local_deep_research/web/routers/settings.py b/src/local_deep_research/web/routers/settings.pyindex 06f64358fb..7f3eb3a357 100644--- a/src/local_deep_research/web/routers/settings.py+++ b/src/local_deep_research/web/routers/settings.py@@ -51,6 +51,7 @@ from ..dependencies.rate_limit import ()from ..dependencies.threadpool import run_db_syncfrom ..template_config import templates+from .notes import _log_value_previewimport jsonimport math@@ -1936,7 +1937,9 @@ def _save_all_settings_sync(form_data: dict, username: str):value = Nonelogger.warning(- f"Corrected corrupted value for {key}: {value}"+ "Corrected corrupted value for {}: {}",+ _log_value_preview(key),+ value,)# NOTE: No JSON pre-parsing is done here. After the# corruption replacement above, values are Python dicts@@ -2052,8 +2055,8 @@ def _save_all_settings_sync(form_data: dict, username: str):if not _is_allowed_new_setting_key(key):logger.warning("Security: Rejected setting outside allowed "- "namespaces: {!r} (user={!r})",- key,+ "namespaces: {} (user={!r})",+ _log_value_preview(key),username,)validation_errors.append(@@ -2073,8 +2076,8 @@ def _save_all_settings_sync(form_data: dict, username: str):if _embeds_sentinel_on_create(key, None, value):logger.warning("Rejected redaction-sentinel value for new key "- "{!r} via save_all_settings (user={!r})",- key,+ "{} via save_all_settings (user={!r})",+ _log_value_preview(key),username,)validation_errors.append(@@ -2445,7 +2448,9 @@ def _save_settings_sync(form_data: dict, username: str) -> dict:if _policy_err is not None:logger.warning("Rejected settings POST: {}",- _policy_err.get("error", "Invalid policy setting"),+ _log_value_preview(+ _policy_err.get("error", "Invalid policy setting")+ ),)return {"ok": False,@@ -2477,8 +2482,8 @@ def _save_settings_sync(form_data: dict, username: str) -> dict:if db_setting is None and not _is_allowed_new_setting_key(key):logger.warning("Security: Rejected setting outside allowed "- "namespaces: {!r} (user={!r})",- key,+ "namespaces: {} (user={!r})",+ _log_value_preview(key),username,)rejected_count += 1@@ -2498,8 +2503,8 @@ def _save_settings_sync(form_data: dict, username: str) -> dict:):logger.warning("Rejected redaction-sentinel value for new key "- "{!r} via save_settings (user={!r})",- key,+ "{} via save_settings (user={!r})",+ _log_value_preview(key),username,)sentinel_rejected_ui_elements.append(None)@@ -2651,11 +2656,15 @@ def _save_settings_sync(form_data: dict, username: str) -> dict:if not settings_manager.set_setting(key, value, commit=False):failed_count += 1- logger.warning(f"Failed to save setting {key}")+ logger.warning(+ "Failed to save setting {}", _log_value_preview(key)+ )else:changed_settings.append(key)except Exception:- logger.exception(f"Error saving setting {key}")+ logger.exception(+ "Error saving setting {}", _log_value_preview(key)+ )failed_count += 1if rejected_count:@@ -4267,7 +4276,10 @@ def api_reset_engine_rate_limiting(return {"message": f"Rate limiting data reset for {engine_type}"}except Exception:- logger.exception(f"Error resetting rate limiting for {engine_type}")+ logger.exception(+ "Error resetting rate limiting for {}",+ _log_value_preview(engine_type),+ )return JSONResponse({"error": "An internal error occurred"}, status_code=500)@@ -4374,7 +4386,9 @@ def get_bulk_settings("exists": value is not None,}except Exception:- logger.warning(f"Error getting setting {key}")+ logger.warning(+ "Error getting setting {}", _log_value_preview(key)+ )result[key] = {"value": None,"exists": False,@@ -4819,7 +4833,7 @@ def api_get_db_setting({"error": f"Setting not found: {key}"}, status_code=404)except Exception:- logger.exception(f"Error getting setting {key}")+ logger.exception("Error getting setting {}", _log_value_preview(key))return JSONResponse({"error": "Failed to retrieve settings"}, status_code=500)@@ -5152,8 +5166,8 @@ def _api_update_setting_sync(data, key, username):if not _is_allowed_new_setting_key(key):logger.warning("Security: Rejected setting outside allowed "- "namespaces: {!r} (user={!r})",- key,+ "namespaces: {} (user={!r})",+ _log_value_preview(key),username,)return JSONResponse(@@ -5208,9 +5222,9 @@ def _api_update_setting_sync(data, key, username):)if _embeds_sentinel_on_create(key, _create_ui, _create_guard_value):logger.warning(- "Rejected redaction-sentinel value for {!r} via "+ "Rejected redaction-sentinel value for {} via ""api_update_setting create (user={!r})",- key,+ _log_value_preview(key),username,)return JSONResponse(@@ -5295,7 +5309,7 @@ def _api_update_setting_sync(data, key, username):status_code=500,)except Exception:- logger.exception(f"Error updating setting {key}")+ logger.exception("Error updating setting {}", _log_value_preview(key))return JSONResponse({"error": "Failed to update setting"}, status_code=500)@@ -5367,7 +5381,7 @@ def api_delete_setting({"error": f"Failed to delete setting {key}"}, status_code=500)except Exception:- logger.exception(f"Error deleting setting {key}")+ logger.exception("Error deleting setting {}", _log_value_preview(key))return JSONResponse({"error": "Failed to delete setting"}, status_code=500)diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 6edd3e24bb..fbb2a3a7a6 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -20,6 +20,7 @@ from ...settings.manager import (# Output directory for research resultsfrom ...config.paths import get_research_outputs_directoryfrom ...config.search_config import get_search+from ...security.log_sanitizer import redact_and_bound_for_logfrom ...constants import ResearchStatusfrom ...database.models import ResearchHistory, ResearchStrategyfrom ...database.session_context import get_user_db_session@@ -430,10 +431,10 @@ def save_research_strategy(research_id, strategy_name, *, username):try:from ..routers.notes import _log_value_preview- logger.debug(+ logger.opt(lazy=True).debug("save_research_strategy called with research_id={}, strategy_name={}",- research_id,- _log_value_preview(strategy_name),+ lambda: research_id,+ lambda: _log_value_preview(strategy_name),)with get_user_db_session(username) as session:# Check if a strategy already exists for this research@@ -1078,8 +1079,17 @@ def run_research_process(research_id, query, mode, **kwargs):)return+ # (#6938: the query reaches this thread unvalidated from the+ # request body, so it previews instead of f-stringing — same+ # conversion as the parameter lines below. Imported at call time+ # for the same reason as in save_research_strategy above.)+ from ..routers.notes import _log_value_preview+ from ...security.ssrf_validator import redact_url_for_log+logger.info(- f"Starting research process for ID {research_id}, query: {query}"+ "Starting research process for ID {}, query: {}",+ research_id,+ _log_value_preview(query),)# Extract key parameters@@ -1108,15 +1118,32 @@ def run_research_process(research_id, query, mode, **kwargs):log_settings(settings_snapshot, "Settings snapshot received in thread")# Strategy should already be saved in the database before thread starts- logger.info(f"Research strategy: {strategy}")+ # (#6938: thread-side parameters reach here unvalidated from the+ # request body, so both lines preview them instead of f-stringing —+ # same conversion #6756 made on the save path; the helper is+ # imported at function entry above.)+ logger.info("Research strategy: {}", _log_value_preview(strategy))# Log all parameters for debugginglogger.info(- f"Research parameters: provider={model_provider}, model={model}, "- f"search_engine={search_engine}, max_results={max_results}, "- f"time_period={time_period}, iterations={iterations}, "- f"questions_per_iteration={questions_per_iteration}, "- f"custom_endpoint={custom_endpoint}, strategy={strategy}"+ "Research parameters: provider={}, model={}, "+ "search_engine={}, max_results={}, "+ "time_period={}, iterations={}, "+ "questions_per_iteration={}, custom_endpoint={}, strategy={}",+ _log_value_preview(model_provider),+ _log_value_preview(model),+ _log_value_preview(search_engine),+ _log_value_preview(max_results),+ _log_value_preview(time_period),+ _log_value_preview(iterations),+ _log_value_preview(questions_per_iteration),+ # The endpoint URL can carry a credential (``?key=``, userinfo),+ # so log only its scheme://host:port; the preview's cut must+ # never run on the raw URL.+ redact_url_for_log(custom_endpoint)+ if isinstance(custom_endpoint, str)+ else _log_value_preview(custom_endpoint),+ _log_value_preview(strategy),)# Reapply current operator environment policy at actual dispatch time.@@ -1585,8 +1612,14 @@ def run_research_process(research_id, query, mode, **kwargs):use_llm = Noneif model or search_engine or model_provider:# Log that we're overriding system settings+ # (#6938: same request-derived values as the parameter lines+ # above, so they preview instead of f-stringing.)logger.info(- f"Overriding system settings with: provider={model_provider}, model={model}, search_engine={search_engine}"+ "Overriding system settings with: provider={}, "+ "model={}, search_engine={}",+ _log_value_preview(model_provider),+ _log_value_preview(model),+ _log_value_preview(search_engine),)# Override LLM if model or model_provider specified@@ -1618,11 +1651,15 @@ def run_research_process(research_id, query, mode, **kwargs):)logger.info(- f"Successfully set LLM to: provider={model_provider}, model={model}"+ "Successfully set LLM to: provider={}, model={}",+ _log_value_preview(model_provider),+ _log_value_preview(model),)except Exception as e:logger.exception(- f"Error setting LLM provider={model_provider}, model={model}"+ "Error setting LLM provider={}, model={}",+ _log_value_preview(model_provider),+ _log_value_preview(model),)error_msg = str(e)# Surface configuration errors to user instead of silently continuing@@ -1685,11 +1722,13 @@ def run_research_process(research_id, query, mode, **kwargs):settings_snapshot=settings_snapshot,)logger.info(- f"Successfully created search engine: {search_engine}"+ "Successfully created search engine: {}",+ _log_value_preview(search_engine),)except Exception as e:logger.exception(- f"Error creating search engine {search_engine}"+ "Error creating search engine {}",+ _log_value_preview(search_engine),)error_msg = str(e)# Surface configuration errors to user instead of silently continuing@@ -1706,9 +1745,14 @@ def run_research_process(research_id, query, mode, **kwargs):keyword in error_msg.lower()for keyword in config_error_keywords):- # This is a configuration error the user can fix+ # This is a configuration error the user can fix.+ # (#6938: the engine name is request-derived, so the+ # raised message carries its bounded preview — the+ # ValueError type and the keyword gate above it are+ # unchanged.)raise ValueError(- f"Search Engine Configuration Error ({search_engine}): {error_msg}"+ f"Search Engine Configuration Error "+ f"({_log_value_preview(search_engine)}): {error_msg}") from e# For other errors, re-raise to avoid silent failuresraise@@ -1909,7 +1953,8 @@ def run_research_process(research_id, query, mode, **kwargs):raw_formatted_findings, str) and raw_formatted_findings.startswith("Error:"):logger.error(- f"Detected error in formatted findings: {raw_formatted_findings[:100]}..."+ "Detected error in formatted findings: {}",+ redact_and_bound_for_log(raw_formatted_findings, 100),)# Determine error type for better user feedback@@ -2390,7 +2435,9 @@ def run_research_process(research_id, query, mode, **kwargs):# Generate headlinelogger.info(- f"Generating headline for query: {query[:100]}"+ "Generating headline for query: {}",+ # (#6938: redacted before it is cut.)+ redact_and_bound_for_log(query, 100),)headline = generate_headline(query,@@ -2400,8 +2447,13 @@ def run_research_process(research_id, query, mode, **kwargs):metadata["generated_headline"] = headline# Generate topics+ # (#6938: the category comes from the+ # request body's metadata.)logger.info(- f"Generating topics with category: {metadata.get('category', 'News')}"+ "Generating topics with category: {}",+ _log_value_preview(+ metadata.get("category", "News")+ ),)topics = generate_topics(query=query,@@ -3402,9 +3454,13 @@ def cancel_research(research_id, username):is not None)if not owns_research:+ # (#6938: research_id is the raw path parameter on this+ # not-found branch.)+ from ..routers.notes import _log_value_preview+logger.info(- f"Research {research_id} not found for this user; "- "refusing to cancel."+ "Research {} not found for this user; refusing to cancel.",+ _log_value_preview(research_id),)return False@@ -3487,7 +3543,10 @@ def cancel_research(research_id, username):return Trueexcept Exception:+ from ..routers.notes import _log_value_preview+logger.exception(- f"Unexpected error in cancel_research for {research_id}"+ "Unexpected error in cancel_research for {}",+ _log_value_preview(research_id),)return Falsediff --git a/src/local_deep_research/web/services/socketio_asgi.py b/src/local_deep_research/web/services/socketio_asgi.pyindex 97514d8a19..42caf272f5 100644--- a/src/local_deep_research/web/services/socketio_asgi.py+++ b/src/local_deep_research/web/services/socketio_asgi.py@@ -17,6 +17,7 @@ Usage:import asyncioimport contextvars+import hashlibfrom typing import Anyimport socketio@@ -28,6 +29,7 @@ from ..research_state import get_active_research_snapshot# Determine WebSocket CORS policy from env varfrom ...settings.env_registry import get_env_setting+from ...security.log_sanitizer import redact_and_bound_for_logdef _resolve_socketio_cors(env_value: str | None) -> str | list[str] | None:@@ -110,6 +112,27 @@ def log_socketio_cors_policy() -> None:_log_socketio_cors_policy(_socketio_cors, _ws_origins_env)+def _research_id_preview(research_id: Any) -> str:+ """Bounded preview of a client-sent ``research_id`` for log lines.++ (#6938: the Socket.IO payload's id is any JSON value of up to the+ engine.io buffer size, logged on the rejection paths before any+ ownership match. Imported at call time so this module never imports+ the routers package at import time.)+ """+ from ..routers.notes import _log_value_preview++ return _log_value_preview(research_id)+++# What engine.io's ``_log_error_once`` receives for a repeat it will not+# emit (see ``_install_origin_rejection_logging``).+_ENGINEIO_SUPPRESSED_TEXT = "Rejected (repeat; text not rendered)."+# ``logging.INFO``: engine.io logs through the standard library, whose+# level numbers are fixed; this module itself logs only through loguru.+_STDLIB_INFO_LEVEL = 20++def _install_origin_rejection_logging(sio: "socketio.AsyncServer") -> bool:"""Re-emit engine.io's silenced WebSocket origin rejections via loguru.@@ -140,19 +163,69 @@ def _install_origin_rejection_logging(sio: "socketio.AsyncServer") -> bool:cap = 100def _log_error_once(message, message_key):- if (- message_key == "bad-origin"- and len(warned) < cap- and message not in warned- ):- warned.add(message)- logger.warning(- f"Socket.IO rejected a WebSocket handshake: {message} Set "- "LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS to this origin if it is "- "your front-end; behind a TLS-terminating proxy, also forward "- "X-Forwarded-Proto so the same-origin check sees https."+ # (#6938: the message embeds the client's Origin header, which+ # has no length limit on the polling transport, so this module's+ # warning and the text handed on to engine.io's own logger are the+ # redacted, bounded form. Redaction still costs a few ms on+ # adversarial input (``redact_and_bound_for_log`` scans up to 1,200+ # characters for a 300-character result) and this path is pre-auth+ # and not rate limited, so it runs only when that text is actually+ # logged: for each of the first ``cap`` distinct messages, and when+ # engine.io's logger will emit the line (the first time a key is+ # seen, unless its level was lowered). The dedup key is a fixed-size SHA-256+ # digest of the raw message, so deciding whether to warn needs no+ # redaction; once the cap is reached it is not computed at all.)+ is_text = isinstance(message, str)+ redacted: list[str] = []++ def _bounded() -> str:+ if not redacted:+ redacted.append(+ redact_and_bound_for_log(message, 300)+ if is_text+ else type(message).__name__+ )+ return redacted[0]++ if message_key == "bad-origin" and len(warned) < cap:+ dedup_key = (+ hashlib.sha256(+ message.encode("utf-8", "surrogatepass")+ ).hexdigest()+ if is_text+ else type(message).__name__)- return original(message, message_key)+ if dedup_key not in warned:+ warned.add(dedup_key)+ logger.warning(+ f"Socket.IO rejected a WebSocket handshake: {_bounded()} "+ "Set LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS to this origin "+ "if it is your front-end; behind a TLS-terminating proxy, "+ "also forward X-Forwarded-Proto so the same-origin check "+ "sees https."+ )+ if not is_text:+ return original(message, message_key)+ if _engineio_will_log(message_key):+ return original(_bounded(), message_key)+ # engine.io drops this line (a repeat key, logged at INFO under its+ # ERROR-level logger); hand it a constant so its bookkeeping runs+ # unchanged without paying for a redaction nobody reads.+ return original(_ENGINEIO_SUPPRESSED_TEXT, message_key)++ def _engineio_will_log(message_key) -> bool:+ """Whether engine.io's ``_log_error_once`` emits for this key.++ It logs at ERROR the first time a key is seen and at INFO after+ that (``engineio.base_server``). Anything this cannot determine+ counts as "will log", so the redacted text is passed on.+ """+ try:+ if message_key not in eio.log_message_keys:+ return True+ return bool(eio.logger.isEnabledFor(_STDLIB_INFO_LEVEL))+ except Exception:+ return Trueeio._log_error_once = _log_error_oncereturn True@@ -600,7 +673,9 @@ async def _user_owns_research(username: str, research_id: str) -> bool:return await run_db_sync(_owns_research_sync, username, research_id)except Exception:logger.exception(- f"Ownership check failed for user={username} rid={research_id}"+ "Ownership check failed for user={} rid={}",+ username,+ _research_id_preview(research_id),)return False@@ -657,7 +732,9 @@ async def on_subscribe(sid, data):if not username:logger.warning(- f"Rejected subscribe from unauthenticated sid {sid} for {research_id}"+ "Rejected subscribe from unauthenticated sid {} for {}",+ sid,+ _research_id_preview(research_id),)await sio.emit("subscribe_error",@@ -712,7 +789,9 @@ async def on_subscribe(sid, data):if not owns:logger.warning(- f"Rejected subscribe: user {username} does not own research {research_id}"+ "Rejected subscribe: user {} does not own research {}",+ username,+ _research_id_preview(research_id),)await sio.emit("subscribe_error",@@ -778,7 +857,9 @@ async def on_unsubscribe(sid, data):if not username:logger.info(- f"Rejected unsubscribe from unauthenticated sid {sid} for {research_id}"+ "Rejected unsubscribe from unauthenticated sid {} for {}",+ sid,+ _research_id_preview(research_id),)return@@ -808,7 +889,9 @@ async def on_unsubscribe(sid, data):if not await _user_owns_research(username, research_id):logger.info(- f"Rejected unsubscribe from sid {sid}: user does not own research {research_id}"+ "Rejected unsubscribe from sid {}: user does not own research {}",+ sid,+ _research_id_preview(research_id),)returndiff --git a/tests/web/routers/test_research_model_log_preview_bound.py b/tests/web/routers/test_research_model_log_preview_bound.pyindex 3a94706af3..6e9f3f43f9 100644--- a/tests/web/routers/test_research_model_log_preview_bound.py+++ b/tests/web/routers/test_research_model_log_preview_bound.py@@ -46,13 +46,19 @@ field the function logs, so (W1) at any one of those sites, not just thenamed ones, fails the probe and not only a source guard."""+import asyncioimport inspectimport jsonfrom contextlib import contextmanager-from unittest.mock import MagicMock, patch+from unittest.mock import AsyncMock, MagicMock, patchimport pytest+from local_deep_research.followup_research import (+ service as followup_service_module,+)+from local_deep_research.web.routers import api as api_module+from local_deep_research.web.routers import followup as followup_modulefrom local_deep_research.web.routers import notes as notes_modulefrom local_deep_research.web.routers import research as research_modulefrom local_deep_research.web.routers import settings as settings_module@@ -461,3 +467,1576 @@ class TestSettingsCheckboxLogSite:"any replacement still logs only key/type/length, via loguru ""brace args (#6201, #6305)")+++# The #6938 remainder: the sites #6756's review named as "a natural+# follow-up PR" (the thread-side ``run_research_process`` strategy and+# parameter lines) plus the ones it marked optional (the api router's+# SSRF refusal, the followup router's params/query lines, and the+# config-write ``blocked_keys`` warning), and — once those landed — the+# same-function siblings that would have kept the #6938 changelog claim+# false: ``run_research_process``'s query-entry, override, LLM and+# search-engine lines (including the ``Search Engine Configuration+# Error`` raise) and the followup service's ``Prepared follow-up+# research`` question line.+_EAGER_REMAINDER_LOGS = {+ "run_research_process": (+ 'f"Starting research process',+ 'f"Research strategy',+ 'f"Research parameters',+ 'f"Overriding system settings',+ 'f"Successfully set LLM',+ 'f"Error setting LLM',+ 'f"Successfully created search engine',+ 'f"Error creating search engine',+ "Search Engine Configuration Error ({search_engine})",+ ),+ "api_add_resource": ('f"SSRF protection: Rejected URL',),+ "_start_followup_sync": (+ 'f"Research params keys',+ 'f"Query value',+ ),+ "save_raw_config": ('f"Security: Blocked attempt to write config',),+ "perform_followup": (+ 'f"Prepared follow-up research',+ 'f"Parent research not found',+ ),+ # The not-found paths, where the parent id is still the raw body+ # value (both followup routes reach them before any other check).+ "load_parent_research": ('f"Parent research not found',),+ "prepare_followup": ('f"Parent research {parent_id} not found',),+}+_BOUNDED_REMAINDER_CALLS = {+ "run_research_process": (+ "_log_value_preview(query)",+ "_log_value_preview(strategy)",+ "_log_value_preview(model_provider)",+ "_log_value_preview(model)",+ "_log_value_preview(search_engine)",+ ),+ "api_add_resource": (+ "redact_url_for_log(url)",+ "_log_value_preview(redact_url_for_log(url))",+ ),+ "_start_followup_sync": (+ "_log_value_preview(params_keys)",+ "_log_value_preview(query_value)",+ ),+ "save_raw_config": ("_log_value_preview(blocked_keys)",),+ "perform_followup": (+ "_log_value_preview(request.question)",+ "_log_value_preview(request.parent_research_id)",+ ),+ "load_parent_research": ("_log_value_preview(parent_research_id)",),+ "prepare_followup": ("_log_value_preview(parent_id)",),+}+# The callables the deferred-site source guards inspect (the followup+# site is a service method, so entries are callables, not modules).+_REMAINDER_SOURCES = {+ "run_research_process": research_service_module.run_research_process,+ "api_add_resource": api_module.api_add_resource,+ "_start_followup_sync": followup_module._start_followup_sync,+ "save_raw_config": research_module.save_raw_config,+ "perform_followup": (+ followup_service_module.FollowUpResearchService.perform_followup+ ),+ "load_parent_research": (+ followup_service_module.FollowUpResearchService.load_parent_research+ ),+ "prepare_followup": followup_module.prepare_followup,+}+++class _StopAfterParameterLogs(BaseException):+ """Escapes ``run_research_process``'s ``except Exception`` handler.++ Raised by the patched ``apply_environment_overrides_to_snapshot``+ (the first call after the two parameter log lines) so the probe+ proves the lines ran without driving the real research pipeline.+ ``BaseException`` so the function's broad ``except Exception`` /+ ``finally`` cleanup paths do not swallow it.+ """+++def _json_request(payload):+ """A ``Request`` double whose ``json()`` resolves to ``payload``."""+ request = MagicMock()+ request.json = AsyncMock(return_value=payload)+ return request+++def _bounded_line(caplog_text, prefix):+ """The single captured log line starting with ``prefix``."""+ return next(line for line in caplog_text.splitlines() if prefix in line)+++class TestDeferredRequestValueLogSites:+ """#6938: the remaining request-derived log sites the #6756 review+ deferred. Same policy as above — the probes feed a wide value to+ each site and fail if the emitted line (or the repr work behind it)+ is unbounded again."""++ @pytest.mark.parametrize("function_name", sorted(_EAGER_REMAINDER_LOGS))+ def test_body_values_are_logged_through_the_bounded_preview(+ self, function_name+ ):+ """Catches (W1) at each deferred call site: the wiring itself."""+ source = inspect.getsource(_REMAINDER_SOURCES[function_name])+ for eager in _EAGER_REMAINDER_LOGS[function_name]:+ assert eager not in source, (+ f"{function_name} interpolates a request-derived value "+ f"into an eager f-string again ({eager}...) (#6938)"+ )+ for bounded in _BOUNDED_REMAINDER_CALLS[function_name]:+ assert bounded in source, (+ f"{function_name} no longer routes a request-derived "+ f"value through the bounded log preview "+ f"({bounded}) (#6938)"+ )++ def test_routers_bind_the_audited_notes_helper(self):+ """Catches (W2) via identity for the two newly-bound routers."""+ assert api_module._log_value_preview is notes_module._log_value_preview+ assert (+ followup_module._log_value_preview+ is notes_module._log_value_preview+ )++ def test_add_resource_rejected_url_log_is_bounded(self, loguru_caplog):+ """A rejected non-string URL never reaches a log formatter or repr."""+ wide = _wide()+ request = _json_request({"title": "t", "url": wide})++ CountingValue.reprs = 0+ with (+ loguru_caplog.at_level("WARNING"),+ patch(+ "local_deep_research.security.ssrf_validator.validate_url",+ return_value=False,+ ),+ ):+ response = asyncio.run(+ api_module.api_add_resource(request, "research-1", "testuser")+ )++ assert response.status_code == 400+ line = _bounded_line(+ loguru_caplog.text, "SSRF protection: Rejected URL"+ )+ assert len(line) < 500+ assert line.endswith("(non-string)")+ assert CountingValue.reprs == 0++ def test_add_resource_rejected_url_log_hides_credentials_and_bounds_host(+ self, loguru_caplog+ ):+ secret = "credential-do-not-log"+ url = (+ f"https://alice:{secret}@{'a' * 50_000}.example/private"+ f"?token={secret}"+ )+ request = _json_request({"title": "t", "url": url})++ with (+ loguru_caplog.at_level("WARNING"),+ patch(+ "local_deep_research.security.ssrf_validator.validate_url",+ return_value=False,+ ),+ ):+ response = asyncio.run(+ api_module.api_add_resource(request, "research-1", "testuser")+ )++ assert response.status_code == 400+ line = _bounded_line(+ loguru_caplog.text, "SSRF protection: Rejected URL"+ )+ assert len(line) < 500+ assert secret not in line+ assert "alice" not in line+ assert "/private" not in line++ def test_model_pricing_failure_does_not_log_exception_text(+ self, loguru_caplog_full+ ):+ from local_deep_research.web.routers.metrics import api_model_pricing++ secret = "pricing-exception-secret"+ model = f"https://alice:{secret}@models.example/private?token={secret}"+ calculator = (+ "local_deep_research.metrics.pricing.cost_calculator.CostCalculator"+ )+ with (+ loguru_caplog_full.at_level("ERROR"),+ patch(calculator, side_effect=RuntimeError(secret)),+ ):+ response = api_model_pricing(MagicMock(), model, username="alice")++ assert response.status_code == 500+ assert "Error getting pricing for model" in loguru_caplog_full.text+ assert "RuntimeError" in loguru_caplog_full.text+ assert secret not in loguru_caplog_full.text++ def test_start_followup_sync_params_logs_are_bounded(self, loguru_caplog):+ """Catches (W1)/(W2) at the followup params/query lines, through+ the real call.++ ``perform_followup`` is patched to return a 50,001-entry dict+ (wide keys plus a wide ``query`` value), so both the keys line+ and the query line interpolate wide data. The settings snapshot+ reports an empty ``llm.model`` so the function returns its 400+ right after the four log lines, before spawning anything.+ Measured: 22 element reprs with the bounded preview, 100,000+ with the eager f-strings.+ """+ research_params = {CountingValue(i): None for i in range(50_000)}+ research_params["query"] = _wide()+ service = MagicMock()+ service.load_parent_research.return_value = object()+ service.perform_followup.return_value = research_params+ settings_manager = MagicMock()+ settings_manager.get_all_settings.return_value = {+ "llm.model": {"value": ""}+ }++ @contextmanager+ def _session_ctx(*args, **kwargs):+ yield MagicMock()++ CountingValue.reprs = 0+ with (+ loguru_caplog.at_level("INFO"),+ patch.object(+ followup_module, "FollowUpResearchService", return_value=service+ ),+ patch.object(+ followup_module,+ "resolve_user_password",+ return_value=(None, False),+ ),+ patch(+ "local_deep_research.settings.manager.SettingsManager",+ return_value=settings_manager,+ ),+ patch(+ "local_deep_research.database.session_context"+ ".get_user_db_session",+ _session_ctx,+ ),+ ):+ response = followup_module._start_followup_sync(+ {"parent_research_id": "r-1", "question": "q"}, "testuser"+ )++ assert response.status_code == 400+ assert (+ len(_bounded_line(loguru_caplog.text, "Research params keys")) < 500+ )+ assert len(_bounded_line(loguru_caplog.text, "Query value")) < 500+ assert CountingValue.reprs < 100++ def test_save_raw_config_blocked_keys_log_is_bounded(self, loguru_caplog):+ """Catches (W1)/(W2) at the blocked-keys warning, through the+ real call.++ The raw TOML carries 50,000 blocked keys (every key matches the+ ``module`` pattern), so ``find_blocked_keys`` returns a 50,000+ path list and the warning line interpolates all of it. No DB or+ file access happens before the 403 return.+ """+ raw_config = "\n".join(f"module_path_{i} = 1" for i in range(50_000))+ request = _json_request({"raw_config": raw_config})++ with loguru_caplog.at_level("WARNING"):+ response = asyncio.run(+ research_module.save_raw_config(request, "testuser")+ )++ assert response.status_code == 403+ body = json.loads(response.body)+ assert len(body["blocked_keys"]) == 50_000+ line = _bounded_line(+ loguru_caplog.text,+ "Security: Blocked attempt to write config",+ )+ assert len(line) < 500++ def test_run_research_process_parameter_logs_are_bounded(+ self, loguru_caplog+ ):+ """Catches (W1)/(W2) at the thread-side strategy and parameter+ lines, through the real call.++ Every body-derived parameter the two INFO lines interpolate is+ a 50,000-entry dict. ``apply_environment_overrides_to_snapshot``+ (the first call after the lines) raises ``_StopAfterParameterLogs``,+ a ``BaseException`` the function's ``except Exception`` handler+ cannot swallow, so the probe stops before the research pipeline.+ The query is a short string so the count isolates the two+ parameter lines (the query's own entry line, bounded since the+ #6938 sibling fix, has its own probe below). Measured: 20+ element reprs with the bounded preview (10 per line), 500,000+ with the eager f-strings.+ """+ wide = _wide()+ CountingValue.reprs = 0+ with (+ loguru_caplog.at_level("INFO"),+ patch.object(research_service_module, "set_search_context"),+ patch.object(+ research_service_module,+ "apply_environment_overrides_to_snapshot",+ side_effect=_StopAfterParameterLogs,+ ),+ patch.object(research_service_module, "_sio_emit"),+ patch.object(research_service_module, "cleanup_research_resources"),+ patch(+ "local_deep_research.web.research_state"+ ".is_termination_requested",+ return_value=False,+ ),+ patch("local_deep_research.settings.logger.log_settings"),+ ):+ with pytest.raises(_StopAfterParameterLogs):+ research_service_module.run_research_process(+ "research-1",+ "q",+ "quick",+ username="testuser",+ model_provider=wide,+ model=wide,+ search_engine=wide,+ max_results=wide,+ time_period=wide,+ iterations=wide,+ questions_per_iteration=wide,+ custom_endpoint=wide,+ strategy=wide,+ )++ assert (+ len(_bounded_line(loguru_caplog.text, "Research strategy:")) < 500+ )+ assert (+ len(_bounded_line(loguru_caplog.text, "Research parameters:"))+ < 2000+ )+ assert CountingValue.reprs < 200++ def test_run_research_process_entry_and_override_logs_are_bounded(+ self, loguru_caplog+ ):+ """Catches (W1)/(W2) at the query-entry line and the+ same-function ``Overriding system settings`` sibling that kept+ the #6938 changelog claim false, through the real call.++ The query is a 100,000-char string and every override value+ (``model_provider``, ``model``, ``search_engine``) a+ 50,000-entry dict; ``get_llm`` — the first call after the+ ``Overriding`` line — raises ``_StopAfterParameterLogs`` so the+ probe stops before the LLM/search pipeline. Measured: 60+ element reprs with the bounded preview (10 per wide value per+ line), 300,000+ with the eager f-strings; both emitted lines+ stay under a few hundred chars instead of growing with the+ body.+ """+ wide = _wide()+ CountingValue.reprs = 0+ with (+ loguru_caplog.at_level("INFO"),+ patch.object(research_service_module, "set_search_context"),+ patch.object(+ research_service_module,+ "apply_environment_overrides_to_snapshot",+ lambda snapshot: snapshot,+ ),+ patch.object(+ research_service_module,+ "get_llm",+ side_effect=_StopAfterParameterLogs,+ ),+ patch.object(research_service_module, "_sio_emit"),+ patch.object(research_service_module, "cleanup_research_resources"),+ patch(+ "local_deep_research.web.research_state"+ ".is_termination_requested",+ return_value=False,+ ),+ patch("local_deep_research.settings.logger.log_settings"),+ patch(+ "local_deep_research.config.thread_settings"+ ".set_settings_context",+ ),+ patch("local_deep_research.security.set_active_context"),+ patch(+ "local_deep_research.security.egress.policy"+ ".build_run_egress_context",+ ),+ patch(+ "local_deep_research.security.egress.run_classification"+ ".audit_run_from_snapshot",+ ),+ ):+ with pytest.raises(_StopAfterParameterLogs):+ research_service_module.run_research_process(+ "research-1",+ "q" * 100_000,+ "quick",+ username="testuser",+ model_provider=wide,+ model=wide,+ search_engine=wide,+ )++ assert (+ len(_bounded_line(loguru_caplog.text, "Starting research process"))+ < 500+ )+ assert (+ len(_bounded_line(loguru_caplog.text, "Overriding system settings"))+ < 500+ )+ assert CountingValue.reprs < 200++ def test_followup_service_question_log_is_bounded(self, loguru_caplog):+ """Catches (W1)/(W2) at the followup service's ``Prepared+ follow-up research`` question line, through the real call.++ The router path hands this service the raw request ``question``+ right after its own bounded params/query lines, and the service+ f-stringed the question (and parent id) in full.+ ``prepare_research_context`` is patched to a truthy context so+ the call reaches the log line with no DB access; the returned+ params must still carry the raw values unchanged. Both are+ 100,000-char strings, so the eager f-string emitted them in+ full; with the preview the line stays under a few hundred+ chars.+ """+ service = followup_service_module.FollowUpResearchService(+ username="testuser"+ )+ request = followup_service_module.FollowUpRequest(+ parent_research_id="p" * 100_000,+ question="q" * 100_000,+ )++ with (+ loguru_caplog.at_level("INFO"),+ patch.object(+ service,+ "prepare_research_context",+ return_value={"parent_research_id": "parent-1"},+ ),+ ):+ params = service.perform_followup(request)++ assert params["query"] == request.question+ assert params["parent_research_id"] == request.parent_research_id+ line = _bounded_line(loguru_caplog.text, "Prepared follow-up research")+ assert len(line) < 500+ assert "q" * 150 not in line+ assert "p" * 150 not in line+++class TestRawParentIdAndUrlLogSites:+ """#6938 follow-through: the lines that log the RAW request value on+ the paths an attacker actually reaches, which run before the bounded+ lines above.++ * the follow-up parent id on its not-found paths — every+ ``/api/followup/prepare`` and ``/start`` call reaches+ ``load_parent_research`` with the body's unchecked+ ``parent_research_id``, and ``/prepare`` logs it a second time;+ * the scheme / host of a request-supplied URL inside+ ``validate_url`` (the add-resource route calls it with the body+ URL before its own bounded refusal line) and in+ ``redact_url_for_log``, whose ``scheme://host`` form was+ credential-free but not length-bounded.++ Each probe feeds a 100,000-char value and asserts the emitted line+ stays short. On the pre-fix code every one of these lines carried+ the full value.+ """++ HUGE = 100_000++ @staticmethod+ def _not_found_session():+ """``get_user_db_session`` double whose lookup finds no row."""++ @contextmanager+ def _session_ctx(*args, **kwargs):+ session = MagicMock()+ session.query.return_value.filter_by.return_value.first.return_value = None+ yield session++ return _session_ctx++ def test_load_parent_research_not_found_log_is_bounded(self, loguru_caplog):+ parent_id = "p" * self.HUGE+ service = followup_service_module.FollowUpResearchService(+ username="testuser"+ )+ with (+ loguru_caplog.at_level("WARNING"),+ patch.object(+ followup_service_module,+ "get_user_db_session",+ self._not_found_session(),+ ),+ ):+ assert service.load_parent_research(parent_id) == {}++ line = _bounded_line(loguru_caplog.text, "Parent research not found")+ assert len(line) < 500+ assert "p" * 150 not in line++ def test_perform_followup_empty_context_log_is_bounded(self, loguru_caplog):+ service = followup_service_module.FollowUpResearchService(+ username="testuser"+ )+ request = followup_service_module.FollowUpRequest(+ parent_research_id="p" * self.HUGE,+ question="q",+ )+ with (+ loguru_caplog.at_level("WARNING"),+ patch.object(service, "prepare_research_context", return_value={}),+ ):+ params = service.perform_followup(request)++ assert params["parent_research_id"] == request.parent_research_id+ line = _bounded_line(loguru_caplog.text, "using empty context")+ assert len(line) < 500+ assert "p" * 150 not in line++ def test_prepare_followup_unknown_parent_logs_are_bounded(+ self, loguru_caplog+ ):+ """Through the real route: both not-found warnings (service and+ router) stay bounded, and the route still answers 404."""+ parent_id = "p" * self.HUGE+ request = _json_request(+ {"parent_research_id": parent_id, "question": "q"}+ )+ settings_manager = MagicMock()+ settings_manager.get_all_settings.return_value = {}++ async def _inline_run_db_sync(fn, *args, **kwargs):+ return fn(*args, **kwargs)++ with (+ loguru_caplog.at_level("WARNING"),+ patch.object(followup_module, "run_db_sync", _inline_run_db_sync),+ patch(+ "local_deep_research.settings.manager.SettingsManager",+ return_value=settings_manager,+ ),+ patch(+ "local_deep_research.database.session_context"+ ".get_user_db_session",+ self._not_found_session(),+ ),+ patch.object(+ followup_service_module,+ "get_user_db_session",+ self._not_found_session(),+ ),+ ):+ response = asyncio.run(+ followup_module.prepare_followup(request, "testuser")+ )++ assert response.status_code == 404+ lines = [+ line+ for line in loguru_caplog.text.splitlines()+ if "Parent research" in line and "not found" in line+ ]+ assert len(lines) == 2, lines+ for line in lines:+ assert len(line) < 500+ assert "p" * 150 not in line++ def test_validate_url_invalid_scheme_log_is_bounded(self, loguru_caplog):+ from local_deep_research.security import ssrf_validator++ url = "a" * self.HUGE + "://example.com/"+ with loguru_caplog.at_level("WARNING"):+ assert ssrf_validator.validate_url(url) is False++ line = _bounded_line(+ loguru_caplog.text, "Blocked URL with invalid scheme"+ )+ assert len(line) < 1000+ assert "a" * 300 not in line++ def test_validate_url_unresolvable_host_log_is_bounded(self, loguru_caplog):+ import socket++ from local_deep_research.security import ssrf_validator++ url = "http://" + "a." * (self.HUGE // 2) + "com/"+ with (+ loguru_caplog.at_level("WARNING"),+ patch.object(+ ssrf_validator.socket,+ "getaddrinfo",+ side_effect=socket.gaierror("no such host"),+ ),+ ):+ assert ssrf_validator.validate_url(url) is False++ line = _bounded_line(loguru_caplog.text, "Failed to resolve hostname")+ assert len(line) < 1000+ assert "a." * 150 not in line++ def test_redact_url_for_log_is_length_bounded(self):+ """A long host is cut with a ``...`` marker; a host past the+ 1,024 characters ``redact_and_bound_for_log`` scans is replaced by+ the log patcher's omitted-length marker instead.++ The second half changed when ``redact_url_for_log`` started to+ redact each component before cutting it+ (``redact_and_bound_for_log``): a 100,000-char host is one+ whitespace-free run longer than the patcher scans, so the patcher's+ own rule drops it whole rather than keep an unscanned prefix. That+ is what the patcher already did to the same host in a raw log line.+ """+ from local_deep_research.security.ssrf_validator import (+ redact_url_for_log,+ )++ redacted = redact_url_for_log(+ "https://" + "h" * 1_000 + ".example:8443/path"+ )+ assert len(redacted) < 1000+ assert redacted.startswith("https://hhh")+ assert redacted.endswith("...:8443")++ redacted = redact_url_for_log(+ "https://" + "h" * self.HUGE + ".example:8443/path"+ )+ assert len(redacted) < 1000+ assert "h" * 300 not in redacted+ assert redacted.endswith(":8443")+ # Ordinary URLs are untouched.+ assert (+ redact_url_for_log("http://u:[email protected]:8080/x")+ == "http://example.com:8080"+ )+++def _secret(n: int, offset: int = 0) -> str:+ """A credential stand-in built at runtime (no token-shaped literal for+ the secret scanners), with no 8-char window repeated within 26 chars."""+ return "".join(chr(ord("A") + (i * 7 + offset) % 26) for i in range(n))+++def _leaked_fragments(secret: str, text: str, width: int = 8) -> list[str]:+ return [+ secret[i : i + width]+ for i in range(len(secret) - width + 1)+ if secret[i : i + width] in text+ ]+++def _credential_urls():+ """The reviewers' shapes: a long URL whose credential label (``?key=``,+ ``?api_key=``, ``?access_token=``, or the ``user:`` before ``@``) sits+ in the middle that a head/tail cut drops, while the cut keeps the end+ of the secret."""+ cases = []+ for n in (48, 64):+ secret = _secret(n)+ for label in (+ "openai?key=",+ "openai/v1/chat?api_key=",+ "openai/v1/chat?access_token=",+ ):+ cases.append(+ (+ "https://generativelanguage.googleapis.com/v1beta/"+ f"{label}{secret}",+ secret,+ )+ )+ for n in (40, 60):+ secret = _secret(n, 3)+ cases.append(+ (+ f"https://svc-account-{'x' * 49}:{secret}@llm.corp.example/v1",+ secret,+ )+ )+ return cases+++class TestRedactBeforeBound:+ """#6938 r3: bounding a log value must never let the log patcher's+ credential redaction see less than it did when the raw value was+ logged.++ ``reprlib`` keeps a long string's first 47 and last 48 characters and+ ``sanitize_for_log`` keeps a prefix, so either cut can drop a+ credential's label while keeping part of the secret. The patcher then+ has no pattern to match. Each probe checks that no 8-char window of the+ secret survives, in the bounded value and after the patcher's own+ redaction (``_redact_log_text``) runs over the emitted line. On+ d7ac5b7630 every probe here leaked.+ """++ @pytest.mark.parametrize(+ ("url", "secret"),+ _credential_urls(),+ ids=lambda v: v[:24] if isinstance(v, str) else None,+ )+ def test_preview_redacts_before_cutting(self, url, secret):+ from local_deep_research.security.log_sanitizer import (+ _redact_log_text,+ )++ preview = notes_module._log_value_preview(url)+ assert _leaked_fragments(secret, preview) == []+ emitted = _redact_log_text("custom_endpoint=" + preview)+ assert _leaked_fragments(secret, emitted) == []+ # Nested strings go through the same redaction.+ nested = notes_module._log_value_preview({"endpoint": [url]})+ assert _leaked_fragments(secret, nested) == []++ @pytest.mark.parametrize(+ ("url", "secret"),+ _credential_urls(),+ ids=lambda v: v[:24] if isinstance(v, str) else None,+ )+ def test_redact_and_bound_redacts_before_cutting(self, url, secret):+ from local_deep_research.security.log_sanitizer import (+ redact_and_bound_for_log,+ )++ for cap in (50, 100, 200):+ bounded = redact_and_bound_for_log(url, cap)+ assert len(bounded) <= cap+ assert _leaked_fragments(secret, bounded) == []++ def test_preview_masks_a_value_under_a_sensitive_key(self):+ secret = _secret(64)+ preview = notes_module._log_value_preview(+ {"api_key": secret, "password": "", "model": "m"}+ )+ assert _leaked_fragments(secret, preview) == []+ # Empty values stay readable, as in the patcher's extra redaction.+ assert "'password': ''" in preview+ assert "'model': 'm'" in preview++ def test_preview_redaction_work_is_budgeted(self):+ """A container of many long strings is not redacted string by+ string without limit: each string is charged at most 512+ characters (only its first 512 are redacted) against a+ 1,024-character budget per preview, and past the budget a string+ is shown as a length, never raw. reprlib renders ten of the+ eleven: two fit the budget, eight do not. Checked on the repr+ before the 100-char backstop, which would cut the later elements+ off anyway."""+ long = "x " * 20_000+ text = notes_module._RedactingRepr().repr([long] * 11)+ assert text.count("<40000-char string not shown>") == 8+ assert len(notes_module._log_value_preview([long] * 11)) <= 100++ def test_research_parameters_line_redacts_custom_endpoint(+ self, loguru_caplog+ ):+ url, secret = _credential_urls()[0]+ with (+ loguru_caplog.at_level("INFO"),+ patch.object(research_service_module, "set_search_context"),+ patch.object(+ research_service_module,+ "apply_environment_overrides_to_snapshot",+ side_effect=_StopAfterParameterLogs,+ ),+ patch.object(research_service_module, "_sio_emit"),+ patch.object(research_service_module, "cleanup_research_resources"),+ patch(+ "local_deep_research.web.research_state"+ ".is_termination_requested",+ return_value=False,+ ),+ patch("local_deep_research.settings.logger.log_settings"),+ ):+ with pytest.raises(_StopAfterParameterLogs):+ research_service_module.run_research_process(+ "research-1",+ "q",+ "quick",+ username="testuser",+ custom_endpoint=url,+ )++ line = _bounded_line(loguru_caplog.text, "Research parameters:")+ assert _leaked_fragments(secret, line) == []+ assert "custom_endpoint=https://generativelanguage.googleapis.com," in (+ line+ )++ def test_notification_rejection_message_bounds_the_host(self):+ """An oversized IPv6 zone is rejected by destination parsing before+ IP policy, without reflecting the host into the error callers log."""+ from local_deep_research.security.notification_validator import (+ NotificationURLValidator,+ )++ url = "http://[fe80::1%25" + "z" * 100_000 + "]/x"+ is_valid, error = NotificationURLValidator.validate_service_url(url)+ assert is_valid is False+ assert error == "Notification destination is unsupported or ambiguous"+ assert len(error) < 1000+ assert "z" * 300 not in error++ def test_notification_unsupported_scheme_message_is_bounded(self):+ from local_deep_research.security.notification_validator import (+ NotificationURLValidator,+ )++ is_valid, error = NotificationURLValidator.validate_service_url(+ "s" * 100_000 + "://example.com/"+ )+ assert is_valid is False+ assert len(error) < 1000+ assert "s" * 300 not in error++ def test_engineio_logger_gets_the_bounded_origin_message(self):+ from local_deep_research.web.services.socketio_asgi import (+ _install_origin_rejection_logging,+ )++ calls = []++ class _Eio:+ def _log_error_once(self, message, message_key):+ calls.append(message)++ class _Sio:+ eio = _Eio()++ server = _Sio()+ assert _install_origin_rejection_logging(server) is True+ server.eio._log_error_once(+ "http://" + "o" * 100_000 + " is not an accepted origin.",+ "bad-origin",+ )+ assert len(calls) == 1+ assert len(calls[0]) <= 300++ def test_auth_log_lines_never_interpolate_the_raw_username(self):+ """Every logger call in ``web/routers/auth.py`` that formats the+ username goes through the bounded preview: registration has no+ maximum length, so a self-registered 100,000-char name would+ otherwise be logged on every login, post-login step, logout and+ password change."""+ import ast++ from local_deep_research.web.routers import auth as auth_module++ tree = ast.parse(inspect.getsource(auth_module))+ raw = []+ for node in ast.walk(tree):+ if not (+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and isinstance(node.func.value, ast.Name)+ and node.func.value.id == "logger"+ ):+ continue+ for arg in node.args:+ for sub in ast.walk(arg):+ if (+ isinstance(sub, ast.FormattedValue)+ and isinstance(sub.value, ast.Name)+ and sub.value.id == "username"+ ):+ raw.append(node.lineno)+ for arg in node.args[1:]:+ if isinstance(arg, ast.Name) and arg.id == "username":+ raw.append(node.lineno)+ assert raw == [], f"raw username logged at auth.py lines {raw}"+++class TestLogValueWorkIsBounded:+ """#6938 r4: the redaction added in r3 must not make a log line's cost+ grow with the request.++ Each guard counts calls (or characters) at the seam that does the+ work, so it fails on 8ab4a0bc0 regardless of machine speed: there a+ preview of ``{a..j: {a..j: {a..j: {a..j: "a"}}}}`` ran ~21,000+ redactions, a dict key of any length went through the sensitive-key+ check in full, and ``validate_safe_path`` redacted every path it+ accepted.+ """++ @staticmethod+ def _tiny_strings(width: int = 10):+ keys = [chr(ord("a") + i) for i in range(width)]+ return {+ a: {b: {c: dict.fromkeys(keys, "a") for c in keys} for b in keys}+ for a in keys+ }++ def test_preview_redaction_calls_are_capped(self):+ from local_deep_research.security.log_sanitizer import redact_for_log++ calls = []++ def counting(text):+ calls.append(len(text))+ return redact_for_log(text)++ with patch.object(notes_module, "redact_for_log", counting):+ preview = notes_module._log_value_preview(self._tiny_strings())+ # Deliberate literal (1,024-char budget / 32-char minimum charge).+ assert 0 < len(calls) <= 32+ # The strings the 100-char preview shows are the first rendered,+ # so they are the ones redacted.+ assert preview.startswith("{'a': {'a': {'a': {'a': 'a', 'b': 'a',")++ def test_preview_key_checks_are_capped(self):+ checked = []+ real = notes_module._is_sensitive_log_key++ def counting(key):+ checked.append(len(key) if isinstance(key, str) else 0)+ return real(key)++ width = 11+ keys = [chr(ord("a") + i) * 40 for i in range(width)]+ value = {+ a: {b: {c: dict.fromkeys(keys, "v") for c in keys} for b in keys}+ for a in keys+ }+ with patch.object(notes_module, "_is_sensitive_log_key", counting):+ notes_module._log_value_preview(value)+ assert len(checked) <= 512+ assert sum(checked) <= 32_768++ def test_huge_key_is_not_checked_and_its_value_is_masked(self):+ checked = []+ real = notes_module._is_sensitive_log_key++ def counting(key):+ checked.append(len(key))+ return real(key)++ secret = _secret(48)+ huge = "k" * 1_000_000+ with patch.object(notes_module, "_is_sensitive_log_key", counting):+ preview = notes_module._log_value_preview({huge: secret})+ disguised = notes_module._log_value_preview(+ {"x" * 1_000_000 + "_api_key": secret}+ )+ assert all(n <= 32_768 for n in checked), checked+ assert _leaked_fragments(secret, preview) == []+ assert _leaked_fragments(secret, disguised) == []++ def test_unchecked_key_still_reports_dropped_entries(self):+ """A value masked because the key budget ran out is still walked+ for the items-omitted flag (with no budget, so nothing under it is+ checked)."""+ eleven = {f"k{i}": "v" for i in range(11)}+ bounded, omitted = notes_module._bound_dict_shaped_walk(+ {"k" * 40_000: eleven}, 0+ )+ assert list(bounded.values()) == ["[REDACTED]"]+ assert omitted is True+ _, omitted = notes_module._bound_dict_shaped_walk(+ {"k" * 40_000: {f"k{i}": "v" for i in range(10)}}, 0+ )+ assert omitted is False++ def test_patcher_key_check_fails_closed_past_the_bound(self):+ from local_deep_research.security.log_sanitizer import (+ _is_sensitive_log_key,+ redact_log_extra,+ )++ assert _is_sensitive_log_key("model") is False+ assert _is_sensitive_log_key("k" * 32_768) is False+ assert _is_sensitive_log_key("k" * 32_769) is True+ assert redact_log_extra({"k" * 40_000: "v"}) == {+ "k" * 40_000: "[REDACTED]"+ }++ def test_validate_safe_path_redacts_only_to_log_a_rejection(self, tmp_path):+ from local_deep_research.security import path_validator++ (tmp_path / "app.js").write_text("x")+ seen = []++ def counting(value, max_length):+ seen.append(len(value))+ return value[:max_length]++ with patch.object(path_validator, "redact_and_bound_for_log", counting):+ path_validator.PathValidator.validate_safe_path(+ "app.js", str(tmp_path)+ )+ assert seen == []+ with pytest.raises(ValueError):+ path_validator.PathValidator.validate_safe_path(+ "../" * 20_000 + "etc/passwd", str(tmp_path)+ )+ assert len(seen) == 1++ def test_validate_safe_path_rejection_log_is_redacted(+ self, tmp_path, loguru_caplog+ ):+ from local_deep_research.security import path_validator++ secret = _secret(40)+ # One long key-shaped run (redacted to a marker) puts the URL+ # userinfo 30 characters before the 1,024-character scan bound+ # (4 * 200 is below the 1,024 minimum), so the cut falls inside the+ # secret and the redacted head is short enough to be shown whole.+ # A plain slice keeps 10 secret characters without their ``@``.+ start = 1_024 - 30+ prefix = "../sk-" + "A" * (start - len("../sk-") - 1) + " "+ for path in (+ f"../https://svc-{'x' * 200}:{secret}@h/x",+ f"{prefix}https://svc-account:{secret}@h/x" + " tail" * 50,+ ):+ loguru_caplog.clear()+ with loguru_caplog.at_level("WARNING"), pytest.raises(ValueError):+ path_validator.PathValidator.validate_safe_path(+ path, str(tmp_path)+ )+ assert "Path traversal attempt blocked" in loguru_caplog.text+ assert _leaked_fragments(secret, loguru_caplog.text) == []+++class TestRedactionRunsOnlyWhenLogged:+ """#6938 r5: a pre-auth or per-row log site redacts only when its text+ is actually logged.++ On 80d651e9b the Socket.IO origin hook redacted the (unbounded,+ attacker-chosen) Origin on EVERY rejected handshake, including after+ its 100-origin warning cap and on every repeat that engine.io's+ ERROR-level logger drops, and ``get_news_feed`` redacted every row's+ full stored query for INFO lines on every feed load. Each guard counts+ calls at the redaction seam, so it fails there regardless of machine+ speed.+ """++ # Standard-library level numbers (engine.io logs through ``logging``).+ ERROR, INFO = 40, 20++ @staticmethod+ def _engineio_stub(seen_keys, level):+ calls = []++ class _StdlibLogger:+ def isEnabledFor(self, wanted):+ return wanted >= level++ eio_logger = _StdlibLogger()++ class _Eio:+ log_message_keys = set(seen_keys)+ logger = eio_logger++ def _log_error_once(self, message, message_key):+ calls.append(message)++ class _Sio:+ eio = _Eio()++ return _Sio(), calls++ @staticmethod+ def _counting_redaction(module):+ seen = []+ real = module.redact_and_bound_for_log++ def counting(value, max_length):+ seen.append(len(value))+ return real(value, max_length)++ return seen, patch.object(module, "redact_and_bound_for_log", counting)++ def test_origin_hook_redacts_nothing_past_the_cap(self):+ from local_deep_research.web.services import socketio_asgi++ server, calls = self._engineio_stub({"bad-origin"}, self.ERROR)+ assert socketio_asgi._install_origin_rejection_logging(server)+ seen, patched = self._counting_redaction(socketio_asgi)+ hostile = "https://a:b@ " * 3_000 + " is not an accepted origin."+ with patched:+ for i in range(100):+ server.eio._log_error_once(+ f"http://o{i}.test is not an accepted origin.",+ "bad-origin",+ )+ assert len(seen) == 100 # one per warning emitted+ for _ in range(50):+ server.eio._log_error_once(hostile, "bad-origin")+ assert len(seen) == 100, (+ "the hook redacted an origin it neither warned about nor "+ f"handed to an emitting engine.io logger ({len(seen)} calls)"+ )+ assert len(calls) == 150+ assert all(len(c) <= 300 for c in calls)+ assert hostile not in calls++ def test_origin_hook_redacts_a_repeated_origin_once(self):+ from local_deep_research.web.services import socketio_asgi++ server, calls = self._engineio_stub({"bad-origin"}, self.ERROR)+ socketio_asgi._install_origin_rejection_logging(server)+ seen, patched = self._counting_redaction(socketio_asgi)+ with patched:+ for _ in range(20):+ server.eio._log_error_once(+ "http://same.test is not an accepted origin.",+ "bad-origin",+ )+ assert len(seen) == 1+ assert len(calls) == 20++ @pytest.mark.parametrize(+ "seen_keys,level",+ [+ (set(), "ERROR"), # first occurrence: engine.io logs at ERROR+ ({"bad-origin"}, "INFO"), # repeats emitted: logger lowered+ ],+ )+ def test_origin_hook_hands_an_emitting_engineio_the_redacted_text(+ self, seen_keys, level+ ):+ from local_deep_research.web.services import socketio_asgi++ server, calls = self._engineio_stub(seen_keys, getattr(self, level))+ socketio_asgi._install_origin_rejection_logging(server)+ secret = _secret(40)+ origin = f"https://svc-{'x' * 200}:{secret}@h"+ for _ in range(2): # past the warning dedup, too+ server.eio._log_error_once(+ origin + " is not an accepted origin.", "bad-origin"+ )+ assert len(calls) == 2+ for text in calls:+ assert len(text) <= 300+ assert text.endswith(" is not an accepted origin.")+ assert _leaked_fragments(secret, text) == []++ def test_news_feed_rows_are_not_redacted_unless_logged(self):+ """With no sink at the per-row lines' level nothing is redacted;+ their lazy arguments, when a sink does take them, are redacted+ before they are cut."""+ from contextlib import contextmanager as _cm+ from datetime import UTC, datetime++ from sqlalchemy import create_engine+ from sqlalchemy.orm import sessionmaker++ from local_deep_research.database.models import Base, ResearchHistory+ from local_deep_research.news import api as news_api++ secret = _secret(40)+ # The password starts inside every line's cut, so a cut made+ # before redaction would keep part of it.+ query = f"latest news https://u:{secret}@h/x " + "q" * 20_000+ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ session_local = sessionmaker(bind=engine)+ now = datetime.now(UTC).isoformat()+ seed = session_local()+ for i in range(6):+ seed.add(+ ResearchHistory(+ id=f"r{i}",+ query=query,+ title=None,+ mode="quick",+ status="completed",+ created_at=now,+ completed_at=now,+ report_content="Answer.",+ research_meta={"is_news_search": True},+ )+ )+ seed.commit()+ seed.close()++ @_cm+ def _fake_user_db(username=None, password=None):+ db = session_local()+ try:+ yield db+ finally:+ db.close()++ seen, patched = self._counting_redaction(news_api)+ mock_logger = MagicMock()+ try:+ with (+ patch(+ "local_deep_research.database.session_context."+ "get_user_db_session",+ _fake_user_db,+ ),+ patch.object(news_api, "logger", mock_logger),+ patched,+ ):+ result = news_api.get_news_feed(+ user_id="testuser", limit=20, use_cache=False+ )+ assert len(result["news_items"]) == 6+ assert seen == [], (+ f"get_news_feed redacted {len(seen)} values for log "+ "lines no sink was taking"+ )+ rendered = []+ for call in mock_logger.opt.return_value.debug.call_args_list:+ rendered.extend(+ arg() if callable(arg) else arg for arg in call.args[1:]+ )+ finally:+ engine.dispose()+ texts = [r for r in rendered if isinstance(r, str)]+ assert any(t.startswith("latest news https://") for t in texts)+ assert any(t.startswith("News: latest news") for t in texts)+ for text in texts:+ assert len(text) <= 50+ assert _leaked_fragments(secret, text) == []+ assert seen, "the lazy arguments never reached the redaction"+++# Files this PR's log redaction covers. A ``value[:N]`` slice of a logged+# value cuts it before the patcher's redaction sees it; the only slices+# left are of ids (uuid prefixes) and the authenticated user's own name.+_REDACT_BEFORE_CUT_MODULES = (+ "local_deep_research.chat.service",+ "local_deep_research.news.api",+ "local_deep_research.security.notification_validator",+ "local_deep_research.security.path_validator",+ "local_deep_research.security.url_validator",+ "local_deep_research.web.routers.auth",+ "local_deep_research.web.routers.library",+ "local_deep_research.web.routers.news_flask_api",+ "local_deep_research.web.routers.research",+ "local_deep_research.web.services.research_service",+)+++def _sliced_name(node):+ """``x`` for ``x[:N]``, ``x.y`` for ``x.y[:N]``, ``x['k']`` for+ ``x['k'][:N]``; None for anything else."""+ import ast++ if not (+ isinstance(node, ast.Subscript)+ and isinstance(node.slice, ast.Slice)+ and node.slice.lower is None+ and node.slice.upper is not None+ ):+ return None+ return ast.unparse(node.value)+++def _is_logger_chain(node):+ """``logger``, or ``logger.opt(...)`` / ``logger.bind(...)`` chains."""+ import ast++ while isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):+ node = node.func.value+ return isinstance(node, ast.Name) and node.id == "logger"++[email protected]("module_name", _REDACT_BEFORE_CUT_MODULES)+def test_logged_values_are_redacted_before_they_are_cut(module_name):+ """#6938 r4: every ``logger`` call in these modules cuts a value only+ after redacting it (``redact_and_bound_for_log`` or the preview), never+ with a bare slice or ``sanitize_for_log``. On+ 8ab4a0bc0 ``run_research_process`` still logged ``query[:100]``: a URL+ whose ``@`` sits past offset 100 then kept 22 characters of its+ password through the patcher."""+ import ast+ import importlib++ module = importlib.import_module(module_name)+ tree = ast.parse(inspect.getsource(module))+ cut = []+ for node in ast.walk(tree):+ if not (+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and _is_logger_chain(node.func.value)+ ):+ continue+ for arg in node.args:+ for sub in ast.walk(arg):+ if (+ isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "sanitize_for_log"+ ):+ # Strips and cuts, but does not redact.+ cut.append((node.lineno, ast.unparse(sub)))+ continue+ name = _sliced_name(sub)+ if name is None:+ continue+ if name.endswith("id") or name == "self.username":+ continue+ cut.append((node.lineno, name))+ assert cut == [], f"{module_name} cuts before redacting: {cut}"+++class TestRedactionCostIsBoundedPerValue:+ """#6938 r6: redacting a value for a short log text scans only a+ bounded head of it, and DEBUG lines redact only when a sink takes+ them.++ On 6f6b7dd223 the preview and ``redact_and_bound_for_log`` redacted+ up to 32 KiB of each string to show at most a few hundred characters+ (~100-170 ms for one adversarial 33 KB string, against ~0.02 ms for+ the unredacted preview), and sixteen DEBUG lines that the default+ INFO sinks never emit ran it eagerly on every call. Each guard counts+ characters or calls at the redaction seam, so it fails there+ regardless of machine speed.+ """++ HOSTILE = "https://a:b@ " * 2_600++ @staticmethod+ def _counting(module):+ seen = []+ real = module.redact_for_log++ def counting(text):+ seen.append(len(text))+ return real(text)++ return seen, patch.object(module, "redact_for_log", counting)++ @pytest.mark.parametrize(+ "shape", ["str", "list", "dict"], ids=["str", "list", "dict"]+ )+ def test_preview_redacts_a_bounded_head_of_a_long_string(self, shape):+ value = {+ "str": self.HOSTILE,+ "list": [self.HOSTILE],+ # Under 32 KiB, so the old per-preview budget redacted it whole.+ "dict": {"model": self.HOSTILE[:30_000]},+ }[shape]+ seen, patched = self._counting(notes_module)+ with patched:+ preview = notes_module._log_value_preview(value)+ assert seen, "the long string was never redacted"+ # Deliberate literals: 512 chars per string, 1,024 per preview.+ assert max(seen) <= 512, seen+ assert sum(seen) <= 1_024, seen+ assert "a:b@" not in preview+ if shape == "str":+ assert "characters omitted from log output" in preview++ @pytest.mark.parametrize("max_length", [60, 100, 256])+ def test_redact_and_bound_redacts_a_bounded_head(self, max_length):+ from local_deep_research.security import log_sanitizer++ seen, patched = self._counting(log_sanitizer)+ with patched:+ bounded = log_sanitizer.redact_and_bound_for_log(+ self.HOSTILE, max_length+ )+ assert seen+ # Deliberate literal: the larger of 1,024 and 4 * max_length.+ assert sum(seen) <= max(1_024, 4 * max_length), seen+ assert len(bounded) <= max_length+ assert "a:b@" not in bounded++ _BOUNDARY_SHAPES = [+ "https://svc-account:{s}@llm.corp.example/v1",+ "https://h.example/v1?api_key={s}&a=1",+ "api_key={s}",+ 'password="{s} two words {s}"',+ "Authorization: Bearer {s}",+ ]++ @staticmethod+ def _boundary_value(bound, offset, shape):+ """A value whose credential starts ``bound + offset`` characters in.++ The prefix is ONE long key-shaped run (an ``sk-`` key, redacted to a+ short marker), so the redacted head is short and the region around+ the cut is inside the first characters every output shows. Padding+ with ordinary words instead leaves that region past the visible+ window of each output, so a cut that slices mid-credential would+ pass unseen.+ """+ secret = _secret(40)+ start = bound + offset+ prefix = "sk-" + "A" * (start - 4) + " "+ value = prefix + shape.format(s=secret) + " tail" * 50+ return secret, value++ @pytest.mark.parametrize("offset", [-60, -45, -35, -30, -22, -12, -1, 0, 1])+ @pytest.mark.parametrize("shape", _BOUNDARY_SHAPES)+ def test_a_credential_across_the_preview_bound_never_leaks(+ self, offset, shape+ ):+ """The head is cut only at a whitespace boundary, dropping the+ whole run the bound falls in, so a credential that starts just+ before the bound is redacted whole or dropped whole, never kept+ in part without its label."""+ secret, value = self._boundary_value(+ notes_module._PREVIEW_STRING_REDACTION_MAX_CHARS, offset, shape+ )+ assert (+ _leaked_fragments(secret, notes_module.redact_for_log(value)) == []+ )+ for text in (+ notes_module._RedactingRepr().repr(value),+ notes_module._log_value_preview(value),+ notes_module._log_value_preview({"endpoint": [value]}),+ ):+ assert _leaked_fragments(secret, text) == [], text++ @pytest.mark.parametrize("offset", [-60, -45, -35, -30, -22, -12, -1, 0, 1])+ @pytest.mark.parametrize("shape", _BOUNDARY_SHAPES)+ def test_a_credential_across_the_head_bound_never_leaks(+ self, offset, shape+ ):+ from local_deep_research.security.log_sanitizer import (+ bounded_redaction_chars,+ redact_and_bound_for_log,+ redact_head_for_log,+ )++ for bound in (512, 1_024, 1_200):+ secret, value = self._boundary_value(bound, offset, shape)+ head = redact_head_for_log(value, bound)+ assert _leaked_fragments(secret, head) == [], (bound, head)+ for max_length in (60, 100, 256, 300):+ secret, value = self._boundary_value(+ bounded_redaction_chars(max_length), offset, shape+ )+ text = redact_and_bound_for_log(value, max_length)+ assert _leaked_fragments(secret, text) == [], (max_length, text)++ def test_research_not_found_previews_only_when_logged(self):+ calls = []++ def counting(value):+ calls.append(value)+ return notes_module._log_value_preview(value)++ mock_logger = MagicMock()+ with (+ patch.object(research_module, "logger", mock_logger),+ patch.object(research_module, "_log_value_preview", counting),+ ):+ response = research_module._research_not_found("r" * 50_000)+ assert response.status_code == 404+ assert calls == [], "previewed for a line no sink was taking"+ rendered = [+ arg() if callable(arg) else arg+ for call in mock_logger.opt.return_value.debug.call_args_list+ for arg in call.args[1:]+ ]+ assert len(calls) == 1+ # One 50,000-char run is longer than the scanned head, so the+ # patcher's rule drops it whole and only its length is shown.+ assert any(+ isinstance(r, str)+ and len(r) <= 100+ and "50000 characters omitted" in r+ for r in rendered+ ), rendered+ assert "Research not found" in rendered+++_REDACTING_CALLS = frozenset(+ {"_log_value_preview", "redact_and_bound_for_log", "redact_for_log"}+)+++def _debug_lines_redacting_eagerly(tree):+ """``logger.debug``/``.trace`` calls that redact an argument before+ loguru knows whether any sink takes the line (no ``opt(lazy=True)``,+ or a redacting call outside the lambdas)."""+ import ast++ found = []+ for node in ast.walk(tree):+ if not (+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr in ("debug", "trace")+ and _is_logger_chain(node.func.value)+ ):+ continue+ chain = node.func.value+ lazy = (+ isinstance(chain, ast.Call)+ and isinstance(chain.func, ast.Attribute)+ and chain.func.attr == "opt"+ and any(+ kw.arg == "lazy"+ and isinstance(kw.value, ast.Constant)+ and kw.value.value is True+ for kw in chain.keywords+ )+ )+ lambdas = set()+ for arg in [*node.args, *(kw.value for kw in node.keywords)]:+ if lazy and isinstance(arg, ast.Lambda):+ lambdas.update(id(sub) for sub in ast.walk(arg))+ for arg in [*node.args, *(kw.value for kw in node.keywords)]:+ for sub in ast.walk(arg):+ if id(sub) in lambdas or not isinstance(sub, ast.Call):+ continue+ func = sub.func+ name = getattr(func, "id", None) or getattr(func, "attr", None)+ if name in _REDACTING_CALLS:+ found.append(node.lineno)+ return found+++def test_no_debug_line_redacts_eagerly():+ """#6938 r6: a DEBUG line runs the preview or the redaction only+ inside ``logger.opt(lazy=True)`` lambdas, so the default INFO sinks+ cost no redaction. On 6f6b7dd223 sixteen DEBUG lines (research+ router and service, history, rag, auth, library, topic generator,+ dns pinning, notification validator) ran it eagerly.++ Scope: only the three names in ``_REDACTING_CALLS``. About 45 DEBUG+ lines (downloaders, search engines, url builder) still call+ ``redact_url_for_log`` eagerly; each call scans at most 1,024+ characters per URL component, so it is bounded and not guarded."""+ import ast+ from pathlib import Path++ import local_deep_research++ root = Path(local_deep_research.__file__).parent+ eager = {}+ for path in sorted(root.rglob("*.py")):+ source = path.read_text(encoding="utf-8")+ if not any(name in source for name in _REDACTING_CALLS):+ continue+ lines = _debug_lines_redacting_eagerly(ast.parse(source))+ if lines:+ eager[str(path.relative_to(root))] = lines+ assert eager == {}, f"DEBUG lines redacting eagerly: {eager}"+++def test_eager_debug_guard_positive_control():+ import ast++ code = (+ "logger.debug('a {}', _log_value_preview(x))\n"+ "logger.opt(lazy=True).debug('b {}', redact_and_bound_for_log(x, 9))\n"+ "logger.opt(lazy=True).debug('c {}', lambda: _log_value_preview(x))\n"+ "logger.info('d {}', _log_value_preview(x))\n"+ )+ assert _debug_lines_redacting_eagerly(ast.parse(code)) == [1, 2]diff --git a/tests/web/test_exception_handler_matrix.py b/tests/web/test_exception_handler_matrix.pyindex 34eec05a8c..f6dfa360ec 100644--- a/tests/web/test_exception_handler_matrix.py+++ b/tests/web/test_exception_handler_matrix.py@@ -667,7 +667,7 @@ class TestCatchAllHandlerMatrix:resp = matrix_client.get("/api/boom", headers=API)assert resp.json() == {"error": "Server error"}- assert "Unhandled exception: GET /api/boom" in loguru_caplog_full.text+ assert "Unhandled exception: GET '/api/boom'" in loguru_caplog_full.textassert RAISE_SITE_SECRET in loguru_caplog_full.text, ("the catch-all must log the exception it hides from the client")@@ -732,7 +732,7 @@ class TestJSONDecodeErrorHandlerMatrix:# Positive control: the log line exists and is genuinely useful,# so the absence assertion below is not passing on an empty# capture or a handler that logs nothing at all.- assert "JSON decode error handling POST /api/echo" in text+ assert "JSON decode error handling POST '/api/echo'" in textassert "Expecting" in text, ("the parser's own .msg must be logged -- without it the ""operator cannot tell a truncated body from a wrong "diff --git a/tests/web/test_secure_cookie_middleware.py b/tests/web/test_secure_cookie_middleware.pyindex 5860c6ceab..cc7039cd62 100644--- a/tests/web/test_secure_cookie_middleware.py+++ b/tests/web/test_secure_cookie_middleware.py@@ -126,6 +126,24 @@ def test_public_http_warning_is_emitted_once_across_repeated_requests():assert middleware._warned_insecure_public is True+def test_public_http_warning_bounds_a_long_scoped_address():+ """#6938: a public IPv6 address with a scope id parses at any length,+ and under TRUST_PROXY_HEADERS it is the client's X-Forwarded-For+ entry, so the logged form is capped (an ordinary address, as above,+ is logged unchanged and unquoted)."""+ middleware = _warning_middleware()++ with patch("local_deep_research.web.fastapi_app.logger.warning") as warning:+ _run_warning_request(+ middleware,+ scheme="http",+ client_ip="2607:f8b0::1%" + "z" * 100_000,+ )++ warning.assert_called_once()+ assert len(warning.call_args.args[1]) <= 64++def test_private_and_loopback_http_stay_silent():middleware = _warning_middleware()