~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(fetch): redact URLs + drop full page content from fetch-path logs ([FETCH] + content_fetcher) (#4767)
LearningCircuit303315256b4c
diff --git a/changelog.d/4767.security.md b/changelog.d/4767.security.mdnew file mode 100644index 0000000000..07a0a4a71e--- /dev/null+++ b/changelog.d/4767.security.md@@ -0,0 +1,42 @@+Fetch-path log events in the modules whose log sites this change rewrites —+the LangGraph fetch tool (`advanced_search_system/tools/fetch`),+`ContentFetcher` (`content_fetcher/fetcher.py`), the+`research_library/downloaders/*` downloaders (base, direct-PDF, generic,+bioRxiv, Semantic Scholar, HTML/Crawl4AI/Playwright) and their shared+`extraction/pipeline.py`, and `SafeSession.send`'s redirect guard+(`security/safe_requests.py`) — no longer leak URL credentials, page+content, or exception detail into the log sinks (stderr, log file,+encrypted DB, frontend progress stream). Callees reached from those paths+keep their own logging and are unchanged here: the fetch tool's library+resolver (`tools/fetch/library_resolver.py`), the+`extraction/*_extractor.py` extractors, `security/ssrf_validator.py` and+`security/egress/policy.py` still keep their own logging (`logger.exception`,+or `logger.debug(..., exc_info=True)` for `metadata_extractor.py` and+`newspaper_extractor.py`). Every URL-bearing log site on the fetch paths —+ContentFetcher, the HTML/Crawl4AI/Playwright downloaders, the LangGraph+fetch tool (including the local-library `source=library` resolution event),+and the shared extraction pipeline's `fetch_and_extract` /+`batch_fetch_and_extract` / specialized-downloader paths — now renders only+the redacted `scheme://host:port` origin (RFC 3986 userinfo, path, query and+fragment are dropped). Failure events use the explicit+`logger.opt(exception=False)` form: no traceback is attached. Where the+caught error is the only diagnostic left, its message is kept inline rather+than dropped altogether, but only through `scrub_error` (with any credential+in scope passed as a known literal): it rewrites credentials and query+strings but leaves the path, so a caught network error can no longer+re-embed a credential via its message, though a bare (non-credentialed)+path can still surface that way. This applies at the session-close and+PDF-extraction handlers in+`downloaders/base.py` and the Semantic Scholar API handlers, matching the+`safe_msg` shape the OpenAlex downloader already uses. The summary-fetch+success event is bounded to mode, status, redacted origin and character+counts — page body, focus, overall query, title and summary text are no+longer logged. Two deliberate, visible side effects of the redaction, kept+for safety: per-domain rate-limit engine keys on the downloader paths are+now derived from the URL's own parsed authority through one shared helper,+`rate_limit_authority` in `downloaders/base.py` (userinfo is dropped, so a+userinfo-bearing URL and its bare-origin equivalent share one bucket, and a+URL whose authority will not parse — or whose host carries whitespace —+buckets as `invalid_authority`), and the `[FETCH]` diagnostic events remain+f-string rendered (values are redacted before interpolation, not passed as+structured kwargs).diff --git a/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py b/src/local_deep_research/advanced_search_system/tools/fetch/__init__.pyindex e43d0409ab..8271cb2260 100644--- a/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py+++ b/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py@@ -403,7 +403,8 @@ def _fetch_raw_content(result = payloadurl = result.get("url") or urllogger.info(- f"[FETCH] mode={mode_label} source=library url={url} — "+ f"[FETCH] mode={mode_label} source=library "+ f"url={redact_url_for_log(url)} — ""resolved local library document directly")else: # _KIND_REWRITTEN — citation marker resolved to a URL@@ -510,17 +511,16 @@ def _make_full_fetch_tool(f"({_denial_reason(exc)}). {_EGRESS_DENIAL_HINT}")except Exception as exc:- # Message carries the mode + a REDACTED scheme://host only (no- # userinfo/path/query) so an operator can locate the failure without- # the log line leaking credentials, query tokens, or page content.- # The traceback follows the sink's diagnose setting (off by default;- # see utilities/log_utils). The agent/user-facing return is scrubbed- # separately below.+ # logger.opt(exception=False).error — explicit no-traceback form+ # that satisfies both custom-checks (no bare logger.error in an+ # except block) and the security contract (no logger.exception+ # traceback, which can embed the raw URL). Message carries the mode+ # + a REDACTED scheme://host only (no userinfo/path/query); the+ # agent/user-facing return is scrubbed separately below.target_url = getattr(exc, "target", "") or url- logger.exception(- "fetch_content tool error (mode={}, url={})",- mode_label,- redact_url_for_log(target_url),+ logger.opt(exception=False).error(+ f"[FETCH] mode={mode_label} status=error "+ f"url={redact_url_for_log(target_url)}")return sanitize_error_for_agent(f"Error fetching {target_url}: {exc}"@@ -607,9 +607,8 @@ def _make_summary_fetch_tool(# retry it under a different focus.if not content.strip():logger.info(- f"[FETCH] mode={mode_label} url={url} — "- "empty page content, returning NOT RELEVANT without "- "LLM call or collector registration"+ f"[FETCH] mode={mode_label} status=empty_content "+ f"url={redact_url_for_log(url)}")return f"NOT RELEVANT (no extractable content at {url})"@@ -629,39 +628,17 @@ def _make_summary_fetch_tool(summary_msg, "content", str(summary_msg)).strip()except Exception as exc:- # Redacted scheme://host + mode only — no page content,- # focus, or credentials in the message. Traceback follows- # the sink's diagnose setting (off by default).- logger.exception(- "fetch_content summary LLM error (mode={}, url={})",- mode_label,- redact_url_for_log(url),+ # Explicit no-traceback form (see full-fetch variant): a+ # redacted scheme://host + mode only, no page content, focus,+ # or credentials. Agent-facing return is scrubbed below.+ logger.opt(exception=False).error(+ f"[FETCH] mode={mode_label} status=summary_error "+ f"url={redact_url_for_log(url)}")return sanitize_error_for_agent(f"Error summarizing {url}: {exc}")- # Diagnostic log: per-fetch input/output for evaluating the- # summariser. Single multi-line block so it's atomic per call- # and easy to grep with ``grep -A1000 "[FETCH] mode="``.- log_lines = [- f"[FETCH] mode={mode_label} url={url}",- f"[FETCH] focus: {focus}",- ]- if use_query:- log_lines.append(f"[FETCH] overall_query: {overall_query}")- log_lines.extend(- [- f"[FETCH] title: {title}",- f"[FETCH] page_text ({len(content)} chars):",- content,- f"[FETCH] summary returned ({len(summary)} chars):",- summary or "(empty)",- "[FETCH] ---",- ]- )- logger.info("\n".join(log_lines))-# Guard 2 — empty LLM summary. The model decided nothing on# the page answers the focus (or it returned a malformed/empty# response). Treat as NOT RELEVANT and skip collector@@ -669,8 +646,24 @@ def _make_summary_fetch_tool(# later with a different focus instead of seeing it as# already-cached with an empty body.if not summary:+ logger.info(+ f"[FETCH] mode={mode_label} status=empty_summary "+ f"url={redact_url_for_log(url)} "+ f"page_chars={len(content)}"+ )return f"NOT RELEVANT (no spans matched focus at {url})"+ # Bounded success event: mode, status, redacted origin, and+ # page/summary character counts only. Raw focus, overall query,+ # title, body, and summary text are deliberately NOT logged —+ # they persist to DB/frontend sinks and, for private+ # collection/library documents, are sensitive.+ logger.info(+ f"[FETCH] mode={mode_label} status=success "+ f"url={redact_url_for_log(url)} "+ f"page_chars={len(content)} summary_chars={len(summary)}"+ )+cite_idx = _register_in_collector(collector, url, title, summary)msg = f"[{cite_idx}] Title: {title}\nURL: {url}\n\n{summary}"if limit > 0 and current_count is not None:@@ -687,17 +680,16 @@ def _make_summary_fetch_tool(f"({_denial_reason(exc)}). {_EGRESS_DENIAL_HINT}")except Exception as exc:- # Message carries the mode + a REDACTED scheme://host only (no- # userinfo/path/query) so an operator can locate the failure without- # the log line leaking credentials, query tokens, or page content.- # The traceback follows the sink's diagnose setting (off by default;- # see utilities/log_utils). The agent/user-facing return is scrubbed- # separately below.+ # logger.opt(exception=False).error — explicit no-traceback form+ # that satisfies both custom-checks (no bare logger.error in an+ # except block) and the security contract (no logger.exception+ # traceback, which can embed the raw URL). Message carries the mode+ # + a REDACTED scheme://host only (no userinfo/path/query); the+ # agent/user-facing return is scrubbed separately below.target_url = getattr(exc, "target", "") or url- logger.exception(- "fetch_content tool error (mode={}, url={})",- mode_label,- redact_url_for_log(target_url),+ logger.opt(exception=False).error(+ f"[FETCH] mode={mode_label} status=error "+ f"url={redact_url_for_log(target_url)}")return sanitize_error_for_agent(f"Error fetching {target_url}: {exc}"diff --git a/src/local_deep_research/content_fetcher/fetcher.py b/src/local_deep_research/content_fetcher/fetcher.pyindex 56d0e22693..94a418b8f9 100644--- a/src/local_deep_research/content_fetcher/fetcher.py+++ b/src/local_deep_research/content_fetcher/fetcher.py@@ -13,6 +13,7 @@ from loguru import loggerfrom .url_classifier import URLClassifier, URLTypefrom ..research_library.downloaders.base import ContentTypefrom ..security.egress.fetch import policy_aware_validate_url+from ..security.ssrf_validator import redact_url_for_logfrom ..utilities.resource_utils import safe_close# Default maximum content length (500KB of text)@@ -98,7 +99,7 @@ class ContentFetcher:downloader = ArxivDownloader(timeout=self.timeout)except ImportError:- logger.warning("ArxivDownloader not available")+ logger.warning("content_fetcher.arxiv_downloader_unavailable")elif url_type in (URLType.PUBMED, URLType.PMC):try:@@ -108,7 +109,7 @@ class ContentFetcher:downloader = PubMedDownloader(timeout=self.timeout)except ImportError:- logger.warning("PubMedDownloader not available")+ logger.warning("content_fetcher.pubmed_downloader_unavailable")elif url_type == URLType.SEMANTIC_SCHOLAR:try:@@ -118,7 +119,9 @@ class ContentFetcher:downloader = SemanticScholarDownloader(timeout=self.timeout)except ImportError:- logger.warning("SemanticScholarDownloader not available")+ logger.warning(+ "content_fetcher.semantic_scholar_downloader_unavailable"+ )elif url_type in (URLType.BIORXIV, URLType.MEDRXIV):try:@@ -128,7 +131,7 @@ class ContentFetcher:downloader = BioRxivDownloader(timeout=self.timeout)except ImportError:- logger.warning("BioRxivDownloader not available")+ logger.warning("content_fetcher.biorxiv_downloader_unavailable")elif url_type == URLType.PDF:try:@@ -138,7 +141,9 @@ class ContentFetcher:downloader = DirectPDFDownloader(timeout=self.timeout)except ImportError:- logger.warning("DirectPDFDownloader not available")+ logger.warning(+ "content_fetcher.direct_pdf_downloader_unavailable"+ )elif url_type == URLType.HTML:try:@@ -152,7 +157,7 @@ class ContentFetcher:enable_js_rendering=self.enable_js_rendering,)except ImportError:- logger.warning("HTMLDownloader not available")+ logger.warning("content_fetcher.html_downloader_unavailable")elif url_type == URLType.DOI:# DOI URLs typically redirect to publisher pages@@ -168,7 +173,7 @@ class ContentFetcher:enable_js_rendering=self.enable_js_rendering,)except ImportError:- logger.warning("HTMLDownloader not available")+ logger.warning("content_fetcher.html_downloader_unavailable")# Cache the downloaderif downloader:@@ -204,10 +209,7 @@ class ContentFetcher:scope = self.egress_context.scopeexcept (ImportError, AttributeError): # pragma: no cover - defensive- logger.debug(- "could not resolve egress scope for downloader session",- exc_info=True,- )+ logger.debug("content_fetcher.egress_scope_unavailable")returnif scope == EgressScope.PRIVATE_ONLY:session = getattr(downloader, "session", None)@@ -270,7 +272,10 @@ class ContentFetcher:# Policy-aware so PRIVATE_ONLY egress scope can actually reach# private hosts (lab deployments) without disabling SSRF globally.if not policy_aware_validate_url(url, self.egress_context):- logger.warning(f"URL failed SSRF validation: {url}")+ logger.warning(+ "content_fetcher.ssrf_denied url={url}",+ url=redact_url_for_log(url),+ )return {"status": "error","url": url,@@ -286,14 +291,11 @@ class ContentFetcher:# each remembering to wrap the call site.if self.egress_context is not None:from ..security.egress.policy import evaluate_url- from ..security.ssrf_validator import redact_url_for_logurl_decision = evaluate_url(url, self.egress_context)if not url_decision.allowed:logger.bind(policy_audit=True).warning(- "fetch URL denied by egress policy",- # Redact: a denied URL may carry userinfo creds / API-key- # query params; log only scheme://host:port.+ "content_fetcher.egress_denied url={url} scope={scope} reason={reason}",url=redact_url_for_log(url),scope=self.egress_context.scope.value,reason=url_decision.reason,@@ -309,7 +311,11 @@ class ContentFetcher:),}- logger.info(f"Fetching content from {url} (detected: {source_name})")+ logger.info(+ "content_fetcher.fetch_started url={url} source_type={source_type}",+ url=redact_url_for_log(url),+ source_type=source_name,+ )# Get the appropriate downloaderdownloader = self._get_downloader(url_type)@@ -344,8 +350,8 @@ class ContentFetcher:# this branch as ARXIV, so they are not denied the fallback.if not result.is_success and url_type not in _NO_HTML_FALLBACK:logger.debug(- f"Specialized downloader failed for {url}, "- "trying HTML fallback"+ "content_fetcher.html_fallback_started url={url}",+ url=redact_url_for_log(url),)html_downloader = self._get_downloader(URLType.HTML)if html_downloader:@@ -398,10 +404,15 @@ class ContentFetcher:try:metadata = downloader.get_metadata(url)except Exception:- logger.debug(- "Failed to fetch metadata for {}",- url,- exc_info=True,+ # Best-effort/optional metadata; expected to fail+ # routinely (e.g. no metadata available for this+ # URL type) so keep this at DEBUG, not ERROR, to+ # avoid flooding alerting. Still drop the exception+ # attachment to keep raw/credentialed URLs out of+ # the DB/frontend log sinks.+ logger.opt(exception=False).debug(+ "content_fetcher.metadata_failed url={url}",+ url=redact_url_for_log(url),)return {@@ -422,7 +433,10 @@ class ContentFetcher:}except Exception as e:- logger.exception(f"Error fetching content from {url}")+ logger.opt(exception=False).error(+ "content_fetcher.download_error url={url}",+ url=redact_url_for_log(url),+ )return {"status": "error","url": url,diff --git a/src/local_deep_research/research_library/downloaders/base.py b/src/local_deep_research/research_library/downloaders/base.pyindex 2adff87626..bf7952a5d5 100644--- a/src/local_deep_research/research_library/downloaders/base.py+++ b/src/local_deep_research/research_library/downloaders/base.py@@ -14,11 +14,54 @@ from ...web_search_engines.rate_limiting import (AdaptiveRateLimitTracker,)from ...security import SafeSession+from ...security.log_sanitizer import scrub_error+from ...security.ssrf_validator import redact_url_for_log# Import centralized User-Agent from constantsfrom ...constants import USER_AGENT # noqa: F401 - re-exported for backward compatibility+def rate_limit_authority(url: str) -> str:+ """Return *url*'s authority (``host`` or ``host:port``) for rate-limit keys.++ RFC 3986 userinfo, path, query and fragment are dropped and an IPv6+ literal keeps its brackets. A URL with no authority at all yields+ ``""``; one whose authority will not parse (an invalid port, an+ unterminated ``[``) or whose host carries whitespace or a control+ character yields ``"invalid_authority"``.++ All four downloader fetch paths derive their per-host adaptive+ rate-limit bucket through this one helper, so the keys cannot drift+ apart. It parses the *original* URL rather than re-parsing+ ``redact_url_for_log(url)``: that helper is a display formatter, and its+ rendering of an input it cannot parse has no authority left to recover+ -- ``" https://slow-host.example/paper"`` renders as ``"?:// https"``,+ while ``requests`` lstrips that same leading whitespace and fetches the+ URL anyway. Re-parsing the rendering therefore dropped every+ whitespace-prefixed host into one shared bucket, where a single+ 429-heavy host raises the wait for all the others.++ ``AdaptiveRateLimitTracker`` renders the key into its own log messages,+ so the value must stay one printable token. A host carrying whitespace+ or a control character is not a legal RFC 3986 reg-name, and is not the+ host contacted either -- ``requests`` percent-encodes it, preparing+ ``"https://exa mple.com/p"`` as ``https://exa%20mple.com/p`` -- so it+ buckets as ``"invalid_authority"`` rather than being echoed into a log+ line.+ """+ try:+ parsed = urlparse(url)+ hostname = parsed.hostname or ""+ authority = f"[{hostname}]" if ":" in hostname else hostname+ if parsed.port is not None:+ authority = f"{authority}:{parsed.port}"+ except ValueError:+ return "invalid_authority"+ if any(ch.isspace() or not ch.isprintable() for ch in authority):+ return "invalid_authority"+ return authority++class ContentType(Enum):"""Supported content types for download."""@@ -65,8 +108,21 @@ class BaseDownloader(ABC):if hasattr(self, "session") and self.session:try:self.session.close()- except Exception:- logger.exception("Error closing downloader session")+ except Exception as exc:+ # Keep the scrubbed message -- an event saying only that+ # *something* failed is not a usable diagnostic -- but not+ # the traceback, whose frame-locals loguru's ``diagnose``+ # renders. That is the middle ground ``log_sanitizer``+ # documents ("log without the traceback instead --+ # ``logger.warning(scrub_error(exc, *known_secrets))``") and+ # the ``safe_msg`` shape the sibling ``openalex`` downloader+ # already uses. ERROR is kept (the level the+ # ``logger.exception`` this replaced logged at): this+ # handler's frames hold no URL and no credential.+ safe_msg = scrub_error(exc)+ logger.opt(exception=False).error(+ f"Error closing downloader session: {safe_msg}"+ )finally:self.session = None # type: ignore[assignment]@@ -161,7 +217,10 @@ class BaseDownloader(ABC):try:return content.decode("utf-8")except UnicodeDecodeError:- logger.exception(f"Failed to decode text content from {url}")+ logger.opt(exception=False).error(+ f"Failed to decode text content from "+ f"{redact_url_for_log(url)}"+ )return Nonedef _is_pdf_content(self, response: requests.Response) -> bool:@@ -200,14 +259,13 @@ class BaseDownloader(ABC):Returns:PDF content as bytes, or None if download failed"""- # Extract domain for rate limiting (each domain gets its own rate limit)- domain = urlparse(url).netloc- engine_type = f"pdf_download_{domain}"+ engine_type = f"pdf_download_{rate_limit_authority(url)}"max_attempts = 3logger.debug(- f"Downloading PDF from {url} with adaptive rate limiting (max {max_attempts} attempts)"+ f"Downloading PDF from {redact_url_for_log(url)} with adaptive "+ f"rate limiting (max {max_attempts} attempts)")for attempt in range(1, max_attempts + 1):@@ -234,7 +292,8 @@ class BaseDownloader(ABC):if response.status_code == 200:if self._is_pdf_content(response):logger.debug(- f"Successfully downloaded PDF from {url} on attempt {attempt}"+ f"Successfully downloaded PDF from "+ f"{redact_url_for_log(url)} on attempt {attempt}")# Record successful outcomeself.rate_tracker.record_outcome(@@ -262,7 +321,8 @@ class BaseDownloader(ABC):503,]: # Rate limit or service unavailablelogger.warning(- f"Attempt {attempt}/{max_attempts} - HTTP {response.status_code} from {url}"+ f"Attempt {attempt}/{max_attempts} - HTTP "+ f"{response.status_code} from {redact_url_for_log(url)}")# Record rate limit failureself.rate_tracker.record_outcome(@@ -274,13 +334,16 @@ class BaseDownloader(ABC):)if attempt == max_attempts:logger.error(- f"Failed to download from {url}: HTTP {response.status_code} after {max_attempts} attempts"+ f"Failed to download from "+ f"{redact_url_for_log(url)}: HTTP "+ f"{response.status_code} after {max_attempts} attempts")return None# Continue retry loop with adaptive waitcontinuelogger.warning(- f"Failed to download from {url}: HTTP {response.status_code}"+ f"Failed to download from {redact_url_for_log(url)}: "+ f"HTTP {response.status_code}")# Record failure but don't retry for other status codesself.rate_tracker.record_outcome(@@ -305,16 +368,20 @@ class BaseDownloader(ABC):error_type=type(e).__name__,)if attempt == max_attempts:- logger.exception(- f"{type(e).__name__} downloading from {url} after {max_attempts} attempts"+ logger.opt(exception=False).error(+ f"{type(e).__name__} downloading from "+ f"{redact_url_for_log(url)} after {max_attempts} attempts")return Nonelogger.warning(- f"Attempt {attempt}/{max_attempts} - {type(e).__name__} downloading from {url}"+ f"Attempt {attempt}/{max_attempts} - {type(e).__name__} "+ f"downloading from {redact_url_for_log(url)}")continue # Retry with adaptive waitexcept requests.exceptions.RequestException as e:- logger.exception(f"Request error downloading from {url}")+ logger.opt(exception=False).error(+ f"Request error downloading from {redact_url_for_log(url)}"+ )# Record failure but don't retryself.rate_tracker.record_outcome(engine_type=engine_type,@@ -325,7 +392,9 @@ class BaseDownloader(ABC):)return Noneexcept Exception:- logger.exception(f"Unexpected error downloading from {url}")+ logger.opt(exception=False).error(+ f"Unexpected error downloading from {redact_url_for_log(url)}"+ )# Record failure but don't retryself.rate_tracker.record_outcome(engine_type=engine_type,@@ -369,8 +438,17 @@ class BaseDownloader(ABC):full_text = "\n".join(text_content)return full_text if full_text.strip() else None- except Exception:- logger.exception("Failed to extract text from PDF")+ except Exception as exc:+ # Scrubbed message, no traceback -- see ``close`` above. pypdf can+ # raise ``PdfReadError`` with a message that embeds a slice of+ # the raw stream (e.g. a malformed header byte sequence). The+ # message is kept here not because it is always the whole+ # diagnostic, but because this frame holds only the PDF bytes --+ # no URL or credential -- so there is nothing for it to leak.+ safe_msg = scrub_error(exc)+ logger.opt(exception=False).error(+ f"Failed to extract text from PDF: {safe_msg}"+ )return Nonedef _fetch_text_from_api(self, url: str) -> Optional[str]:diff --git a/src/local_deep_research/research_library/downloaders/biorxiv.py b/src/local_deep_research/research_library/downloaders/biorxiv.pyindex 87cf95d7f2..d5004acbf2 100644--- a/src/local_deep_research/research_library/downloaders/biorxiv.py+++ b/src/local_deep_research/research_library/downloaders/biorxiv.py@@ -9,6 +9,7 @@ from urllib.parse import urlparseimport requestsfrom loguru import logger+from ...security.ssrf_validator import redact_url_for_logfrom .base import BaseDownloader, ContentType, DownloadResult@@ -69,7 +70,9 @@ class BioRxivDownloader(BaseDownloader):skip_reason="Invalid bioRxiv/medRxiv URL format")- logger.info(f"Downloading bioRxiv/medRxiv PDF from {pdf_url}")+ logger.info(+ f"Downloading bioRxiv/medRxiv PDF from {redact_url_for_log(pdf_url)}"+ )pdf_content = super()._download_pdf(pdf_url)if pdf_content:@@ -88,7 +91,10 @@ class BioRxivDownloader(BaseDownloader):status_code=response.status_code,)except requests.RequestException:- logger.debug("Failed to check bioRxiv/medRxiv URL: {}", url)+ logger.opt(exception=False).debug(+ "Failed to check bioRxiv/medRxiv URL: {}",+ redact_url_for_log(url),+ )return DownloadResult(skip_reason="Failed to download PDF from bioRxiv/medRxiv")@@ -101,10 +107,14 @@ class BioRxivDownloader(BaseDownloader):pdf_url = self._convert_to_pdf_url(url)if not pdf_url:- logger.error(f"Could not convert to PDF URL: {url}")+ logger.error(+ f"Could not convert to PDF URL: {redact_url_for_log(url)}"+ )return None- logger.info(f"Downloading bioRxiv/medRxiv PDF from {pdf_url}")+ logger.info(+ f"Downloading bioRxiv/medRxiv PDF from {redact_url_for_log(pdf_url)}"+ )return super()._download_pdf(pdf_url)def _download_text(self, url: str) -> Optional[bytes]:@@ -191,7 +201,10 @@ class BioRxivDownloader(BaseDownloader):)return "\n".join(text_parts)- except Exception as e:- logger.debug(f"Failed to fetch abstract from bioRxiv/medRxiv: {e}")+ except Exception:+ logger.opt(exception=False).debug(+ "Failed to fetch abstract from bioRxiv/medRxiv: {}",+ redact_url_for_log(url),+ )return Nonediff --git a/src/local_deep_research/research_library/downloaders/direct_pdf.py b/src/local_deep_research/research_library/downloaders/direct_pdf.pyindex 973c89983f..011ff2f009 100644--- a/src/local_deep_research/research_library/downloaders/direct_pdf.py+++ b/src/local_deep_research/research_library/downloaders/direct_pdf.py@@ -7,6 +7,7 @@ from urllib.parse import urlparsefrom loguru import loggerfrom .base import BaseDownloader, ContentType, DownloadResult+from ...security.ssrf_validator import redact_url_for_logclass DirectPDFDownloader(BaseDownloader):@@ -39,7 +40,7 @@ class DirectPDFDownloader(BaseDownloader):return Falseexcept Exception:- logger.warning(f"Error parsing URL {url}")+ logger.warning(f"Error parsing URL {redact_url_for_log(url)}")return Falsedef download(@@ -76,11 +77,16 @@ class DirectPDFDownloader(BaseDownloader):skip_reason="Could not download PDF from direct link")# Try to download PDF directly- logger.info(f"Attempting direct PDF download from {url}")+ logger.info(+ f"Attempting direct PDF download from {redact_url_for_log(url)}"+ )pdf_content = super()._download_pdf(url)if pdf_content:- logger.info(f"Successfully downloaded PDF directly from {url}")+ logger.info(+ f"Successfully downloaded PDF directly from "+ f"{redact_url_for_log(url)}"+ )return DownloadResult(content=pdf_content, is_success=True)# Try to determine specific reason for failuretry:@@ -113,5 +119,5 @@ class DirectPDFDownloader(BaseDownloader):self, url: str, headers: Optional[Dict[str, str]] = None) -> Optional[bytes]:"""Download PDF directly from URL."""- logger.info(f"Downloading PDF directly from: {url}")+ logger.info(f"Downloading PDF directly from: {redact_url_for_log(url)}")return super()._download_pdf(url)diff --git a/src/local_deep_research/research_library/downloaders/extraction/pipeline.py b/src/local_deep_research/research_library/downloaders/extraction/pipeline.pyindex 3912ef7a18..de1dc79efe 100644--- a/src/local_deep_research/research_library/downloaders/extraction/pipeline.py+++ b/src/local_deep_research/research_library/downloaders/extraction/pipeline.py@@ -26,6 +26,7 @@ from .readability_extractor import ReadabilityExtractorfrom .justext_extractor import JustextExtractorfrom .newspaper_extractor import NewspaperExtractorfrom .metadata_extractor import extract_metadata, metadata_to_text+from ....security.ssrf_validator import redact_url_for_logfrom ....utilities.lxml_thread_safety import install_per_thread_html_parsers# Route newspaper4k's and readabilipy's parser-less lxml.html.fromstring calls@@ -500,16 +501,17 @@ def _try_specialized_downloader(if len(text.strip()) >= MIN_CONTENT_LENGTH:logger.debug(f"Pipeline: specialized downloader ({url_type.value}) "- f"returned {len(text)} chars for {url}"+ f"returned {len(text)} chars for "+ f"{redact_url_for_log(url)}")return _SpecializedResult(content=text,fallback_allowed=not arxiv_terminal,)except Exception:- logger.debug(- f"Pipeline: specialized downloader failed for {url}",- exc_info=True,+ logger.opt(exception=False).debug(+ f"Pipeline: specialized downloader failed for "+ f"{redact_url_for_log(url)}")finally:try:@@ -518,9 +520,11 @@ def _try_specialized_downloader(passif failure.fallback_allowed:+ # Specialized downloader didn't produce content — fall back to HTMLlogger.debug(f"Pipeline: specialized downloader ({url_type.value}) returned "- f"no content for {url}, falling back to HTML pipeline"+ f"no content for {redact_url_for_log(url)}, "+ f"falling back to HTML pipeline")return failure@@ -572,9 +576,9 @@ def fetch_and_extract(try:specialized = _try_specialized_downloader(url, timeout=timeout)except Exception:- logger.debug(- f"Pipeline: specialized downloader error for {url}",- exc_info=True,+ logger.opt(exception=False).debug(+ f"Pipeline: specialized downloader error for "+ f"{redact_url_for_log(url)}")specialized = _SpecializedResult(fallback_allowed=not is_arxiv_paper_url(url)@@ -603,7 +607,9 @@ def fetch_and_extract(return result.decode("utf-8", errors="replace")return Noneexcept Exception:- logger.exception(f"fetch_and_extract failed for {url}")+ logger.opt(exception=False).error(+ f"fetch_and_extract failed for {redact_url_for_log(url)}"+ )return Nonefinally:try:@@ -672,9 +678,9 @@ def batch_fetch_and_extract(results[url] = Nonecontinueexcept Exception:- logger.debug(- f"Pipeline: specialized downloader error for {url}",- exc_info=True,+ logger.opt(exception=False).debug(+ f"Pipeline: specialized downloader error for "+ f"{redact_url_for_log(url)}")if is_arxiv_paper_url(url):results[url] = None@@ -699,8 +705,9 @@ def batch_fetch_and_extract(else:results[url] = Noneexcept Exception:- logger.exception(- f"batch_fetch_and_extract failed for {url}"+ logger.opt(exception=False).error(+ f"batch_fetch_and_extract failed for "+ f"{redact_url_for_log(url)}")results[url] = Nonefinally:diff --git a/src/local_deep_research/research_library/downloaders/generic.py b/src/local_deep_research/research_library/downloaders/generic.pyindex 47ac0dc929..10ad940580 100644--- a/src/local_deep_research/research_library/downloaders/generic.py+++ b/src/local_deep_research/research_library/downloaders/generic.py@@ -7,6 +7,7 @@ import requestsfrom urllib.parse import urlparsefrom loguru import logger+from ...security.ssrf_validator import redact_url_for_logfrom .base import BaseDownloader, ContentType, DownloadResult@@ -53,13 +54,17 @@ class GenericDownloader(BaseDownloader):)return DownloadResult(skip_reason="Could not download PDF from URL")# Try to download as PDF- logger.info(f"Attempting generic download from {url}")+ logger.info(+ f"Attempting generic download from {redact_url_for_log(url)}"+ )# Try direct downloadpdf_content = super()._download_pdf(url)if pdf_content:- logger.info(f"Successfully downloaded PDF from {url}")+ logger.info(+ f"Successfully downloaded PDF from {redact_url_for_log(url)}"+ )return DownloadResult(content=pdf_content, is_success=True)# If the URL doesn't end with .pdf, try adding it@@ -67,7 +72,9 @@ class GenericDownloader(BaseDownloader):parsed = urlparse(url)if not parsed.path.endswith(".pdf"):pdf_url = url.rstrip("/") + ".pdf"- logger.debug(f"Trying with .pdf extension: {pdf_url}")+ logger.debug(+ f"Trying with .pdf extension: {redact_url_for_log(pdf_url)}"+ )pdf_content = super()._download_pdf(pdf_url)else:pdf_content = None@@ -76,7 +83,9 @@ class GenericDownloader(BaseDownloader):pdf_content = Noneif pdf_content:- logger.info(f"Successfully downloaded PDF from {pdf_url}")+ logger.info(+ f"Successfully downloaded PDF from {redact_url_for_log(pdf_url)}"+ )return DownloadResult(content=pdf_content, is_success=True)# Diagnostic request: determine WHY the download failed.@@ -145,7 +154,9 @@ class GenericDownloader(BaseDownloader):skip_reason="Could not connect to server - website may be down")except requests.RequestException:- logger.warning("Unexpected error checking URL: {}", url)+ logger.opt(exception=False).warning(+ "Unexpected error checking URL: {}", redact_url_for_log(url)+ )return DownloadResult(skip_reason="Network error - could not reach the website")@@ -154,13 +165,17 @@ class GenericDownloader(BaseDownloader):self, url: str, headers: Optional[Dict[str, str]] = None) -> Optional[bytes]:"""Attempt to download PDF from URL."""- logger.info(f"Attempting generic download from {url}")+ logger.info(+ f"Attempting generic download from {redact_url_for_log(url)}"+ )# Try direct downloadpdf_content = super()._download_pdf(url)if pdf_content:- logger.info(f"Successfully downloaded PDF from {url}")+ logger.info(+ f"Successfully downloaded PDF from {redact_url_for_log(url)}"+ )return pdf_content# If the URL doesn't end with .pdf, try adding it@@ -168,7 +183,9 @@ class GenericDownloader(BaseDownloader):parsed = urlparse(url)if not parsed.path.endswith(".pdf"):pdf_url = url.rstrip("/") + ".pdf"- logger.debug(f"Trying with .pdf extension: {pdf_url}")+ logger.debug(+ f"Trying with .pdf extension: {redact_url_for_log(pdf_url)}"+ )pdf_content = super()._download_pdf(pdf_url)else:pdf_content = None@@ -177,8 +194,10 @@ class GenericDownloader(BaseDownloader):pdf_content = Noneif pdf_content:- logger.info(f"Successfully downloaded PDF from {pdf_url}")+ logger.info(+ f"Successfully downloaded PDF from {redact_url_for_log(pdf_url)}"+ )return pdf_content- logger.warning(f"Failed to download PDF from {url}")+ logger.warning(f"Failed to download PDF from {redact_url_for_log(url)}")return Nonediff --git a/src/local_deep_research/research_library/downloaders/html.py b/src/local_deep_research/research_library/downloaders/html.pyindex ec241783ab..0ded4b31ec 100644--- a/src/local_deep_research/research_library/downloaders/html.py+++ b/src/local_deep_research/research_library/downloaders/html.py@@ -10,10 +10,16 @@ from urllib.parse import urlparsefrom loguru import loggerfrom bs4 import BeautifulSoup-from .base import BaseDownloader, ContentType, DownloadResult+from .base import (+ BaseDownloader,+ ContentType,+ DownloadResult,+ rate_limit_authority,+)from .extraction.pipeline import extract_content_with_metadatafrom ...constants import BROWSER_USER_AGENTfrom ...security import sanitize_error_for_client+from ...security.ssrf_validator import redact_url_for_logdef _as_markdown_text(value: str) -> str:@@ -79,7 +85,10 @@ class HTMLDownloader(BaseDownloader):Extracted text as UTF-8 bytes, or None if failed"""if content_type == ContentType.PDF:- logger.warning(f"HTML downloader cannot download PDFs: {url}")+ logger.warning(+ "html.download_pdf_unsupported url={url}",+ url=redact_url_for_log(url),+ )return Nonetry:@@ -95,7 +104,10 @@ class HTMLDownloader(BaseDownloader):return Noneexcept Exception:- logger.exception(f"Failed to download HTML from {url}")+ logger.opt(exception=False).error(+ "html.download_failed url={url}",+ url=redact_url_for_log(url),+ )return Nonedef download_with_result(@@ -130,10 +142,14 @@ class HTMLDownloader(BaseDownloader):)except Exception as e:- logger.exception(f"Failed to download HTML from {url}")+ logger.opt(exception=False).error(+ "html.download_result_failed url={url}",+ url=redact_url_for_log(url),+ )# skip_reason propagates to the browser via the download SSE# stream; the fetch URL can carry credentials — scrub before- # returning (full detail stays in the server log above).+ # returning (the exception detail is deliberately NOT logged+ # above; a traceback could re-embed the credentialed URL).return DownloadResult(skip_reason=sanitize_error_for_client(f"Error: {str(e)}"))@@ -151,9 +167,11 @@ class HTMLDownloader(BaseDownloader):Callers that require the response to stay on a specific path mustcompare the returned URL themselves."""- logger.debug(f"Static fetch: {url}")- domain = urlparse(url).netloc- engine_type = f"html_download_{domain}"+ logger.debug(+ "html.fetch_started url={url}",+ url=redact_url_for_log(url),+ )+ engine_type = f"html_download_{rate_limit_authority(url)}"wait_time = self.rate_tracker.apply_rate_limit(engine_type)@@ -177,12 +195,22 @@ class HTMLDownloader(BaseDownloader):retry_count=1,search_result_count=1,)+ logger.debug(+ "html.fetch_succeeded url={url}",+ url=redact_url_for_log(url),+ )return response.text, response.urllogger.warning(- f"Unexpected content type for HTML download: {content_type}"+ "html.fetch_unexpected_content_type url={url} status={status}",+ url=redact_url_for_log(url),+ status=response.status_code,)return None, None- logger.warning(f"HTTP {response.status_code} fetching {url}")+ logger.warning(+ "html.fetch_failed url={url} status={status}",+ url=redact_url_for_log(url),+ status=response.status_code,+ )self.rate_tracker.record_outcome(engine_type=engine_type,wait_time=wait_time,@@ -193,7 +221,10 @@ class HTMLDownloader(BaseDownloader):return None, Noneexcept Exception as e:- logger.exception(f"Error fetching HTML from {url}")+ logger.opt(exception=False).error(+ "html.fetch_error url={url}",+ url=redact_url_for_log(url),+ )self.rate_tracker.record_outcome(engine_type=engine_type,wait_time=wait_time,@@ -218,8 +249,9 @@ class HTMLDownloader(BaseDownloader):content = result["content"]logger.info(- f"Extracted {len(content)} chars from {url} "- f"(title: {title[:50] + '...' if title and len(title) > 50 else title})"+ "html.extract_succeeded url={url} content_length={content_length}",+ url=redact_url_for_log(url),+ content_length=len(content),)return {"title": title,@@ -229,7 +261,10 @@ class HTMLDownloader(BaseDownloader):}except Exception:- logger.exception("Error extracting content from HTML")+ logger.opt(exception=False).error(+ "html.extract_failed url={url}",+ url=redact_url_for_log(url),+ )return Nonedef _format_extracted_content(self, extracted: Dict[str, Any]) -> str:@@ -286,5 +321,8 @@ class HTMLDownloader(BaseDownloader):return metadataexcept Exception:- logger.exception(f"Error extracting metadata from {url}")+ logger.opt(exception=False).error(+ "html.metadata_extract_failed url={url}",+ url=redact_url_for_log(url),+ )return {"url": url}diff --git a/src/local_deep_research/research_library/downloaders/playwright_html.py b/src/local_deep_research/research_library/downloaders/playwright_html.pyindex c165f423bd..20816a9b1c 100644--- a/src/local_deep_research/research_library/downloaders/playwright_html.py+++ b/src/local_deep_research/research_library/downloaders/playwright_html.py@@ -19,9 +19,11 @@ from urllib.parse import urljoin, urlparsefrom loguru import logger+from .base import rate_limit_authorityfrom .html import HTMLDownloaderfrom ...constants import BROWSER_USER_AGENTfrom ...security import ssrf_validator+from ...security.ssrf_validator import redact_url_for_logfrom ...security.safe_requests import (_MAX_REDIRECTS,_REDIRECT_STATUS_CODES,@@ -396,16 +398,17 @@ class PlaywrightHTMLDownloader(HTMLDownloader):# request.headers and must never let an exception escape# this route handler and fall through to an unguarded# fetch — abort the hop exactly like a failed fetch below.- logger.debug(- "Playwright: failed to build guarded hop headers",- exc_info=True,+ logger.opt(exception=False).debug(+ "Playwright: failed to build guarded hop headers")route.abort("failed")returntry:response = route.fetch(**fetch_kwargs)except Exception:- logger.debug("Playwright: guarded fetch failed", exc_info=True)+ logger.opt(exception=False).debug(+ "Playwright: guarded fetch failed"+ )route.abort("failed")returnnext_url = self._redirect_target(current, response)@@ -532,16 +535,17 @@ class PlaywrightHTMLDownloader(HTMLDownloader):# request.headers and must never let an exception escape# this route handler and fall through to an unguarded# fetch — abort the hop exactly like a failed fetch below.- logger.debug(- "Crawl4AI: failed to build guarded hop headers",- exc_info=True,+ logger.opt(exception=False).debug(+ "Crawl4AI: failed to build guarded hop headers")await route.abort("failed")returntry:response = await route.fetch(**fetch_kwargs)except Exception:- logger.debug("Crawl4AI: guarded fetch failed", exc_info=True)+ logger.opt(exception=False).debug(+ "Crawl4AI: guarded fetch failed"+ )await route.abort("failed")returnnext_url = self._redirect_target(current, response)@@ -629,9 +633,8 @@ class PlaywrightHTMLDownloader(HTMLDownloader):try:parsed = _parse_one_set_cookie(raw)except Exception:- logger.debug(- "Browser guard: failed to parse a Set-Cookie header",- exc_info=True,+ logger.opt(exception=False).debug(+ "Browser guard: failed to parse a Set-Cookie header")continueif parsed is None:@@ -733,9 +736,8 @@ class PlaywrightHTMLDownloader(HTMLDownloader):live_cookies = await context.cookies(next_hop_url)return "; ".join(f"{c['name']}={c['value']}" for c in live_cookies)except Exception:- logger.debug(- "Crawl4AI: failed to re-apply redirect-hop cookies",- exc_info=True,+ logger.opt(exception=False).debug(+ "Crawl4AI: failed to re-apply redirect-hop cookies")# Prefer sending NO cookie to the next hop over resending a# previous hop's (possibly cross-domain) one: "" clears the@@ -773,9 +775,8 @@ class PlaywrightHTMLDownloader(HTMLDownloader):live_cookies = context.cookies(next_hop_url)return "; ".join(f"{c['name']}={c['value']}" for c in live_cookies)except Exception:- logger.debug(- "Playwright: failed to re-apply redirect-hop cookies",- exc_info=True,+ logger.opt(exception=False).debug(+ "Playwright: failed to re-apply redirect-hop cookies")return "" if next_hop_url is not None else None@@ -899,7 +900,9 @@ class PlaywrightHTMLDownloader(HTMLDownloader):# SafeSession raises ValueError on an SSRF-unsafe hop; network /# parse errors land here too. Fail open for politeness — the# actual navigation is still validated by the browser guard.- logger.debug("Guarded robots.txt check failed open", exc_info=True)+ logger.opt(exception=False).debug(+ "Guarded robots.txt check failed open"+ )return Truedef _fetch_html(self, url: str) -> Optional[str]:@@ -937,8 +940,7 @@ class PlaywrightHTMLDownloader(HTMLDownloader):def _fetch_with_crawl4ai(self, url: str) -> Optional[str]:"""Fetch HTML using Crawl4AI with ethical defaults."""- domain = urlparse(url).netloc- engine_type = f"crawl4ai_download_{domain}"+ engine_type = f"crawl4ai_download_{rate_limit_authority(url)}"try:from crawl4ai import (@@ -947,7 +949,10 @@ class PlaywrightHTMLDownloader(HTMLDownloader):CrawlerRunConfig,)except ImportError:- logger.debug("crawl4ai not installed — using Playwright")+ logger.debug(+ "crawl4ai.unavailable url={url}",+ url=redact_url_for_log(url),+ )return None# Ethical robots.txt check — done HERE through the guarded@@ -962,7 +967,10 @@ class PlaywrightHTMLDownloader(HTMLDownloader):)return "" # Empty string signals intentional skip- logger.debug(f"Crawl4AI fetch: {url}")+ logger.debug(+ "crawl4ai.fetch_started url={url}",+ url=redact_url_for_log(url),+ )wait_time = self.rate_tracker.apply_rate_limit(engine_type)browser_cfg = BrowserConfig(@@ -1060,7 +1068,11 @@ class PlaywrightHTMLDownloader(HTMLDownloader):if result.success and result.html:html = result.html- logger.debug(f"Crawl4AI: got {len(html)} bytes from {url}")+ logger.debug(+ "crawl4ai.fetch_succeeded url={url} content_length={content_length}",+ url=redact_url_for_log(url),+ content_length=len(html),+ )self.rate_tracker.record_outcome(engine_type=engine_type,wait_time=wait_time,@@ -1074,8 +1086,8 @@ class PlaywrightHTMLDownloader(HTMLDownloader):error_msg = getattr(result, "error_message", "") or ""if "robots.txt" in error_msg.lower():logger.info(- "Crawl4AI: blocked by robots.txt for {}",- ssrf_validator.redact_url_for_log(url),+ "crawl4ai.robots_denied url={url}",+ url=redact_url_for_log(url),)# Don't fall back to Playwright — respect the blockself.rate_tracker.record_outcome(@@ -1089,8 +1101,8 @@ class PlaywrightHTMLDownloader(HTMLDownloader):status = getattr(result, "status_code", "unknown")logger.debug(- f"Crawl4AI: failed for {url} — "- f"success={result.success}, status={status}"+ "crawl4ai.fetch_failed url={url}",+ url=redact_url_for_log(url),)self.rate_tracker.record_outcome(engine_type=engine_type,@@ -1102,7 +1114,17 @@ class PlaywrightHTMLDownloader(HTMLDownloader):return Noneexcept Exception as e:- logger.debug(f"Crawl4AI error for {url}: {e}")+ # DEBUG, not ERROR: this except is normal control flow — it+ # returns None, so _fetch_html falls back to+ # _fetch_with_playwright and the fetch usually then succeeds.+ # Logging this at ERROR would write a false-alarm entry into the+ # encrypted DB sink and the frontend progress stream for every+ # crawl4ai hiccup, even when the overall fetch didn't fail.+ logger.opt(exception=False).debug(+ "crawl4ai.fetch_error url={url} error_type={error_type}",+ url=redact_url_for_log(url),+ error_type=type(e).__name__,+ )self.rate_tracker.record_outcome(engine_type=engine_type,wait_time=wait_time,@@ -1114,9 +1136,11 @@ class PlaywrightHTMLDownloader(HTMLDownloader):def _fetch_with_playwright(self, url: str) -> Optional[str]:"""Fetch HTML using plain Playwright (fallback)."""- logger.debug(f"Playwright fetch: {url}")- domain = urlparse(url).netloc- engine_type = f"playwright_download_{domain}"+ logger.debug(+ "playwright.fetch_started url={url}",+ url=redact_url_for_log(url),+ )+ engine_type = f"playwright_download_{rate_limit_authority(url)}"wait_time = self.rate_tracker.apply_rate_limit(engine_type)@@ -1131,7 +1155,10 @@ class PlaywrightHTMLDownloader(HTMLDownloader):# --disable-dev-shm-usage: Docker's default /dev/shm is 64 MB,# which Chromium can blow through and OOM. Use /tmp instead.if self._browser is None:- logger.debug("Playwright: launching Chromium browser")+ logger.debug(+ "playwright.launch_started url={url}",+ url=redact_url_for_log(url),+ )pw = sync_playwright().start()try:self._browser = pw.chromium.launch(@@ -1187,10 +1214,17 @@ class PlaywrightHTMLDownloader(HTMLDownloader):try:page.close()except Exception:- logger.debug("Failed to close Playwright page")+ logger.debug(+ "playwright.page_close_failed url={url}",+ url=redact_url_for_log(url),+ )if html:- logger.debug(f"Playwright: got {len(html)} bytes from {url}")+ logger.debug(+ "playwright.fetch_succeeded url={url} content_length={content_length}",+ url=redact_url_for_log(url),+ content_length=len(html),+ )self.rate_tracker.record_outcome(engine_type=engine_type,wait_time=wait_time,@@ -1200,14 +1234,23 @@ class PlaywrightHTMLDownloader(HTMLDownloader):)return html- logger.debug(f"Playwright: empty response from {url}")+ logger.debug(+ "playwright.fetch_empty url={url}",+ url=redact_url_for_log(url),+ )return Noneexcept ImportError:- logger.warning("playwright not installed — cannot use JS rendering")+ logger.warning(+ "playwright.unavailable url={url}",+ url=redact_url_for_log(url),+ )return Noneexcept Exception as e:- logger.exception(f"Playwright error fetching {url}")+ logger.opt(exception=False).error(+ "playwright.fetch_error url={url}",+ url=redact_url_for_log(url),+ )self.rate_tracker.record_outcome(engine_type=engine_type,wait_time=wait_time,@@ -1223,15 +1266,13 @@ class PlaywrightHTMLDownloader(HTMLDownloader):try:self._browser.close()except Exception:- logger.debug(- "Failed to close Playwright browser", exc_info=True- )+ logger.debug("playwright.browser_close_failed")self._browser = Noneif self._playwright:try:self._playwright.stop()except Exception:- logger.debug("Failed to stop Playwright", exc_info=True)+ logger.debug("playwright.stop_failed")self._playwright = Nonesuper().close()@@ -1325,7 +1366,14 @@ class AutoHTMLDownloader(HTMLDownloader):)self._last_raw_html = response.textexcept Exception:- logger.debug("Failed to fetch raw HTML for SPA detection")+ # Expected/routine (403s, challenge pages, network blips) —+ # keep at DEBUG, not ERROR, to avoid flooding alerting. Still+ # drop the exception attachment: a network error here can embed+ # the raw/credentialed URL or a cookie value.+ logger.opt(exception=False).debug(+ "auto_html.raw_fetch_failed url={url}",+ url=redact_url_for_log(url),+ )return Nonedef download(self, url, content_type=None):@@ -1336,12 +1384,17 @@ class AutoHTMLDownloader(HTMLDownloader):content_type = ContentType.TEXT# First: try static fetch (fast)- logger.debug(f"Auto: trying static fetch for {url}")+ logger.debug(+ "auto_html.static_fetch_started url={url}",+ url=redact_url_for_log(url),+ )result = super().download(url, content_type)if result and len(result) >= self.min_content_length:logger.debug(- f"Auto: static fetch succeeded ({len(result)} bytes) for {url}"+ "auto_html.static_fetch_succeeded url={url} content_length={content_length}",+ url=redact_url_for_log(url),+ content_length=len(result),)return result@@ -1353,23 +1406,27 @@ class AutoHTMLDownloader(HTMLDownloader):if needs_js or no_content:if not self.enable_js_rendering:logger.debug(- f"Auto: would fall back to JS rendering for {url}, "- "but JS rendering is disabled "- "(setting: web.enable_javascript_rendering)"+ "auto_html.js_fallback_disabled url={url}",+ url=redact_url_for_log(url),)return result- reason = "SPA signals" if needs_js else "no/short content"logger.info(- f"Auto: {reason} for {url}, falling back to JS rendering"+ "auto_html.js_fallback_started url={url}",+ url=redact_url_for_log(url),)pw_dl = self._get_playwright_downloader()pw_result = pw_dl.download(url, content_type)if pw_result and len(pw_result) > len(result or b""):logger.info(- f"Auto: JS rendering succeeded ({len(pw_result)} bytes) for {url}"+ "auto_html.js_succeeded url={url} content_length={content_length}",+ url=redact_url_for_log(url),+ content_length=len(pw_result),)return pw_result- logger.debug(f"Auto: JS rendering did not improve result for {url}")+ logger.debug(+ "auto_html.js_not_improved url={url}",+ url=redact_url_for_log(url),+ )return result@@ -1381,7 +1438,10 @@ class AutoHTMLDownloader(HTMLDownloader):content_type = ContentType.TEXT# First: try static fetch (fast)- logger.debug(f"Auto: trying static fetch for {url}")+ logger.debug(+ "auto_html.static_fetch_started url={url}",+ url=redact_url_for_log(url),+ )result = super().download_with_result(url, content_type)if (@@ -1390,7 +1450,9 @@ class AutoHTMLDownloader(HTMLDownloader):and len(result.content) >= self.min_content_length):logger.debug(- f"Auto: static fetch succeeded ({len(result.content)} bytes) for {url}"+ "auto_html.static_fetch_succeeded url={url} content_length={content_length}",+ url=redact_url_for_log(url),+ content_length=len(result.content),)return result@@ -1406,14 +1468,13 @@ class AutoHTMLDownloader(HTMLDownloader):if needs_js or no_content:if not self.enable_js_rendering:logger.debug(- f"Auto: would fall back to JS rendering for {url}, "- "but JS rendering is disabled "- "(setting: web.enable_javascript_rendering)"+ "auto_html.js_fallback_disabled url={url}",+ url=redact_url_for_log(url),)return result- reason = "SPA signals" if needs_js else "no/short content"logger.info(- f"Auto: {reason} for {url}, falling back to JS rendering"+ "auto_html.js_fallback_started url={url}",+ url=redact_url_for_log(url),)pw_dl = self._get_playwright_downloader()pw_result = pw_dl.download_with_result(url, content_type)@@ -1423,11 +1484,15 @@ class AutoHTMLDownloader(HTMLDownloader):and len(pw_result.content) > len(result.content or b"")):logger.info(- f"Auto: JS rendering succeeded "- f"({len(pw_result.content)} bytes) for {url}"+ "auto_html.js_succeeded url={url} content_length={content_length}",+ url=redact_url_for_log(url),+ content_length=len(pw_result.content),)return pw_result- logger.debug(f"Auto: JS rendering did not improve result for {url}")+ logger.debug(+ "auto_html.js_not_improved url={url}",+ url=redact_url_for_log(url),+ )return resultdiff --git a/src/local_deep_research/research_library/downloaders/semantic_scholar.py b/src/local_deep_research/research_library/downloaders/semantic_scholar.pyindex 192704fb6d..7dda6ce721 100644--- a/src/local_deep_research/research_library/downloaders/semantic_scholar.py+++ b/src/local_deep_research/research_library/downloaders/semantic_scholar.py@@ -11,6 +11,8 @@ from urllib.parse import urlparseimport requestsfrom loguru import logger+from ...security.log_sanitizer import scrub_error+from ...security.ssrf_validator import redact_url_for_logfrom .base import BaseDownloader, ContentType, DownloadResult@@ -78,7 +80,9 @@ class SemanticScholarDownloader(BaseDownloader):)# Download the PDF from the open access URL- logger.info(f"Downloading open access PDF from: {pdf_url}")+ logger.info(+ f"Downloading open access PDF from: {redact_url_for_log(pdf_url)}"+ )pdf_content = super()._download_pdf(pdf_url)if pdf_content:@@ -143,7 +147,8 @@ class SemanticScholarDownloader(BaseDownloader):pdf_url = open_access_pdf.get("url")if pdf_url:logger.info(- f"Found open access PDF for paper {paper_id}: {pdf_url}"+ f"Found open access PDF for paper {paper_id}: "+ f"{redact_url_for_log(str(pdf_url))}")return str(pdf_url)@@ -162,12 +167,35 @@ class SemanticScholarDownloader(BaseDownloader):)return None- except requests.exceptions.RequestException:- logger.exception("Failed to query Semantic Scholar API")+ # Both handlers keep the scrubbed message rather than dropping the+ # API error -- the ``safe_msg`` shape the sibling ``openalex``+ # downloader uses for the same handler pair. No traceback: these+ # frames hold the Semantic Scholar API key (``self.api_key`` and the+ # ``headers`` dict built from it), which loguru's ``diagnose``+ # renders for every frame-local, so ``scrub_error`` is passed that+ # key as a known literal on top of its shape-based scrubbing.+ #+ # WARNING rather than the ERROR main's ``logger.exception`` logged+ # at: open-access PDF discovery is optional -- the caller falls back+ # to the landing page -- so a network blip or a malformed response+ # here is routine, not an outage.+ except requests.exceptions.RequestException as exc:+ safe_msg = scrub_error(exc, self.api_key)+ logger.opt(exception=False).warning(+ "Failed to query Semantic Scholar API for paper {}: {}",+ paper_id,+ safe_msg,+ )return None- except ValueError:+ except ValueError as exc:# JSON decode errors are expected runtime errors- logger.exception("Failed to parse Semantic Scholar API response")+ safe_msg = scrub_error(exc, self.api_key)+ logger.opt(exception=False).warning(+ "Failed to parse Semantic Scholar API response for paper "+ "{}: {}",+ paper_id,+ safe_msg,+ )return None# Note: KeyError and TypeError are not caught - they indicate programming# bugs that should propagate for debuggingdiff --git a/src/local_deep_research/security/safe_requests.py b/src/local_deep_research/security/safe_requests.pyindex f1dce89009..9e2076a7d7 100644--- a/src/local_deep_research/security/safe_requests.py+++ b/src/local_deep_research/security/safe_requests.py@@ -741,13 +741,15 @@ class SafeSession(requests.Session):block_link_local=self.block_link_local,):logger.warning(- f"Request to {request.url} blocked by SSRF validation"+ f"Request to {ssrf_validator.redact_url_for_log(request.url)} "+ f"blocked by SSRF validation")# Note: This error says "security validation" while safe_get/# safe_post say "SSRF validation". The difference indicates the# source (session vs standalone function) in logs.raise ValueError(- f"Redirect target failed security validation (possible SSRF): {request.url}"+ f"Redirect target failed security validation (possible SSRF): "+ f"{ssrf_validator.redact_url_for_log(request.url)}")# Pin the validated IP for the connection this send performs. send()diff --git a/src/local_deep_research/utilities/log_utils.py b/src/local_deep_research/utilities/log_utils.pyindex 07612587be..8c69c96c44 100644--- a/src/local_deep_research/utilities/log_utils.py+++ b/src/local_deep_research/utilities/log_utils.py@@ -83,9 +83,9 @@ Default log directory to use."""# Cap how much of a single log record's message we ship to the browser over-# socket.io. Some diagnostic log lines (e.g. ``[FETCH] page_text``) inline-# the full extracted page body — up to ~10 KB per call — which is useless-# in the UI (a single massive blob fills the viewport) and inflates both+# socket.io. Some diagnostic / agent log lines can carry large payloads+# (model outputs, long tracebacks, extracted text) — many KB per call — which+# is useless in the UI (a single massive blob fills the viewport) and inflates both# wire traffic and client-side state. Container-log/stderr, file, and DB# sinks remain unchanged, so full diagnostics are preserved for grep/DB# queries. The cap bounds the *prefix* preserved from the original message;@@ -637,10 +637,10 @@ def _truncate_for_frontend(message: str) -> str:appended that names the original length and points the user at theserver-side logs for the full text, so the returned string is``FRONTEND_MESSAGE_MAX_LENGTH`` plus the fixed indicator overhead- (~100 bytes). Verbose diagnostic logs (e.g. ``[FETCH] page_text``- which inlines the full extracted page body) are useless in the UI- when displayed in full and inflate socket payloads + client-side- memory; container-log/stderr, file, and DB sinks remain unchanged.+ (~100 bytes). Verbose diagnostic / agent logs (model outputs, long+ tracebacks, extracted text) are useless in the UI when displayed in+ full and inflate socket payloads + client-side memory;+ container-log/stderr, file, and DB sinks remain unchanged."""if len(message) <= FRONTEND_MESSAGE_MAX_LENGTH:return messagediff --git a/tests/advanced_search_system/tools/_fetch_sink_support.py b/tests/advanced_search_system/tools/_fetch_sink_support.pynew file mode 100644index 0000000000..27c3ea9282--- /dev/null+++ b/tests/advanced_search_system/tools/_fetch_sink_support.py@@ -0,0 +1,301 @@+"""Shared support for fetch-tool sink-leak tests.++Provides constants, mock builders, a real-sink harness context manager,+and assertion helpers used by both ``test_fetch_success_sinks`` and+``test_fetch_error_sinks``.+"""++from __future__ import annotations++import io+import re+from contextlib import contextmanager+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++from loguru import logger++from local_deep_research.utilities import log_utils+from local_deep_research.utilities.log_utils import (+ database_sink,+ frontend_progress_sink,+)++# ---------------------------------------------------------------------------+# Distinctive markers — any leak is unambiguous in assertion failures.+# ---------------------------------------------------------------------------++FOCUS = "UNIQUE_FOCUS_MARKER_xyz789"+QUERY = "UNIQUE_QUERY_MARKER_abc456"+TITLE = "UNIQUE_TITLE_MARKER_def012"+BODY = "UNIQUE_BODY_CONTENT_markerghi345"+SUMMARY = "UNIQUE_SUMMARY_TEXT_markerjkl678"+CRED_SECRET = "CRED_SECRET_mno901"+QUERY_TOKEN = "QUERY_TOKEN_pqr234"+EXC_TEXT = "UNIQUE_EXCEPTION_TEXT_stu567"++CREDENTIALED_URL = (+ f"https://user:{CRED_SECRET}@safe.example:8443/secretpath?key={QUERY_TOKEN}"+)+REDACTED_ORIGIN = "https://safe.example:8443"++ENCODED_URL = (+ f"https://user%40domain:{CRED_SECRET}@safe.example:8443"+ f"/secretpath?key={QUERY_TOKEN}"+)+DOUBLE_ENCODED_URL = (+ f"https://user%2540domain:{CRED_SECRET}@safe.example:8443"+ f"/secretpath?key={QUERY_TOKEN}"+)++FORBIDDEN = [+ FOCUS,+ QUERY,+ TITLE,+ BODY,+ SUMMARY,+ CRED_SECRET,+ QUERY_TOKEN,+ EXC_TEXT,+ "secretpath",+ # Userinfo shapes exactly as they appear in the three URLs above:+ # ``user:<cred>@`` (CREDENTIALED_URL) and the percent-encoded+ # ``user%40domain`` / ``user%2540domain`` forms (ENCODED_URL /+ # DOUBLE_ENCODED_URL). A marker that no input can produce asserts+ # nothing.+ "user:",+ "user%40domain",+ "user%2540domain",+]++FETCH_EVENT_RE = re.compile(+ r"^\[FETCH\] mode=(?P<mode>\S+) status=(?P<status>\S+)"+ r" url=(?P<url>\S+)"+ r"(?: page_chars=(?P<page_chars>\d+))?"+ r"(?: summary_chars=(?P<summary_chars>\d+))?\s*$"+)+++# ---------------------------------------------------------------------------+# Sink harness — real Loguru sinks, patched external seams.+# ---------------------------------------------------------------------------+++@contextmanager+def create_sink_harness(tmp_path):+ """Configure real Loguru sinks + patch external seams.++ Adds five handlers (stderr StringIO with ``enqueue=True``, file,+ ``database_sink``, ``frontend_progress_sink``, capture) on top of+ whatever handlers already exist — does **not** call+ ``logger.remove()`` globally. Only the added handler IDs are+ removed in the ``finally`` block.++ Yields a SimpleNamespace:+ db_entries, socket_payloads, records, stderr, file_path, flush+ """+ stderr_buf = io.StringIO()+ log_file = tmp_path / "fetch_test.log"++ db_entries = []+ socket_payloads = []+ records = []++ def capture_sink(message):+ records.append(message.record)++ handler_ids = [+ logger.add(+ stderr_buf,+ level="DEBUG",+ format="{message}",+ diagnose=False,+ enqueue=True,+ ),+ logger.add(+ str(log_file), level="DEBUG", format="{message}", diagnose=False+ ),+ logger.add(database_sink, level="DEBUG", diagnose=False),+ logger.add(frontend_progress_sink, level="DEBUG", diagnose=False),+ logger.add(capture_sink, level="DEBUG", diagnose=False),+ ]+ # ``src/local_deep_research/__init__.py`` disables the package's loguru+ # logging by default; re-enable it for the harness and restore that+ # default in the ``finally`` below (same pairing as ``loguru_caplog`` in+ # tests/conftest.py).+ logger.enable("local_deep_research")++ def _capture_emit(event, research_id, payload, **kw):+ socket_payloads.append((event, research_id, payload))++ try:+ # Post-FastAPI-migration, `database_sink` no longer gates on Flask's+ # `has_app_context()`; it instead checks whether it is running on the+ # event loop or off the main thread (see log_utils.database_sink).+ # Under plain synchronous pytest execution (no event loop, thread+ # name "MainThread") it takes the *direct-write* branch and calls+ # `_write_log_to_database` synchronously rather than enqueuing via+ # `_log_queue` -- so patching `_log_queue` (the pre-migration+ # strategy, back when Flask's `has_app_context()` was False in tests+ # and always forced the queueing branch) is no longer on the+ # exercised path. Patch `_write_log_to_database` directly instead,+ # matching the current synchronous code path.+ with patch.object(+ log_utils, "_write_log_to_database", db_entries.append+ ):+ # `frontend_progress_sink` no longer goes through a Flask-era+ # `SocketIOService` class; it calls the module-level+ # `emit_to_subscribers` function imported into log_utils.+ with patch.object(+ log_utils, "emit_to_subscribers", side_effect=_capture_emit+ ):+ with logger.contextualize(+ research_id="test-rid", username="test-user"+ ):+ yield SimpleNamespace(+ db_entries=db_entries,+ socket_payloads=socket_payloads,+ records=records,+ stderr=stderr_buf,+ file_path=log_file,+ flush=lambda: logger.complete(),+ )+ finally:+ logger.complete()+ for hid in handler_ids:+ try:+ logger.remove(hid)+ except ValueError:+ pass+ logger.disable("local_deep_research")+++# ---------------------------------------------------------------------------+# Mock builders+# ---------------------------------------------------------------------------+++def fetcher_cm(*, status="success", title="", content=""):+ """Build a ContentFetcher context-manager mock."""+ fetcher = MagicMock()+ fetcher.fetch.return_value = {+ "status": status,+ "title": title,+ "content": content,+ }+ cm = MagicMock()+ cm.__enter__.return_value = fetcher+ cm.__exit__.return_value = False+ return cm+++def model_returning(text: str):+ """Model whose ``invoke`` returns a message with ``.content == text``."""+ msg = MagicMock()+ msg.content = text+ model = MagicMock()+ model.invoke.return_value = msg+ return model+++def model_raising(exc: Exception):+ """Model whose ``invoke`` raises."""+ model = MagicMock()+ model.invoke.side_effect = exc+ return model+++# ---------------------------------------------------------------------------+# Extraction helpers+# ---------------------------------------------------------------------------+++def fetch_events_from(records):+ """Return only records whose message is a [FETCH] event."""+ return [r for r in records if r["message"].lstrip().startswith("[FETCH]")]+++def fetch_db_messages(db_entries):+ """Extract [FETCH] messages from DB queue entries."""+ return [e["message"] for e in db_entries if "[FETCH]" in e["message"]]+++def fetch_socket_messages(socket_payloads):+ """Extract [FETCH] messages from frontend socket payloads."""+ return [+ payload["log_entry"]["message"]+ for _event, _rid, payload in socket_payloads+ if "[FETCH]" in payload["log_entry"]["message"]+ ]+++def fetch_file_lines(file_path):+ """Read the file sink and return [FETCH] lines."""+ content = file_path.read_text()+ return [line for line in content.splitlines() if "[FETCH]" in line]+++def fetch_stderr_lines(stderr_buf):+ """Extract [FETCH] lines from the stderr buffer."""+ content = stderr_buf.getvalue()+ return [line for line in content.splitlines() if "[FETCH]" in line]+++# ---------------------------------------------------------------------------+# Assertion helpers+# ---------------------------------------------------------------------------+++def assert_no_forbidden(text, context):+ """Assert none of the FORBIDDEN markers appear in *text*."""+ for marker in FORBIDDEN:+ assert marker not in text, (+ f"FORBIDDEN value {marker!r} found in {context}:\n{text}"+ )+++def assert_safe_origin(text, context):+ """Assert the redacted origin appears exactly once."""+ origin_count = text.count(REDACTED_ORIGIN)+ assert origin_count == 1, (+ f"Expected exactly 1 redacted origin {REDACTED_ORIGIN!r} "+ f"in {context}, got {origin_count}:\n{text}"+ )+++def assert_record_exception_none(record, context):+ """Assert the loguru record has no exception attached."""+ assert record["exception"] is None, (+ f"Record exception should be None in {context}, "+ f"got {record['exception']!r}"+ )+++def assert_all_sinks_clean(harness):+ """Assert every [FETCH] event across all sinks is leak-free.++ Checks DB queue entries, frontend socket payloads, stderr buffer,+ file output, and captured records (message, extra, exception).+ """+ for msg in fetch_db_messages(harness.db_entries):+ assert_no_forbidden(msg, "database_sink queued message")+ assert_safe_origin(msg, "database_sink queued message")++ for msg in fetch_socket_messages(harness.socket_payloads):+ assert_no_forbidden(msg, "frontend_progress_sink socket payload")+ assert_safe_origin(msg, "frontend_progress_sink socket payload")++ for line in fetch_stderr_lines(harness.stderr):+ assert_no_forbidden(line, "stderr StringIO")+ assert_safe_origin(line, "stderr StringIO")++ for line in fetch_file_lines(harness.file_path):+ assert_no_forbidden(line, "file sink output")+ assert_safe_origin(line, "file sink output")++ for record in fetch_events_from(harness.records):+ assert_no_forbidden(record["message"], "record message")+ assert_no_forbidden(str(record["extra"]), "record extra")+ assert_no_forbidden(str(record["exception"]), "record exception")+ assert_safe_origin(record["message"], "record message")+ assert_record_exception_none(record, "record exception")diff --git a/tests/advanced_search_system/tools/test_fetch_error_sinks.py b/tests/advanced_search_system/tools/test_fetch_error_sinks.pynew file mode 100644index 0000000000..1bbdf417dc--- /dev/null+++ b/tests/advanced_search_system/tools/test_fetch_error_sinks.py@@ -0,0 +1,184 @@+"""Sink-leak tests for fetch-tool error-path events.++Verifies that full-fetch outer failure, summary-model failure, and+summary outer failure emit static ``logger.error`` events — no+traceback, no exception attachment, no forbidden values in any sink.+"""++from __future__ import annotations++from unittest.mock import MagicMock, patch++import pytest++from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (+ SearchResultsCollector,+)+from local_deep_research.advanced_search_system.tools.fetch import (+ build_fetch_tool,+)++from ._fetch_sink_support import (+ BODY,+ CRED_SECRET,+ create_sink_harness,+ CREDENTIALED_URL,+ EXC_TEXT,+ FOCUS,+ FETCH_EVENT_RE,+ fetch_events_from,+ fetcher_cm,+ model_raising,+ model_returning,+ QUERY,+ REDACTED_ORIGIN,+ SUMMARY,+ TITLE,+ assert_all_sinks_clean,+ assert_record_exception_none,+)+++def sink_harness(tmp_path):+ with create_sink_harness(tmp_path) as harness:+ yield harness+++# ---------------------------------------------------------------------------+# Test 5: full-fetch outer failure+# ---------------------------------------------------------------------------+++def test_full_fetch_outer_failure_emits_error_without_traceback(sink_harness):+ """A full-mode fetch exception must emit a static logger.error event+ with status=error — no traceback, no exception attachment."""+ collector = SearchResultsCollector([])+ tool = build_fetch_tool("full", collector)+ assert tool is not None++ fetcher = MagicMock()+ fetcher.fetch.side_effect = Exception(EXC_TEXT)+ cm = MagicMock()+ cm.__enter__.return_value = fetcher+ cm.__exit__.return_value = False++ with patch(+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm+ ):+ out = tool.invoke({"url": CREDENTIALED_URL})++ sink_harness.flush()++ assert "Error fetching" in out+ assert CRED_SECRET not in out++ fetch_records = fetch_events_from(sink_harness.records)+ assert len(fetch_records) == 1+ event_msg = fetch_records[0]["message"].strip()+ match = FETCH_EVENT_RE.match(event_msg)+ assert match is not None, f"Event does not match schema: {event_msg!r}"+ assert match.group("mode") == "full"+ assert match.group("status") == "error"+ assert match.group("url") == REDACTED_ORIGIN++ assert_record_exception_none(+ fetch_records[0], "full-fetch outer failure record"+ )++ assert_all_sinks_clean(sink_harness)+++# ---------------------------------------------------------------------------+# Test 6: summary-model failure (LLM invoke raises)+# ---------------------------------------------------------------------------+++def test_summary_model_failure_emits_error_without_traceback(sink_harness):+ """A summary-mode LLM invoke exception must emit a static+ logger.error event with status=summary_error — no traceback."""+ collector = SearchResultsCollector([])+ model = model_raising(Exception(EXC_TEXT))+ tool = build_fetch_tool(+ "summary_focus_query",+ collector,+ model=model,+ overall_query=QUERY,+ )+ assert tool is not None+ cm = fetcher_cm(title=TITLE, content=BODY * 5)++ with patch(+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm+ ):+ out = tool.invoke({"url": CREDENTIALED_URL, "focus": FOCUS})++ sink_harness.flush()++ assert "Error summarizing" in out+ assert CRED_SECRET not in out++ fetch_records = fetch_events_from(sink_harness.records)+ assert len(fetch_records) == 1+ event_msg = fetch_records[0]["message"].strip()+ match = FETCH_EVENT_RE.match(event_msg)+ assert match is not None, f"Event does not match schema: {event_msg!r}"+ assert match.group("mode") == "summary_focus_query"+ assert match.group("status") == "summary_error"+ assert match.group("url") == REDACTED_ORIGIN++ assert_record_exception_none(+ fetch_records[0], "summary-model failure record"+ )++ assert_all_sinks_clean(sink_harness)+++# ---------------------------------------------------------------------------+# Test 7: summary outer failure+# ---------------------------------------------------------------------------+++def test_summary_outer_failure_emits_error_without_traceback(sink_harness):+ """A summary-mode outer exception must emit a static logger.error+ event with status=error — no traceback, no exception attachment."""+ collector = SearchResultsCollector([])+ model = model_returning(SUMMARY)+ tool = build_fetch_tool(+ "summary_focus_query",+ collector,+ model=model,+ overall_query=QUERY,+ )+ assert tool is not None++ fetcher = MagicMock()+ fetcher.fetch.side_effect = Exception(EXC_TEXT)+ cm = MagicMock()+ cm.__enter__.return_value = fetcher+ cm.__exit__.return_value = False++ with patch(+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm+ ):+ out = tool.invoke({"url": CREDENTIALED_URL, "focus": FOCUS})++ sink_harness.flush()++ assert "Error fetching" in out+ assert CRED_SECRET not in out++ fetch_records = fetch_events_from(sink_harness.records)+ assert len(fetch_records) == 1+ event_msg = fetch_records[0]["message"].strip()+ match = FETCH_EVENT_RE.match(event_msg)+ assert match is not None, f"Event does not match schema: {event_msg!r}"+ assert match.group("mode") == "summary_focus_query"+ assert match.group("status") == "error"+ assert match.group("url") == REDACTED_ORIGIN++ assert_record_exception_none(+ fetch_records[0], "summary outer failure record"+ )++ assert_all_sinks_clean(sink_harness)diff --git a/tests/advanced_search_system/tools/test_fetch_library_sink.py b/tests/advanced_search_system/tools/test_fetch_library_sink.pynew file mode 100644index 0000000000..9b6ba6a12c--- /dev/null+++ b/tests/advanced_search_system/tools/test_fetch_library_sink.py@@ -0,0 +1,111 @@+"""Sink-leak test for the local-library ``[FETCH] source=library`` event.++The library branch of ``_fetch_raw_content`` resolves a document from the+user DB and logs a ``[FETCH] mode=... source=library url=...`` event. The+URL there is the fetch URL a user typed (or a document URL returned by the+library), so it may carry credentials — the event must render only the+redacted scheme://host:port origin across every real sink, and no HTTP+fetch may run (it is a local read).+"""++from __future__ import annotations++import re+from unittest.mock import patch++import pytest++from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (+ SearchResultsCollector,+)+from local_deep_research.advanced_search_system.tools.fetch import (+ build_fetch_tool,+)++from ._fetch_sink_support import (+ BODY,+ CREDENTIALED_URL,+ create_sink_harness,+ TITLE,+ REDACTED_ORIGIN,+ assert_all_sinks_clean,+ assert_record_exception_none,+ fetch_db_messages,+ fetch_events_from,+ fetch_file_lines,+ fetch_socket_messages,+ fetch_stderr_lines,+)++FETCH_LIBRARY_EVENT_RE = re.compile(+ r"^\[FETCH\] mode=(?P<mode>\S+) source=library url=(?P<url>\S+) "+ r"— resolved local library document directly\s*$"+)+++def sink_harness(tmp_path):+ with create_sink_harness(tmp_path) as harness:+ yield harness+++def test_library_resolved_fetch_emits_redacted_event_to_all_sinks(sink_harness):+ """A library-resolved fetch must emit one ``source=library`` event whose+ URL is the redacted origin only — in every sink — with no ContentFetcher+ run (local DB read, not HTTP)."""+ collector = SearchResultsCollector([])+ library_resolver = lambda url: ( # noqa: E731 - one-shot test stub+ {+ "status": "success",+ "title": TITLE,+ "content": BODY * 3,+ "url": CREDENTIALED_URL,+ }+ if url == CREDENTIALED_URL+ else None+ )+ tool = build_fetch_tool(+ "full", collector, library_resolver=library_resolver+ )+ assert tool is not None++ # If pre-resolution regresses and falls through to the HTTP path, the+ # patched ContentFetcher raises and this test fails.+ def _no_http(*_args, **_kwargs):+ raise AssertionError(+ "ContentFetcher must not run for a library-resolved URL"+ )++ with patch(+ "local_deep_research.content_fetcher.ContentFetcher",+ side_effect=_no_http,+ ):+ out = tool.invoke({"url": CREDENTIALED_URL})++ sink_harness.flush()++ # The full tool returns the document (registered as citation [1]).+ assert out.startswith("[1] ")+ assert BODY in out+ assert len(collector.results) == 1++ db_msgs = fetch_db_messages(sink_harness.db_entries)+ socket_msgs = fetch_socket_messages(sink_harness.socket_payloads)+ stderr_lines = fetch_stderr_lines(sink_harness.stderr)+ file_lines = fetch_file_lines(sink_harness.file_path)+ fetch_records = fetch_events_from(sink_harness.records)++ assert len(db_msgs) == 1, f"Expected 1 DB event, got {db_msgs}"+ assert len(socket_msgs) == 1, f"Expected 1 socket event, got {socket_msgs}"+ assert len(file_lines) == 1, f"Expected 1 file line, got {file_lines}"+ assert len(fetch_records) == 1, f"Expected 1 record, got {fetch_records}"+ assert len(stderr_lines) >= 1++ event_msg = fetch_records[0]["message"].strip()+ match = FETCH_LIBRARY_EVENT_RE.match(event_msg)+ assert match is not None, f"Event does not match schema: {event_msg!r}"+ assert match.group("mode") == "full"+ assert match.group("url") == REDACTED_ORIGIN++ assert_record_exception_none(fetch_records[0], "library-resolved record")+ assert_all_sinks_clean(sink_harness)diff --git a/tests/advanced_search_system/tools/test_fetch_modes.py b/tests/advanced_search_system/tools/test_fetch_modes.pyindex 6ca3406217..e3b587c28b 100644--- a/tests/advanced_search_system/tools/test_fetch_modes.py+++ b/tests/advanced_search_system/tools/test_fetch_modes.py@@ -337,46 +337,6 @@ def test_summary_mode_egress_denial_returns_message_not_raises():assert collector.results == []-def test_fetch_error_log_redacts_url_and_adds_mode():- """The server-log line for a fetch error carries the MODE and a REDACTED- scheme://host (no userinfo / path / query) — enough to locate the failure- without leaking credentials, query tokens, page paths, or content. Asserted- on the args passed to logger.exception (robust to loguru sink config)."""- collector = SearchResultsCollector([])- tool = build_fetch_tool("full", collector)-- fetcher = MagicMock()- fetcher.fetch.side_effect = Exception("boom")- cm = MagicMock()- cm.__enter__.return_value = fetcher- cm.__exit__.return_value = False-- url = (- "https://user:[email protected]:8080/secretpath?token=ABCXYZ"- )- with patch(- "local_deep_research.advanced_search_system.tools.fetch.logger"- ) as mock_logger:- with patch(- "local_deep_research.content_fetcher.ContentFetcher",- return_value=cm,- ):- tool.invoke({"url": url})-- mock_logger.exception.assert_called_once()- args = mock_logger.exception.call_args.args- # args = (template, mode_label, redacted_url)- assert "mode={}" in args[0] and "url={}" in args[0]- assert "full" in args # the mode- assert (- "https://proxy.example.com:8080" in args- ) # redacted scheme://host:port- flat = " ".join(map(str, args))- assert "SECRET123" not in flat # userinfo dropped- assert "ABCXYZ" not in flat # query token dropped- assert "secretpath" not in flat # path dropped--# ---------------------------------------------------------------------------# Library-document and citation-marker URL pre-resolution (A3).#diff --git a/tests/advanced_search_system/tools/test_fetch_success_sinks.py b/tests/advanced_search_system/tools/test_fetch_success_sinks.pynew file mode 100644index 0000000000..e487effc41--- /dev/null+++ b/tests/advanced_search_system/tools/test_fetch_success_sinks.py@@ -0,0 +1,225 @@+"""Sink-leak tests for fetch-tool success and empty-status events.++Verifies that summary success, empty-content, and empty-summary log+events emitted to real Loguru sinks contain ONLY bounded metadata:+mode, status, redacted origin, and page/summary character counts.+"""++from __future__ import annotations++from unittest.mock import patch++import pytest++from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (+ SearchResultsCollector,+)+from local_deep_research.advanced_search_system.tools.fetch import (+ build_fetch_tool,+)++from ._fetch_sink_support import (+ BODY,+ CREDENTIALED_URL,+ create_sink_harness,+ DOUBLE_ENCODED_URL,+ ENCODED_URL,+ FOCUS,+ FETCH_EVENT_RE,+ fetch_events_from,+ fetch_db_messages,+ fetch_file_lines,+ fetch_socket_messages,+ fetch_stderr_lines,+ fetcher_cm,+ model_returning,+ QUERY,+ REDACTED_ORIGIN,+ SUMMARY,+ TITLE,+ assert_all_sinks_clean,+)+++def sink_harness(tmp_path):+ with create_sink_harness(tmp_path) as harness:+ yield harness+++# ---------------------------------------------------------------------------+# Test 1: summary success — encoded credentialed URL+# ---------------------------------------------------------------------------+++def test_summary_success_encoded_url_emits_safe_event_to_all_sinks(+ sink_harness,+):+ """Summary success must emit one bounded event per sink with only+ mode, status, redacted origin, and char counts."""+ collector = SearchResultsCollector([])+ model = model_returning(SUMMARY)+ tool = build_fetch_tool(+ "summary_focus_query",+ collector,+ model=model,+ overall_query=QUERY,+ )+ assert tool is not None+ cm = fetcher_cm(title=TITLE, content=BODY * 5)++ with patch(+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm+ ):+ out = tool.invoke({"url": ENCODED_URL, "focus": FOCUS})++ sink_harness.flush()++ assert out.startswith("[1] ")+ assert SUMMARY in out++ db_msgs = fetch_db_messages(sink_harness.db_entries)+ socket_msgs = fetch_socket_messages(sink_harness.socket_payloads)+ stderr_lines = fetch_stderr_lines(sink_harness.stderr)+ file_lines = fetch_file_lines(sink_harness.file_path)+ fetch_records = fetch_events_from(sink_harness.records)++ assert len(db_msgs) == 1, f"Expected 1 DB event, got {db_msgs}"+ assert len(socket_msgs) == 1, f"Expected 1 socket event, got {socket_msgs}"+ assert len(file_lines) == 1, f"Expected 1 file line, got {file_lines}"+ assert len(fetch_records) == 1, f"Expected 1 record, got {fetch_records}"+ assert len(stderr_lines) >= 1++ event_msg = fetch_records[0]["message"].strip()+ match = FETCH_EVENT_RE.match(event_msg)+ assert match is not None, f"Event does not match schema: {event_msg!r}"+ assert match.group("mode") == "summary_focus_query"+ assert match.group("status") == "success"+ assert match.group("url") == REDACTED_ORIGIN+ assert match.group("page_chars") is not None+ assert match.group("summary_chars") is not None++ assert_all_sinks_clean(sink_harness)+++# ---------------------------------------------------------------------------+# Test 2: summary success — double-encoded credentialed URL+# ---------------------------------------------------------------------------+++def test_summary_success_double_encoded_url_emits_safe_origin(sink_harness):+ """A double-encoded credentialed URL must still redact to the same+ safe scheme://host:port origin across every sink."""+ collector = SearchResultsCollector([])+ model = model_returning(SUMMARY)+ tool = build_fetch_tool(+ "summary_focus_query",+ collector,+ model=model,+ overall_query=QUERY,+ )+ assert tool is not None+ cm = fetcher_cm(title=TITLE, content=BODY * 3)++ with patch(+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm+ ):+ out = tool.invoke({"url": DOUBLE_ENCODED_URL, "focus": FOCUS})++ sink_harness.flush()++ assert out.startswith("[1] ")+ assert SUMMARY in out++ fetch_records = fetch_events_from(sink_harness.records)+ assert len(fetch_records) == 1+ event_msg = fetch_records[0]["message"].strip()+ match = FETCH_EVENT_RE.match(event_msg)+ assert match is not None, f"Event does not match schema: {event_msg!r}"+ assert match.group("url") == REDACTED_ORIGIN++ assert_all_sinks_clean(sink_harness)+++# ---------------------------------------------------------------------------+# Test 3: empty page content+# ---------------------------------------------------------------------------+++def test_empty_content_emits_bounded_empty_content_status(sink_harness):+ """An empty page must emit status=empty_content with only mode and+ redacted origin — no LLM call, no collector registration."""+ collector = SearchResultsCollector([])+ model = model_returning(SUMMARY)+ tool = build_fetch_tool(+ "summary_focus_query",+ collector,+ model=model,+ overall_query=QUERY,+ )+ assert tool is not None+ cm = fetcher_cm(title=TITLE, content="")++ with patch(+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm+ ):+ out = tool.invoke({"url": CREDENTIALED_URL, "focus": FOCUS})++ sink_harness.flush()++ assert out.startswith("NOT RELEVANT")+ assert collector.results == []+ model.invoke.assert_not_called()++ fetch_records = fetch_events_from(sink_harness.records)+ assert len(fetch_records) == 1+ event_msg = fetch_records[0]["message"].strip()+ match = FETCH_EVENT_RE.match(event_msg)+ assert match is not None, f"Event does not match schema: {event_msg!r}"+ assert match.group("mode") == "summary_focus_query"+ assert match.group("status") == "empty_content"+ assert match.group("url") == REDACTED_ORIGIN++ assert_all_sinks_clean(sink_harness)+++# ---------------------------------------------------------------------------+# Test 4: empty summary (page has content, LLM returns empty)+# ---------------------------------------------------------------------------+++def test_empty_summary_emits_bounded_empty_summary_status(sink_harness):+ """A non-empty page whose LLM summary comes back empty must emit+ status=empty_summary with mode, redacted origin, and page_chars."""+ collector = SearchResultsCollector([])+ model = model_returning("")+ tool = build_fetch_tool(+ "summary_focus_query",+ collector,+ model=model,+ overall_query=QUERY,+ )+ assert tool is not None+ cm = fetcher_cm(title=TITLE, content=BODY * 4)++ with patch(+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm+ ):+ out = tool.invoke({"url": CREDENTIALED_URL, "focus": FOCUS})++ sink_harness.flush()++ assert out.startswith("NOT RELEVANT")+ assert collector.results == []++ fetch_records = fetch_events_from(sink_harness.records)+ assert len(fetch_records) == 1+ event_msg = fetch_records[0]["message"].strip()+ match = FETCH_EVENT_RE.match(event_msg)+ assert match is not None, f"Event does not match schema: {event_msg!r}"+ assert match.group("mode") == "summary_focus_query"+ assert match.group("status") == "empty_summary"+ assert match.group("url") == REDACTED_ORIGIN+ assert match.group("page_chars") is not None++ assert_all_sinks_clean(sink_harness)diff --git a/tests/content_fetcher/test_fetch_logging_sinks.py b/tests/content_fetcher/test_fetch_logging_sinks.pynew file mode 100644index 0000000000..08e5cac3ad--- /dev/null+++ b/tests/content_fetcher/test_fetch_logging_sinks.py@@ -0,0 +1,305 @@+from io import StringIO+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest+from loguru import logger++from local_deep_research.content_fetcher.fetcher import ContentFetcher+from local_deep_research.content_fetcher.url_classifier import URLType+from local_deep_research.research_library.downloaders.base import DownloadResult+from local_deep_research.research_library.downloaders.playwright_html import (+ AutoHTMLDownloader,+)+from local_deep_research.security.egress.policy import (+ Decision,+ EgressContext,+ EgressScope,+)+++_SECRET = "credential-do-not-log"+_EXCEPTION_TEXT = "network-error-do-not-log"+_URL = (+ f"https://alice:{_SECRET}@origin.example:8443/private/%2Fencoded"+ f"?token={_SECRET}&next=%2Felsewhere#fragment"+)+_ORIGIN = "https://origin.example:8443"+_FORBIDDEN = (+ "alice",+ _SECRET,+ "/private/",+ "%2Fencoded",+ "token=",+ "next=",+ "fragment",+ _EXCEPTION_TEXT,+ "Traceback",+)+++def rendered_sinks(tmp_path, monkeypatch):+ import local_deep_research.utilities.log_utils as log_utils++ stderr = StringIO()+ log_file = tmp_path / "fetcher.log"+ database_entries = []+ frontend_events = []+ records = []++ def _emit_to_subscribers(_event, _research_id, payload, **_kwargs):+ frontend_events.append(payload)++ # Post-FastAPI-migration, `database_sink` no longer gates on Flask's+ # `has_app_context()` (that symbol no longer exists on log_utils at+ # all); it instead checks whether it is running on the event loop or+ # off the main thread, and under plain synchronous pytest execution+ # takes the direct-write branch -- see log_utils.database_sink and+ # _write_log_to_database. `frontend_progress_sink` no longer goes+ # through a Flask-era `SocketIOService` class either; it calls the+ # module-level `emit_to_subscribers` function imported into log_utils.+ monkeypatch.setattr(+ log_utils, "_write_log_to_database", database_entries.append+ )+ monkeypatch.setattr(log_utils, "emit_to_subscribers", _emit_to_subscribers)+ logger.enable("local_deep_research")+ sink_ids = [+ logger.add(+ stderr,+ level="DEBUG",+ format="{message}\n{exception}",+ backtrace=True,+ diagnose=False,+ ),+ logger.add(+ log_file,+ level="DEBUG",+ format="{message}\n{exception}",+ backtrace=True,+ diagnose=False,+ ),+ logger.add(log_utils.database_sink, level="DEBUG", diagnose=False),+ logger.add(+ log_utils.frontend_progress_sink, level="DEBUG", diagnose=False+ ),+ logger.add(+ lambda message: records.append(message.record), level="DEBUG"+ ),+ ]+ capture = SimpleNamespace(+ stderr=stderr,+ log_file=log_file,+ database_entries=database_entries,+ frontend_events=frontend_events,+ records=records,+ )+ try:+ yield capture+ finally:+ for sink_id in sink_ids:+ logger.remove(sink_id)+ logger.disable("local_deep_research")+++def _assert_no_sensitive_text(text):+ for marker in _FORBIDDEN:+ assert marker not in text+++def _assert_rendered_event(capture, event, *, frontend=True):+ stderr_lines = [+ line for line in capture.stderr.getvalue().splitlines() if event in line+ ]+ assert len(stderr_lines) == 1+ assert stderr_lines[0].count(_ORIGIN) == 1++ file_output = capture.log_file.read_text()+ database_output = "\n".join(+ entry["message"] for entry in capture.database_entries+ )+ frontend_output = "\n".join(str(event) for event in capture.frontend_events)+ for output in (+ capture.stderr.getvalue(),+ file_output,+ database_output,+ frontend_output,+ ):+ _assert_no_sensitive_text(output)+ assert event in file_output+ assert event in database_output+ if frontend:+ assert event in frontend_output+++def _context():+ return logger.contextualize(research_id="research-1", username="tester")+++def test_ssrf_denial_logs_one_safe_event_to_all_rendered_sinks(rendered_sinks):+ with patch(+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",+ return_value=False,+ ):+ with _context():+ result = ContentFetcher().fetch(_URL)++ assert result["status"] == "error"+ assert "SSRF" in result["error"]+ _assert_rendered_event(rendered_sinks, "content_fetcher.ssrf_denied")+++def test_egress_denial_is_audit_only_and_never_reaches_frontend(rendered_sinks):+ context = EgressContext(+ scope=EgressScope.PRIVATE_ONLY,+ primary_engine="library",+ require_local_llm=True,+ require_local_embeddings=True,+ )+ with (+ patch(+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",+ return_value=True,+ ),+ patch(+ "local_deep_research.security.egress.policy.evaluate_url",+ return_value=Decision(False, "scope_mismatch_private_only"),+ ),+ _context(),+ ):+ result = ContentFetcher(egress_context=context).fetch(_URL)++ assert result["status"] == "error"+ assert (+ result["error"]+ == "URL refused by egress policy (scope_mismatch_private_only)"+ )+ audit_records = [+ record+ for record in rendered_sinks.records+ if record["extra"].get("policy_audit")+ ]+ assert len(audit_records) == 1+ assert audit_records[0]["extra"]["reason"] == "scope_mismatch_private_only"+ assert rendered_sinks.frontend_events == []+ _assert_rendered_event(+ rendered_sinks, "content_fetcher.egress_denied", frontend=False+ )+++def test_downloader_exception_keeps_result_but_omits_exception_from_logs(+ rendered_sinks,+):+ downloader = MagicMock()+ downloader.download_with_result.side_effect = RuntimeError(+ f"{_EXCEPTION_TEXT}: {_URL}"+ )+ fetcher = ContentFetcher()+ fetcher._downloaders[URLType.HTML] = downloader++ with (+ patch(+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",+ return_value=True,+ ),+ _context(),+ ):+ result = fetcher.fetch(_URL)++ assert result["error"] == f"{_EXCEPTION_TEXT}: {_URL}"+ _assert_rendered_event(rendered_sinks, "content_fetcher.download_error")+++def test_metadata_exception_preserves_success_without_rendering_exception(+ rendered_sinks,+):+ downloader = MagicMock()+ downloader.download_with_result.return_value = DownloadResult(+ content=b"content", is_success=True+ )+ downloader.get_metadata.side_effect = RuntimeError(+ f"{_EXCEPTION_TEXT}: {_URL}"+ )+ fetcher = ContentFetcher()+ fetcher._downloaders[URLType.HTML] = downloader++ with (+ patch(+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",+ return_value=True,+ ),+ _context(),+ ):+ result = fetcher.fetch(_URL)++ assert result["status"] == "success"+ assert result["title"] is None+ _assert_rendered_event(rendered_sinks, "content_fetcher.metadata_failed")+++def test_specialized_html_fallback_logs_one_safe_origin(rendered_sinks):+ # PubMed, not arXiv: ``URLType.ARXIV`` is in ``_NO_HTML_FALLBACK``, so a+ # failed arXiv download is terminal and never reaches the generic HTML+ # fallback whose event is pinned here. PubMed ("for example, PubMed is+ # paywalled" in fetcher.fetch) is the fallback-eligible case.+ specialized = MagicMock()+ specialized.download_with_result.return_value = DownloadResult(+ skip_reason="failed"+ )+ html = MagicMock()+ html.download_with_result.return_value = DownloadResult(+ content=b"content", is_success=True+ )+ html.get_metadata.return_value = {}+ fetcher = ContentFetcher()+ fetcher._downloaders[URLType.PUBMED] = specialized+ fetcher._downloaders[URLType.HTML] = html++ with (+ patch(+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",+ return_value=True,+ ),+ patch(+ "local_deep_research.content_fetcher.fetcher.URLClassifier"+ ) as classifier,+ _context(),+ ):+ classifier.classify.return_value = URLType.PUBMED+ classifier.get_source_name.return_value = "PubMed"+ result = fetcher.fetch(_URL)++ assert result["status"] == "success"+ _assert_rendered_event(+ rendered_sinks, "content_fetcher.html_fallback_started"+ )+++def test_content_fetcher_auto_html_network_exception_logs_safe_static_events(+ rendered_sinks,+):+ downloader = AutoHTMLDownloader(enable_js_rendering=False)+ downloader.rate_tracker = MagicMock()+ downloader.rate_tracker.apply_rate_limit.return_value = 0+ downloader.session = MagicMock()+ downloader.session.get.side_effect = ConnectionError(+ f"{_EXCEPTION_TEXT}: {_URL}"+ )+ fetcher = ContentFetcher()+ fetcher._downloaders[URLType.HTML] = downloader++ try:+ with (+ patch(+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",+ return_value=True,+ ),+ _context(),+ ):+ result = fetcher.fetch(_URL)+ finally:+ downloader.close()++ assert result["status"] == "error"+ _assert_rendered_event(rendered_sinks, "html.fetch_error")+ _assert_rendered_event(rendered_sinks, "auto_html.raw_fetch_failed")diff --git a/tests/research_library/downloaders/test_biorxiv_logging_sinks.py b/tests/research_library/downloaders/test_biorxiv_logging_sinks.pynew file mode 100644index 0000000000..c18cafc6f8--- /dev/null+++ b/tests/research_library/downloaders/test_biorxiv_logging_sinks.py@@ -0,0 +1,85 @@+from io import StringIO+from unittest.mock import Mock, patch++import pytest+import requests+from loguru import logger++from local_deep_research.research_library.downloaders.base import (+ BaseDownloader,+ ContentType,+)+from local_deep_research.research_library.downloaders.biorxiv import (+ BioRxivDownloader,+)++_SECRET = "credential-do-not-log"+_URL = f"https://user:{_SECRET}@origin.example/private?token={_SECRET}"+_ORIGIN = "https://origin.example"+++def rendered_log():+ output = StringIO()+ logger.enable("local_deep_research")+ sink_id = logger.add(output, level="DEBUG", format="{message}\n{exception}")+ try:+ yield output+ finally:+ logger.remove(sink_id)+ logger.disable("local_deep_research")+++def _assert_redacted(output: StringIO) -> None:+ rendered = output.getvalue()+ assert _ORIGIN in rendered+ assert _SECRET not in rendered+ assert "user:" not in rendered+ assert "token=" not in rendered+++def test_download_result_success_logs_only_origin(rendered_log):+ with patch.object(BaseDownloader, "_download_pdf", return_value=b"%PDF"):+ result = BioRxivDownloader().download_with_result(_URL)++ assert result.is_success+ _assert_redacted(rendered_log)+++def test_download_result_head_failure_logs_only_origin(rendered_log):+ downloader = BioRxivDownloader()+ downloader.session.head = Mock(+ side_effect=requests.RequestException(f"request failed: {_URL}")+ )+ with patch.object(BaseDownloader, "_download_pdf", return_value=None):+ result = downloader.download_with_result(_URL)++ assert not result.is_success+ _assert_redacted(rendered_log)+++def test_pdf_conversion_failure_logs_only_origin(rendered_log):+ downloader = BioRxivDownloader()+ downloader._convert_to_pdf_url = Mock(return_value=None)++ assert downloader._download_pdf(_URL) is None+ _assert_redacted(rendered_log)+++def test_pdf_download_start_logs_only_origin(rendered_log):+ with patch.object(BaseDownloader, "_download_pdf", return_value=None):+ assert BioRxivDownloader()._download_pdf(_URL) is None++ _assert_redacted(rendered_log)+++def test_abstract_fetch_failure_logs_only_origin(rendered_log):+ downloader = BioRxivDownloader()+ downloader.session.get = Mock(+ side_effect=requests.RequestException(f"fetch failed: {_URL}")+ )+ with patch.object(BaseDownloader, "_download_pdf", return_value=None):+ result = downloader.download_with_result(_URL, ContentType.TEXT)++ assert not result.is_success+ _assert_redacted(rendered_log)diff --git a/tests/research_library/downloaders/test_direct_pdf_logging_sinks.py b/tests/research_library/downloaders/test_direct_pdf_logging_sinks.pynew file mode 100644index 0000000000..96ba3ccee4--- /dev/null+++ b/tests/research_library/downloaders/test_direct_pdf_logging_sinks.py@@ -0,0 +1,400 @@+"""Sink-leak tests for the direct-PDF download path's log events.++``DirectPDFDownloader.download_with_result`` -> ``_download_pdf`` ->+``BaseDownloader._download_pdf`` log the raw fetch URL — which can carry+credentials — and previously used ``logger.exception``, attaching the caught+error (whose message often embeds the same URL) to every sink. These tests+pin the redacted + no-attachment shape of those events and the redacted+rate-limit engine key.+"""++from __future__ import annotations++from io import StringIO+from unittest.mock import Mock++import pytest+import requests+from loguru import logger++import local_deep_research.research_library.downloaders.direct_pdf as direct_pdf_mod+from local_deep_research.research_library.downloaders.base import (+ BaseDownloader,+ rate_limit_authority,+)+from local_deep_research.research_library.downloaders.direct_pdf import (+ ContentType,+ DirectPDFDownloader,+)++_SECRET = "credential-do-not-log"+_EXCEPTION_TEXT = "network-error-do-not-log"+_URL = (+ f"https://alice:{_SECRET}@origin.example:8443/private/%2Fencoded"+ f"?token={_SECRET}&next=%2Felsewhere#fragment"+)+_ORIGIN = "https://origin.example:8443"+_CLOSE_ERROR_TEXT = "connection pool already released"+_FORBIDDEN = (+ "alice",+ _SECRET,+ "/private/",+ "%2Fencoded",+ "token=",+ "next=",+ "fragment",+ _EXCEPTION_TEXT,+ "Traceback",+)+++def rendered_log():+ output = StringIO()+ logger.enable("local_deep_research")+ sink_id = logger.add(+ output,+ level="DEBUG",+ format="{message}\n{exception}",+ backtrace=True,+ diagnose=False,+ )+ try:+ yield output+ finally:+ logger.remove(sink_id)+ logger.disable("local_deep_research")+++def _assert_safe_event(output, event, require_origin=True):+ lines = [line for line in output.getvalue().splitlines() if event in line]+ assert len(lines) == 1+ if require_origin:+ assert lines[0].count(_ORIGIN) == 1+ for marker in _FORBIDDEN:+ assert marker not in output.getvalue()+++def _pdf_response():+ response = Mock()+ response.status_code = 200+ response.content = b"%PDF-1.4 fake-bytes"+ response.headers = {"content-type": "application/pdf"}+ return response+++def _make_downloader(monkeypatch, session_get):+ downloader = DirectPDFDownloader()+ monkeypatch.setattr(downloader.session, "get", session_get)+ monkeypatch.setattr(+ downloader.rate_tracker, "apply_rate_limit", lambda _engine: 0.0+ )+ monkeypatch.setattr(downloader.rate_tracker, "record_outcome", Mock())+ return downloader+++def test_text_path_success_renders_safe_events(rendered_log, monkeypatch):+ downloader = _make_downloader(+ monkeypatch, lambda *_a, **_k: _pdf_response()+ )+ monkeypatch.setattr(+ DirectPDFDownloader,+ "extract_text_from_pdf",+ staticmethod(lambda _content: "text"),+ )++ result = downloader.download_with_result(_URL, ContentType.TEXT)++ assert result.is_success+ assert result.content == b"text"+ _assert_safe_event(rendered_log, "Downloading PDF directly from:")+ _assert_safe_event(rendered_log, "Downloading PDF from")+ _assert_safe_event(rendered_log, "Successfully downloaded PDF from")+++def test_pdf_path_success_renders_safe_events(rendered_log, monkeypatch):+ downloader = _make_downloader(+ monkeypatch, lambda *_a, **_k: _pdf_response()+ )++ result = downloader.download_with_result(_URL)++ assert result.is_success+ _assert_safe_event(rendered_log, "Attempting direct PDF download from")+ _assert_safe_event(+ rendered_log, "Successfully downloaded PDF directly from"+ )+++ ("exc", "event"),+ [+ (+ requests.exceptions.RequestException(f"{_EXCEPTION_TEXT}: {_URL}"),+ "Request error downloading from",+ ),+ (+ ValueError(f"{_EXCEPTION_TEXT}: {_URL}"),+ "Unexpected error downloading from",+ ),+ ],+)+def test_immediate_failures_render_safe_events(+ rendered_log, monkeypatch, exc, event+):+ def _raise(*_a, **_k):+ raise exc++ downloader = _make_downloader(monkeypatch, _raise)++ assert downloader._download_pdf(_URL) is None++ _assert_safe_event(rendered_log, event)+++def test_connection_error_exhaustion_renders_safe_events(+ rendered_log, monkeypatch+):+ def _raise(*_a, **_k):+ raise requests.exceptions.ConnectionError(f"{_EXCEPTION_TEXT}: {_URL}")++ downloader = _make_downloader(monkeypatch, _raise)++ assert downloader._download_pdf(_URL) is None++ output = rendered_log.getvalue()+ final = [line for line in output.splitlines() if "after 3 attempts" in line]+ assert len(final) == 1+ assert final[0].count(_ORIGIN) == 1+ attempts = [+ line for line in output.splitlines() if "downloading from" in line+ ]+ assert len(attempts) == 3+ for line in attempts:+ assert line.count(_ORIGIN) == 1+ for marker in _FORBIDDEN:+ assert marker not in output+++def test_http_error_status_renders_safe_event(rendered_log, monkeypatch):+ response = Mock()+ response.status_code = 404+ response.content = b""+ response.headers = {}+ downloader = _make_downloader(monkeypatch, lambda *_a, **_k: response)++ assert downloader._download_pdf(_URL) is None++ _assert_safe_event(rendered_log, "Failed to download from")+++def test_http_rate_limited_exhaustion_renders_safe_events(+ rendered_log, monkeypatch+):+ response = Mock()+ response.status_code = 429+ response.content = b""+ response.headers = {}+ downloader = _make_downloader(monkeypatch, lambda *_a, **_k: response)++ assert downloader._download_pdf(_URL) is None++ output = rendered_log.getvalue()+ final = [line for line in output.splitlines() if "after 3 attempts" in line]+ assert len(final) == 1+ assert final[0].count(_ORIGIN) == 1+ attempts = [line for line in output.splitlines() if "HTTP 429 from" in line]+ assert len(attempts) == 3+ for line in attempts:+ assert line.count(_ORIGIN) == 1+ for marker in _FORBIDDEN:+ assert marker not in output+++def test_decode_failure_renders_safe_event(rendered_log, monkeypatch):+ downloader = _make_downloader(monkeypatch, Mock())+ monkeypatch.setattr(+ downloader, "download", lambda _url, _content_type: b"\xff\xfe"+ )++ assert downloader.download_text(_URL) is None++ _assert_safe_event(rendered_log, "Failed to decode text content from")+++def test_can_handle_parse_error_renders_safe_event(rendered_log, monkeypatch):+ def _raise(_url):+ raise ValueError(_EXCEPTION_TEXT)++ monkeypatch.setattr(direct_pdf_mod, "urlparse", _raise)++ assert DirectPDFDownloader().can_handle(_URL) is False++ _assert_safe_event(rendered_log, "Error parsing URL")+++ ("authority", "expected_authority"),+ [+ ("origin.example", "origin.example"),+ ("origin.example:8443", "origin.example:8443"),+ ("[2001:db8::1]", "[2001:db8::1]"),+ ("[2001:db8::1]:8443", "[2001:db8::1]:8443"),+ ],+)+def test_rate_limit_engine_key_omits_userinfo_and_preserves_authority(+ monkeypatch, authority, expected_authority+):+ captured = []+ url = f"https://alice:secret@{authority}/file.pdf"++ def _capture(engine_type):+ captured.append(engine_type)+ return 0.0++ response = Mock()+ response.status_code = 404+ response.content = b""+ response.headers = {}+ downloader = DirectPDFDownloader()+ monkeypatch.setattr(downloader.session, "get", lambda *_a, **_k: response)+ monkeypatch.setattr(downloader.rate_tracker, "apply_rate_limit", _capture)+ monkeypatch.setattr(downloader.rate_tracker, "record_outcome", Mock())++ assert downloader._download_pdf(url) is None++ assert captured == [f"pdf_download_{expected_authority}"]+ assert "alice" not in captured[0]+ assert "secret" not in captured[0]+++ "url",+ [+ f"https://alice:{_SECRET}@origin.example:bad/file.pdf",+ f"https://alice:{_SECRET}@origin.example:99999/file.pdf",+ f"http://alice:{_SECRET}@[/file.pdf",+ ],+)+def test_malformed_authority_reaches_normal_download_failure(+ rendered_log, monkeypatch, url+):+ captured = []+ response = Mock(status_code=404, content=b"", headers={})+ downloader = _make_downloader(monkeypatch, lambda *_a, **_k: response)+ monkeypatch.setattr(+ downloader.rate_tracker,+ "apply_rate_limit",+ lambda engine_type: captured.append(engine_type) or 0.0,+ )++ assert downloader._download_pdf(url) is None++ assert captured == ["pdf_download_invalid_authority"]+ assert "alice" not in captured[0]+ assert _SECRET not in captured[0]+ _assert_safe_event(+ rendered_log, "Downloading PDF from", require_origin=False+ )+ _assert_safe_event(+ rendered_log, "Failed to download from", require_origin=False+ )+ assert url not in rendered_log.getvalue()+++def test_extract_text_from_pdf_failure_attaches_no_exception(rendered_log):+ assert BaseDownloader.extract_text_from_pdf(b"not a pdf") is None++ _assert_safe_event(+ rendered_log, "Failed to extract text from PDF", require_origin=False+ )+ # Same middle ground as ``close``: pypdf's own message ("Stream has+ # ended unexpectedly") is the whole diagnostic and cannot carry a URL --+ # the frame holds only the PDF bytes -- so it is kept, without a+ # traceback.+ rendered = rendered_log.getvalue()+ event = next(+ line+ for line in rendered.splitlines()+ if "Failed to extract text from PDF" in line+ )+ assert event.split("Failed to extract text from PDF:", 1)[1].strip()+ assert "Traceback" not in rendered+++def test_close_failure_attaches_no_exception(rendered_log, monkeypatch):+ downloader = DirectPDFDownloader()+ monkeypatch.setattr(+ downloader.session,+ "close",+ Mock(side_effect=RuntimeError(_CLOSE_ERROR_TEXT)),+ )++ downloader.close()++ _assert_safe_event(+ rendered_log, "Error closing downloader session", require_origin=False+ )+ # The scrubbed type+message survives -- "something failed" is not a+ # usable event -- while the traceback (and every frame-local loguru's+ # ``diagnose`` would render with it) stays out. Safe here because this+ # handler's frames hold no URL: the only value in scope is the session.+ assert _CLOSE_ERROR_TEXT in rendered_log.getvalue()+ assert "Traceback" not in rendered_log.getvalue()+++ ("url", "expected"),+ [+ ("https://origin.example/paper.pdf", "origin.example"),+ (+ f"https://alice:{_SECRET}@origin.example:8443/p?token={_SECRET}",+ "origin.example:8443",+ ),+ # Leading whitespace: ``urlsplit`` lstrips C0-control-or-space and so+ # does ``requests`` when it prepares the request, so the URL really+ # is fetched and its per-host bucket must survive. Deriving the key+ # from ``redact_url_for_log(url)`` instead yielded "" here and+ # merged every such host into one adaptive rate-limit bucket.+ (" https://slow-host.example/paper", "slow-host.example"),+ ("\thttps://tab-host.example/paper", "tab-host.example"),+ ("http://[2001:db8::1]:8080/paper.pdf", "[2001:db8::1]:8080"),+ ("http://[2001:db8::1]/paper.pdf", "[2001:db8::1]"),+ (f"https://alice:{_SECRET}@origin.example:bad/p", "invalid_authority"),+ (+ f"https://alice:{_SECRET}@origin.example:99999/p",+ "invalid_authority",+ ),+ (f"http://alice:{_SECRET}@[/paper.pdf", "invalid_authority"),+ # Whitespace inside the host is not a legal RFC 3986 reg-name and is+ # percent-encoded by ``requests`` before the request leaves, so it is+ # not the host contacted either; the tracker renders the key into its+ # own log messages, so it must stay one printable token.+ ("https://exa mple.com/paper.pdf", "invalid_authority"),+ # No authority at all -- one degenerate bucket, as on main.+ ("/relative/paper.pdf", ""),+ ("", ""),+ ],+)+def test_rate_limit_authority_matrix(url, expected):+ authority = rate_limit_authority(url)++ assert authority == expected+ assert "alice" not in authority+ assert _SECRET not in authority+ assert not any(ch.isspace() or not ch.isprintable() for ch in authority)+++def test_rate_limit_authority_ignores_an_oversized_url():+ url = "https://origin.example:8443/" + "a" * 100_000++ assert rate_limit_authority(url) == "origin.example:8443"+++def test_rate_limit_authority_keeps_distinct_hosts_in_distinct_buckets():+ keys = {+ rate_limit_authority(f" https://{host}/paper")+ for host in ("slow-host.example", "fast-host.example")+ }++ assert keys == {"slow-host.example", "fast-host.example"}diff --git a/tests/research_library/downloaders/test_generic_logging_sinks.py b/tests/research_library/downloaders/test_generic_logging_sinks.pynew file mode 100644index 0000000000..404cd5ed3e--- /dev/null+++ b/tests/research_library/downloaders/test_generic_logging_sinks.py@@ -0,0 +1,77 @@+from io import StringIO+from unittest.mock import Mock, patch++import pytest+import requests+from loguru import logger++from local_deep_research.research_library.downloaders.base import BaseDownloader+from local_deep_research.research_library.downloaders.generic import (+ GenericDownloader,+)++_SECRET = "credential-do-not-log"+_URL = f"https://user:{_SECRET}@origin.example/private?token={_SECRET}"+_ORIGIN = "https://origin.example"+++def rendered_log():+ output = StringIO()+ logger.enable("local_deep_research")+ sink_id = logger.add(output, level="DEBUG", format="{message}\n{exception}")+ try:+ yield output+ finally:+ logger.remove(sink_id)+ logger.disable("local_deep_research")+++def _assert_redacted(output: StringIO) -> None:+ rendered = output.getvalue()+ assert _ORIGIN in rendered+ assert _SECRET not in rendered+ assert "user:" not in rendered+ assert "token=" not in rendered+++ "method_name", ["download_with_result", "_download_pdf"]+)+def test_direct_success_logs_only_origin(rendered_log, method_name):+ with patch.object(BaseDownloader, "_download_pdf", return_value=b"%PDF"):+ getattr(GenericDownloader(), method_name)(_URL)++ _assert_redacted(rendered_log)+++ "method_name", ["download_with_result", "_download_pdf"]+)+def test_extension_success_logs_only_origin(rendered_log, method_name):+ with patch.object(+ BaseDownloader, "_download_pdf", side_effect=[None, b"%PDF"]+ ):+ getattr(GenericDownloader(), method_name)(_URL)++ _assert_redacted(rendered_log)+++def test_diagnostic_failure_logs_only_origin(rendered_log):+ downloader = GenericDownloader()+ downloader.session.get = Mock(+ side_effect=requests.RequestException(f"request failed: {_URL}")+ )++ with patch.object(BaseDownloader, "_download_pdf", return_value=None):+ result = downloader.download_with_result(_URL)++ assert not result.is_success+ _assert_redacted(rendered_log)+++def test_terminal_failure_logs_only_origin(rendered_log):+ with patch.object(BaseDownloader, "_download_pdf", return_value=None):+ assert GenericDownloader()._download_pdf(_URL) is None++ _assert_redacted(rendered_log)diff --git a/tests/research_library/downloaders/test_html_logging_sinks.py b/tests/research_library/downloaders/test_html_logging_sinks.pynew file mode 100644index 0000000000..ef53f6dd79--- /dev/null+++ b/tests/research_library/downloaders/test_html_logging_sinks.py@@ -0,0 +1,475 @@+import sys+import types+from io import StringIO+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest+from loguru import logger++from local_deep_research.research_library.downloaders.base import (+ ContentType,+ rate_limit_authority,+)+from local_deep_research.research_library.downloaders.html import HTMLDownloader+from local_deep_research.research_library.downloaders.playwright_html import (+ AutoHTMLDownloader,+ PlaywrightHTMLDownloader,+)+++_SECRET = "credential-do-not-log"+_EXCEPTION_TEXT = "network-error-do-not-log"+_TITLE = "title-do-not-log"+_URL = (+ f"https://alice:{_SECRET}@origin.example:8443/private/%2Fencoded"+ f"?token={_SECRET}&next=%2Felsewhere#fragment"+)+_ORIGIN = "https://origin.example:8443"+_FORBIDDEN = (+ "alice",+ _SECRET,+ "/private/",+ "%2Fencoded",+ "token=",+ "next=",+ "fragment",+ _EXCEPTION_TEXT,+ _TITLE,+ "Traceback",+)+++def rendered_log():+ output = StringIO()+ logger.enable("local_deep_research")+ sink_id = logger.add(+ output,+ level="DEBUG",+ format="{message}\n{exception}",+ backtrace=True,+ diagnose=False,+ )+ try:+ yield output+ finally:+ logger.remove(sink_id)+ logger.disable("local_deep_research")+++def _assert_safe_event(output, event):+ lines = [line for line in output.getvalue().splitlines() if event in line]+ assert len(lines) == 1+ assert lines[0].count(_ORIGIN) == 1+ for marker in _FORBIDDEN:+ assert marker not in output.getvalue()+++def _html_downloader(response=None, error=None):+ downloader = HTMLDownloader()+ rate_tracker = MagicMock()+ rate_tracker.apply_rate_limit.return_value = 0+ downloader.rate_tracker = rate_tracker+ downloader.session = MagicMock()+ downloader.session.get.return_value = response+ downloader.session.get.side_effect = error+ return downloader, rate_tracker+++ ("response", "error", "event"),+ [+ (+ SimpleNamespace(+ status_code=200,+ headers={"content-type": "text/html"},+ text="<html>ok</html>",+ ),+ None,+ "html.fetch_succeeded",+ ),+ (+ SimpleNamespace(+ status_code=200,+ headers={"content-type": "application/pdf"},+ text="",+ ),+ None,+ "html.fetch_unexpected_content_type",+ ),+ (+ SimpleNamespace(status_code=503, headers={}, text=""),+ None,+ "html.fetch_failed",+ ),+ (None, RuntimeError(f"{_EXCEPTION_TEXT}: {_URL}"), "html.fetch_error"),+ ],+)+def test_static_fetch_branches_render_one_safe_origin(+ rendered_log, response, error, event+):+ downloader, rate_tracker = _html_downloader(response=response, error=error)++ with downloader:+ downloader._fetch_html(_URL)++ rate_tracker.apply_rate_limit.assert_called_once_with(+ "html_download_origin.example:8443"+ )+ _assert_safe_event(rendered_log, event)+++ ("method_name", "event"),+ [+ ("download", "html.download_failed"),+ ("download_with_result", "html.download_result_failed"),+ ],+)+def test_html_download_exception_branches_do_not_render_exception(+ rendered_log, method_name, event+):+ downloader = HTMLDownloader()+ with patch.object(+ downloader,+ "_fetch_html",+ side_effect=RuntimeError(f"{_EXCEPTION_TEXT}: {_URL}"),+ ):+ getattr(downloader, method_name)(_URL, ContentType.TEXT)++ _assert_safe_event(rendered_log, event)+++def test_hostile_title_is_omitted_from_success_log(rendered_log):+ downloader = HTMLDownloader()+ with patch(+ "local_deep_research.research_library.downloaders.html.extract_content_with_metadata",+ return_value={"title": _TITLE, "content": "useful content"},+ ):+ extracted = downloader._extract_content("<html></html>", _URL)++ assert extracted is not None+ assert extracted["title"] == _TITLE+ _assert_safe_event(rendered_log, "html.extract_succeeded")+++def test_metadata_exception_uses_safe_static_event(rendered_log):+ downloader = HTMLDownloader()+ with (+ patch.object(downloader, "_fetch_html", return_value="<html></html>"),+ patch(+ "local_deep_research.research_library.downloaders.html.BeautifulSoup",+ side_effect=RuntimeError(f"{_EXCEPTION_TEXT}: {_URL}"),+ ),+ ):+ metadata = downloader.get_metadata(_URL)++ assert metadata == {"url": _URL}+ _assert_safe_event(rendered_log, "html.metadata_extract_failed")+++def test_extract_exception_renders_safe_static_event(rendered_log):+ downloader = HTMLDownloader()+ with patch(+ "local_deep_research.research_library.downloaders.html.extract_content_with_metadata",+ side_effect=RuntimeError(f"{_EXCEPTION_TEXT}: {_URL}"),+ ):+ assert downloader._extract_content("<html></html>", _URL) is None++ _assert_safe_event(rendered_log, "html.extract_failed")+++def _install_crawl4ai(monkeypatch, result):+ class Config:+ def __init__(self, **_kwargs):+ pass++ class Crawler:+ def __init__(self, **_kwargs):+ # The downloader installs its SSRF route guard via+ # crawler_strategy.set_hook() before navigating; a guard-install+ # failure fails closed (returns None) and emits none of the+ # crawl4ai.* events. Provide a no-op strategy so the guarded+ # fetch path proceeds and its event is rendered.+ self.crawler_strategy = SimpleNamespace(+ set_hook=lambda *_args, **_kwargs: None+ )++ async def __aenter__(self):+ return self++ async def __aexit__(self, *_args):+ return False++ async def arun(self, **_kwargs):+ if isinstance(result, Exception):+ raise result+ return result++ module = types.ModuleType("crawl4ai")+ module.__dict__.update(+ AsyncWebCrawler=Crawler,+ BrowserConfig=Config,+ CrawlerRunConfig=Config,+ )+ monkeypatch.setitem(sys.modules, "crawl4ai", module)+++ ("result", "event"),+ [+ (+ SimpleNamespace(success=True, html="<html>ok</html>"),+ "crawl4ai.fetch_succeeded",+ ),+ (+ SimpleNamespace(+ success=False, html="", error_message="robots.txt denied"+ ),+ "crawl4ai.robots_denied",+ ),+ (+ SimpleNamespace(success=False, html="", status_code=503),+ "crawl4ai.fetch_failed",+ ),+ (RuntimeError(f"{_EXCEPTION_TEXT}: {_URL}"), "crawl4ai.fetch_error"),+ ],+)+def test_crawl4ai_branches_render_safe_events(+ rendered_log, monkeypatch, result, event+):+ _install_crawl4ai(monkeypatch, result)+ downloader = PlaywrightHTMLDownloader()+ # Close the robots.txt network seam: the real check fetches+ # ``/robots.txt`` through SafeSession before the key is applied.+ monkeypatch.setattr(downloader, "_robots_allows", lambda _url: True)+ downloader.rate_tracker = MagicMock()+ downloader.rate_tracker.apply_rate_limit.return_value = 0++ with downloader:+ downloader._fetch_with_crawl4ai(_URL)++ downloader.rate_tracker.apply_rate_limit.assert_called_once_with(+ "crawl4ai_download_origin.example:8443"+ )+ _assert_safe_event(rendered_log, event)+++def _install_playwright(monkeypatch, page):+ class Browser:+ def new_page(self, **_kwargs):+ return page++ def close(self):+ return None++ class Playwright:+ chromium = SimpleNamespace(launch=lambda **_kwargs: Browser())++ def stop(self):+ return None++ package = types.ModuleType("playwright")+ sync_api = types.ModuleType("playwright.sync_api")+ sync_api.__dict__["sync_playwright"] = lambda: SimpleNamespace(+ start=lambda: Playwright()+ )+ monkeypatch.setitem(sys.modules, "playwright", package)+ monkeypatch.setitem(sys.modules, "playwright.sync_api", sync_api)+++ ("content", "error", "event"),+ [+ ("<html>ok</html>", None, "playwright.fetch_succeeded"),+ ("", None, "playwright.fetch_empty"),+ (+ None,+ RuntimeError(f"{_EXCEPTION_TEXT}: {_URL}"),+ "playwright.fetch_error",+ ),+ ],+)+def test_playwright_branches_render_safe_events(+ rendered_log, monkeypatch, content, error, event+):+ page = MagicMock()+ page.goto.side_effect = error+ page.content.return_value = content+ _install_playwright(monkeypatch, page)+ downloader = PlaywrightHTMLDownloader()+ downloader.rate_tracker = MagicMock()+ downloader.rate_tracker.apply_rate_limit.return_value = 0++ with downloader:+ downloader._fetch_with_playwright(_URL)++ downloader.rate_tracker.apply_rate_limit.assert_called_once_with(+ "playwright_download_origin.example:8443"+ )+ _assert_safe_event(rendered_log, event)+++def test_auto_html_success_fallback_and_raw_exception_events_are_safe(+ rendered_log,+):+ downloader = AutoHTMLDownloader(+ min_content_length=10, enable_js_rendering=True+ )+ downloader.rate_tracker = MagicMock()+ downloader.rate_tracker.apply_rate_limit.return_value = 0+ downloader._playwright_downloader = MagicMock()+ downloader._playwright_downloader.download.return_value = (+ b"long enough body"+ )++ def static_download(*_args):+ downloader._last_raw_html = '<div id="root"></div>'+ return b"short"++ with patch.object(HTMLDownloader, "download", side_effect=static_download):+ assert downloader.download(_URL) == b"long enough body"+ downloader.session = MagicMock()+ downloader.session.get.side_effect = RuntimeError(+ f"{_EXCEPTION_TEXT}: {_URL}"+ )+ try:+ assert downloader._fetch_html(_URL) is None+ finally:+ downloader.close()++ _assert_safe_event(rendered_log, "auto_html.js_fallback_started")+ _assert_safe_event(rendered_log, "auto_html.js_succeeded")+ _assert_safe_event(rendered_log, "auto_html.raw_fetch_failed")+++ ("static_result", "event"),+ [+ (b"long enough body", "auto_html.static_fetch_succeeded"),+ (None, "auto_html.js_fallback_disabled"),+ ],+)+def test_auto_html_static_success_and_disabled_failure_events_are_safe(+ rendered_log, static_result, event+):+ downloader = AutoHTMLDownloader(+ min_content_length=10, enable_js_rendering=False+ )+ with patch.object(HTMLDownloader, "download", return_value=static_result):+ downloader.download(_URL)+ downloader.close()+ _assert_safe_event(rendered_log, event)+++# ---------------------------------------------------------------------------+# Rate-limit engine keys — one shared derivation across the three sites.+# ---------------------------------------------------------------------------++# Same matrix as tests/research_library/downloaders/+# test_direct_pdf_logging_sinks.py's ``pdf_download_`` cases: all four keys+# come from ``base.rate_limit_authority`` so they cannot drift apart.+_AUTHORITY_CASES = [+ ("https://origin.example:8443/paper", "origin.example:8443"),+ (_URL, "origin.example:8443"),+ # Leading whitespace survives to the fetch (``requests`` lstrips it when+ # preparing), so the per-host bucket must survive too. The previous+ # derivation re-parsed ``redact_url_for_log(url)`` — which renders+ # ``?:// https`` for this input — and produced an empty authority,+ # merging every whitespace-prefixed host into one bucket.+ (" https://slow-host.example/paper", "slow-host.example"),+ ("http://[2001:db8::1]:8080/paper", "[2001:db8::1]:8080"),+ (+ f"https://alice:{_SECRET}@origin.example:99999/paper",+ "invalid_authority",+ ),+ (f"http://alice:{_SECRET}@[/paper", "invalid_authority"),+]+++def _drive_html(url, _monkeypatch):+ # Same (url, monkeypatch) signature as the two browser drivers so the+ # parametrisation below can treat all three uniformly; the static path+ # needs no module stubbing, so its monkeypatch argument goes unused.+ downloader, rate_tracker = _html_downloader(+ response=SimpleNamespace(status_code=503, headers={}, text="")+ )+ with downloader:+ downloader._fetch_html(url)+ return rate_tracker+++def _drive_crawl4ai(url, monkeypatch):+ _install_crawl4ai(+ monkeypatch, SimpleNamespace(success=True, html="<html>ok</html>")+ )+ downloader = PlaywrightHTMLDownloader()+ # Close the robots.txt network seam: the real check fetches+ # ``/robots.txt`` through SafeSession before the key is applied.+ monkeypatch.setattr(downloader, "_robots_allows", lambda _url: True)+ downloader.rate_tracker = MagicMock()+ downloader.rate_tracker.apply_rate_limit.return_value = 0+ with downloader:+ downloader._fetch_with_crawl4ai(url)+ return downloader.rate_tracker+++def _drive_playwright(url, monkeypatch):+ page = MagicMock()+ page.content.return_value = "<html>ok</html>"+ _install_playwright(monkeypatch, page)+ downloader = PlaywrightHTMLDownloader()+ downloader.rate_tracker = MagicMock()+ downloader.rate_tracker.apply_rate_limit.return_value = 0+ with downloader:+ downloader._fetch_with_playwright(url)+ return downloader.rate_tracker++[email protected](("url", "expected_authority"), _AUTHORITY_CASES)+ ("driver", "prefix"),+ [+ (_drive_html, "html_download_"),+ (_drive_crawl4ai, "crawl4ai_download_"),+ (_drive_playwright, "playwright_download_"),+ ],+)+def test_engine_keys_come_from_the_shared_authority_helper(+ monkeypatch, driver, prefix, url, expected_authority+):+ rate_tracker = driver(url, monkeypatch)++ rate_tracker.apply_rate_limit.assert_called_once_with(+ f"{prefix}{expected_authority}"+ )+ key = rate_tracker.apply_rate_limit.call_args[0][0]+ assert key == prefix + rate_limit_authority(url)+ assert "alice" not in key+ assert _SECRET not in key+ assert not any(ch.isspace() or not ch.isprintable() for ch in key)+++ ("driver", "prefix"),+ [+ (_drive_html, "html_download_"),+ (_drive_crawl4ai, "crawl4ai_download_"),+ (_drive_playwright, "playwright_download_"),+ ],+)+def test_whitespace_prefixed_urls_keep_per_host_buckets(+ monkeypatch, driver, prefix+):+ keys = [+ driver(+ f" https://{host}/paper", monkeypatch+ ).apply_rate_limit.call_args[0][0]+ for host in ("slow-host.example", "fast-host.example")+ ]++ assert keys == [+ f"{prefix}slow-host.example",+ f"{prefix}fast-host.example",+ ]diff --git a/tests/research_library/downloaders/test_pipeline_logging_sinks.py b/tests/research_library/downloaders/test_pipeline_logging_sinks.pynew file mode 100644index 0000000000..aad2e5576b--- /dev/null+++ b/tests/research_library/downloaders/test_pipeline_logging_sinks.py@@ -0,0 +1,217 @@+"""Sink-leak tests for the extraction pipeline's fetch-path log events.++``fetch_and_extract`` / ``batch_fetch_and_extract`` /+``_try_specialized_downloader`` log on failure with the raw fetch URL —+which can carry credentials. The ``logger.exception`` sites among them+attached the caught error (whose message often embeds the same URL) to+every sink; the ``exc_info=True`` sites attached nothing, because loguru+has no ``exc_info`` keyword — it is swallowed as a bound extra+(``record["extra"]["exc_info"]``) and renders no traceback — so those sites+leaked only through the raw URL in the message itself. These tests pin the+redacted + no-attachment shape of all of those events.+"""++from __future__ import annotations++from io import StringIO+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest+from loguru import logger++import local_deep_research.research_library.downloaders.extraction.pipeline as pipeline_mod+from local_deep_research.research_library.downloaders.extraction.pipeline import (+ batch_fetch_and_extract,+ fetch_and_extract,+)++_SECRET = "credential-do-not-log"+_EXCEPTION_TEXT = "network-error-do-not-log"+_URL = (+ f"https://alice:{_SECRET}@origin.example:8443/private/%2Fencoded"+ f"?token={_SECRET}&next=%2Felsewhere#fragment"+)+_ORIGIN = "https://origin.example:8443"+_FORBIDDEN = (+ "alice",+ _SECRET,+ "/private/",+ "%2Fencoded",+ "token=",+ "next=",+ "fragment",+ _EXCEPTION_TEXT,+ "Traceback",+)+++def rendered_log():+ output = StringIO()+ logger.enable("local_deep_research")+ sink_id = logger.add(+ output,+ level="DEBUG",+ format="{message}\n{exception}",+ backtrace=True,+ diagnose=False,+ )+ try:+ yield output+ finally:+ logger.remove(sink_id)+ logger.disable("local_deep_research")+++def _assert_safe_event(output, event):+ lines = [line for line in output.getvalue().splitlines() if event in line]+ assert len(lines) == 1+ assert lines[0].count(_ORIGIN) == 1+ for marker in _FORBIDDEN:+ assert marker not in output.getvalue()+++def _auto_html_downloader_raising():+ downloader_cls = MagicMock()+ downloader_cls.return_value.download.side_effect = RuntimeError(+ f"{_EXCEPTION_TEXT}: {_URL}"+ )+ return downloader_cls+++def test_fetch_and_extract_failure_renders_safe_event(rendered_log):+ with (+ # ``_try_specialized_downloader`` returns a ``_SpecializedResult``+ # (content, fallback_allowed); the defaults -- no content, fallback+ # allowed -- are what sends ``fetch_and_extract`` into the generic+ # HTML pipeline that raises below.+ patch.object(+ pipeline_mod,+ "_try_specialized_downloader",+ return_value=pipeline_mod._SpecializedResult(),+ ),+ patch(+ "local_deep_research.research_library.downloaders"+ ".playwright_html.AutoHTMLDownloader",+ _auto_html_downloader_raising(),+ ),+ ):+ assert fetch_and_extract(_URL) is None++ _assert_safe_event(rendered_log, "fetch_and_extract failed for")+++def test_fetch_and_extract_specialized_error_renders_safe_event(rendered_log):+ with (+ patch.object(+ pipeline_mod,+ "_try_specialized_downloader",+ side_effect=RuntimeError(f"{_EXCEPTION_TEXT}: {_URL}"),+ ),+ patch(+ "local_deep_research.research_library.downloaders"+ ".playwright_html.AutoHTMLDownloader",+ _auto_html_downloader_raising(),+ ),+ ):+ assert fetch_and_extract(_URL) is None++ _assert_safe_event(rendered_log, "specialized downloader error for")+ _assert_safe_event(rendered_log, "fetch_and_extract failed for")+++def test_batch_fetch_and_extract_failures_render_safe_events(rendered_log):+ with (+ patch.object(+ pipeline_mod,+ "_try_specialized_downloader",+ side_effect=RuntimeError(f"{_EXCEPTION_TEXT}: {_URL}"),+ ),+ patch(+ "local_deep_research.research_library.downloaders"+ ".playwright_html.AutoHTMLDownloader",+ _auto_html_downloader_raising(),+ ),+ ):+ results = batch_fetch_and_extract([_URL])++ assert results == {_URL: None}+ _assert_safe_event(rendered_log, "specialized downloader error for")+ _assert_safe_event(rendered_log, "batch_fetch_and_extract failed for")+++def _install_specialized(+ monkeypatch, download_result=None, download_error=None+):+ """Route ``_URL`` through a stubbed *PubMed* specialized downloader.++ PubMed rather than arXiv on purpose. A paper URL classified ARXIV is+ terminal in ``_try_specialized_downloader`` (``fallback_allowed`` False),+ so its "returned no content for ..." event -- one of the redacted lines+ pinned here -- is never emitted, and its downloader is resolved through a+ dynamic import guarded by ``issubclass(..., BaseDownloader)`` that a stub+ callable cannot satisfy. PubMed keeps every logging branch reachable.+ """+ from local_deep_research.content_fetcher.url_classifier import (+ URLClassifier,+ URLType,+ )++ monkeypatch.setattr(URLClassifier, "classify", lambda _url: URLType.PUBMED)+ downloader = MagicMock()+ if download_error is not None:+ downloader.download_with_result.side_effect = download_error+ else:+ downloader.download_with_result.return_value = download_result+ monkeypatch.setattr(+ "local_deep_research.research_library.downloaders.pubmed.PubMedDownloader",+ lambda timeout=30: downloader,+ )+ return downloader+++def test_specialized_downloader_success_renders_safe_event(+ rendered_log, monkeypatch+):+ _install_specialized(+ monkeypatch,+ download_result=SimpleNamespace(is_success=True, content=b"x" * 60),+ )++ result = pipeline_mod._try_specialized_downloader(_URL)++ assert result.content == "x" * 60+ assert result.fallback_allowed is True+ _assert_safe_event(rendered_log, "returned 60 chars for")+++def test_specialized_downloader_failure_renders_safe_events(+ rendered_log, monkeypatch+):+ _install_specialized(+ monkeypatch,+ download_error=RuntimeError(f"{_EXCEPTION_TEXT}: {_URL}"),+ )++ result = pipeline_mod._try_specialized_downloader(_URL)++ assert result.content is None+ assert result.fallback_allowed is True+ _assert_safe_event(rendered_log, "specialized downloader failed for")+ _assert_safe_event(rendered_log, "no content for")+++def test_specialized_downloader_empty_result_renders_safe_event(+ rendered_log, monkeypatch+):+ _install_specialized(+ monkeypatch,+ download_result=SimpleNamespace(is_success=False, content=None),+ )++ result = pipeline_mod._try_specialized_downloader(_URL)++ assert result.content is None+ assert result.fallback_allowed is True+ _assert_safe_event(rendered_log, "no content for")diff --git a/tests/research_library/downloaders/test_playwright_guard_logging_sinks.py b/tests/research_library/downloaders/test_playwright_guard_logging_sinks.pynew file mode 100644index 0000000000..77a77ea958--- /dev/null+++ b/tests/research_library/downloaders/test_playwright_guard_logging_sinks.py@@ -0,0 +1,230 @@+"""Record-shape tests for the Playwright/Crawl4AI guard log events.++The browser route guards, the Set-Cookie parser, the per-hop cookie+re-derivation, and the guarded robots.txt check all log their failure+branches with ``logger.opt(exception=False).debug(...)``: a static+message with NO exception attached. An attached exception would render+the caught error's value — network errors embed the raw, possibly+credentialed URL — into every sink. These tests pin the intended final+record shape: static message, ``record["exception"] is None``, and no+stray ``extra`` fields (the pre-PR ``exc_info=True`` kwarg form stored+``exc_info: True`` in ``extra`` while pretending to attach a traceback).+"""++from __future__ import annotations++import asyncio+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest+from loguru import logger++from local_deep_research.research_library.downloaders.playwright_html import (+ PlaywrightHTMLDownloader,+)+from local_deep_research.security import ssrf_validator++_SECRET = "credential-do-not-log"+_EXCEPTION_TEXT = "network-error-do-not-log"+_URL = (+ f"https://alice:{_SECRET}@origin.example:8443/private/%2Fencoded"+ f"?token={_SECRET}&next=%2Felsewhere#fragment"+)+++def record_sink():+ records = []+ logger.enable("local_deep_research")+ sink_id = logger.add(+ lambda message: records.append(message.record),+ level="DEBUG",+ diagnose=False,+ )+ try:+ yield records+ finally:+ logger.remove(sink_id)+ logger.disable("local_deep_research")+++def _event_record(records, event):+ matched = [r for r in records if event in r["message"]]+ assert len(matched) == 1, (+ f"expected exactly one {event!r} record, got {len(matched)}"+ )+ return matched[0]+++def _assert_static_no_attachment(records, event):+ record = _event_record(records, event)+ assert record["exception"] is None, (+ f"{event!r} must not attach an exception: {record['exception']!r}"+ )+ assert record["extra"] == {}, (+ f"{event!r} must not carry extra fields: {record['extra']!r}"+ )+ for marker in (_EXCEPTION_TEXT, _SECRET, "Traceback"):+ assert marker not in record["message"]+++def _guard_error():+ return RuntimeError(f"{_EXCEPTION_TEXT}: {_URL}")+++def _redirect_response():+ return SimpleNamespace(+ status=302,+ headers={"location": "https://origin.example:8443/next"},+ )+++class _SyncRoute:+ """Fake Playwright route for the sync (plain-Playwright) guard."""++ def __init__(self, *, fetch_result=None, fetch_error=None, request=None):+ self.request = request if request is not None else MagicMock()+ self.request.url = _URL+ self.request.method = "GET"+ self._fetch_result = fetch_result+ self._fetch_error = fetch_error+ self.aborts = []++ def fetch(self, **_kwargs):+ if self._fetch_error is not None:+ raise self._fetch_error+ return self._fetch_result++ def abort(self, reason):+ self.aborts.append(reason)++ def fulfill(self, **_kwargs):+ raise AssertionError("terminal hop must not be reached here")+++class _AsyncRoute:+ """Fake Playwright route for the async (Crawl4AI) guard."""++ def __init__(self, *, fetch_result=None, fetch_error=None):+ self.request = MagicMock()+ self.request.url = _URL+ self.request.method = "GET"+ self._fetch_result = fetch_result+ self._fetch_error = fetch_error+ self.aborts = []++ async def fetch(self, **_kwargs):+ if self._fetch_error is not None:+ raise self._fetch_error+ return self._fetch_result++ async def abort(self, reason):+ self.aborts.append(reason)++ async def fulfill(self, **_kwargs):+ raise AssertionError("terminal hop must not be reached here")+++def _hop_request():+ """A request whose ``headers`` blow up once a cookie override exists.++ Iteration 1 of the guard never reads ``request.headers`` (the cookie+ override is still ``None``); on the redirect hop the override becomes+ non-``None`` and ``_apply_hop_cookie_header`` iterates+ ``request.headers.items()`` — which raises, pinning the guarded+ hop-headers failure branch.+ """+ request = MagicMock()+ request.url = _URL+ request.method = "GET"+ request.headers.items.side_effect = _guard_error()+ return request+++def _run_guard(downloader, route):+ with patch.object(ssrf_validator, "validate_url", return_value=True):+ downloader._playwright_route_guard(route)+++def _run_async_guard(downloader, route):+ with patch.object(ssrf_validator, "validate_url", return_value=True):+ asyncio.run(downloader._crawl4ai_route_guard(route))+++def test_sync_guard_fetch_failure_logs_static_debug(record_sink):+ route = _SyncRoute(fetch_error=_guard_error())+ _run_guard(PlaywrightHTMLDownloader(), route)++ assert route.aborts == ["failed"]+ _assert_static_no_attachment(+ record_sink, "Playwright: guarded fetch failed"+ )+++def test_sync_guard_hop_and_cookie_failures_log_static_debug(record_sink):+ # The redirect hop makes the cookie re-derivation read the context jar+ # (which raises), then the next hop's header rebuild read fail too.+ route = _SyncRoute(+ fetch_result=_redirect_response(), request=_hop_request()+ )+ route.request.frame.page.context.cookies.side_effect = _guard_error()+ _run_guard(PlaywrightHTMLDownloader(), route)++ assert route.aborts == ["failed"]+ _assert_static_no_attachment(+ record_sink, "Playwright: failed to re-apply redirect-hop cookies"+ )+ _assert_static_no_attachment(+ record_sink, "Playwright: failed to build guarded hop headers"+ )+++def test_crawl4ai_guard_fetch_failure_logs_static_debug(record_sink):+ route = _AsyncRoute(fetch_error=_guard_error())+ _run_async_guard(PlaywrightHTMLDownloader(), route)++ assert route.aborts == ["failed"]+ _assert_static_no_attachment(record_sink, "Crawl4AI: guarded fetch failed")+++def test_crawl4ai_guard_hop_and_cookie_failures_log_static_debug(record_sink):+ route = _AsyncRoute(fetch_result=_redirect_response())+ route.request.headers.items.side_effect = _guard_error()+ route.request.frame.page.context.cookies.side_effect = _guard_error()+ _run_async_guard(PlaywrightHTMLDownloader(), route)++ assert route.aborts == ["failed"]+ _assert_static_no_attachment(+ record_sink, "Crawl4AI: failed to re-apply redirect-hop cookies"+ )+ _assert_static_no_attachment(+ record_sink, "Crawl4AI: failed to build guarded hop headers"+ )+++def test_set_cookie_parse_failure_logs_static_debug(record_sink):+ # A non-str Set-Cookie value makes the parser raise; the guard must log+ # a static debug event and skip the cookie, not attach the exception.+ response = SimpleNamespace(+ headers_array=[{"name": "set-cookie", "value": 123}]+ )++ cookies = PlaywrightHTMLDownloader._cookies_from_response(response, _URL)++ assert cookies == []+ _assert_static_no_attachment(+ record_sink, "Browser guard: failed to parse a Set-Cookie header"+ )+++def test_robots_check_failure_fails_open_with_static_debug(record_sink):+ downloader = PlaywrightHTMLDownloader()+ downloader.session = MagicMock()+ downloader.session.get.side_effect = _guard_error()++ assert downloader._robots_allows(_URL) is True++ _assert_static_no_attachment(+ record_sink, "Guarded robots.txt check failed open"+ )diff --git a/tests/research_library/downloaders/test_semantic_scholar_logging_sinks.py b/tests/research_library/downloaders/test_semantic_scholar_logging_sinks.pynew file mode 100644index 0000000000..8ed8a4594e--- /dev/null+++ b/tests/research_library/downloaders/test_semantic_scholar_logging_sinks.py@@ -0,0 +1,111 @@+from io import StringIO+from unittest.mock import Mock, patch++import pytest+import requests+from loguru import logger++from local_deep_research.research_library.downloaders.base import BaseDownloader+from local_deep_research.research_library.downloaders.semantic_scholar import (+ SemanticScholarDownloader,+)++_SECRET = "credential-do-not-log"+_PDF_URL = f"https://user:{_SECRET}@origin.example/private?token={_SECRET}"+_ORIGIN = "https://origin.example"+_PAPER_ID = "a" * 40+++def rendered_log():+ output = StringIO()+ logger.enable("local_deep_research")+ sink_id = logger.add(output, level="DEBUG", format="{message}\n{exception}")+ try:+ yield output+ finally:+ logger.remove(sink_id)+ logger.disable("local_deep_research")+++def _assert_redacted(output: StringIO) -> None:+ rendered = output.getvalue()+ assert _ORIGIN in rendered+ assert _SECRET not in rendered+ assert "user:" not in rendered+ assert "token=" not in rendered+++def test_api_pdf_discovery_logs_only_origin(rendered_log):+ response = Mock(status_code=200)+ response.json.return_value = {"openAccessPdf": {"url": _PDF_URL}}+ downloader = SemanticScholarDownloader()+ downloader.session.get = Mock(return_value=response)++ assert downloader._get_pdf_url(_PAPER_ID) == _PDF_URL+ _assert_redacted(rendered_log)+++def test_pdf_download_start_logs_only_origin(rendered_log):+ downloader = SemanticScholarDownloader()+ downloader._get_pdf_url = Mock(return_value=_PDF_URL)+ paper_url = f"https://www.semanticscholar.org/paper/{_PAPER_ID}"++ with patch.object(BaseDownloader, "_download_pdf", return_value=b"%PDF"):+ result = downloader.download_with_result(paper_url)++ assert result.is_success+ _assert_redacted(rendered_log)+++def _assert_no_exception_leak(+ output: StringIO, records: list, surviving_prefix: str+) -> None:+ rendered = output.getvalue()+ assert _PAPER_ID in rendered+ assert _SECRET not in rendered+ assert "user:" not in rendered+ assert "token=" not in rendered+ assert all(record["exception"] is None for record in records)+ # The scrubbed message survives -- an event that says only that+ # *something* failed is not a usable diagnostic -- but it reaches the+ # sinks through ``scrub_error``: userinfo and query string are rewritten+ # even when the caught error embeds a fully credentialed URL, and no+ # traceback (which would render this frame's API key) is attached.+ assert surviving_prefix in rendered+ assert "https://[REDACTED]:[REDACTED]@origin.example" in rendered+ assert "?<redacted>" in rendered+++def test_api_request_failure_does_not_attach_exception(rendered_log):+ records = []+ record_sink_id = logger.add(+ lambda message: records.append(message.record), level="DEBUG"+ )+ try:+ downloader = SemanticScholarDownloader()+ downloader.session.get = Mock(+ side_effect=requests.RequestException(f"failed: {_PDF_URL}")+ )+ assert downloader._get_pdf_url(_PAPER_ID) is None+ finally:+ logger.remove(record_sink_id)++ _assert_no_exception_leak(rendered_log, records, "failed: ")+++def test_api_parse_failure_does_not_attach_exception(rendered_log):+ records = []+ record_sink_id = logger.add(+ lambda message: records.append(message.record), level="DEBUG"+ )+ try:+ response = Mock(status_code=200)+ response.json.side_effect = ValueError(f"bad json: {_PDF_URL}")+ downloader = SemanticScholarDownloader()+ downloader.session.get = Mock(return_value=response)+ assert downloader._get_pdf_url(_PAPER_ID) is None+ finally:+ logger.remove(record_sink_id)++ _assert_no_exception_leak(rendered_log, records, "bad json: ")diff --git a/tests/research_library/test_download_service_contracts.py b/tests/research_library/test_download_service_contracts.pyindex 84baa3da2a..7b2de80594 100644--- a/tests/research_library/test_download_service_contracts.py+++ b/tests/research_library/test_download_service_contracts.py@@ -1215,9 +1215,10 @@ def test_error_returned_to_the_client_is_credential_scrubbed(db, store, seeded):@pytest.mark.xfail(strict=True,reason=(- "DEFECT: _download_pdf logs the raw resource URL at INFO "- '("Using {downloader} for {url}"), as do the downloaders '- '("Downloading PDF from {url}"). The global loguru patcher only '+ "DEFECT: _download_pdf logs the raw resource URL at INFO, both "+ 'when selecting a downloader ("Using {downloader} for {url}") and '+ 'on its own success path ("Successfully stored PDF in database: '+ '{resource.url}"). The global loguru patcher only '"strips control characters, so URL userinfo credentials and ""query-string API keys are written verbatim to the console sink, ""the log database and the Socket.IO frontend sink. "diff --git a/tests/security/test_safe_requests_logging_sinks.py b/tests/security/test_safe_requests_logging_sinks.pynew file mode 100644index 0000000000..5d178e4ac9--- /dev/null+++ b/tests/security/test_safe_requests_logging_sinks.py@@ -0,0 +1,41 @@+from io import StringIO++import pytest+import requests+from loguru import logger++from local_deep_research.security.safe_requests import SafeSession++_SECRET = "credential-do-not-log"+_DESTINATION = f"http://user:{_SECRET}@127.0.0.1/private?token={_SECRET}"+_ORIGIN = "http://127.0.0.1"+++def test_blocked_redirect_logs_only_destination_origin():+ session = SafeSession()+ original = requests.Request("GET", "https://origin.example/start").prepare()+ redirect = requests.Response()+ redirect.status_code = 302+ redirect.headers["Location"] = _DESTINATION+ redirect.request = original+ destination = next(+ session.resolve_redirects(redirect, original, yield_requests=True)+ )+ output = StringIO()+ logger.enable("local_deep_research")+ sink_id = logger.add(output, level="DEBUG", format="{message}\n{exception}")++ try:+ with pytest.raises(ValueError) as raised:+ session.send(destination)+ finally:+ logger.remove(sink_id)+ logger.disable("local_deep_research")+ session.close()++ rendered = output.getvalue()+ assert _ORIGIN in rendered+ assert _SECRET not in rendered+ assert "user:" not in rendered+ assert "token=" not in rendered+ assert _SECRET not in str(raised.value)