~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(security): redact URLs in failure-path downloader logging (#6541)
LearningCircuit347531422162
diff --git a/changelog.d/6541.security.md b/changelog.d/6541.security.mdnew file mode 100644index 0000000000..9a2fe535bd--- /dev/null+++ b/changelog.d/6541.security.md@@ -0,0 +1 @@+Download URLs are now logged in redacted form (scheme://host:port only) across the downloader stack, the download service and `safe_get`/`safe_post`/`SafeSession`, and in the library router's queue-all and download routes and the link-analytics metrics: these web-sourced URLs can carry credentials in their userinfo or presigned tokens in query strings, which previously landed in server logs. This covers fetch failure and refusal logs as well as the attempt and progress lines written before every fetch, at every log level. Fetch failure handlers for web-sourced URLs no longer attach tracebacks or exception messages (request errors embed the full URL even with `diagnose=False`) and log only the exception type; the OpenAlex and Semantic Scholar API-lookup handlers, whose requests go to app-built API URLs, still log the exception text after credential scrubbing (database persistence errors, whose SQLAlchemy text can echo the stored URL, are tracked separately in #6829). Download failure reasons that the library routes and the retry classifier log are withheld when they contain any URL-part delimiter (`/ \ ? # @ ;`), including fixed reasons that happen to contain one, and a rate-limit failure's domain no longer includes userinfo, nor do the domains the domain classifier and the link-analytics metrics derive from stored resource URLs (which it logged and persisted as the classification key, and whose failure handlers now log only the exception type), nor do the domains the library page's domain filter, its research PDF previews and the collection search results show (the domain filter still finds a credentialed URL by its host). All of these domains and keys come from one helper that returns an empty domain for a missing (`NULL`) URL instead of raising. When a password or username holds an unencoded `/`, `?` or `#`, the parser ends the host inside the userinfo; the redacted log form, these domains and keys, the downloaders' rate-limit keys and the SSRF validator's resolution-failure and resolves-to-private log lines (which no longer print the parsed host) then show a placeholder or an empty domain instead of that userinfo fragment whenever an `@` follows the parsed host in the URL as written (a dot segment such as `/../`, which the parser removes from the path, does not hide it: `https://tok/en@host/../a` is redacted) and either the parsed authority itself still holds a userinfo (a password holding an unencoded `@` before the delimiter, as in `https://admin:[email protected]#1@host/`, whose parsed host `ss.example` is the password's tail; this applies to `localhost` and IP literals too), or the parsed host is a single label or carries a port (`localhost` and IP literals excepted). The remaining ambiguous shapes are a userinfo with no `@` before its first `/`, `?` or `#` that is either a dotted name with no digits-only port (`https://john.doe/x@host/`, `https://john.doe:#pw@host/`) or `localhost` / an IP literal (`https://127.0.0.1:80/x@host/`): these cannot be told apart from a real host with an `@` in its path (`https://medium.com/@user`) and are shown as parsed, which can surface the username and, in the IP/`localhost` case, a digits-only password prefix. A real host with an explicit port and an `@` later in the URL (`https://git.example:8443/@user`), and any URL with userinfo and an `@` later in it (`https://user:[email protected]/@group`), are now logged as `https://<redacted>`, get an empty domain and share the `invalid_authority` rate-limit key; uncredentialed URLs with an `@` in the path or query on a dotted host (`https://medium.com/@user`, `https://a.example/[email protected]`) are unaffected. Domain classifications persisted before this change under a key that includes userinfo are not migrated: those rows keep their credentialed key, and the next classification run classifies the domain again under its clean key. The LLM rate-limit key drops userinfo too, and the LLM wrapper's local-endpoint debug line logs the redacted base URL; this is preventive, as LLM rate limiting is currently disabled and the key is not used. The download service's own log lines for a PDF download's skip or failure reason go through the same withholding as the library routes'. The bulk download route's exception handler logs only the exception type, not its message, which can echo the resource URL. The exception messages raised by `safe_get`/`safe_post`/`SafeSession` (SSRF refusals, redirect refusals, too-many-redirects, and `require_https` scheme and downgrade refusals) are redacted at source. The retry-refusal log lines (queue-all's skip line and the download service's text-extraction skips) withhold their reason the same way, because a resource permanently failed before this change keeps its stored failure message, which can hold the rate-limited URL's userinfo; the reason returned to the requesting user is unchanged. The failed-text-extraction record's log lines and the document scheduler's text-extraction log lines withhold the failure reason too, and the document scheduler logs only the exception type for an error while processing a resource. The extraction pipeline also withholds skip reasons in its fallback and terminal-failure logs, including the batch path.diff --git a/src/local_deep_research/domain_classifier/classifier.py b/src/local_deep_research/domain_classifier/classifier.pyindex edf9b227c7..5528c4516d 100644--- a/src/local_deep_research/domain_classifier/classifier.py+++ b/src/local_deep_research/domain_classifier/classifier.py@@ -9,6 +9,7 @@ from sqlalchemy.orm import Sessionfrom ..config.llm_config import get_llmfrom ..database.models import ResearchResourcefrom ..database.session_context import get_user_db_session+from ..security import url_authority_without_userinfofrom ..utilities.sql_utils import escape_like as _escape_likefrom ..utilities.json_utils import extract_json, get_llm_response_textfrom .models import DomainClassification@@ -274,8 +275,12 @@ JSON Response:""")return classification- except Exception:- logger.exception(f"Error classifying domain {domain}")+ except Exception as e:+ # Type name only: this frame holds the sample resource URLs,+ # which a traceback's locals or the exception text can echo.+ logger.warning(+ f"Error classifying domain {domain} ({type(e).__name__})"+ )return Nonedef classify_all_domains(@@ -301,16 +306,18 @@ JSON Response:"""try:with get_user_db_session(self.username) as session:# Get all unique domains- from urllib.parse import urlparse-resources = session.query(ResearchResource.url).distinct().all()domains = set()for (url,) in resources:if url:try:- parsed = urlparse(url)- domain = parsed.netloc.lower()+ # Authority minus userinfo (empty when that+ # is ambiguous): a stored URL's user:pass@+ # would otherwise land in the logs, the+ # progress payload and the persisted+ # DomainClassification key.+ domain = url_authority_without_userinfo(url).lower()if domain.startswith("www."):domain = domain[4:]if domain:@@ -391,8 +398,13 @@ JSON Response:"""f"Failed to classify domain {domain}")- except Exception:- logger.exception(f"Error classifying domain {domain}")+ except Exception as e:+ # Type name only: this frame holds the raw+ # resource URLs, which a traceback can echo.+ logger.warning(+ f"Error classifying domain {domain} "+ f"({type(e).__name__})"+ )results["failed"] += 1results["domains"].append({@@ -407,8 +419,11 @@ JSON Response:""")return results- except Exception:- logger.exception("Error in classify_all_domains")+ except Exception as e:+ # Type name only: this frame holds the raw resource URLs.+ logger.warning(+ f"Error in classify_all_domains ({type(e).__name__})"+ )results["error"] = "Classification failed"return resultsdiff --git a/src/local_deep_research/library/download_management/failure_classifier.py b/src/local_deep_research/library/download_management/failure_classifier.pyindex 890ec57d9b..ca798407b6 100644--- a/src/local_deep_research/library/download_management/failure_classifier.py+++ b/src/local_deep_research/library/download_management/failure_classifier.py@@ -8,10 +8,14 @@ Uses inheritance to organize different failure categories and their retry behavifrom abc import ABCfrom datetime import datetime, timedelta, UTCfrom typing import Optional-from urllib.parse import urlparsefrom loguru import logger+from ...security import (+ failure_reason_for_log,+ url_authority_without_userinfo,+)+class BaseFailure(ABC):"""Base class for all failure types with common functionality"""@@ -192,7 +196,11 @@ class FailureClassifier:"gone", "Resource permanently removed (410)")if status_code == 429:- domain = urlparse(url).netloc if url else "unknown"+ # netloc minus userinfo: the domain lands in the failure+ # message, which is logged and persisted.+ domain = (+ url_authority_without_userinfo(url) if url else "unknown"+ )return RateLimitFailure(domain, details)if status_code == 503:return TemporaryFailure(@@ -357,7 +365,8 @@ class FailureClassifier:# Default to temporary failure with 1-hour cooldownlogger.warning(- f"[FAILURE_CLASSIFIER] Unclassified error: {error_type} - {details}"+ f"[FAILURE_CLASSIFIER] Unclassified error: {error_type} - "+ f"{failure_reason_for_log(details)}")return TemporaryFailure("unknown_error", f"Unknown error: {error_type}", timedelta(hours=1)diff --git a/src/local_deep_research/research_library/downloaders/arxiv.py b/src/local_deep_research/research_library/downloaders/arxiv.pyindex d985a12b23..6296881923 100644--- a/src/local_deep_research/research_library/downloaders/arxiv.py+++ b/src/local_deep_research/research_library/downloaders/arxiv.py@@ -11,6 +11,8 @@ from urllib.parse import urlparsefrom bs4 import BeautifulSoup, NavigableString, PageElement, Tagfrom loguru import logger+from ...security import redact_url_for_log+from ...constants import USER_AGENTfrom ...utilities.arxiv import extract_arxiv_id, is_arxiv_paper_urlfrom ...utilities.arxiv_api import arxiv_api_request_gate@@ -249,7 +251,9 @@ class ArxivDownloader(HTMLDownloader):# Extract arXiv IDarxiv_id = self._extract_arxiv_id(url)if not arxiv_id:- logger.error(f"Could not extract arXiv ID from {url}")+ logger.error(+ f"Could not extract arXiv ID from {redact_url_for_log(url)}"+ )return None# Construct PDF URL@@ -479,7 +483,7 @@ class ArxivDownloader(HTMLDownloader):logger.info("arXiv HTML request for {} redirected to {}; not a rendition",arxiv_id,- final_url,+ redact_url_for_log(final_url),)return None@@ -907,7 +911,7 @@ class ArxivDownloader(HTMLDownloader):error_type = "UnusableFeed"except Exception as e:- logger.debug(f"Failed to fetch from arXiv API: {e}")+ logger.debug(f"Failed to fetch from arXiv API ({type(e).__name__})")error_type = type(e).__name__if api_text is not None:diff --git a/src/local_deep_research/research_library/downloaders/base.py b/src/local_deep_research/research_library/downloaders/base.pyindex f55aebdaaf..c1ed1e8916 100644--- a/src/local_deep_research/research_library/downloaders/base.py+++ b/src/local_deep_research/research_library/downloaders/base.py@@ -22,7 +22,10 @@ from ...utilities.pdf_extraction_limits import ()from ...utilities.pdf_stream_release import PypdfWalkReleaserfrom ...security.log_sanitizer import scrub_error-from ...security.ssrf_validator import redact_url_for_log+from ...security.ssrf_validator import (+ authority_may_be_userinfo,+ redact_url_for_log,+)from ...utilities.resource_utils import safe_close# Import centralized User-Agent from constants@@ -56,13 +59,29 @@ def rate_limit_authority(url: str) -> str:``"https://exa mple.com/p"`` as ``https://exa%20mple.com/p`` -- so itbuckets as ``"invalid_authority"`` rather than being echoed into a logline.++ An authority that may really be a userinfo prefix+ (``https://tok/en@host/`` parses to the host ``tok``,+ ``https://admin:[email protected]#1@host/`` to ``ss.example``; see+ ``authority_may_be_userinfo``) also yields ``"invalid_authority"``, so+ the tracker never logs a fragment of a credential as a key."""try:parsed = urlparse(url)hostname = parsed.hostname or ""- authority = f"[{hostname}]" if ":" in hostname else hostname+ host = f"[{hostname}]" if ":" in hostname else hostname+ authority = hostif parsed.port is not None:authority = f"{authority}:{parsed.port}"+ # ``authority``, not ``host``: ``https://u:@:1#x@host/`` parses to+ # an empty host and the port ``1``, a fragment of the password.+ if authority and authority_may_be_userinfo(+ host,+ parsed.port is not None,+ url,+ has_userinfo="@" in parsed.netloc,+ ):+ return "invalid_authority"except ValueError:return "invalid_authority"if any(ch.isspace() or not ch.isprintable() for ch in authority):@@ -548,7 +567,8 @@ class BaseDownloader(ABC):continue # Retry with adaptive waitexcept requests.exceptions.RequestException as e:request_error = (- f"Request error downloading from {redact_url_for_log(url)}"+ f"Request error downloading from {redact_url_for_log(url)} "+ f"({type(e).__name__})")if on_transport_failure is not None:logger.warning(request_error)@@ -585,14 +605,17 @@ class BaseDownloader(ABC):if on_transport_failure is not None:on_transport_failure()return None- except Exception:+ except Exception as e:# Includes the ValueError SafeSession raises when the URL# fails validation, which is also how a failed DNS lookup# surfaces, so an offline machine lands here. A caller that# passed on_transport_failure handles it (see the docstring),# so it is not an error here; ERROR records reach the# user's browser via frontend_progress_sink.- unexpected_error = f"Unexpected error downloading from {redact_url_for_log(url)}"+ unexpected_error = (+ f"Unexpected error downloading from {redact_url_for_log(url)} "+ f"({type(e).__name__})"+ )if on_transport_failure is not None:logger.warning(unexpected_error)else:diff --git a/src/local_deep_research/research_library/downloaders/biorxiv.py b/src/local_deep_research/research_library/downloaders/biorxiv.pyindex d5004acbf2..0896b2a383 100644--- a/src/local_deep_research/research_library/downloaders/biorxiv.py+++ b/src/local_deep_research/research_library/downloaders/biorxiv.py@@ -201,10 +201,11 @@ class BioRxivDownloader(BaseDownloader):)return "\n".join(text_parts)- except Exception:+ except Exception as e:logger.opt(exception=False).debug(- "Failed to fetch abstract from bioRxiv/medRxiv: {}",+ "Failed to fetch abstract from bioRxiv/medRxiv: {} ({})",redact_url_for_log(url),+ type(e).__name__,)return Nonediff --git a/src/local_deep_research/research_library/downloaders/extraction/pipeline.py b/src/local_deep_research/research_library/downloaders/extraction/pipeline.pyindex fc133ddcfd..d9069aae69 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.log_sanitizer import failure_reason_for_logfrom ....security.ssrf_validator import redact_url_for_logfrom ....utilities.lxml_thread_safety import install_per_thread_html_parsers@@ -526,11 +527,11 @@ def _try_specialized_downloader(result.skip_reasonor "Specialized downloader returned no usable content")- except Exception:+ except Exception as e:skip_reason = "Specialized downloader failed"logger.opt(exception=False).debug(f"Pipeline: specialized downloader failed for "- f"{redact_url_for_log(url)}"+ f"{redact_url_for_log(url)} ({type(e).__name__})")finally:try:@@ -543,7 +544,7 @@ def _try_specialized_downloader(logger.debug(f"Pipeline: specialized downloader ({url_type.value}) returned "f"no content for {redact_url_for_log(url)} "- f"({failure.skip_reason}), falling back to HTML pipeline"+ f"({failure_reason_for_log(failure.skip_reason)}), falling back to HTML pipeline")return failure@@ -594,10 +595,10 @@ def fetch_and_extract(# Try specialized downloader first (arXiv, PubMed, etc.)try:specialized = _try_specialized_downloader(url, timeout=timeout)- except Exception:+ except Exception as e:logger.opt(exception=False).debug(f"Pipeline: specialized downloader error for "- f"{redact_url_for_log(url)}"+ f"{redact_url_for_log(url)} ({type(e).__name__})")specialized = _SpecializedResult(fallback_allowed=not is_arxiv_paper_url(url)@@ -608,7 +609,9 @@ def fetch_and_extract(logger.warning("Pipeline: terminal specialized download failed for {}: {}",redact_url_for_log(url),- specialized.skip_reason or "reason unavailable",+ failure_reason_for_log(+ specialized.skip_reason or "reason unavailable"+ ),)return None@@ -630,9 +633,12 @@ def fetch_and_extract(if result:return result.decode("utf-8", errors="replace")return None- except Exception:+ except Exception as e:+ # Type name only -- exception texts embed the raw URL and loguru+ # renders them with any traceback even when diagnose=False.logger.opt(exception=False).error(- f"fetch_and_extract failed for {redact_url_for_log(url)}"+ f"fetch_and_extract failed for {redact_url_for_log(url)} "+ f"({type(e).__name__})")return Nonefinally:@@ -702,14 +708,16 @@ def batch_fetch_and_extract(logger.warning("Pipeline: terminal specialized download failed for {}: {}",redact_url_for_log(url),- specialized.skip_reason or "reason unavailable",+ failure_reason_for_log(+ specialized.skip_reason or "reason unavailable"+ ),)results[url] = Nonecontinue- except Exception:+ except Exception as e:logger.opt(exception=False).debug(f"Pipeline: specialized downloader error for "- f"{redact_url_for_log(url)}"+ f"{redact_url_for_log(url)} ({type(e).__name__})")if is_arxiv_paper_url(url):results[url] = None@@ -733,10 +741,10 @@ def batch_fetch_and_extract(results[url] = data.decode("utf-8", errors="replace")else:results[url] = None- except Exception:+ except Exception as e:logger.opt(exception=False).error(f"batch_fetch_and_extract failed for "- f"{redact_url_for_log(url)}"+ f"{redact_url_for_log(url)} ({type(e).__name__})")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 3dd5c2ab55..7c6dd31386 100644--- a/src/local_deep_research/research_library/downloaders/generic.py+++ b/src/local_deep_research/research_library/downloaders/generic.py@@ -193,9 +193,11 @@ class GenericDownloader(BaseDownloader):return DownloadResult(skip_reason="Could not connect to server - website may be down")- except requests.RequestException:+ except requests.RequestException as e:logger.opt(exception=False).warning(- "Unexpected error checking URL: {}", redact_url_for_log(url)+ "Unexpected error checking URL: {} ({})",+ redact_url_for_log(url),+ type(e).__name__,)return DownloadResult(skip_reason="Network error - could not reach the website"diff --git a/src/local_deep_research/research_library/downloaders/openalex.py b/src/local_deep_research/research_library/downloaders/openalex.pyindex 190fb3a867..451e6f9e26 100644--- a/src/local_deep_research/research_library/downloaders/openalex.py+++ b/src/local_deep_research/research_library/downloaders/openalex.py@@ -12,6 +12,7 @@ from urllib.parse import urlparseimport requestsfrom loguru import logger+from ...security import redact_url_for_logfrom ...security.log_sanitizer import scrub_errorfrom ...utilities.openalex_enrichment import (normalize_openalex_api_key,@@ -124,7 +125,9 @@ class OpenAlexDownloader(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:@@ -230,7 +233,7 @@ class OpenAlexDownloader(BaseDownloader):pdf_url = best_oa_location.get("pdf_url")if pdf_url:logger.info(- f"Found open access PDF for work {work_id}: {pdf_url}"+ f"Found open access PDF for work {work_id}: {redact_url_for_log(pdf_url)}")return str(pdf_url)@@ -238,7 +241,7 @@ class OpenAlexDownloader(BaseDownloader):landing_url = best_oa_location.get("landing_page_url")if landing_url:logger.info(- f"Found landing page for work {work_id}: {landing_url}"+ f"Found landing page for work {work_id}: {redact_url_for_log(landing_url)}")# Validate that landing page is actually a PDF before returningtry:@@ -259,10 +262,12 @@ class OpenAlexDownloader(BaseDownloader):f"Landing page is not a PDF (Content-Type: {content_type}), skipping")except Exception as exc:- safe_msg = self._scrub(exc)+ # Type only: urllib3 errors embed the scheme-less+ # path and query, which the scrubber misses.logger.warning(- f"Failed to validate landing page URL for "- f"work {work_id}: {safe_msg}"+ f"Failed to validate landing page URL "+ f"({type(exc).__name__}) for work {work_id}: "+ f"{redact_url_for_log(landing_url)}")logger.info(diff --git a/src/local_deep_research/research_library/downloaders/playwright_html.py b/src/local_deep_research/research_library/downloaders/playwright_html.pyindex bd8796a89a..69a7abced0 100644--- a/src/local_deep_research/research_library/downloaders/playwright_html.py+++ b/src/local_deep_research/research_library/downloaders/playwright_html.py@@ -1247,9 +1247,13 @@ class PlaywrightHTMLDownloader(HTMLDownloader):)return Noneexcept Exception as e:+ # Type name only: Playwright error texts embed the navigated+ # URL, and loguru renders ``ExcType: str(e)`` with a traceback+ # even when diagnose=False.logger.opt(exception=False).error(- "playwright.fetch_error url={url}",+ "playwright.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,diff --git a/src/local_deep_research/research_library/downloaders/pubmed.py b/src/local_deep_research/research_library/downloaders/pubmed.pyindex 55fa37730f..ea7aae7bc8 100644--- a/src/local_deep_research/research_library/downloaders/pubmed.py+++ b/src/local_deep_research/research_library/downloaders/pubmed.py@@ -8,6 +8,7 @@ from typing import Optionalfrom urllib.parse import urlparsefrom loguru import logger+from ...security import redact_url_for_logfrom .base import BaseDownloader, ContentType, DownloadResult@@ -187,7 +188,9 @@ class PubMedDownloader(BaseDownloader):skip_reason=f"Article PMID:{pmid} not found in Europe PMC database")except Exception as e:- logger.debug(f"Error checking article status: {e}")+ logger.debug(+ f"Error checking article status ({type(e).__name__})"+ )# Try to find PMC ID via NCBIpmc_id = self._get_pmc_id_from_pmid(pmid)@@ -309,7 +312,9 @@ class PubMedDownloader(BaseDownloader):return textexcept Exception as e:- logger.debug(f"Failed to fetch text from Europe PMC: {e}")+ logger.debug(+ f"Failed to fetch text from Europe PMC ({type(e).__name__})"+ )return None@@ -412,7 +417,7 @@ class PubMedDownloader(BaseDownloader):return self._download_via_europe_pmc(pmcid)except Exception as e:- logger.debug(f"Europe PMC API query failed: {e}")+ logger.debug(f"Europe PMC API query failed ({type(e).__name__})")return None@@ -445,7 +450,7 @@ class PubMedDownloader(BaseDownloader):return f"PMC{pmc_id_num}"except Exception as e:- logger.debug(f"NCBI E-utilities lookup failed: {e}")+ logger.debug(f"NCBI E-utilities lookup failed ({type(e).__name__})")# Fallback: Try scraping the PubMed pagetry:@@ -459,7 +464,7 @@ class PubMedDownloader(BaseDownloader):return pmc_match.group(0)except Exception as e:- logger.debug(f"PubMed page scraping failed: {e}")+ logger.debug(f"PubMed page scraping failed ({type(e).__name__})")return None@@ -468,7 +473,7 @@ class PubMedDownloader(BaseDownloader):# Europe PMC PDF URLpdf_url = f"https://europepmc.org/backend/ptpmcrender.fcgi?accid={pmc_id}&blobtype=pdf"- logger.debug(f"Trying Europe PMC: {pdf_url}")+ logger.debug(f"Trying Europe PMC: {redact_url_for_log(pdf_url)}")pdf_content = self._download_pdf(pdf_url)if pdf_content:@@ -485,7 +490,7 @@ class PubMedDownloader(BaseDownloader):]for pdf_url in url_patterns:- logger.debug(f"Trying NCBI PMC: {pdf_url}")+ logger.debug(f"Trying NCBI PMC: {redact_url_for_log(pdf_url)}")# Add referer header for NCBIheaders = {diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex f3e63e9e76..4294841d18 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -21,6 +21,7 @@ from urllib.parse import urlparseimport requestsfrom loguru import logger+from ...security import redact_url_for_logfrom sqlalchemy.orm import Sessionimport pdfplumberfrom pypdf import PdfReader@@ -41,7 +42,11 @@ from ...database.models.download_tracker import (# — do not add a raw requests.get()/post() here. GHSA-9c54 was exactly# that bypass, and `is_downloadable_domain` upstream is a relevance# filter, not a security control.-from ...security import safe_get, sanitize_error_for_client+from ...security import (+ failure_reason_for_log,+ safe_get,+ sanitize_error_for_client,+)from ...security.client_safe_errors import (CLIENT_SAFE_DOWNLOAD_MESSAGES,client_safe_download_message,@@ -535,7 +540,7 @@ class DownloadService:allowed, reason = self._check_url_against_policy(url)if not allowed:logger.warning(- f"Skipping text extraction for {url}: refused by "+ f"Skipping text extraction for {redact_url_for_log(url)}: refused by "f"egress policy ({reason})")return None@@ -544,7 +549,7 @@ class DownloadService:for downloader in self.downloaders:if downloader.can_handle(url):logger.info(- f"Using {downloader.__class__.__name__} for text extraction from {url}"+ f"Using {downloader.__class__.__name__} for text extraction from {redact_url_for_log(url)}")try:# Try to get text content@@ -554,11 +559,18 @@ class DownloadService:f"Successfully extracted text for: {resource.title[:50]}")return text- except Exception:- logger.exception("Failed to extract text")+ except Exception as e:+ # Type name only: downloader exception texts can+ # embed the raw resource URL.+ logger.warning(+ f"Failed to extract text ({type(e).__name__}) "+ f"for {redact_url_for_log(url)}"+ )break- logger.warning(f"Could not extract text for {url}")+ logger.warning(+ f"Could not extract text for {redact_url_for_log(url)}"+ )return Nonedef queue_research_downloads(@@ -612,7 +624,7 @@ class DownloadService:)if not allowed:logger.warning(- f"Skipping queue for {resource.url}: refused by "+ f"Skipping queue for {redact_url_for_log(resource.url)}: refused by "f"egress policy ({reason})")continue@@ -939,7 +951,7 @@ class DownloadService:allowed, reason = self._check_url_against_policy(url)if not allowed:logger.warning(- f"Skipping PDF download for {url}: refused by egress "+ f"Skipping PDF download for {redact_url_for_log(url)}: refused by egress "f"policy ({reason})")return False, f"egress_policy_denied:{reason}", None@@ -956,7 +968,7 @@ class DownloadService:for downloader in self.downloaders:if downloader.can_handle(url):logger.info(- f"Using {downloader.__class__.__name__} for {url}"+ f"Using {downloader.__class__.__name__} for {redact_url_for_log(url)}")result = downloader.download_with_result(url, ContentType.PDF@@ -970,14 +982,18 @@ class DownloadService:if result.skip_reason:skip_reason = result.skip_reasonstatus_code = result.status_code- logger.info(f"Download skipped: {skip_reason}")+ logger.info(+ f"Download skipped: {failure_reason_for_log(skip_reason)}"+ )if isinstance(downloader, (ArxivDownloader, GenericDownloader)):breakif selected_downloader is None:- logger.error(f"No downloader found for {url}")+ logger.error(+ f"No downloader found for {redact_url_for_log(url)}"+ )skip_reason = "No compatible downloader available"# Produce the canonical text BEFORE the persistence block.@@ -1023,10 +1039,10 @@ class DownloadService:logger.warning(f"Text production returned empty text for: {resource_title[:50]}")- except Exception:- logger.exception(- "Failed to produce text after PDF download, "- "but PDF download succeeded"+ except Exception as e:+ logger.warning(+ "Failed to produce text after PDF download "+ f"({type(e).__name__}), but PDF download succeeded")text_details = None@@ -1092,7 +1108,9 @@ class DownloadService:# survives whatever the caller does with the session# after this early return.sess.commit()- logger.info(f"Download failed with reason: {error_msg}")+ logger.info(+ f"Download failed with reason: {failure_reason_for_log(error_msg)}"+ )return False, error_msg, status_code# Get PDF storage mode setting. Resolve through the operator gate@@ -1405,13 +1423,13 @@ class DownloadService:if pdf_storage_mode == "database":logger.info(- f"Successfully stored PDF in database: {resource.url}"+ f"Successfully stored PDF in database: {redact_url_for_log(resource.url)}")elif pdf_storage_mode == "filesystem":logger.info(f"Successfully downloaded: {tracker.file_path}")else:logger.info(- f"Successfully extracted text from: {resource.url}"+ f"Successfully extracted text from: {redact_url_for_log(resource.url)}")# Commit the PDF persistence as its own transaction BEFORE@@ -1465,11 +1483,15 @@ class DownloadService:return True, None, status_codeexcept Exception as e:- logger.exception(f"Download failed for {url}")+ # Transport exceptions can embed credentials or a signed URL.+ logger.warning(+ f"Download failed ({type(e).__name__}) for "+ f"{redact_url_for_log(url)}"+ )# Two distinct outputs:- # * server-side diagnostic (persisted in DownloadAttempt.error_message- # and emitted via logger.exception above) — full str(e), with- # credential scrubbing applied so secrets don't reach the DB.+ # * server-side diagnostic persisted in DownloadAttempt.error_message+ # — full str(e), with credential scrubbing applied. The log+ # above carries only the exception class and redacted URL.# * caller-safe skip_reason (the second tuple element, and what# flows into retry-manager / bulk-stream SSE messages) — must# never carry SQL text, target URLs, or file paths. The Zotero@@ -1761,12 +1783,19 @@ class DownloadService:# Check retry eligibility before network-dependent extractionif self.retry_manager:- decision = self.retry_manager.should_retry_resource(resource_id)- if not decision.can_retry:+ retry_decision = self.retry_manager.should_retry_resource(+ resource_id+ )+ if not retry_decision.can_retry:+ # The reason can embed a stored failure_message; rows+ # written before the domain fix may hold URL userinfo.+ # The caller still gets the reason unchanged (the+ # user's own data).logger.info(- f"Skipping resource {resource_id}: {decision.reason}"+ f"Skipping resource {resource_id}: "+ f"{failure_reason_for_log(retry_decision.reason)}")- return False, decision.reason+ return False, retry_decision.reason# Try source-specific direct text extractionresult = self._try_api_text_extraction(session, resource)@@ -1991,12 +2020,16 @@ class DownloadService:# local-only strategies below still run and download_as_text's own# gate, after them, returns the denial (so the budget still holds).if self.retry_manager:- decision = self.retry_manager.should_retry_resource(resource.id)- if not decision.can_retry:+ retry_decision = self.retry_manager.should_retry_resource(+ resource.id+ )+ if not retry_decision.can_retry:+ # The reason can embed a stored failure_message (see+ # download_as_text).logger.info("Skipping canonical arXiv text for resource {}: {}",resource.id,- decision.reason,+ failure_reason_for_log(retry_decision.reason),)try:cached_outcome = self._text_from_cached_pdf(@@ -2049,7 +2082,9 @@ class DownloadService:)except Exception as exc:safe_rollback(session, "_try_arxiv_text_extraction")- logger.exception("Canonical arXiv text extraction failed")+ logger.warning(+ f"Canonical arXiv text extraction failed ({type(exc).__name__})"+ )# Caller-visible: fixed token only. sanitize_error_for_client()# scrubs credentials but leaves SQL text / URLs / paths intact,# and this string flows into download_as_text's return and the@@ -2227,7 +2262,7 @@ class DownloadService:) -> Optional[Tuple[bool, Optional[str]]]:"""Try source-specific direct text extraction."""logger.info(- f"Attempting direct API text extraction from: {resource.url}"+ f"Attempting direct API text extraction from: {redact_url_for_log(resource.url)}")downloader = self._get_downloader(resource.url)@@ -2240,7 +2275,7 @@ class DownloadService:allowed, reason = self._check_url_against_policy(resource.url)if not allowed:logger.warning(- f"Skipping API text extraction for {resource.url}: refused "+ f"Skipping API text extraction for {redact_url_for_log(resource.url)}: refused "f"by egress policy ({reason})")return False, f"egress_policy_denied:{reason}"@@ -2304,14 +2339,14 @@ class DownloadService:) -> Tuple[bool, Optional[str]]:"""Fallback: Download PDF to memory and extract text."""logger.info(- f"Direct text extraction unavailable; trying in-memory PDF for: {resource.url}"+ f"Direct text extraction unavailable; trying in-memory PDF for: {redact_url_for_log(resource.url)}")downloader = self._get_downloader(resource.url)if not downloader:error_msg = "No compatible downloader found"logger.warning(- f"✗ FAILED: {error_msg} for '{resource.title[:50]}...'"+ f"✗ FAILED: {failure_reason_for_log(error_msg)} for '{resource.title[:50]}...'")self._record_failed_text_extraction(session, resource, error=error_msg@@ -2324,7 +2359,7 @@ class DownloadService:if not allowed:error_msg = f"egress_policy_denied:{reason}"logger.warning(- f"Skipping fallback PDF download for {resource.url}: "+ f"Skipping fallback PDF download for {redact_url_for_log(resource.url)}: "f"refused by egress policy ({reason})")self._record_failed_text_extraction(@@ -2338,7 +2373,7 @@ class DownloadService:if not result.is_success or not result.content:error_msg = result.skip_reason or "Failed to download PDF"logger.warning(- f"✗ FAILED: Could not download PDF for '{resource.title[:50]}...' | Error: {error_msg}"+ f"✗ FAILED: Could not download PDF for '{resource.title[:50]}...' | Error: {failure_reason_for_log(error_msg)}")self._record_failed_text_extraction(session, resource, error=f"PDF download failed: {error_msg}"@@ -2351,7 +2386,7 @@ class DownloadService:if not text:error_msg = "PDF text extraction returned empty text"logger.warning(- f"Failed to extract text from PDF for: {resource.url}"+ f"Failed to extract text from PDF for: {redact_url_for_log(resource.url)}")self._record_failed_text_extraction(session, resource, error=error_msg@@ -2421,8 +2456,13 @@ class DownloadService:return response.content- except Exception:- logger.exception("Generic download failed")+ except Exception as e:+ # raise_for_status()/SafeSession texts embed the raw URL —+ # log the exception type and the redacted URL only.+ logger.warning(+ f"Generic download failed ({type(e).__name__}) for "+ f"{redact_url_for_log(url)}"+ )return Nonedef _download_arxiv(self, url: str) -> Optional[bytes]:@@ -2434,8 +2474,11 @@ class DownloadService:pdf_url += ".pdf"return self._download_generic(pdf_url)- except Exception:- logger.exception("arXiv download failed")+ except Exception as e:+ logger.warning(+ f"arXiv download failed ({type(e).__name__}) for "+ f"{redact_url_for_log(url)}"+ )return Nonedef _try_europe_pmc(self, pmid: str) -> Optional[bytes]:@@ -2485,7 +2528,7 @@ class DownloadService:):return pdf_response.contentexcept Exception as e:- logger.debug(f"Europe PMC download failed: {e}")+ logger.debug(f"Europe PMC download failed ({type(e).__name__})")return None@@ -2535,7 +2578,9 @@ class DownloadService:)return response.contentexcept Exception as e:- logger.debug(f"Direct Europe PMC download failed: {e}")+ logger.debug(+ f"Direct Europe PMC download failed ({type(e).__name__})"+ )return None# If it's a regular PubMed URL, try to find PMC version@@ -2640,11 +2685,11 @@ class DownloadService:)except Exception as e:logger.debug(- f"Europe PMC download with PMC ID failed: {e}"+ f"Europe PMC download with PMC ID failed ({type(e).__name__})")except Exception as e:logger.debug(- f"API lookup failed, trying webpage scraping: {e}"+ f"API lookup failed, trying webpage scraping ({type(e).__name__})")# Fallback to webpage scraping if API fails@@ -2692,7 +2737,7 @@ class DownloadService:return response.contentexcept Exception as e:logger.debug(- f"Europe PMC download failed: {e}"+ f"Europe PMC download failed ({type(e).__name__})")else:logger.info(@@ -2708,11 +2753,18 @@ class DownloadService:) # Max 5 secondsraiseexcept Exception as e:- logger.debug(f"Could not check for PMC version: {e}")+ logger.debug(+ f"Could not check for PMC version "+ f"({type(e).__name__})"+ )return self._download_generic(url)- except Exception:- logger.exception("PubMed download failed")+ except Exception as e:+ # A re-raised HTTPError's text embeds the raw resource URL.+ logger.warning(+ f"PubMed download failed ({type(e).__name__}) for "+ f"{redact_url_for_log(url)}"+ )return Nonedef _download_semantic_scholar(self, url: str) -> Optional[bytes]:@@ -2730,8 +2782,11 @@ class DownloadService:pdf_url += ".full.pdf"return self._download_generic(pdf_url)- except Exception:- logger.exception("bioRxiv download failed")+ except Exception as e:+ logger.warning(+ f"bioRxiv download failed ({type(e).__name__}) for "+ f"{redact_url_for_log(url)}"+ )return Nonedef _save_text_with_db(@@ -2968,7 +3023,8 @@ class DownloadService:doc.extraction_quality = "low"doc.status = DocumentStatus.FAILEDlogger.info(- f"Recorded failed text extraction for document {doc.id}: {error}"+ f"Recorded failed text extraction for document {doc.id}: "+ f"{failure_reason_for_log(error)}")else:# Create a new Document for failed extraction@@ -3003,7 +3059,8 @@ class DownloadService:session.add(doc)logger.info(- f"Created failed document {doc_id} for resource {resource.id}: {error}"+ f"Created failed document {doc_id} for resource "+ f"{resource.id}: {failure_reason_for_log(error)}")except Exception:diff --git a/src/local_deep_research/research_library/services/library_service.py b/src/local_deep_research/research_library/services/library_service.pyindex ba16bdc142..00f5ba04b3 100644--- a/src/local_deep_research/research_library/services/library_service.py+++ b/src/local_deep_research/research_library/services/library_service.py@@ -32,6 +32,7 @@ from ...database.session_context import get_user_db_sessionfrom ...config.paths import get_library_directoryfrom ...utilities.db_utils import get_settings_managerfrom ...utilities.resource_utils import safe_close+from ...security import url_authority_without_userinfofrom ...utilities.sql_utils import escape_like as _escape_likefrom ..utils import (find_tracker_by_url,@@ -870,18 +871,20 @@ class LibraryService:entry = previews[rid]- # Domain breakdown (within the SQL LIMIT budget)+ # Domain breakdown (within the SQL LIMIT budget); authority+ # minus userinfo, which the response would otherwise carry.+ # The helper never raises and returns "" when unparseable.domain = "unknown"if resource and resource.url:- try:- domain = urlparse(resource.url).netloc or "unknown"- except Exception:- logger.debug("Failed to parse resource URL for domain")+ domain = (+ url_authority_without_userinfo(resource.url)+ or "unknown"+ )elif doc.original_url:- try:- domain = urlparse(doc.original_url).netloc or "unknown"- except Exception:- logger.debug("Failed to parse document URL for domain")+ domain = (+ url_authority_without_userinfo(doc.original_url)+ or "unknown"+ )if domain not in entry["domains"]:entry["domains"][domain] = {@@ -1184,14 +1187,17 @@ class LibraryService:netlocs.add(domain)return sorted(netlocs)- def _extract_domain(self, url: str) -> str:- """Extract domain from URL."""- from urllib.parse import urlparse+ def _extract_domain(self, url: Optional[str]) -> str:+ """Extract domain from URL.- try:- return urlparse(url).netloc- except (ValueError, AttributeError):- return ""+ The authority minus userinfo: a stored URL's ``user:pass@`` would+ otherwise reach the library page's domain filter and the+ document payloads. The domain filter's substring match still+ finds a credentialed URL by its host. ``""`` for a ``None``+ (``ResearchResource.url`` is nullable), unparseable or+ ambiguous-authority URL; never raises.+ """+ return url_authority_without_userinfo(url)def _get_storage_path(self) -> str:"""Get library storage path from settings (respects LDR_DATA_DIR)."""diff --git a/src/local_deep_research/research_library/utils/__init__.py b/src/local_deep_research/research_library/utils/__init__.pyindex 8c18974cf9..a92a9d8109 100644--- a/src/local_deep_research/research_library/utils/__init__.py+++ b/src/local_deep_research/research_library/utils/__init__.py@@ -14,6 +14,8 @@ from urllib.parse import unquote, urlparsefrom fastapi.responses import JSONResponsefrom loguru import logger+from ...security import redact_url_for_log+from ...config.paths import get_library_directoryfrom ...database.models.library import Document, DocumentCollectionfrom ...security.ip_ranges import PRIVATE_IP_RANGES@@ -223,7 +225,7 @@ def is_downloadable_domain(url: str) -> bool:return Falseexcept Exception:- logger.warning(f"Error parsing URL {url}")+ logger.warning(f"Error parsing URL {redact_url_for_log(url)}")return Falsediff --git a/src/local_deep_research/scheduler/background.py b/src/local_deep_research/scheduler/background.pyindex c14089b2b7..ae7fbeb7af 100644--- a/src/local_deep_research/scheduler/background.py+++ b/src/local_deep_research/scheduler/background.py@@ -22,7 +22,7 @@ from ..constants import ResearchStatusfrom ..database.credential_store_base import CredentialStoreBasefrom ..database.session_context import safe_rollbackfrom ..database.thread_local_session import thread_cleanup-from ..security.log_sanitizer import redact_secrets+from ..security.log_sanitizer import failure_reason_for_log, redact_secrets# RAG indexing imports. The reconciler builds RAG services via the lazily# imported ``rag_service_factory`` (see _reconcile_unindexed_documents), so the@@ -1282,8 +1282,11 @@ class BackgroundJobScheduler:f"[DOC_SCHEDULER] Successfully extracted text for resource {resource_id}")else:+ # The reason can be exception text+ # that embeds a presigned URL.logger.warning(- f"[DOC_SCHEDULER] Failed to extract text for resource {resource_id}: {error}"+ f"[DOC_SCHEDULER] Failed to extract text for resource {resource_id}: "+ f"{failure_reason_for_log(error)}")except Exception as resource_error:# No shared session to recover here:@@ -1293,17 +1296,12 @@ class BackgroundJobScheduler:# next iteration (issue #3827 is# structurally closed by the scoped# sessions rather than by a rollback).- # ``password`` is in scope and was- # passed into the enclosing- # ``DownloadService``. Drop the- # traceback chain + redact str(e) to- # avoid leaking the SQLCipher master- # password.- safe_msg = redact_secrets(- str(resource_error), password- )+ # Exception text can carry the URL's+ # path/query and the SQLCipher master+ # password. Log its type only.logger.warning(- f"[DOC_SCHEDULER] Error processing resource {resource_id}: {safe_msg}"+ f"[DOC_SCHEDULER] Error processing resource {resource_id}: "+ f"{type(resource_error).__name__}")logger.info(f"[DOC_SCHEDULER] Text extraction completed for research {research['id']}: {resources_processed}/{len(resources)} resources processed"diff --git a/src/local_deep_research/security/__init__.py b/src/local_deep_research/security/__init__.pyindex 3b86cce517..cc18e29fa5 100644--- a/src/local_deep_research/security/__init__.py+++ b/src/local_deep_research/security/__init__.py@@ -30,12 +30,14 @@ from .ssrf_validator import (get_safe_url,is_ip_blocked,redact_url_for_log,+ url_authority_without_userinfo,validate_url,)from .url_validator import URLValidatorfrom .account_lockout import AccountLockoutManager, get_account_lockout_managerfrom .password_validator import PasswordValidatorfrom .log_sanitizer import (+ failure_reason_for_log,redact_secrets,sanitize_error_details,sanitize_error_for_agent,@@ -102,12 +104,14 @@ __all__ = ["is_ip_blocked","assert_base_url_safe","redact_url_for_log",+ "url_authority_without_userinfo","get_safe_module_class","ModuleNotAllowedError","ALLOWED_MODULES","AccountLockoutManager","get_account_lockout_manager","PasswordValidator",+ "failure_reason_for_log","redact_secrets","sanitize_error_details","sanitize_error_for_agent",diff --git a/src/local_deep_research/security/log_sanitizer.py b/src/local_deep_research/security/log_sanitizer.pyindex d53ab28eb8..08960a01f9 100644--- a/src/local_deep_research/security/log_sanitizer.py+++ b/src/local_deep_research/security/log_sanitizer.py@@ -555,6 +555,47 @@ def sanitize_error_for_agent(message: str) -> str:return sanitize_error_for_client(message, max_length=_AGENT_ERROR_MAX_LEN)+#: Characters that delimit every secret-bearing part of a URL: path ``/``+#: (and ``\\``), query ``?``, fragment ``#``, userinfo ``@`` and path+#: parameters ``;``. A string with none of them can hold at most a host.+_URL_PART_DELIMITERS = frozenset("/\\?#@;")++#: Placeholder logged instead of a failure reason that may embed a URL.+FAILURE_REASON_WITHHELD = "<withheld: may embed a URL>"+++def failure_reason_for_log(reason: Any) -> str:+ """Return a download failure reason in a form that is safe to log.++ The reason strings that ``DownloadService.download_resource`` and+ ``download_as_text`` return are usually fixed categories+ (``"egress_policy_denied:..."``, ``"No compatible downloader+ available"``), but their exception paths return+ ``sanitize_error_for_client(str(e))``. That removes credential+ *shapes* only: request and urllib3 exception texts keep the URL's path+ and query (``with url: /p?X-Amz-Signature=...``), so presigned tokens+ survive it. The exception path logs its own cause (exception type and+ redacted URL) where it is caught, so a log line further up needs only+ the category.++ Fails closed on shape: a reason containing any URL-part delimiter is+ replaced by :data:`FAILURE_REASON_WITHHELD`; anything else is returned+ unchanged. The test is on shape, not origin, so a fixed reason that+ happens to contain a delimiter (``"Unexpected content type: text/html+ - expected PDF"``) is withheld too; that loss of detail is accepted+ rather than trying to tell a fixed reason from exception text. The+ result is for logs only: callers keep passing the original reason to+ their response or database.+ """+ if reason is None:+ return "None"+ if not isinstance(reason, str):+ return f"<{type(reason).__name__}>"+ if any(char in _URL_PART_DELIMITERS for char in reason):+ return FAILURE_REASON_WITHHELD+ return reason++def sanitize_error_details(value: Any) -> Any:"""Recursively redact credential *shapes* from the string leaves of astructured ``details`` value (``dict`` / ``list`` / ``tuple`` / dataclass).diff --git a/src/local_deep_research/security/safe_requests.py b/src/local_deep_research/security/safe_requests.pyindex 6681c7e93c..b43878671c 100644--- a/src/local_deep_research/security/safe_requests.py+++ b/src/local_deep_research/security/safe_requests.py@@ -19,6 +19,12 @@ from . import ssrf_validatorfrom ..constants import USER_AGENTfrom ..utilities.resource_utils import safe_close+# Log lines and raised exception texts below carry only scheme://host:port:+# the texts flow into caller logs (loguru renders ``ExcType: str(e)``) and+# into DB error columns, and the URLs can hold userinfo passwords or+# presigned query tokens.+_redact = ssrf_validator.redact_url_for_log+# Default timeout for all HTTP requests (prevents hanging)DEFAULT_TIMEOUT = 30 # seconds@@ -333,7 +339,7 @@ def safe_get()if not url.lower().startswith("https://"):raise ValueError(- f"URL must use https when require_https is set: {url}"+ f"URL must use https when require_https is set: {_redact(url)}")# Validate URL to prevent SSRFif not ssrf_validator.validate_url(@@ -342,7 +348,7 @@ def safe_get(allow_private_ips=allow_private_ips,):raise ValueError(- f"URL failed security validation (possible SSRF): {url}"+ f"URL failed security validation (possible SSRF): {_redact(url)}")# Ensure timeout is set@@ -405,12 +411,14 @@ def safe_get("https://"):logger.warning(- f"Redirect to {redirect_url} would downgrade to "- f"cleartext (from {url}, hop {redirects_followed + 1})"+ f"Redirect to {_redact(redirect_url)} would downgrade "+ f"to cleartext (from {_redact(url)}, hop "+ f"{redirects_followed + 1})")response.close()raise ValueError(- f"Redirect would downgrade to cleartext: {redirect_url}"+ "Redirect would downgrade to cleartext: "+ f"{_redact(redirect_url)}")# Validate redirect target against SSRF rules@@ -420,12 +428,13 @@ def safe_get(allow_private_ips=allow_private_ips,):logger.warning(- f"Redirect to {redirect_url} blocked by SSRF validation "- f"(from {url}, hop {redirects_followed + 1})"+ f"Redirect to {_redact(redirect_url)} blocked by SSRF "+ f"validation (from {_redact(url)}, hop "+ f"{redirects_followed + 1})")response.close()raise ValueError(- f"Redirect target failed SSRF validation: {redirect_url}"+ f"Redirect target failed SSRF validation: {_redact(redirect_url)}")# Credentials do not follow the hop out of their own scope.@@ -455,7 +464,7 @@ def safe_get(# requests.TooManyRedirects (delegated to the base class).# Callers should catch ValueError for standalone functions.raise ValueError(- f"Too many redirects ({_MAX_REDIRECTS}) from {url}"+ f"Too many redirects ({_MAX_REDIRECTS}) from {_redact(url)}")_check_response_size(response)@@ -463,10 +472,12 @@ def safe_get(return responseexcept requests.Timeout:- logger.warning(f"Request timeout after {timeout}s: {current_url}")+ logger.warning(+ f"Request timeout after {timeout}s: {_redact(current_url)}"+ )raiseexcept requests.RequestException:- logger.warning(f"Request failed for {current_url}")+ logger.warning(f"Request failed for {_redact(current_url)}")raise@@ -519,7 +530,7 @@ def safe_post(allow_private_ips=allow_private_ips,):raise ValueError(- f"URL failed security validation (possible SSRF): {url}"+ f"URL failed security validation (possible SSRF): {_redact(url)}")# Ensure timeout is set@@ -577,12 +588,13 @@ def safe_post(allow_private_ips=allow_private_ips,):logger.warning(- f"Redirect to {redirect_url} blocked by SSRF validation "- f"(from {url}, hop {redirects_followed + 1})"+ f"Redirect to {_redact(redirect_url)} blocked by SSRF "+ f"validation (from {_redact(url)}, hop "+ f"{redirects_followed + 1})")response.close()raise ValueError(- f"Redirect target failed SSRF validation: {redirect_url}"+ f"Redirect target failed SSRF validation: {_redact(redirect_url)}")redirect_method = _resolve_redirect_method(@@ -604,14 +616,15 @@ def safe_post()):logger.warning(- f"Redirect to {redirect_url} not followed: it would "- f"re-send the request body outside the scope of "- f"{current_url} (hop {redirects_followed + 1})"+ f"Redirect to {_redact(redirect_url)} not followed: it "+ f"would re-send the request body outside the scope "+ f"of {_redact(current_url)} (hop "+ f"{redirects_followed + 1})")response.close()raise ValueError("Redirect would re-send the request body outside "- f"the requested scope: {redirect_url}"+ f"the requested scope: {_redact(redirect_url)}")# Credentials do not follow the hop out of their own scope.kwargs["headers"] = _headers_for_redirect(@@ -646,7 +659,7 @@ def safe_post(# requests.TooManyRedirects (delegated to the base class).# Callers should catch ValueError for standalone functions.raise ValueError(- f"Too many redirects ({_MAX_REDIRECTS}) from {url}"+ f"Too many redirects ({_MAX_REDIRECTS}) from {_redact(url)}")_check_response_size(response)@@ -654,10 +667,12 @@ def safe_post(return responseexcept requests.Timeout:- logger.warning(f"Request timeout after {timeout}s: {current_url}")+ logger.warning(+ f"Request timeout after {timeout}s: {_redact(current_url)}"+ )raiseexcept requests.RequestException:- logger.warning(f"Request failed for {current_url}")+ logger.warning(f"Request failed for {_redact(current_url)}")raise@@ -815,13 +830,13 @@ class SafeSession(requests.Session):following_the_hop = not self._preparing_next_onlyif prepared_request.body is not None and following_the_hop:logger.warning(- f"Redirect to {prepared_request.url} not followed: it "- f"would re-send the request body outside the scope of "- f"{response.request.url}"+ f"Redirect to {_redact(prepared_request.url)} not "+ f"followed: it would re-send the request body outside "+ f"the scope of {_redact(response.request.url)}")raise ValueError("Redirect would re-send the request body outside "- f"the requested scope: {prepared_request.url}"+ f"the requested scope: {_redact(prepared_request.url)}")for name in [header@@ -841,7 +856,7 @@ class SafeSession(requests.Session):block_link_local=self.block_link_local,):raise ValueError(- f"URL failed security validation (possible SSRF): {url}"+ f"URL failed security validation (possible SSRF): {_redact(url)}")# Ensure timeout is set@@ -880,15 +895,14 @@ class SafeSession(requests.Session):block_link_local=self.block_link_local,):logger.warning(- f"Request to {ssrf_validator.redact_url_for_log(request.url)} "- f"blocked by SSRF validation"+ f"Request to {_redact(request.url)} 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): "- f"{ssrf_validator.redact_url_for_log(request.url)}"+ "Redirect target failed security validation (possible "+ f"SSRF): {_redact(request.url)}")# Pin the validated IP for the connection this send performs. send()@@ -1033,7 +1047,7 @@ def safe_get_with_retries(raisewait = backoff_times[min(attempt, len(backoff_times) - 1)]logger.warning(- f"{exc.__class__.__name__} on {url}; "+ f"{exc.__class__.__name__} on {_redact(url)}; "f"retrying in {wait}s "f"(attempt {attempt + 1}/{max_retries})")@@ -1051,7 +1065,7 @@ def safe_get_with_retries(else backoff_times[min(attempt, len(backoff_times) - 1)])logger.warning(- f"HTTP {response.status_code} on {url}; "+ f"HTTP {response.status_code} on {_redact(url)}; "f"retrying in {wait}s "f"(attempt {attempt + 1}/{max_retries})")@@ -1084,7 +1098,7 @@ def safe_get_with_retries(raisewait = backoff_times[min(attempt, len(backoff_times) - 1)]logger.warning(- f"{exc.__class__.__name__} reading body of {url}; "+ f"{exc.__class__.__name__} reading body of {_redact(url)}; "f"retrying in {wait}s "f"(attempt {attempt + 1}/{max_retries})")diff --git a/src/local_deep_research/security/ssrf_validator.py b/src/local_deep_research/security/ssrf_validator.pyindex 116dc67224..6e6cada560 100644--- a/src/local_deep_research/security/ssrf_validator.py+++ b/src/local_deep_research/security/ssrf_validator.py@@ -525,6 +525,9 @@ def validate_url(allow_private_ips=allow_private_ips,block_link_local=block_link_local,):+ # The parsed host is not logged raw: for a userinfo+ # holding an unencoded delimiter it is a credential+ # fragment. redact_url_for_log applies the ambiguity rule.logger.warning(f"Blocked URL - host resolves to internal/private "f"IP: {ip_str} - {redact_url_for_log(url)}"@@ -609,6 +612,138 @@ def get_safe_url(return default+#: Schemes ``redact_url_for_log`` may echo for a host-less URL. Anything+#: else may be the username of a scheme-less ``user:pass@host`` string.+_HOSTLESS_LOGGABLE_SCHEMES = frozenset(+ {+ "http",+ "https",+ "file",+ "ftp",+ "data",+ "javascript",+ "mailto",+ "ws",+ "wss",+ }+)+++#: Leading characters both parsers skip before the scheme: ``urlsplit``+#: strips C0 controls and space, ``redact_url_for_log`` strips Unicode+#: whitespace before ``parse_url``.+_URL_LEADING_STRIP_RE = re.compile(r"^[\x00-\x20\s]*")++#: An optional scheme followed by ``//``: where a parsed authority begins.+_RAW_AUTHORITY_START_RE = re.compile(r"(?:[A-Za-z][A-Za-z0-9+.\-]*:)?//")++#: Characters ``urlsplit`` deletes anywhere in a URL before parsing.+_URL_REMOVED_CHARS = str.maketrans("", "", "\t\r\n")+++def _split_raw_authority(url: str, delimiters: str) -> tuple[str, str]:+ """Split *url* as written into ``(authority, rest)``.++ See ``_raw_after_authority`` for how the authority is delimited.+ """+ s = url.translate(_URL_REMOVED_CHARS)+ s = s[_URL_LEADING_STRIP_RE.match(s).end() :]+ match = _RAW_AUTHORITY_START_RE.match(s)+ start = match.end() if match else 0+ ends = [i for i in (s.find(d, start) for d in delimiters) if i >= 0]+ end = min(ends) if ends else len(s)+ return s[start:end], s[end:]+++def _raw_authority_has_userinfo(url: str, delimiters: str) -> bool:+ """Whether the authority of *url*, as written, holds an ``@``.++ ``urllib3.parse_url`` sets ``auth = auth or None``, so an authority+ that starts with ``@`` (an empty userinfo, as in+ ``https://@john.doe/s3cret@host/``) parses with ``auth is None``;+ this check counts it as a userinfo, as the ``urlparse``-based+ siblings already do.+ """+ return "@" in _split_raw_authority(url, delimiters)[0]+++def _raw_after_authority(url: str, delimiters: str) -> str:+ """Return the text of *url* as written after its authority.++ The authority runs from the ``//`` after the scheme to the first of+ *delimiters* (``/?#`` for ``urlsplit``; ``urllib3.parse_url`` also+ ends it at ``\\``). This is taken from the raw string, never from the+ parsed path: for http(s) ``parse_url`` removes dot segments, so the+ path of ``https://tok/en@host/../a`` parses to ``/a`` and the ``@``+ that marks ``tok`` as a userinfo fragment would be gone. Without a+ ``//`` the search starts at the beginning of the string, which can+ only include more text (fail closed).+ """+ return _split_raw_authority(url, delimiters)[1]+++def authority_may_be_userinfo(+ host: str,+ has_port: bool,+ url: str,+ *,+ has_userinfo: bool = False,+ delimiters: str = "/?#",+) -> bool:+ """Whether a parsed ``host[:port]`` may really be a userinfo prefix.++ Shared by ``redact_url_for_log``, ``url_authority_without_userinfo``+ and the downloaders' ``rate_limit_authority``. *url* is the raw URL+ the authority was parsed from and *delimiters* the characters that+ end the authority for that parser; whether an ``@`` follows the+ authority is decided on the URL as written (``_raw_after_authority``),+ so a dot segment (``https://tok/en@host/../a``, which ``parse_url``+ normalises to the path ``/a``) cannot hide it.+ A userinfo holding an unencoded ``/``, ``?``, ``#`` (or, for urllib3,+ ``\\``) ends the authority early, so ``https://tok/en@host/`` parses+ to the host ``tok`` and ``https://john.doe:1234#x@host/`` to+ ``john.doe:1234``. That shape always leaves an ``@`` after the parsed+ authority. With one there, the authority is treated as ambiguous+ when:++ * the parsed authority itself carried a userinfo (*has_userinfo*):+ a password holding an unencoded ``@`` *and* a later delimiter+ (``https://admin:[email protected]#1@host/``) is split at its own ``@``,+ so the "host" (``ss.example``) is the password's tail -- this applies+ to every host, ``localhost`` and IP literals included;+ * the host is a single label (no ``.``), or+ * a port was parsed -- it may be the leading digits of a password,++ the last two unless the host is ``localhost`` or an IP literal, which+ are not plausible usernames (``http://localhost:8080/?email=a@b``+ stays). A real credentialed URL with an ``@`` in its path or query+ (``https://u:[email protected]/@group``) therefore fails closed.++ Residual: a userinfo whose text before its first ``/``, ``?`` or+ ``#`` holds no ``@`` and is either a dotted name with no+ ``:digits`` port (``https://john.doe/x@host/``,+ ``https://john.doe:#pw@host/``) or ``localhost`` / an IP literal+ with or without one (``https://127.0.0.1:80/x@host/``) is+ indistinguishable from a real host followed by an ``@`` in the path+ (``https://medium.com/@user``) and is not flagged. Only that text+ (a username, plus a digits-only password prefix for the IP/localhost+ case) can surface.+ """+ if "@" not in _raw_after_authority(url, delimiters):+ return False+ if has_userinfo:+ return True+ bare = host.strip("[]")+ if host.startswith("[") or bare.lower() == "localhost":+ return False+ try:+ ipaddress.IPv4Address(bare)+ return False+ except ValueError:+ pass+ return has_port or "." not in host++def redact_url_for_log(url: str) -> str:"""Return ``scheme://host:port`` (no userinfo, path, query, fragment).@@ -629,18 +764,106 @@ def redact_url_for_log(url: str) -> str:(``http://user:pass@host/``). A rejected URL is by definitionadversarial-shaped, but it may still carry the operator's realcredentials if a misconfiguration produced it.++ Total by design: it runs inside failure handlers, so it never raises.+ A non-``str`` input yields ``"<unparseable:TYPE>"`` (the egress audit+ log's placeholder) and any parse error yields ``"<unparseable>"``.+ When no host parses, the "scheme" is only kept if it is a well-known+ one: in a scheme-less ``user:pass@host`` the parser reads the+ username as the scheme, so an unknown one becomes ``?``.++ When the parsed authority may be a userinfo prefix (see+ ``authority_may_be_userinfo``: ``https://tok/en@host/`` parses to the+ host ``tok``), the authority is replaced by ``<redacted>``."""+ if not isinstance(url, str):+ return f"<unparseable:{type(url).__name__}>"try:# requests strips leading whitespace before it fetches; parse_url does# not, and would put the scheme in the host slot.- u = parse_url(url.lstrip() if isinstance(url, str) else url)+ u = parse_url(url.lstrip())+ if not u.host:+ scheme = (u.scheme or "").lower()+ if scheme not in _HOSTLESS_LOGGABLE_SCHEMES:+ scheme = "?"+ return f"{scheme}://<no-host>"scheme = u.scheme or "?"- host = u.host or "<no-host>"+ # The raw URL, not u.path: parse_url removes dot segments.+ if authority_may_be_userinfo(+ u.host,+ u.port is not None,+ url,+ # Also the raw text: parse_url drops an empty userinfo+ # (``https://@john.doe/x@host/`` has ``auth is None``).+ has_userinfo=u.auth is not None+ or _raw_authority_has_userinfo(url, "/?#\\"),+ delimiters="/?#\\",+ ):+ if scheme.lower() not in _HOSTLESS_LOGGABLE_SCHEMES:+ scheme = "?"+ return f"{scheme}://<redacted>"+ host = u.host# (#6938: scheme and host are unbounded in a request-supplied URL,# so each is capped — every caller's log line stays bounded.)scheme = redact_and_bound_for_log(scheme, _LOG_COMPONENT_MAX_CHARS)host = redact_and_bound_for_log(host, _LOG_COMPONENT_MAX_CHARS)host_port = f"{host}:{u.port}" if u.port else hostreturn f"{scheme}://{host_port}"- except (LocationParseError, ValueError):+ except Exception: # never raise from a log-formatting helperreturn "<unparseable>"+++def url_authority_without_userinfo(url: object) -> str:+ """Return a URL's ``host[:port]`` with any userinfo removed.++ For display and keying (library domain filters, domain-classifier+ keys, rate-limit keys, failure messages). For an ordinary URL the+ result is exactly ``urllib.parse.urlparse(url).netloc``, case+ preserved, so keys derived from it stay stable; a ``user:pass@host``+ netloc yields ``host``.++ Returns ``""`` (never raises) when no credential-free authority can+ be determined:++ * a non-``str`` or empty input (``urlparse(None)`` yields bytes) or a+ parse error;+ * a port that is not a valid port number. A password holding an+ unencoded ``/``, ``?`` or ``#`` ends the netloc early, so+ ``https://alice:pa#ss@host/`` parses to the netloc ``alice:pa``,+ whose "port" is the start of the password;+ * an authority followed by an ``@`` later in the URL that itself+ carried a userinfo, or whose host is a single label or which+ carries a port (for the last two, ``localhost`` and IP literals+ excepted): the shape a userinfo holding one of those delimiters+ leaves behind (``https://tok/en@host/`` parses to the netloc+ ``tok``, ``https://user:12#34@host/`` to ``user:12``,+ ``https://john.doe:1234/x@host/`` to ``john.doe:1234`` and+ ``https://admin:[email protected]#1@host/`` to ``admin:[email protected]``).+ See ``authority_may_be_userinfo``, which ``redact_url_for_log``+ and ``rate_limit_authority`` share.++ Residual: see ``authority_may_be_userinfo`` -- a dotted username+ directly followed by the delimiter (``https://john.doe/x@host/``) is+ returned as parsed.+ """+ if not isinstance(url, str) or not url:+ return ""+ try:+ parsed = urlparse(url)+ userinfo, at, authority = parsed.netloc.rpartition("@")+ if not authority:+ return ""+ # ``.port`` raises ValueError for a non-numeric or out-of-range+ # port; that "port" may be the start of a password.+ port = parsed.port+ if authority.startswith("["):+ host = authority.partition("]")[0] + "]"+ else:+ host = authority.partition(":")[0]+ if authority_may_be_userinfo(+ host, port is not None, url, has_userinfo=bool(at)+ ):+ return ""+ return authority+ except Exception: # never raise from a display/keying helper+ return ""diff --git a/src/local_deep_research/web/routers/api.py b/src/local_deep_research/web/routers/api.pyindex ace80a288d..8b51b76ad9 100644--- a/src/local_deep_research/web/routers/api.py+++ b/src/local_deep_research/web/routers/api.py@@ -12,7 +12,6 @@ from ...constants import ResearchStatusfrom ...database.models import QueuedResearch, ResearchHistoryfrom ...database.session_context import get_user_db_sessionfrom ...config.constants import DEFAULT_OLLAMA_URL-from ...security.ssrf_validator import redact_url_for_logfrom ...utilities.url_utils import normalize_urlfrom .notes import _log_value_preview@@ -26,7 +25,7 @@ from ..services.resource_service import (get_resources_for_research,)from local_deep_research.settings import SettingsManager-from ...security import safe_get, strip_settings_snapshot+from ...security import redact_url_for_log, safe_get, strip_settings_snapshotfrom ..dependencies.json_body import json_body_errorfrom typing import Annotated@@ -416,7 +415,9 @@ def check_ollama_status(}ollama_base_url = _ollama_base_url_from_config(raw_ollama_base_url)- logger.info(f"Checking Ollama status at: {ollama_base_url}")+ logger.info(+ f"Checking Ollama status at: {redact_url_for_log(ollama_base_url)}"+ )outcome, probe_result = _probe_ollama_tags(ollama_base_url)diff --git a/src/local_deep_research/web/routers/library.py b/src/local_deep_research/web/routers/library.pyindex cbcb6b8002..100495e976 100644--- a/src/local_deep_research/web/routers/library.py+++ b/src/local_deep_research/web/routers/library.py@@ -40,6 +40,7 @@ from ...security.url_validator import URLValidatorfrom ...research_library.services.download_service import DownloadServicefrom ...research_library.services.library_service import LibraryServicefrom ...research_library.services.pdf_storage_manager import PDFStorageManager+from ...security import failure_reason_for_log, redact_url_for_logfrom ...research_library.utils import (apply_user_subdir,get_document_for_resource,@@ -777,7 +778,12 @@ def download_single_resource({"success": False, "error": "Resource not found"},status_code=404,)- logger.warning(f"Download failed for resource {resource_id}: {error}")+ # The reason may be exception text that keeps the URL's path and+ # query; download_service logs the cause itself where it is caught.+ logger.warning(+ f"Download failed for resource {resource_id}: "+ f"{failure_reason_for_log(error)}"+ )return JSONResponse({"success": False,@@ -807,7 +813,8 @@ def download_text_single(if not success:if error:logger.warning(- f"Download as text failed for resource {resource_id}: {error}"+ f"Download as text failed for resource {resource_id}: "+ f"{failure_reason_for_log(error)}")return {"success": False,@@ -947,8 +954,11 @@ def download_all_text(error_msg = error or "Text extraction failed"except Exception as e:- logger.exception(- f"Error extracting text for resource {rid}"+ # Type name only, no traceback: an exception escaping+ # the fetch can embed the raw resource URL in its text.+ logger.warning(+ f"Error extracting text for resource {rid} "+ f"({type(e).__name__})")status = "failed"# CWE-209: only the exception CLASS NAME is surfaced,@@ -1320,11 +1330,11 @@ async def download_bulk(if skip_reason and not success:error_msg = skip_reasonlogger.info(- f"{'Download' if mode == 'pdf' else 'Text extraction'} skipped for resource {resource_id}: {skip_reason}"+ f"{'Download' if mode == 'pdf' else 'Text extraction'} skipped for resource {resource_id}: {failure_reason_for_log(skip_reason)}")logger.debug(- f"{'Download' if mode == 'pdf' else 'Text extraction'} result: success={success}, status={status}, skip_reason={skip_reason}"+ f"{'Download' if mode == 'pdf' else 'Text extraction'} result: success={success}, status={status}, skip_reason={failure_reason_for_log(skip_reason)}")except Exception as e:# Release the claim so a later run can retry this row:@@ -1344,17 +1354,20 @@ async def download_bulk()# Log error but continue processing. `error_msg`# (str(e)) is used ONLY for the keyword classification- # below (`.lower()` checks) and the server log line —- # it is never written into `skip_reason`, which the- # yield below sends to the client. Only `error_type`- # (the exception CLASS NAME) reaches skip_reason, same- # "class name only" mitigation as- # journal_quality/downloader.py (CodeQL alerts- # 7650/7684) — CWE-209.+ # below (`.lower()` checks) — it is never logged+ # (an exception escaping download_resource /+ # download_as_text can embed the raw resource URL:+ # urllib3 "with url: ...", SQLAlchemy+ # "[parameters: ...]") and never written into+ # `skip_reason`, which the yield below sends to the+ # client. Only `error_type` (the exception CLASS NAME)+ # reaches the log and skip_reason, same "class name+ # only" mitigation as journal_quality/downloader.py+ # (CodeQL alerts 7650/7684) — CWE-209.error_msg = str(e)error_type = type(e).__name__logger.warning(- f"CAUGHT Download exception for resource {resource_id}: {error_type}: {error_msg}"+ f"CAUGHT Download exception for resource {resource_id}: {error_type}")# Check if this is a skip reason (not a real error)# Use error category + categorized message for user display@@ -1393,7 +1406,7 @@ async def download_bulk(if error_msg and not skip_reason:skip_reason = f"Processing failed - {error_type}"logger.debug(- f"Setting skip_reason from error_msg: {error_msg}"+ f"Setting skip_reason from error type: {error_type}")# Send progress update@@ -1407,7 +1420,10 @@ async def download_bulk(# Add skip reason if availableif skip_reason:update_data["error"] = skip_reason- logger.info(f"Sending skip reason to UI: {skip_reason}")+ logger.info(+ "Sending skip reason to UI: "+ f"{failure_reason_for_log(skip_reason)}"+ )yield f"data: {json.dumps(update_data)}\n\n"@@ -1547,8 +1563,12 @@ def queue_all_undownloaded(if not filter_result or not filter_result.can_retry:skipped_count += 1if filter_result:+ # A permanently failed row's reason embeds its stored+ # failure_message, which rows written before the+ # domain fix may hold with URL userinfo.logger.debug(- f"Skipping resource {resource.id} due to retry policy: {filter_result.reason}"+ f"Skipping resource {resource.id} due to retry policy: "+ f"{failure_reason_for_log(filter_result.reason)}")else:logger.debug(@@ -1568,17 +1588,17 @@ def queue_all_undownloaded(logger.info("Found PubMed URL: {}",# (#6938: redacted before it is cut.)- redact_and_bound_for_log(resource.url, 100),+ redact_and_bound_for_log(+ redact_url_for_log(resource.url), 100+ ),)if not is_downloadable:skipped_count += 1logger.opt(lazy=True).debug("Skipping non-downloadable URL: {}",- lambda: (- redact_and_bound_for_log(resource.url, 100)- if resource.url- else "None"+ lambda: redact_and_bound_for_log(+ redact_url_for_log(resource.url), 100),)continuediff --git a/src/local_deep_research/web/routers/library_search.py b/src/local_deep_research/web/routers/library_search.pyindex b030cf676b..b7258d5987 100644--- a/src/local_deep_research/web/routers/library_search.py+++ b/src/local_deep_research/web/routers/library_search.py@@ -442,9 +442,8 @@ def _enrich_with_research_metadata(results, username, db_password):def _enrich_with_document_metadata(results, username, db_password):"""Add file type, domain, and creation date to search results."""- from urllib.parse import urlparse-from ...database.session_context import get_user_db_session+ from ...security import url_authority_without_userinfodoc_ids = [r["document_id"] for r in results if r.get("document_id")]if not doc_ids:@@ -475,10 +474,12 @@ def _enrich_with_document_metadata(results, username, db_password):else None)if row.original_url:- try:- result["domain"] = urlparse(row.original_url).netloc- except (ValueError, AttributeError):- result["domain"] = "unknown"+ # Authority minus userinfo, which the JSON would+ # otherwise carry; "" when unparseable or when the+ # authority is ambiguous (the helper never raises).+ result["domain"] = url_authority_without_userinfo(+ row.original_url+ )else:result["domain"] = Noneelse:diff --git a/src/local_deep_research/web/routers/metrics.py b/src/local_deep_research/web/routers/metrics.pyindex 287d8cf05e..fa5bfcb47e 100644--- a/src/local_deep_research/web/routers/metrics.py+++ b/src/local_deep_research/web/routers/metrics.py@@ -11,7 +11,6 @@ from ..template_config import templatesfrom datetime import datetime, timedelta, UTCfrom typing import Any, Annotated-from urllib.parse import urlparsefrom loguru import loggerfrom sqlalchemy import case, func@@ -39,6 +38,7 @@ from ...metrics.query_utils import (get_time_filter_condition,)from ...metrics.search_tracker import get_search_tracker+from ...security import redact_url_for_log, url_authority_without_userinfofrom ..dependencies.json_body import json_body_errorfrom .notes import _log_value_preview@@ -53,8 +53,10 @@ router = APIRouter(prefix="/metrics", tags=["metrics"])def _extract_domain(url):"""Extract normalized domain from URL, stripping www. prefix."""try:- parsed = urlparse(url)- domain = parsed.netloc.lower()+ # Authority minus userinfo (empty when that is ambiguous),+ # matching DomainClassifier's key: the domain is returned to the+ # UI, logged and sent back to be classified and persisted.+ domain = url_authority_without_userinfo(url).lower()if domain.startswith("www."):domain = domain[4:]return domain if domain else None@@ -320,8 +322,14 @@ def get_link_analytics(period="30d", username=None):domain_connections[research_id] = []domain_connections[research_id].append(domain)- except Exception:- logger.exception(f"Error parsing URL {resource.url}")+ except Exception as e:+ # Type name and redacted URL only: the exception+ # text and traceback can carry the raw URL.+ logger.warning(+ "Error parsing URL "+ f"{redact_url_for_log(resource.url)} "+ f"({type(e).__name__})"+ )# Sort domains by count and get top 10sorted_domains = sorted(@@ -1074,7 +1082,10 @@ def api_research_link_metrics(category_counts.get("Unclassified", 0) + 1)except (AttributeError, KeyError) as e:- logger.debug(f"Error classifying domain {domain}: {e}")+ logger.debug(+ f"Error classifying domain {domain}: "+ f"{type(e).__name__}"+ )# Sort domains by countsorted_domains = sorted(diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_tinyfish.py b/src/local_deep_research/web_search_engines/engines/search_engine_tinyfish.pyindex a5ef5f136c..7b3a6db19c 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_tinyfish.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_tinyfish.py@@ -148,9 +148,7 @@ class TinyFishSearchEngine(BaseSearchEngine):try:display_link = urlparse(link).netloc or ""except Exception:- logger.debug(- f"Failed to parse URL for display: {link[:50]}"- )+ logger.debug("Failed to parse URL for display")preview = {"id": link or str(idx),diff --git a/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py b/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.pyindex 7e0d45b197..1590bfcc17 100644--- a/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py+++ b/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py@@ -6,7 +6,11 @@ import inspectfrom typing import Optionalfrom urllib.parse import urlparse-from ....security import scrub_error+from ....security import (+ redact_url_for_log,+ scrub_error,+ url_authority_without_userinfo,+)from ....security.secure_logging import loggerfrom tenacity import (retry,@@ -142,7 +146,8 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):for local in ["localhost", "127.0.0.1", "0.0.0.0"]):logger.debug(- f"Skipping rate limiting for local URL: {base_url}"+ "Skipping rate limiting for local URL: "+ f"{redact_url_for_log(base_url)}")return True@@ -164,7 +169,15 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):# Clean URL: remove protocol and trailing slashesif url != "unknown":parsed = urlparse(url)- url = parsed.netloc or parsed.path+ # Authority minus userinfo: the key is logged. A+ # scheme-less value keeps the old path fallback unless+ # that path could hold userinfo.+ if parsed.netloc:+ url = url_authority_without_userinfo(url) or "unknown"+ elif "@" in parsed.path:+ url = "unknown"+ else:+ url = parsed.pathurl = url.rstrip("/")# Extract modeldiff --git a/tests/research_library/downloaders/test_pipeline_logging_sinks.py b/tests/research_library/downloaders/test_pipeline_logging_sinks.pyindex aad2e5576b..83f2d9de77 100644--- a/tests/research_library/downloaders/test_pipeline_logging_sinks.py+++ b/tests/research_library/downloaders/test_pipeline_logging_sinks.py@@ -164,9 +164,15 @@ def _install_specialized(downloader.download_with_result.side_effect = download_errorelse:downloader.download_with_result.return_value = download_result++ def make_downloader(timeout=30, allow_private_ips=False):+ assert timeout == 30+ assert allow_private_ips is False+ return downloader+monkeypatch.setattr("local_deep_research.research_library.downloaders.pubmed.PubMedDownloader",- lambda timeout=30: downloader,+ make_downloader,)return downloaderdiff --git a/tests/research_library/test_download_service_contracts.py b/tests/research_library/test_download_service_contracts.pyindex 36737d1d65..f4c475b124 100644--- a/tests/research_library/test_download_service_contracts.py+++ b/tests/research_library/test_download_service_contracts.py@@ -61,8 +61,9 @@ Covered:the producer and the classifier wired together so drift in eitherhalf fails;* an exception message surfaced to the client is credential-scrubbed,- and configured application logging scrubs the same URL before sinks- receive it (holds).+ the download's call sites log only the redacted URL (checked with the+ redaction patcher removed), and configured application logging also+ scrubs the same URL before sinks receive it (holds)."""import hashlib@@ -423,6 +424,38 @@ def log_sink(monkeypatch):yield captured+def raw_log_sink():+ """Capture what the call sites format, with NO redaction patcher.++ ``log_sink`` installs the production ``_sanitize_record`` patcher, so+ a call site that logs a raw URL still passes there. This sink runs+ with the core patcher replaced by a no-op, so it sees each record+ exactly as the call site built it -- as a process that never calls+ ``config_logger`` (benchmark CLI, programmatic API use) would. Restores+ process-wide loguru state afterwards.+ """+ from tests.test_utils import restored_loguru_state++ captured = []++ def _sink(message):+ captured.append(f"{message}{message.record['extra']!r}")++ with restored_loguru_state():+ logger.configure(patcher=lambda record: None)+ logger.enable("local_deep_research")+ logger.remove()+ logger.add(+ _sink,+ level="TRACE",+ format="{level} | {name}:{function} | {message}",+ diagnose=False,+ backtrace=True,+ )+ yield captured++@pytest.fixturedef filesystem_mode(monkeypatch):"""Open the operator gate for unencrypted filesystem PDF storage.@@ -1238,3 +1271,41 @@ def test_download_logs_do_not_leak_url_credentials(db, store, seeded, log_sink):assert logged.strip(), "nothing was captured; the sink is not wired up"assert SECRET_PASSWORD not in loggedassert SECRET_KEY not in logged+++def test_download_call_sites_redact_url_without_the_log_patcher(+ db, store, seeded, raw_log_sink+):+ """CONTRACT: the download's own log calls never format a raw URL.++ Independent of the global redaction patcher: ``raw_log_sink`` has it+ removed, so this fails if a call site regresses to logging the raw+ ``resource.url`` even while ``_sanitize_record`` would hide it.+ """+ # Canary: prove the patcher really is bypassed, otherwise the+ # assertions below would be vacuous.+ logger.info("canary {}", SECRET_URL)+ assert SECRET_KEY in "\n".join(raw_log_sink), (+ "the redaction patcher is still active; this test cannot see "+ "what the call sites log"+ )+ raw_log_sink.clear()++ fixture = seeded(SECRET_URL)+ downloader = StubDownloader(+ DownloadResult(content=PDF_BYTES, is_success=True, status_code=200)+ )+ service = make_service(store, downloader)++ success, reason, _status = service._download_pdf(+ fixture.resource, fixture.tracker, db.session, None+ )+ db.session.commit()+ assert success is True, reason++ logged = "\n".join(raw_log_sink)+ assert logged.strip(), "nothing was captured; the sink is not wired up"+ # The call sites still identify the resource by its (redacted) host.+ assert "journal.example.com" in logged+ assert SECRET_PASSWORD not in logged+ assert SECRET_KEY not in loggeddiff --git a/tests/security/test_downloader_error_url_redaction.py b/tests/security/test_downloader_error_url_redaction.pynew file mode 100644index 0000000000..4e5a397dc7--- /dev/null+++ b/tests/security/test_downloader_error_url_redaction.py@@ -0,0 +1,2464 @@+"""Redaction contracts for failure-path URL logging in the downloader stack.++Fetches are driven by web-influenced URLs (search results, crawled+page content), which routinely carry secrets in query strings —+presigned storage links, session tokens, password-reset URLs — or in+userinfo (``https://user:pass@host/``). When a fetch or parse *fails or+is rejected*, the operator-facing log must show only+``scheme://host:port`` (``redact_url_for_log``) — the discipline the+SSRF validator's own sites and the PDF fetcher (#6521) already follow.++Two leak channels are pinned here:++1. **The URL itself** interpolated into a log call.+2. **The exception text.** requests / urllib3 / SafeSession / Playwright+ exception messages embed the full URL, and loguru renders+ ``ExcType: str(e)`` for ``logger.exception`` even with+ ``diagnose=False``. Failure handlers therefore log+ ``type(e).__name__`` and the redacted URL — never ``str(e)`` and+ never a traceback.++What the structural contract covers (AST scan of ``SCANNED_RELATIVE``):++* every ``logger.<level>(...)`` call at *any* level (trace through+ critical, and ``log``) — including chained receivers such as+ ``logger.opt(...).warning`` and ``logger.bind(...).error`` — where any+ positional+ or keyword argument (f-string pieces, loguru brace-positional args,+ ``!r`` / ``=`` conversions, subscripts, ``str(...)`` wrappers, any+ quote style) references a URL-named identifier (``url``, ``*_url``,+ ``url_*``, ``urls``, ``uri``, ``href``, ``location``, as a bare name+ or attribute; ``*_type`` names such as ``url_type`` are not URLs) that+ is not wrapped in ``redact_url_for_log`` / ``rate_limit_authority``. The+ attempt/progress lines count: they run before every fetch, including+ the ones that then fail;+* every logger call *at any level* inside an ``except ... as e`` block+ that references ``e`` other than as ``type(e)`` / ``e.__class__``;+* every call that attaches a traceback — ``logger.exception`` and any+ ``logger.opt(exception=<anything but a literal False/None>)`` receiver+ (``True``, the exception variable, …) at any level including ``log``+ — in an ``except`` block whose ``try`` body makes a network-shaped+ call (``get``/``post``/``request``/``safe_get``/``download*``/+ ``_fetch*``/``_probe*``/…).++Not covered (documented residuals):++* a URL copied into a differently named variable, or a message string+ pre-built into a variable and then logged;+* an exception aliased to another name (``err = e`` then+ ``logger.error("{}", err)``): only the ``except ... as`` name is+ tracked;+* a fetch wrapped in a helper whose name does not match+ ``NETWORK_CALL``: the traceback rule keys on the called name, not on+ what the callee does;+* a traceback-attaching call in an ``except`` block whose ``try`` makes+ no network-shaped call (persistence and extraction handlers; the+ SQLAlchemy parameter echo there is tracked in #6829);+* modules outside ``SCANNED_RELATIVE``.++``ALLOWED`` lists the reviewed exceptions, each keyed to the exact call+text so that a new offending call in the same function is still+reported.++Exception messages raised by ``security/safe_requests.py`` are redacted+at source; ``TestSafeRequestsExceptionTexts`` pins each raise site.+"""++from __future__ import annotations++import ast+import re+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest+import requests+from loguru import logger++import local_deep_research+++def _src_root() -> Path:+ return Path(local_deep_research.__file__).resolve().parent+++#: Modules whose failure paths handle web-influenced URLs.+SCANNED_RELATIVE = [+ "research_library/downloaders",+ "research_library/services/download_service.py",+ "research_library/utils/__init__.py",+ "scheduler/background.py",+ "security/safe_requests.py",+ "web/routers/api.py",+ "web/routers/library.py",+ "web/routers/metrics.py",+]++#: Levels at which a raw URL must never be interpolated: all of them.+ALL_LEVELS = {+ "trace",+ "debug",+ "info",+ "success",+ "warning",+ "error",+ "exception",+ "critical",+ "log",+}++#: Calls whose result is safe to log even when given a URL.+SAFE_WRAPPERS = {"redact_url_for_log", "_redact", "rate_limit_authority"}++#: Identifiers that name a URL (token-delimited by ``_``).+URL_NAME = re.compile(+ r"(?:^|_)(?:urls?|uri|href|location)(?:_|$)", re.IGNORECASE+)++#: URL-named identifiers that hold no URL (``url_type`` is an enum).+NOT_URL_NAME = re.compile(r"_types?$", re.IGNORECASE)++#: Calls in a ``try`` body that can raise an exception whose text embeds+#: the requested URL.+NETWORK_CALL = re.compile(+ r"^(?:get|post|head|request|send|safe_get|safe_post|goto|arun"+ r"|raise_for_status|download\w*|_download\w*|fetch\w*|_fetch\w*"+ r"|_try_\w+|_probe\w*)$"+)++#: Reasons shared by the metrics-router entries in ``ALLOWED``.+_METRICS_DB_ONLY = (+ "the 'get' calls are dict / query-param .get; the try is database, "+ "settings and local computation work, no fetch"+)+_METRICS_PRICING_ONLY = (+ "the 'get' calls are query-param and dict .get; CostCalculator reads "+ "cached or static pricing, no fetch"+)+_METRICS_JOURNAL_FETCH = (+ "download_journal_data fetches only the app-fixed journal data "+ "sources (journal_quality/data_sources, e.g. OpenAlex, DOAJ), never a "+ "web-sourced URL, and catches each source's fetch error itself "+ "(_fetch_one); what escapes to this handler is settings, disk and "+ "DB-build work"+)++#: Reviewed exceptions: (module relpath, qualified function, rule,+#: whitespace-normalised call text) -> why the flagged call cannot carry+#: a request URL. Keying on the call text means only the reviewed call+#: is exempt; a new offending call in the same function is reported.+ALLOWED = {+ (+ "scheduler/background.py",+ "BackgroundJobScheduler._reload_config",+ "exception-after-network",+ 'logger.exception("Error reloading configuration")',+ ): (+ "the matched 'get' is self.config.get; the try re-reads scheduler "+ "settings and holds no URL or credential"+ ),+ (+ "research_library/services/download_service.py",+ "DownloadService._build_egress_context",+ "exc-text",+ 'logger.bind(policy_audit=True).warning( "DownloadService policy '+ 'unavailable; locking out " "every URL check", reason=str(exc), )',+ ): "policy-construction error text (settings snapshot), no URL",+ (+ "web/routers/api.py",+ "api_add_resource._impl",+ "exception-after-network",+ 'logger.exception("Error adding resource")',+ ): "the 'get' is dict.get on the request body; no fetch in the try",+ (+ "web/routers/api.py",+ "check_ollama_model",+ "exception-after-network",+ 'logger.exception("Error checking Ollama model")',+ ): "_probe_ollama_tags handles request errors itself; SafeSession "+ "refusal texts are redacted at source (security/safe_requests.py)",+ (+ "web/routers/library.py",+ "library_page",+ "exception-after-network",+ 'logger.exception("Error loading library data")',+ ): "the 'get' calls are request.query_params.get; the try reads the "+ "library from the database, no fetch",+ (+ "web/routers/api.py",+ "check_ollama_status",+ "exception-after-network",+ 'logger.exception("Error checking Ollama status")',+ ): "twin of check_ollama_model: _probe_ollama_tags handles request "+ "errors itself; SafeSession refusal texts are redacted at source "+ "(security/safe_requests.py)",+ (+ "web/routers/metrics.py",+ "get_link_analytics",+ "exception-after-network",+ 'logger.exception("Error getting link analytics")',+ ): _METRICS_DB_ONLY,+ (+ "web/routers/metrics.py",+ "api_metrics",+ "exception-after-network",+ 'logger.exception("Error getting metrics")',+ ): _METRICS_DB_ONLY,+ (+ "web/routers/metrics.py",+ "get_rate_limiting_metrics",+ "exception-after-network",+ 'logger.exception("Error getting rate limiting metrics")',+ ): _METRICS_DB_ONLY,+ (+ "web/routers/metrics.py",+ "api_research_link_metrics",+ "exception-after-network",+ 'logger.exception("Error getting research link metrics")',+ ): _METRICS_DB_ONLY,+ (+ "web/routers/metrics.py",+ "api_enhanced_metrics",+ "exception-after-network",+ 'logger.exception("Error getting enhanced metrics")',+ ): _METRICS_DB_ONLY,+ (+ "web/routers/metrics.py",+ "api_save_research_rating",+ "exception-after-network",+ 'logger.exception("Error saving research rating")',+ ): _METRICS_DB_ONLY,+ (+ "web/routers/metrics.py",+ "api_star_reviews",+ "exception-after-network",+ 'logger.exception("Error getting star reviews data")',+ ): _METRICS_DB_ONLY,+ (+ "web/routers/metrics.py",+ "api_cost_calculation",+ "exception-after-network",+ 'logger.exception("Error calculating cost")',+ ): _METRICS_PRICING_ONLY,+ (+ "web/routers/metrics.py",+ "api_cost_analytics",+ "exception-after-network",+ 'logger.exception("Error getting cost analytics")',+ ): _METRICS_DB_ONLY,+ (+ "web/routers/metrics.py",+ "api_link_analytics",+ "exception-after-network",+ 'logger.exception("Error getting link analytics")',+ ): _METRICS_DB_ONLY,+ (+ "web/routers/metrics.py",+ "api_journal_data_download",+ "exception-after-network",+ 'logger.exception("Error downloading journal data")',+ ): _METRICS_JOURNAL_FETCH,+ (+ "web/routers/metrics.py",+ "api_journal_quality",+ "exception-after-network",+ 'logger.exception("Error getting journal quality data")',+ ): _METRICS_DB_ONLY,+ (+ "web/routers/metrics.py",+ "api_user_research_journals",+ "exception-after-network",+ 'logger.exception("Error getting user research journals")',+ ): _METRICS_DB_ONLY,+ (+ "web/routers/metrics.py",+ "api_research_journals",+ "exception-after-network",+ 'logger.exception("Error getting per-research journals")',+ ): _METRICS_DB_ONLY,+}+++def _call_name(node: ast.AST) -> str | None:+ if isinstance(node, ast.Name):+ return node.id+ if isinstance(node, ast.Attribute):+ return node.attr+ return None+++def _logger_level(call: ast.Call) -> str | None:+ """``logger.X(...)``, ``logger.opt(...).X(...)``, ``logger.bind().X``."""+ func = call.func+ if not isinstance(func, ast.Attribute):+ return None+ base = func.value+ while isinstance(base, (ast.Call, ast.Attribute)):+ base = base.func if isinstance(base, ast.Call) else base.value+ if isinstance(base, ast.Name) and base.id == "logger":+ return func.attr+ return None+++def _attaches_traceback(call: ast.Call, level: str) -> bool:+ """``logger.exception`` or a receiver chain with+ ``opt(exception=X)`` where X is anything but a literal False/None:+ loguru then renders ``ExcType: str(e)`` whatever the final level."""+ if level == "exception":+ return True+ node = call.func.value+ while isinstance(node, (ast.Call, ast.Attribute)):+ if isinstance(node, ast.Call):+ if _call_name(node.func) == "opt":+ for kw in node.keywords:+ if kw.arg == "exception" and not (+ isinstance(kw.value, ast.Constant)+ and kw.value.value in (False, None)+ ):+ return True+ node = node.func+ else:+ node = node.value+ return False+++def _url_tainted(expr: ast.AST) -> bool:+ if isinstance(expr, ast.Call) and _call_name(expr.func) in SAFE_WRAPPERS:+ return False+ name = _call_name(expr)+ if name and URL_NAME.search(name) and not NOT_URL_NAME.search(name):+ return True+ return any(_url_tainted(child) for child in ast.iter_child_nodes(expr))+++def _exc_tainted(expr: ast.AST, exc_names: frozenset) -> bool:+ if (+ isinstance(expr, ast.Call)+ and _call_name(expr.func) == "type"+ and len(expr.args) == 1+ ):+ return False # type(e) / type(e).__name__+ if isinstance(expr, ast.Attribute) and expr.attr == "__class__":+ return False # e.__class__.__name__+ if isinstance(expr, ast.Name) and expr.id in exc_names:+ return True+ return any(+ _exc_tainted(child, exc_names) for child in ast.iter_child_nodes(expr)+ )+++def _try_makes_network_call(try_node: ast.Try) -> bool:+ for stmt in try_node.body:+ for node in ast.walk(stmt):+ if isinstance(node, ast.Call):+ name = _call_name(node.func)+ if name and NETWORK_CALL.match(name):+ return True+ return False+++Hit = tuple[str, str, str, int, str]+++def scan_source(source: str, rel: str) -> list[Hit]:+ """Return ``(rel, qualname, rule, lineno, call_text)`` for each+ offending call; ``call_text`` is the call's whitespace-normalised+ source."""+ hits: list[Hit] = []++ def visit(node, qual, exc_names, networked_except):+ if isinstance(+ node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)+ ):+ qual = f"{qual}.{node.name}" if qual else node.name+ if not isinstance(node, ast.ClassDef):+ exc_names = frozenset()+ networked_except = False+ if isinstance(node, ast.Try):+ networked = _try_makes_network_call(node)+ for child in node.body + node.orelse + node.finalbody:+ visit(child, qual, exc_names, networked_except)+ for handler in node.handlers:+ names = exc_names | (+ {handler.name} if handler.name else frozenset()+ )+ for child in handler.body:+ visit(child, qual, frozenset(names), networked)+ return+ if isinstance(node, ast.Call):+ level = _logger_level(node)+ if level in ALL_LEVELS:+ text = " ".join(+ (ast.get_source_segment(source, node) or "").split()+ )+ parts = list(node.args) + [kw.value for kw in node.keywords]+ if any(_url_tainted(p) for p in parts):+ hits.append((rel, qual, "raw-url", node.lineno, text))+ if exc_names and any(_exc_tainted(p, exc_names) for p in parts):+ hits.append((rel, qual, "exc-text", node.lineno, text))+ if networked_except and _attaches_traceback(node, level):+ hits.append(+ (+ rel,+ qual,+ "exception-after-network",+ node.lineno,+ text,+ )+ )+ for child in ast.iter_child_nodes(node):+ visit(child, qual, exc_names, networked_except)++ visit(ast.parse(source), "", frozenset(), False)+ return hits+++def unallowed(hits: list[Hit], allowed=None) -> list[str]:+ """Hits not exempted by an exact ``ALLOWED`` key."""+ allowed = ALLOWED if allowed is None else allowed+ return [+ f"{rel}:{lineno} {qual} [{rule}] {text}"+ for rel, qual, rule, lineno, text in hits+ if (rel, qual, rule, text) not in allowed+ ]+++def structural_offenders() -> list[str]:+ root = _src_root()+ offenders: list[str] = []+ for rel in SCANNED_RELATIVE:+ target = root / rel+ modules = sorted(target.rglob("*.py")) if target.is_dir() else [target]+ for module_path in modules:+ module_rel = module_path.relative_to(root).as_posix()+ hits = scan_source(+ module_path.read_text(encoding="utf-8"), module_rel+ )+ offenders += unallowed(hits)+ return offenders+++def captured_logs():+ messages: list[str] = []+ handler_id = logger.add(lambda m: messages.append(str(m)), level="DEBUG")+ logger.enable("local_deep_research")+ try:+ yield messages+ finally:+ logger.disable("local_deep_research")+ logger.remove(handler_id)+++#: Query-secret variant for the SSRF-rejection probe.+SECRET_URL = "https://user:[email protected]:9001/p?token=T0PSECRET"++#: Userinfo-secret variant for the extraction/conversion failure+#: probes: bare of path/query tokens so the id extractors fail before+#: any fetch attempt. (Their progress lines are redacted too; see+#: ``TestAttemptLinesAreRedacted``.)+SECRET_PLAIN_URL = "https://user:[email protected]:9001/"++#: A public-looking credentialed URL: passes SSRF validation (so the+#: request reaches the mocked transport), carries both secret kinds.+PUBLIC_SECRET_URL = (+ "https://user:[email protected]:8443/a.pdf?token=T0PSECRET"+)+++def _assert_no_secret(captured: list[str]) -> str:+ joined = "\n".join(captured)+ assert "hunter2-secret" not in joined, joined[-800:]+ assert "T0PSECRET" not in joined, joined[-800:]+ return joined+++def _quiet_rate_tracker(downloader) -> None:+ downloader.rate_tracker = MagicMock()+ downloader.rate_tracker.apply_rate_limit.return_value = 0.0+++def _base_download_pdf(url: str):+ """Drive ``BaseDownloader._download_pdf`` directly, isolating the+ base fetch's failure handling from the subclass override's progress+ line (pinned separately in ``TestAttemptLinesAreRedacted``)."""+ from local_deep_research.research_library.downloaders.base import (+ BaseDownloader,+ )+ from local_deep_research.research_library.downloaders.direct_pdf import (+ DirectPDFDownloader,+ )++ downloader = DirectPDFDownloader()+ _quiet_rate_tracker(downloader)+ return downloader, lambda: BaseDownloader._download_pdf(downloader, url)+++class TestStructural:+ def test_no_failure_path_logs_a_raw_url_or_exception_text(self):+ offenders = structural_offenders()+ assert offenders == [], (+ "failure-path log calls interpolate a raw URL or an exception "+ "text, or attach a traceback (logger.exception / "+ "opt(exception=...)) after a network-shaped call, in "+ f"SCANNED_RELATIVE (residuals: module docstring): {offenders}"+ )++ def test_allowlist_entries_are_live(self):+ """A stale ALLOWED entry would silently exempt a future offender."""+ root = _src_root()+ seen = set()+ for rel in {key[0] for key in ALLOWED}:+ source = (root / rel).read_text(encoding="utf-8")+ seen.update(+ (r, q, rule, text)+ for r, q, rule, _, text in scan_source(source, rel)+ )+ assert set(ALLOWED) <= seen, set(ALLOWED) - seen++ @pytest.mark.parametrize(+ "key", sorted(ALLOWED), ids=lambda key: f"{key[1]}:{key[2]}"+ )+ def test_allowlist_does_not_exempt_a_new_call_in_the_same_function(+ self, key+ ):+ """Plant a second offending call of the same rule next to each+ reviewed call, in the real module source: it must be reported+ although its (module, function, rule) matches the entry."""+ rel, qual, rule, _text = key+ source = (_src_root() / rel).read_text(encoding="utf-8")+ tree = ast.parse(source)+ lineno = next(+ h[3] for h in scan_source(source, rel) if h[:3] + h[4:] == key+ )+ handler = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.ExceptHandler)+ and node.lineno <= lineno <= node.end_lineno+ )+ planted = {+ "exc-text": f'logger.warning(f"planted {{{handler.name}}}")',+ "exception-after-network": 'logger.exception("planted")',+ "raw-url": 'logger.warning(f"planted {url}")',+ }[rule]+ lines = source.splitlines(keepends=True)+ target = lines[lineno - 1]+ indent = target[: len(target) - len(target.lstrip())]+ lines.insert(lineno - 1, f"{indent}{planted}\n")+ mutated = "".join(lines)++ assert unallowed(scan_source(source, rel)) == []+ reported = unallowed(scan_source(mutated, rel))+ assert len(reported) == 1 and "planted" in reported[0], reported++ @pytest.mark.parametrize(+ "snippet",+ [+ 'logger.warning(f"x {url}")',+ "logger.warning(f'x {url}')",+ 'logger.error(rf"x {url}")',+ 'logger.warning("x {}", url)',+ 'logger.warning("x {u}", u=url)',+ 'logger.warning(f"x {url!r}")',+ 'logger.warning(f"x {url=}")',+ 'logger.warning(f"x {pdf_url}")',+ 'logger.warning(f"x {self.base_url}")',+ 'logger.warning(f"x {url[:50]}")',+ 'logger.warning(f"x {str(url)}")',+ 'logger.warning(f"x {resource.url}")',+ 'logger.info(f"x {url}")',+ 'logger.debug(f"x {url}")',+ 'logger.trace("x {}", pdf_url)',+ 'logger.success(f"x {landing_url}")',+ 'logger.critical(f"x {url}")',+ 'logger.log("WARNING", f"x {url}")',+ 'logger.opt(depth=1).warning(f"x {url}")',+ 'logger.bind(a=1).error("x {}", redirect_url)',+ 'try:\n f()\nexcept Exception as e:\n logger.debug(f"x {e}")',+ "try:\n f()\nexcept Exception as exc:\n"+ ' logger.warning("x {}", exc)',+ "try:\n f()\nexcept Exception as e:\n"+ ' logger.warning(f"x {str(e)}")',+ "try:\n session.get(u)\nexcept Exception:\n"+ ' logger.exception("failed")',+ "try:\n session.get(u)\nexcept Exception:\n"+ ' logger.opt(exception=True).error("failed")',+ "try:\n session.get(u)\nexcept Exception as e:\n"+ ' logger.opt(exception=e).warning("failed")',+ "try:\n session.get(u)\nexcept Exception as e:\n"+ ' logger.opt(exception=e).log("ERROR", "failed")',+ "try:\n session.get(u)\nexcept Exception as e:\n"+ ' logger.bind(a=1).opt(exception=e).debug("failed")',+ "try:\n _probe_tags(u)\nexcept Exception:\n"+ ' logger.exception("failed")',+ ],+ )+ def test_scanner_flags_each_leak_shape(self, snippet):+ """Teeth: every shape the docstring claims is actually detected."""+ source = "def f():\n" + "".join(+ f" {line}\n" for line in snippet.splitlines()+ )+ assert scan_source(source, "probe.py"), snippet++ @pytest.mark.parametrize(+ "snippet",+ [+ 'logger.warning(f"x {redact_url_for_log(url)}")',+ 'logger.warning("x {}", ssrf_validator.redact_url_for_log(url))',+ 'logger.info(f"x {redact_url_for_log(url)}")',+ 'logger.debug(f"x {url_type.value}")',+ "try:\n f()\nexcept Exception as e:\n"+ ' logger.warning(f"x {type(e).__name__}")',+ "try:\n parse()\nexcept Exception:\n"+ ' logger.exception("failed")',+ "try:\n session.get(u)\nexcept Exception as e:\n"+ ' logger.opt(exception=False).warning(f"x {type(e).__name__}")',+ "try:\n session.get(u)\nexcept Exception:\n"+ ' logger.opt(exception=None).error("failed")',+ "try:\n session.get(u)\nexcept Exception:\n"+ ' logger.opt(depth=1).error("failed")',+ ],+ )+ def test_scanner_passes_safe_shapes(self, snippet):+ source = "def f():\n" + "".join(+ f" {line}\n" for line in snippet.splitlines()+ )+ assert scan_source(source, "probe.py") == [], snippet+++class TestRedactHelperIsTotal:+ """The helper runs inside failure handlers — it must never raise."""++ @pytest.mark.parametrize(+ ("value", "expected"),+ [+ (123, "<unparseable:int>"),+ (b"x", "<unparseable:bytes>"),+ ([], "<unparseable:list>"),+ (None, "<unparseable:NoneType>"),+ ],+ )+ def test_non_string_input_returns_placeholder(self, value, expected):+ from local_deep_research.security import redact_url_for_log++ assert redact_url_for_log(value) == expected++ def test_schemeless_userinfo_does_not_leak_username(self):+ from local_deep_research.security import redact_url_for_log++ # urllib3 reads "user" as the scheme when there is no "//".+ result = redact_url_for_log("user:[email protected]/p")+ assert "user" not in result and "hunter2" not in result+ assert result == "?://<no-host>"++ def test_is_downloadable_domain_non_string_is_false(self):+ from local_deep_research.research_library.utils import (+ is_downloadable_domain,+ )++ assert is_downloadable_domain(123) is False++ def test_direct_pdf_can_handle_non_string_is_false(self):+ from local_deep_research.research_library.downloaders.direct_pdf import (+ DirectPDFDownloader,+ )++ assert DirectPDFDownloader().can_handle(123) is False+++class TestBehavioralSeams:+ def test_arxiv_id_extraction_failure_redacts(self, captured_logs):+ from local_deep_research.research_library.downloaders.arxiv import (+ ArxivDownloader,+ )++ downloader = ArxivDownloader()+ with patch.object(downloader, "_extract_arxiv_id", return_value=None):+ result = downloader._download_pdf(SECRET_PLAIN_URL)++ assert result is None # arrival: the failure branch ran+ joined = _assert_no_secret(captured_logs)+ assert "https://127.0.0.1:9001" in joined, joined[-400:]++ def test_biorxiv_conversion_failure_redacts(self, captured_logs):+ from local_deep_research.research_library.downloaders.biorxiv import (+ BioRxivDownloader,+ )++ downloader = BioRxivDownloader()+ with patch.object(downloader, "_convert_to_pdf_url", return_value=None):+ result = downloader._download_pdf(SECRET_PLAIN_URL)++ assert result is None # arrival: the failure branch ran+ joined = _assert_no_secret(captured_logs)+ assert "https://127.0.0.1:9001" in joined, joined[-400:]++ def test_api_ssrf_rejection_redacts(self, captured_logs, monkeypatch):+ import asyncio++ from local_deep_research.web.routers.api import api_add_resource++ class _FakeRequest:+ headers = {"content-type": "application/json"}++ async def json(self):+ return {"url": SECRET_URL, "title": "probe"}++ # Force the SSRF rejection branch: the validator is imported+ # inside the route, so patch it at its home module.+ monkeypatch.setattr(+ "local_deep_research.security.ssrf_validator.validate_url",+ lambda _url: False,+ )+ response = asyncio.run(+ api_add_resource(_FakeRequest(), research_id="r1", username="u")+ )++ assert response.status_code == 400+ joined = _assert_no_secret(captured_logs)+ assert "https://127.0.0.1:9001" in joined, joined[-400:]+++class TestExceptionTextNeverReachesTheLog:+ """The formatted record — message *and* exception section — must not+ carry the URL that the raised exception's text embeds."""++ def test_safesession_refusal_valueerror(self, captured_logs):+ """SafeSession raises ``ValueError("URL failed security validation+ (possible SSRF): <url>")`` for a private target."""+ _downloader, run = _base_download_pdf(SECRET_URL)+ result = run()++ assert result is None+ joined = _assert_no_secret(captured_logs)+ assert "ValueError" in joined # arrival: the handler logged+ assert "https://127.0.0.1:9001" in joined, joined[-400:]++ @pytest.mark.parametrize(+ "exc",+ [+ requests.exceptions.ConnectionError(+ "HTTPSConnectionPool(host='papers.example.com', port=8443): "+ "Max retries exceeded with url: /a.pdf?token=T0PSECRET "+ f"({PUBLIC_SECRET_URL})"+ ),+ requests.exceptions.HTTPError(+ f"403 Client Error: Forbidden for url: {PUBLIC_SECRET_URL}"+ ),+ RuntimeError(f"unexpected failure fetching {PUBLIC_SECRET_URL}"),+ ],+ ids=["connection-error", "http-error", "unexpected"],+ )+ def test_base_download_pdf_request_failures(self, captured_logs, exc):+ downloader, run = _base_download_pdf(PUBLIC_SECRET_URL)+ with patch.object(downloader.session, "get", side_effect=exc) as get:+ result = run()++ assert result is None+ assert get.called # arrival: the transport was reached+ joined = _assert_no_secret(captured_logs)+ assert type(exc).__name__ in joined, joined[-400:]+ assert "https://papers.example.com:8443" in joined, joined[-400:]++ def test_html_fetch_failure(self, captured_logs):+ from local_deep_research.research_library.downloaders.html import (+ HTMLDownloader,+ )++ downloader = HTMLDownloader()+ _quiet_rate_tracker(downloader)+ exc = requests.exceptions.ConnectionError(+ f"Max retries exceeded with url: {PUBLIC_SECRET_URL}"+ )+ with patch.object(downloader.session, "get", side_effect=exc):+ result = downloader.download(PUBLIC_SECRET_URL)++ assert result is None+ joined = _assert_no_secret(captured_logs)+ assert "ConnectionError" in joined, joined[-400:]++ def test_download_service_generic_http_error(self, captured_logs):+ from local_deep_research.research_library.services import (+ download_service as ds,+ )++ response = MagicMock()+ response.raise_for_status.side_effect = requests.exceptions.HTTPError(+ f"404 Client Error: Not Found for url: {PUBLIC_SECRET_URL}"+ )+ service = ds.DownloadService.__new__(ds.DownloadService)+ with patch.object(ds, "safe_get", return_value=response):+ result = service._download_generic(PUBLIC_SECRET_URL)++ assert result is None+ joined = _assert_no_secret(captured_logs)+ assert "HTTPError" in joined, joined[-400:]+ assert "https://papers.example.com:8443" in joined, joined[-400:]++ def test_rate_limit_key_drops_userinfo(self):+ from local_deep_research.research_library.downloaders.base import (+ rate_limit_authority,+ )++ assert (+ rate_limit_authority(PUBLIC_SECRET_URL) == "papers.example.com:8443"+ )+ assert rate_limit_authority("https://example.com/x") == "example.com"+++class TestAttemptLinesAreRedacted:+ """The INFO/DEBUG attempt lines run before every fetch — including+ the ones that fail — so they must carry the redacted URL only."""++ @staticmethod+ def _failing_transport(downloader):+ _quiet_rate_tracker(downloader)+ exc = requests.exceptions.ConnectionError("refused")+ return (+ patch.object(downloader.session, "get", side_effect=exc),+ patch.object(downloader.session, "head", side_effect=exc),+ )++ @pytest.mark.parametrize(+ ("module", "cls", "method"),+ [+ ("direct_pdf", "DirectPDFDownloader", "download_with_result"),+ ("direct_pdf", "DirectPDFDownloader", "_download_pdf"),+ ("generic", "GenericDownloader", "download_with_result"),+ ("generic", "GenericDownloader", "_download_pdf"),+ ],+ )+ def test_downloader_attempt_lines(self, captured_logs, module, cls, method):+ import importlib++ mod = importlib.import_module(+ f"local_deep_research.research_library.downloaders.{module}"+ )+ downloader = getattr(mod, cls)()+ # No ".pdf" suffix: GenericDownloader also logs its ".pdf" retry.+ url = "https://user:[email protected]:8443/a?token=T0PSECRET"+ get_patch, head_patch = self._failing_transport(downloader)+ with get_patch as get, head_patch:+ getattr(downloader, method)(url)++ assert get.called # arrival: a fetch was attempted+ joined = _assert_no_secret(captured_logs)+ assert "https://papers.example.com:8443" in joined, joined[-400:]++ def test_biorxiv_attempt_line(self, captured_logs):+ from local_deep_research.research_library.downloaders.biorxiv import (+ BioRxivDownloader,+ )++ downloader = BioRxivDownloader()+ get_patch, head_patch = self._failing_transport(downloader)+ with (+ patch.object(+ downloader,+ "_convert_to_pdf_url",+ return_value=PUBLIC_SECRET_URL,+ ),+ get_patch as get,+ head_patch,+ ):+ downloader._download_pdf(PUBLIC_SECRET_URL)++ assert get.called+ joined = _assert_no_secret(captured_logs)+ assert "bioRxiv/medRxiv PDF from https://papers.example.com:8443" in (+ joined+ ), joined[-400:]+++class TestRateLimitKeyCallSite:+ """The rate-limit key is persisted and logged: the call sites must+ feed it through ``rate_limit_authority``, not ``urlparse().netloc``."""++ def test_html_fetch_engine_type_has_no_userinfo(self):+ from local_deep_research.research_library.downloaders.html import (+ HTMLDownloader,+ )++ downloader = HTMLDownloader()+ _quiet_rate_tracker(downloader)+ exc = requests.exceptions.ConnectionError("refused")+ with patch.object(downloader.session, "get", side_effect=exc):+ downloader.download(PUBLIC_SECRET_URL)++ tracker = downloader.rate_tracker+ engine_types = [+ c.kwargs.get("engine_type", c.args[0] if c.args else None)+ for c in tracker.apply_rate_limit.call_args_list+ + tracker.record_outcome.call_args_list+ ]+ assert engine_types, "rate tracker was never consulted"+ assert all(+ et == "html_download_papers.example.com:8443" for et in engine_types+ ), engine_types++ def test_base_pdf_engine_type_has_no_userinfo(self):+ downloader, run = _base_download_pdf(PUBLIC_SECRET_URL)+ exc = requests.exceptions.ConnectionError("refused")+ with patch.object(downloader.session, "get", side_effect=exc):+ run()++ calls = downloader.rate_tracker.apply_rate_limit.call_args_list+ assert calls, "rate tracker was never consulted"+ for c in calls:+ engine_type = c.kwargs.get(+ "engine_type", c.args[0] if c.args else ""+ )+ assert "hunter2-secret" not in engine_type+ assert "user" not in engine_type+ assert "papers.example.com:8443" in engine_type+++#: Presigned + credentialed URL for the safe_requests raise sites.+PRESIGNED_URL = (+ "https://usr-SECRET:[email protected]/p/path-SECRET"+ "?X-Amz-Signature=SIG-SECRET&token=TOK-SECRET"+)+PRESIGNED_SECRETS = (+ "usr-SECRET",+ "pw-SECRET",+ "path-SECRET",+ "SIG-SECRET",+ "TOK-SECRET",+)+++class _FakeResponse:+ def __init__(self, status_code=200, location=None, url=None):+ self.status_code = status_code+ self.headers = {"Location": location} if location else {}+ self.url = url+ self.closed = False++ def close(self):+ self.closed = True+++class TestSafeRequestsExceptionTexts:+ """``safe_requests`` exception messages flow into caller logs+ (``ExcType: str(e)``) and DB error columns: each raise site must name+ only ``scheme://host[:port]`` of the refused URL."""++ @staticmethod+ def _assert_redacted(message: str, host: str = "https://evil.example"):+ for secret in PRESIGNED_SECRETS:+ assert secret not in message, message+ assert host in message, message++ @pytest.fixture+ def sr(self, monkeypatch):+ from contextlib import nullcontext++ from local_deep_research.security import safe_requests++ monkeypatch.setattr(+ safe_requests.dns_pinning,+ "pinned_request",+ lambda *a, **k: nullcontext(),+ )+ return safe_requests++ @staticmethod+ def _validator(monkeypatch, sr, refuse=lambda url: True):+ monkeypatch.setattr(+ sr.ssrf_validator,+ "validate_url",+ lambda url, *a, **k: not refuse(url),+ )++ @pytest.mark.parametrize("func", ["safe_get", "safe_post"])+ def test_initial_validation_refusal(self, sr, monkeypatch, func):+ self._validator(monkeypatch, sr)+ with pytest.raises(ValueError, match="possible SSRF") as excinfo:+ getattr(sr, func)(PRESIGNED_URL)+ self._assert_redacted(str(excinfo.value))++ @staticmethod+ def _transport(monkeypatch, sr, response):+ """Stub both verbs: a 302 hop out of safe_post continues as GET."""+ for verb in ("get", "post"):+ monkeypatch.setattr(sr.requests, verb, lambda *a, **k: response)++ @pytest.mark.parametrize("func", ["safe_get", "safe_post"])+ def test_redirect_target_refusal(self, sr, monkeypatch, func):+ self._validator(monkeypatch, sr, refuse=lambda url: "evil" in url)+ self._transport(+ monkeypatch, sr, _FakeResponse(302, location=PRESIGNED_URL)+ )+ with pytest.raises(ValueError, match="Redirect target") as excinfo:+ getattr(sr, func)("https://origin.example/start")+ self._assert_redacted(str(excinfo.value))++ def test_require_https_initial_refusal(self, sr):+ with pytest.raises(ValueError, match="must use https") as excinfo:+ sr.safe_get(+ PRESIGNED_URL.replace("https://", "http://"),+ require_https=True,+ )+ self._assert_redacted(str(excinfo.value), host="http://evil.example")++ def test_require_https_redirect_downgrade_refusal(self, sr, monkeypatch):+ self._validator(monkeypatch, sr, refuse=lambda url: False)+ self._transport(+ monkeypatch,+ sr,+ _FakeResponse(+ 302, location=PRESIGNED_URL.replace("https://", "http://")+ ),+ )+ with pytest.raises(ValueError, match="downgrade") as excinfo:+ sr.safe_get("https://origin.example/start", require_https=True)+ self._assert_redacted(str(excinfo.value), host="http://evil.example")++ @pytest.mark.parametrize("func", ["safe_get", "safe_post"])+ def test_too_many_redirects(self, sr, monkeypatch, func):+ self._validator(monkeypatch, sr, refuse=lambda url: False)+ self._transport(+ monkeypatch, sr, _FakeResponse(302, location="/p/path-SECRET/n")+ )+ with pytest.raises(ValueError, match="Too many redirects") as excinfo:+ getattr(sr, func)(PRESIGNED_URL)+ self._assert_redacted(str(excinfo.value))++ def test_safe_post_body_scope_refusal(self, sr, monkeypatch):+ self._validator(monkeypatch, sr, refuse=lambda url: False)+ self._transport(+ monkeypatch, sr, _FakeResponse(307, location=PRESIGNED_URL)+ )+ with pytest.raises(ValueError, match="outside") as excinfo:+ sr.safe_post("https://origin.example/submit", data="body")+ self._assert_redacted(str(excinfo.value))++ def test_session_request_refusal(self, sr, monkeypatch):+ self._validator(monkeypatch, sr)+ with pytest.raises(ValueError, match="possible SSRF") as excinfo:+ sr.SafeSession().request("GET", PRESIGNED_URL)+ self._assert_redacted(str(excinfo.value))++ def test_session_send_refusal(self, sr, monkeypatch):+ self._validator(monkeypatch, sr)+ prepared = requests.Request("GET", PRESIGNED_URL).prepare()+ with pytest.raises(ValueError, match="Redirect target") as excinfo:+ sr.SafeSession().send(prepared)+ self._assert_redacted(str(excinfo.value))++ def test_session_rebuild_auth_body_refusal(self, sr):+ prepared = requests.Request(+ "POST", PRESIGNED_URL, data="body"+ ).prepare()+ response = MagicMock()+ response.request.url = "https://origin.example/submit"+ with pytest.raises(ValueError, match="outside") as excinfo:+ sr.SafeSession().rebuild_auth(prepared, response)+ self._assert_redacted(str(excinfo.value))+++#: What ``DownloadService``'s exception path returns for a request+#: failure: ``sanitize_error_for_client(str(e))`` strips credential+#: shapes but keeps the scheme-less path and query of urllib3's text.+PRESIGNED_REASON = (+ "HTTPSConnectionPool(host='bucket.example', port=443): Max retries "+ "exceeded with url: /a.pdf?X-Amz-Signature=T0PSECRET&sig=T0PSECRET"+)+++def _reason_log_names_unwrapped(source: str, names: set[str]) -> list[int]:+ """Line numbers of logger calls that reference one of *names* outside+ a ``failure_reason_for_log(...)`` call. A dotted name+ (``filter_result.reason``) matches that attribute access."""+ lines: list[int] = []++ def walk(node):+ if (+ isinstance(node, ast.Call)+ and _call_name(node.func) == "failure_reason_for_log"+ ):+ return+ if isinstance(node, ast.Name) and node.id in names:+ lines.append(node.lineno)+ if isinstance(node, ast.Attribute) and ast.unparse(node) in names:+ lines.append(node.lineno)+ for child in ast.iter_child_nodes(node):+ walk(child)++ for node in ast.walk(ast.parse(source)):+ if isinstance(node, ast.Call) and _logger_level(node) in ALL_LEVELS:+ for part in list(node.args) + [kw.value for kw in node.keywords]:+ walk(part)+ return lines+++class TestFailureReasonLogging:+ """``download_resource`` / ``download_as_text`` failure reasons can be+ exception text that keeps a presigned query; every log line that+ repeats them goes through ``failure_reason_for_log``."""++ @pytest.mark.parametrize(+ "reason",+ [+ PRESIGNED_REASON,+ "Invalid URL 'user:[email protected]': No scheme",+ "Failed to extract arXiv text: x?token=T0PSECRET",+ "bad fragment #T0PSECRET",+ "path;param=T0PSECRET",+ "C:\\T0PSECRET",+ ],+ )+ def test_helper_withholds_url_bearing_reasons(self, reason):+ from local_deep_research.security import failure_reason_for_log+ from local_deep_research.security.log_sanitizer import (+ FAILURE_REASON_WITHHELD,+ )++ assert failure_reason_for_log(reason) == FAILURE_REASON_WITHHELD++ @pytest.mark.parametrize(+ ("reason", "expected"),+ [+ (+ "egress_policy_denied:private_ip",+ "egress_policy_denied:private_ip",+ ),+ (+ "No compatible downloader available",+ "No compatible downloader available",+ ),+ (None, "None"),+ (42, "<int>"),+ ],+ )+ def test_helper_keeps_categories(self, reason, expected):+ from local_deep_research.security import failure_reason_for_log++ assert failure_reason_for_log(reason) == expected++ @pytest.mark.parametrize(+ "reason",+ [+ # generic.py, with a server-sent content type+ "Unexpected content type: text/html - expected PDF",+ # pubmed.py / biorxiv.py fixed literals+ "Full text not available from the PubMed/PMC APIs",+ "Article not found on bioRxiv/medRxiv",+ ],+ )+ def test_helper_withholds_fixed_reasons_with_a_delimiter(self, reason):+ """Fail-closed on shape, not origin: a fixed, URL-free reason that+ contains one of ``/ \\ ? # @ ;`` is withheld as well. Pins that+ trade-off so it cannot be relaxed into a URL-detection heuristic+ without a deliberate test change."""+ from local_deep_research.security import failure_reason_for_log+ from local_deep_research.security.log_sanitizer import (+ FAILURE_REASON_WITHHELD,+ )++ assert failure_reason_for_log(reason) == FAILURE_REASON_WITHHELD++ @pytest.mark.parametrize(+ ("rel", "names"),+ [+ (+ "web/routers/library.py",+ {"error", "skip_reason", "error_msg", "filter_result.reason"},+ ),+ (+ "library/download_management/failure_classifier.py",+ {"details"},+ ),+ (+ "research_library/services/download_service.py",+ {"skip_reason", "error_msg", "error", "retry_decision.reason"},+ ),+ (+ "scheduler/background.py",+ {"error"},+ ),+ (+ "research_library/downloaders/extraction/pipeline.py",+ {+ "skip_reason",+ "specialized.skip_reason",+ "failure.skip_reason",+ },+ ),+ ],+ )+ def test_reason_log_sites_are_wrapped(self, rel, names):+ source = (_src_root() / rel).read_text(encoding="utf-8")+ assert _reason_log_names_unwrapped(source, names) == []++ def test_reason_scan_flags_an_unwrapped_site(self):+ source = 'logger.warning(f"failed: {error}")\n'+ assert _reason_log_names_unwrapped(source, {"error"}) == [1]++ def test_reason_scan_flags_an_unwrapped_attribute(self):+ source = (+ 'logger.info("skip {}: {}", rid, decision.reason)\n'+ 'logger.info(f"ok: {failure_reason_for_log(decision.reason)}")\n'+ )+ assert _reason_log_names_unwrapped(source, {"decision.reason"}) == [1]++ @staticmethod+ def _download_context(method: str, result):+ service = MagicMock()+ getattr(service, method).return_value = result+ context = MagicMock()+ context.__enter__.return_value = service+ context.__exit__.return_value = False+ return context++ @staticmethod+ def _request(path: str):+ from starlette.requests import Request++ return Request(+ {+ "type": "http",+ "method": "POST",+ "path": path,+ "headers": [],+ "query_string": b"",+ }+ )++ @pytest.mark.parametrize(+ ("route", "method"),+ [+ ("download_single_resource", "download_resource"),+ ("download_text_single", "download_as_text"),+ ],+ )+ def test_single_download_routes_withhold_reason(+ self, captured_logs, route, method+ ):+ from local_deep_research.web.routers import library as library_module++ context = self._download_context(method, (False, PRESIGNED_REASON))+ with (+ patch.object(+ library_module,+ "get_authenticated_user_password",+ return_value="pw",+ ),+ patch.object(+ library_module, "DownloadService", return_value=context+ ),+ ):+ getattr(library_module, route)(+ self._request("/library/api/download/7"),+ resource_id=7,+ username="alice",+ )++ joined = _assert_no_secret(captured_logs)+ # arrival: the failure line ran and named the resource+ assert "failed for resource 7" in joined, joined[-400:]++ @pytest.mark.parametrize("path", ["fallback", "single", "batch"])+ def test_pipeline_reasons_are_withheld(+ self, captured_logs, monkeypatch, path+ ):+ from local_deep_research.research_library.downloaders.base import (+ DownloadResult,+ )+ from local_deep_research.research_library.downloaders.extraction import (+ pipeline,+ )+ from tests.test_utils import restored_loguru_state++ url = "https://pubmed.ncbi.nlm.nih.gov/1/"+ with restored_loguru_state():+ # Assert the call sites themselves protect the reason, even+ # without the application-wide logging redaction patcher.+ logger.configure(patcher=lambda record: None)+ logger.add(+ lambda message: captured_logs.append(str(message)),+ level="DEBUG",+ )+ logger.info("redaction canary {}", PRESIGNED_REASON)+ assert "T0PSECRET" in "\n".join(captured_logs)+ captured_logs.clear()+ if path == "fallback":+ downloader = MagicMock()+ downloader.download_with_result.return_value = DownloadResult(+ skip_reason=PRESIGNED_REASON+ )+ monkeypatch.setattr(+ "local_deep_research.research_library.downloaders.pubmed.PubMedDownloader",+ lambda **kwargs: downloader,+ )+ result = pipeline._try_specialized_downloader(url)+ assert result.fallback_allowed is True+ assert result.skip_reason == PRESIGNED_REASON+ expected_log = "falling back to HTML pipeline"+ else:+ monkeypatch.setattr(+ pipeline,+ "_try_specialized_downloader",+ lambda *args, **kwargs: pipeline._SpecializedResult(+ fallback_allowed=False, skip_reason=PRESIGNED_REASON+ ),+ )+ if path == "single":+ assert pipeline.fetch_and_extract(url) is None+ else:+ assert pipeline.batch_fetch_and_extract([url]) == {+ url: None+ }+ expected_log = "terminal specialized download failed"++ joined = _assert_no_secret(captured_logs)+ assert expected_log in joined+ assert "<withheld: may embed a URL>" in joined++ def test_classifier_unclassified_warning_withholds_reason(+ self, captured_logs+ ):+ from local_deep_research.library.download_management.failure_classifier import (+ FailureClassifier,+ )++ failure = FailureClassifier().classify_failure(+ error_type="str", details=PRESIGNED_REASON+ )++ assert failure.error_type == "unknown_error"+ joined = _assert_no_secret(captured_logs)+ assert "Unclassified error" in joined, joined[-400:]++ def test_classifier_rate_limit_domain_drops_userinfo(self, captured_logs):+ from local_deep_research.library.download_management.failure_classifier import (+ FailureClassifier,+ )++ failure = FailureClassifier().classify_failure(+ error_type="http_error", status_code=429, url=PUBLIC_SECRET_URL+ )++ assert failure.domain == "papers.example.com:8443"+ assert "hunter2-secret" not in failure.message+ _assert_no_secret(captured_logs)+++class TestDomainKeyDropsUserinfo:+ """Domains derived from stored resource URLs carry no userinfo.++ ``urlparse(...).netloc`` keeps ``user:pass@``, so a credentialed+ resource URL used to put the credentials into the classifier's+ progress logs, its results payload and the persisted+ ``DomainClassification.domain`` key. The classifier's failure+ handlers log only the exception type, since their frames hold the+ raw resource URLs.+ """++ CLEAN_DOMAIN = "papers.example.com:8443"++ @staticmethod+ def _session(resource_rows):+ session = MagicMock()+ session.query.return_value.distinct.return_value.all.return_value = (+ resource_rows+ )+ session.query.return_value.filter_by.return_value.first.return_value = (+ None+ )+ session.query.return_value.filter.return_value.limit.return_value.all.return_value = []+ return session++ @staticmethod+ def _run(session, llm, force_update=True):+ from local_deep_research.domain_classifier import classifier as mod++ clf = mod.DomainClassifier(username="alice", settings_snapshot={})+ progress = []+ with (+ patch.object(mod, "get_user_db_session") as mock_gs,+ patch.object(clf, "_get_llm", return_value=llm),+ ):+ mock_gs.return_value.__enter__ = MagicMock(return_value=session)+ mock_gs.return_value.__exit__ = MagicMock(return_value=False)+ results = clf.classify_all_domains(+ force_update=force_update, progress_callback=progress.append+ )+ return results, progress++ def test_persisted_domain_and_logs_drop_userinfo(self, captured_logs):+ session = self._session([(PUBLIC_SECRET_URL,)])+ llm = MagicMock()+ llm.invoke.return_value = MagicMock(+ content='{"category": "Other", "subcategory": "Unknown", '+ '"confidence": 0.5, "reasoning": "r"}'+ )++ results, progress = self._run(session, llm)++ added = [c.args[0] for c in session.add.call_args_list]+ assert [a.domain for a in added] == [self.CLEAN_DOMAIN]+ assert results["classified"] == 1+ assert results["domains"][0]["domain"] == self.CLEAN_DOMAIN+ assert progress[0]["domain"] == self.CLEAN_DOMAIN+ assert "hunter2-secret" not in repr(results)+ # the LLM prompt names the domain, not the credentials+ assert "hunter2-secret" not in llm.invoke.call_args.args[0]+ joined = _assert_no_secret(captured_logs)+ assert f"Processing domain 1/1: {self.CLEAN_DOMAIN}" in joined++ def test_classify_failure_logs_type_only(self, captured_logs):+ session = self._session([(PUBLIC_SECRET_URL,)])+ llm = MagicMock()+ llm.invoke.side_effect = RuntimeError(f"boom {PUBLIC_SECRET_URL}")++ results, _ = self._run(session, llm)++ assert results["failed"] == 1+ joined = _assert_no_secret(captured_logs)+ assert "RuntimeError" in joined, joined[-400:]++ def test_per_domain_handler_logs_type_only(self, captured_logs):+ session = self._session([(PUBLIC_SECRET_URL,)])+ session.query.return_value.filter_by.return_value.first.side_effect = (+ RuntimeError(f"db echo {PUBLIC_SECRET_URL}")+ )++ results, _ = self._run(session, MagicMock(), force_update=False)++ assert results["failed"] == 1+ joined = _assert_no_secret(captured_logs)+ assert "RuntimeError" in joined, joined[-400:]++ def test_outer_handler_logs_type_only(self, captured_logs):+ session = MagicMock()+ session.query.return_value.distinct.return_value.all.side_effect = (+ RuntimeError(f"db echo {PUBLIC_SECRET_URL}")+ )++ results, _ = self._run(session, MagicMock())++ assert results["error"] == "Classification failed"+ joined = _assert_no_secret(captured_logs)+ assert "RuntimeError" in joined, joined[-400:]++ def test_metrics_extract_domain_matches_classifier_key(self):+ from local_deep_research.web.routers.metrics import _extract_domain++ assert _extract_domain(PUBLIC_SECRET_URL) == self.CLEAN_DOMAIN+ assert (+ _extract_domain("https://[email protected]/x") == "example.com"+ )++ def test_llm_rate_limit_key_drops_userinfo(self):+ from types import SimpleNamespace++ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ create_rate_limited_llm_wrapper,+ )++ llm = SimpleNamespace(+ base_url="https://user:[email protected]:8443/v1",+ model_name="m",+ )+ key = create_rate_limited_llm_wrapper(+ llm, provider="openai"+ )._get_rate_limit_key()++ assert key == "openai-llm.example.com:8443-m"+++class TestLibraryDomainsDropUserinfo:+ """The library page's domain filter, its research PDF previews and+ the collection search results show a domain derived from a stored+ URL; ``urlparse(...).netloc`` keeps ``user:pass@``, so each strips+ the userinfo before the domain reaches the UI or a JSON response."""++ CLEAN_DOMAIN = "papers.example.com:8443"++ @staticmethod+ def _library_service():+ from local_deep_research.research_library.services.library_service import (+ LibraryService,+ )++ with patch.object(+ LibraryService, "__init__", lambda self, username: None+ ):+ service = LibraryService.__new__(LibraryService)+ service.username = "alice"+ return service++ def test_unique_domains_drop_userinfo(self):+ from local_deep_research.research_library.services import (+ library_service as mod,+ )++ service = self._library_service()+ session = MagicMock()+ session.query.return_value.filter.return_value.yield_per.return_value = [+ (PUBLIC_SECRET_URL,),+ ("https://papers.example.com:8443/b.pdf",),+ ]+ with patch.object(mod, "get_user_db_session") as mock_gs:+ mock_gs.return_value.__enter__.return_value = session+ mock_gs.return_value.__exit__.return_value = False+ domains = service.get_unique_domains()++ assert domains == [self.CLEAN_DOMAIN]+ assert service._extract_domain(PUBLIC_SECRET_URL) == self.CLEAN_DOMAIN++ def test_domain_filter_still_matches_a_credentialed_url(self):+ """Filtering by the stripped domain finds the stored credentialed+ URL: the filter is a substring match on ``original_url``."""+ from sqlalchemy import Column, Integer, String, create_engine+ from sqlalchemy.orm import Session, declarative_base++ base = declarative_base()++ class Doc(base):+ __tablename__ = "doc"+ id = Column(Integer, primary_key=True)+ original_url = Column(String)++ engine = create_engine("sqlite://")+ base.metadata.create_all(engine)+ service = self._library_service()+ with Session(engine) as session:+ session.add_all(+ [+ Doc(id=1, original_url=PUBLIC_SECRET_URL),+ Doc(id=2, original_url="https://other.example/c.pdf"),+ ]+ )+ session.commit()+ domain = service._extract_domain(PUBLIC_SECRET_URL)+ query = service._apply_domain_filter(+ session.query(Doc.id), Doc, domain+ )+ assert [row.id for row in query.all()] == [1]++ def test_pdf_previews_batch_domains_drop_userinfo(self):+ from local_deep_research.research_library.services import (+ library_service as mod,+ )++ def doc(doc_id, url):+ return MagicMock(+ id=doc_id,+ research_id="r1",+ file_type="pdf",+ status="completed",+ original_url=url,+ filename="a.pdf",+ )++ resource = MagicMock(url=PUBLIC_SECRET_URL, title="A")+ rows = [+ (doc("d1", "https://x.example/unused"), resource),+ (doc("d2", PUBLIC_SECRET_URL), None),+ ]+ session = MagicMock()+ chain = session.query.return_value.outerjoin.return_value+ chain.filter.return_value.order_by.return_value.limit.return_value.all.return_value = rows+ service = self._library_service()+ with patch.object(mod, "get_user_db_session") as mock_gs:+ mock_gs.return_value.__enter__.return_value = session+ mock_gs.return_value.__exit__.return_value = False+ previews = service.get_pdf_previews_batch(["r1"])++ entry = previews["r1"]+ assert list(entry["domains"]) == [self.CLEAN_DOMAIN]+ assert entry["domains"][self.CLEAN_DOMAIN]["total"] == 2+ assert [s["domain"] for s in entry["pdf_sources"]] == [+ self.CLEAN_DOMAIN+ ] * 2+ assert "hunter2-secret" not in repr(previews)++ def test_collection_search_domain_drops_userinfo(self):+ from local_deep_research.web.routers.library_search import (+ _enrich_with_document_metadata,+ )++ row = MagicMock(+ document_id="d1",+ file_type="pdf",+ original_url=PUBLIC_SECRET_URL,+ created_at=None,+ )+ session = MagicMock()+ session.query.return_value.filter.return_value.all.return_value = [row]+ results = [{"document_id": "d1"}]+ with patch(+ "local_deep_research.database.session_context.get_user_db_session"+ ) as mock_gs:+ mock_gs.return_value.__enter__.return_value = session+ mock_gs.return_value.__exit__.return_value = False+ _enrich_with_document_metadata(results, "alice", "pw")++ assert results[0]["domain"] == self.CLEAN_DOMAIN+ assert "hunter2-secret" not in repr(results)+++#: URLs whose userinfo holds an unencoded ``/``, ``?`` or ``#``: the+#: parser ends the netloc inside the userinfo, so ``netloc.rpartition("@")``+#: would keep ``user:<start of password>`` (or a delimiter-split username).+AMBIGUOUS_AUTHORITY_URLS = [+ "https://alice:hunter2-secret#[email protected]/a.pdf",+ "https://AKIAX:hunter2-secret/[email protected]/a.pdf",+ "https://alice:[email protected]/a.pdf",+ "https://hunter2-secret/[email protected]/a.pdf",+ "https://hunter2-secret:12#[email protected]/a.pdf",+]+++class TestUrlAuthorityWithoutUserinfo:+ """``url_authority_without_userinfo`` is the one helper every domain+ and key derivation uses: ordinary URLs keep their exact+ ``urlparse(...).netloc`` (so persisted keys stay stable), userinfo is+ dropped, and an ambiguous or unparseable authority yields ``""``."""++ @pytest.mark.parametrize(+ "url",+ [+ "https://arxiv.org/abs/2301.00001",+ "https://EXAMPLE.com:8080/p",+ "https://www.example.com",+ "https://medium.com/@user/post",+ "http://localhost:8080/[email protected]",+ "http://10.0.0.1/a@b",+ "https://a.example?x=@y",+ "http://[::1]:8080/x",+ "http://intranet/",+ "https://host.example:/p",+ ],+ )+ def test_ordinary_urls_keep_the_parsed_netloc(self, url):+ from urllib.parse import urlparse++ from local_deep_research.security import (+ url_authority_without_userinfo,+ )++ assert url_authority_without_userinfo(url) == urlparse(url).netloc++ @pytest.mark.parametrize(+ ("url", "expected"),+ [+ (PUBLIC_SECRET_URL, "papers.example.com:8443"),+ ("https://u:p@[email protected]/", "papers.example.com"),+ ("https://u:hunter2-secret@[::1]:80/", "[::1]:80"),+ ("https://[email protected]/x", "www.Example.com"),+ ],+ )+ def test_userinfo_is_dropped(self, url, expected):+ from local_deep_research.security import (+ url_authority_without_userinfo,+ )++ assert url_authority_without_userinfo(url) == expected++ @pytest.mark.parametrize("url", AMBIGUOUS_AUTHORITY_URLS)+ def test_ambiguous_authority_fails_closed(self, url):+ from local_deep_research.security import (+ url_authority_without_userinfo,+ )++ assert url_authority_without_userinfo(url) == ""++ @pytest.mark.parametrize(+ "value",+ [+ None,+ b"https://x.example/",+ 42,+ "",+ "not a url",+ "http://[::1/",+ "https://host.example:99999/",+ "http://intranet/@x",+ ],+ )+ def test_non_str_and_unparseable_yield_empty(self, value):+ from local_deep_research.security import (+ url_authority_without_userinfo,+ )++ assert url_authority_without_userinfo(value) == ""+++#: Ambiguous authorities whose userinfo fragment parses as a host, paired+#: with the fragment that must not reach a log line or a key. The last+#: four carry a digits-only password prefix that parses as a *valid*+#: port, so only the "port followed by ``@``" rule catches them.+USERINFO_FRAGMENT_AS_HOST_URLS = [+ ("https://hunter2-secret/[email protected]/a.pdf", "hunter2"),+ ("https://hunter2-secret:12#[email protected]/a.pdf", "hunter2"),+ ("https://ghp_abcdefghij/[email protected]/x.pdf", "ghp_abcdefghij"),+ ("https://[email protected]/", "ghp_abcdefghij"),+ ("https://tok\\[email protected]/", "tok"),+ ("https://deploy:2024/[email protected]/x", "deploy"),+ ("https://x-access-token:1234#[email protected]/o/r", "x-access-token"),+ ("https://john.doe:1234/[email protected]/", "john.doe"),+ ("https://alice.smith:1234#[email protected]/", "alice.smith"),+ ("https://[email protected]:12#[email protected]/", "corp.example"),+]++#: A password holding an unencoded ``@`` followed by a dotted segment and a+#: ``/``, ``?`` or ``#``: the parser splits at the password's own ``@``, so+#: the "host" is the dotted tail of the password (no port, not a single+#: label). The parsed authority carries a userinfo *and* an ``@`` follows+#: it, which is what flags these -- for IP literals and ``localhost`` too.+PASSWORD_AT_DOTTED_TAIL_URLS = [+ ("https://admin:[email protected]#[email protected]/a.pdf", "ss.example"),+ (+ "https://admin:[email protected]/[email protected]/a.pdf",+ "corp.example",+ ),+ ("https://admin:[email protected][email protected]/a.pdf", "pass.example"),+ ("https://admin:[email protected]#[email protected]/a.pdf", "3.14"),+ ("https://admin:[email protected]#[email protected]/a.pdf", "127.0.0.1"),+ ("https://admin:pw@localhost/[email protected]/a.pdf", "localhost"),+ ("https://[email protected]/[email protected]/", "corp.example"),+]+USERINFO_FRAGMENT_AS_HOST_URLS += PASSWORD_AT_DOTTED_TAIL_URLS+++class TestLogAndKeyHelpersShareAmbiguityRule:+ """``redact_url_for_log`` (every failure-path log line),+ ``url_authority_without_userinfo`` (domains and DB keys) and+ ``rate_limit_authority`` (adaptive rate-limit keys, which the tracker+ logs) apply the same ``authority_may_be_userinfo`` rule, so a+ userinfo holding an unencoded delimiter never surfaces as a "host"."""++ @pytest.mark.parametrize("url", AMBIGUOUS_AUTHORITY_URLS)+ def test_redact_url_for_log_never_leaks_the_fixture_secret(self, url):+ from local_deep_research.security import redact_url_for_log++ result = redact_url_for_log(url)+ assert "hunter2" not in result+ assert result in ("<unparseable>", "https://<redacted>")++ @pytest.mark.parametrize(+ ("url", "fragment"), USERINFO_FRAGMENT_AS_HOST_URLS+ )+ def test_redact_url_for_log_redacts_the_authority(self, url, fragment):+ from local_deep_research.security import redact_url_for_log++ assert redact_url_for_log(url) == "https://<redacted>"++ @pytest.mark.parametrize(+ ("url", "fragment"), USERINFO_FRAGMENT_AS_HOST_URLS+ )+ def test_domain_helper_drops_the_fragment(self, url, fragment):+ from local_deep_research.security import (+ url_authority_without_userinfo,+ )++ assert fragment not in url_authority_without_userinfo(url)++ @pytest.mark.parametrize(+ ("url", "fragment"), USERINFO_FRAGMENT_AS_HOST_URLS+ )+ def test_rate_limit_key_drops_the_fragment(self, url, fragment):+ from local_deep_research.research_library.downloaders.base import (+ rate_limit_authority,+ )++ key = rate_limit_authority(url)+ assert fragment not in key+ assert key in ("invalid_authority", "example.com")++ @pytest.mark.parametrize(+ ("url", "expected"),+ [+ ("https://arxiv.org/abs/2301.00001", "https://arxiv.org"),+ ("https://EXAMPLE.com:8080/p", "https://example.com:8080"),+ ("https://medium.com/@user/post", "https://medium.com"),+ (+ "http://localhost:8080/[email protected]",+ "http://localhost:8080",+ ),+ ("http://localhost:5173/@vite/client", "http://localhost:5173"),+ ("http://10.0.0.1:81/a@b", "http://10.0.0.1:81"),+ ("http://[::1]:8080/x@y", "http://[::1]:8080"),+ ("https://a.example?x=@y", "https://a.example"),+ ("http://intranet/", "http://intranet"),+ ("https://a.example/users/@name", "https://a.example"),+ ("https://a.example/[email protected]", "https://a.example"),+ ("https://a.example/p#x@y", "https://a.example"),+ (PUBLIC_SECRET_URL, "https://papers.example.com:8443"),+ (+ "https://u:p@[email protected]/a.pdf",+ "https://papers.example.com",+ ),+ ],+ )+ def test_ordinary_urls_render_unchanged(self, url, expected):+ from urllib.parse import urlparse++ from local_deep_research.research_library.downloaders.base import (+ rate_limit_authority,+ )+ from local_deep_research.security import (+ redact_url_for_log,+ url_authority_without_userinfo,+ )++ assert redact_url_for_log(url) == expected+ netloc = urlparse(url).netloc.rpartition("@")[2]+ assert url_authority_without_userinfo(url) == netloc+ assert rate_limit_authority(url) == netloc.lower()++ @pytest.mark.parametrize(+ "url",+ [+ "https://user:[email protected]/@group",+ "https://[email protected]/[email protected]",+ "http://user:pw@localhost:11434/v1#a@b",+ ],+ )+ def test_credentialed_url_with_a_later_at_fails_closed(self, url):+ """Documented cost of the userinfo rule: a real credentialed URL+ with an ``@`` after its authority cannot be told apart from a+ password holding ``@`` plus a delimiter, so it fails closed."""+ from local_deep_research.research_library.downloaders.base import (+ rate_limit_authority,+ )+ from local_deep_research.security import (+ redact_url_for_log,+ url_authority_without_userinfo,+ )++ assert redact_url_for_log(url).endswith("://<redacted>")+ assert url_authority_without_userinfo(url) == ""+ assert rate_limit_authority(url) == "invalid_authority"++ def test_rate_limit_key_drops_a_password_digit_parsed_as_port(self):+ """``https://u:@:1#x@host/`` parses to an empty host and the port+ ``1``, the start of the password."""+ from local_deep_research.research_library.downloaders.base import (+ rate_limit_authority,+ )++ url = "https://admin:@:1#[email protected]/a.pdf"+ assert rate_limit_authority(url) == "invalid_authority"++ @pytest.mark.parametrize(+ "url",+ [+ "https://hunter2-secret/[email protected]/a.pdf",+ "https://admin:[email protected]#[email protected]/a",+ ],+ )+ @pytest.mark.parametrize("resolution", ["fails", "private"])+ def test_validate_url_never_logs_the_parsed_host_raw(+ self, url, resolution, captured_logs+ ):+ """``validate_url``'s resolution-failure and resolves-to-private+ lines log the redacted URL, not the parsed host, which for these+ shapes is (part of) the password."""+ import socket++ from local_deep_research.security import ssrf_validator++ def fake_getaddrinfo(*args, **kwargs):+ if resolution == "fails":+ raise socket.gaierror("no such host")+ return [+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("10.0.0.5", 0))+ ]++ with patch.object(+ ssrf_validator.socket, "getaddrinfo", side_effect=fake_getaddrinfo+ ):+ assert ssrf_validator.validate_url(url) is False++ joined = "\n".join(captured_logs)+ assert "https://<redacted>" in joined+ assert "hunter2" not in joined+ assert "ss.example" not in joined++ def test_llm_wrapper_local_url_line_is_redacted(self, captured_logs):+ from types import SimpleNamespace++ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ create_rate_limited_llm_wrapper,+ )++ llm = SimpleNamespace(+ base_url="http://user:hunter2-secret@localhost:11434/v1?token=T0PSECRET",+ model_name="m",+ )+ wrapper = create_rate_limited_llm_wrapper(llm, provider="openai")++ assert wrapper._check_if_local_model() is True+ joined = _assert_no_secret(captured_logs)+ assert (+ "Skipping rate limiting for local URL: http://localhost:11434"+ in joined+ )+++#: Ambiguous authorities followed by dot segments. For http(s)+#: ``urllib3.parse_url`` removes dot segments, so the parsed path of+#: ``https://tok/en@host/../a`` is ``/a``: the ``@`` that marks the+#: authority as a userinfo fragment is only in the URL as written.+DOT_SEGMENT_AMBIGUOUS_URLS = [+ ("https://tok/[email protected]/../a", "tok"),+ ("https://admin:[email protected]/[email protected]/../y", "ss.example"),+ ("https://hunter2:12/[email protected]/../a.pdf", "hunter2"),+ ("https://hunter2-secret/[email protected]/..", "hunter2"),+ ("https://hunter2-secret/[email protected]/./..", "hunter2"),+ ("https://deploy:2024/[email protected]/..", "deploy"),+ ("https://admin:pw@localhost/[email protected]/../a", "localhost"),+ ("https://admin:[email protected]/[email protected]/../a", "127.0.0.1"),+ (" https://hunter2-secret/[email protected]/../a", "hunter2"),+ # urllib3 keeps percent-encoded dots, so these were never hidden;+ # pinned so a decoding parser upgrade cannot reopen the gap.+ ("https://hunter2-secret/[email protected]/%2e%2e/a", "hunter2"),+ ("https://hunter2-secret/[email protected]/.%2E/a", "hunter2"),+]+++#: Ambiguous authorities with an *empty* userinfo (the authority starts+#: with ``@``). ``urllib3.parse_url`` sets ``auth = auth or None``, so its+#: parse reports no userinfo; the ``@`` is only in the URL as written.+EMPTY_USERINFO_AMBIGUOUS_URLS = [+ ("https://@john.doe/[email protected]/", "john.doe"),+ ("https://@ss.example#[email protected]/", "ss.example"),+ ("https://@tok.en#[email protected]/", "tok.en"),+ ("https://@1.9#[email protected]:8443/", "1.9"),+]+++class TestEmptyUserinfoIsStillUserinfo:+ """An authority that starts with ``@`` carries a userinfo in all+ three helpers, even though ``parse_url`` drops the empty one."""++ def test_premise_parse_url_drops_an_empty_userinfo(self):+ from urllib3.util import parse_url++ assert (+ parse_url("https://@ss.example#[email protected]/").auth is None+ )++ @pytest.mark.parametrize(("url", "fragment"), EMPTY_USERINFO_AMBIGUOUS_URLS)+ def test_redact_url_for_log_redacts_the_authority(self, url, fragment):+ from local_deep_research.security import redact_url_for_log++ result = redact_url_for_log(url)+ assert result == "https://<redacted>"+ assert fragment not in result++ @pytest.mark.parametrize(("url", "fragment"), EMPTY_USERINFO_AMBIGUOUS_URLS)+ def test_domain_helper_fails_closed(self, url, fragment):+ from local_deep_research.security import (+ url_authority_without_userinfo,+ )++ assert url_authority_without_userinfo(url) == ""++ @pytest.mark.parametrize(("url", "fragment"), EMPTY_USERINFO_AMBIGUOUS_URLS)+ def test_rate_limit_key_fails_closed(self, url, fragment):+ from local_deep_research.research_library.downloaders.base import (+ rate_limit_authority,+ )++ assert rate_limit_authority(url) == "invalid_authority"+++class TestDotSegmentsCannotHideTheLaterAt:+ """The "``@`` after the authority" test reads the URL as written, not+ the parser's normalised path, in all three helpers."""++ def test_premise_parse_url_drops_the_at_with_the_dot_segment(self):+ from urllib3.util import parse_url++ assert parse_url("https://tok/[email protected]/../a").path == "/a"++ @pytest.mark.parametrize(("url", "fragment"), DOT_SEGMENT_AMBIGUOUS_URLS)+ def test_redact_url_for_log_redacts_the_authority(self, url, fragment):+ from local_deep_research.security import redact_url_for_log++ result = redact_url_for_log(url)+ assert result == "https://<redacted>"+ assert fragment not in result++ @pytest.mark.parametrize(("url", "fragment"), DOT_SEGMENT_AMBIGUOUS_URLS)+ def test_domain_helper_fails_closed(self, url, fragment):+ from local_deep_research.security import (+ url_authority_without_userinfo,+ )++ assert url_authority_without_userinfo(url) == ""++ @pytest.mark.parametrize(("url", "fragment"), DOT_SEGMENT_AMBIGUOUS_URLS)+ def test_rate_limit_key_fails_closed(self, url, fragment):+ from local_deep_research.research_library.downloaders.base import (+ rate_limit_authority,+ )++ assert rate_limit_authority(url) == "invalid_authority"++ def test_backslash_userinfo_with_dot_segment_is_redacted(self):+ """urllib3 also ends the authority at ``\\``; ``urlsplit`` does+ not, and reads ``papers.example.com`` as the host."""+ from local_deep_research.security import redact_url_for_log++ url = "https://hunter2-secret\\[email protected]/../a"+ assert redact_url_for_log(url) == "https://<redacted>"++ @pytest.mark.parametrize(+ ("url", "expected"),+ [+ ("https://a.example/x/../y", "https://a.example"),+ ("https://a.example/../@user", "https://a.example"),+ ("http://intranet/../a", "http://intranet"),+ ("https://a.example:8443/a/./b?c=d#e", "https://a.example:8443"),+ ],+ )+ def test_ordinary_dot_segment_urls_render_unchanged(self, url, expected):+ from urllib.parse import urlparse++ from local_deep_research.research_library.downloaders.base import (+ rate_limit_authority,+ )+ from local_deep_research.security import (+ redact_url_for_log,+ url_authority_without_userinfo,+ )++ assert redact_url_for_log(url) == expected+ netloc = urlparse(url).netloc+ assert url_authority_without_userinfo(url) == netloc+ assert rate_limit_authority(url) == netloc.lower()+++class TestDomainCallSitesFailClosed:+ """Every call site that derives a domain or key from a stored URL+ goes through ``url_authority_without_userinfo``, so an ambiguous+ authority never leaks the userinfo prefix and a ``None`` URL never+ raises."""++ @staticmethod+ def _library_service():+ return TestLibraryDomainsDropUserinfo._library_service()++ @pytest.mark.parametrize("url", AMBIGUOUS_AUTHORITY_URLS)+ def test_metrics_extract_domain(self, url):+ from local_deep_research.web.routers.metrics import _extract_domain++ assert _extract_domain(url) is None++ @pytest.mark.parametrize("url", AMBIGUOUS_AUTHORITY_URLS)+ def test_library_service_extract_domain(self, url):+ assert self._library_service()._extract_domain(url) == ""++ def test_library_service_extract_domain_none(self):+ """``ResearchResource.url`` is nullable; a ``None`` URL must give+ an empty domain, not a TypeError from ``bytes.rpartition``."""+ assert self._library_service()._extract_domain(None) == ""++ def test_document_details_with_a_null_resource_url(self):+ from local_deep_research.research_library.services import (+ library_service as mod,+ )++ doc = MagicMock(+ text_content="a b",+ file_path="/lib/a.pdf",+ original_url=None,+ processed_at=None,+ )+ resource = MagicMock(url=None, title="T")+ session = MagicMock()+ query = session.query.return_value+ query.outerjoin.return_value.outerjoin.return_value.filter.return_value.first.return_value = (+ doc,+ resource,+ None,+ )+ query.join.return_value.filter.return_value.all.return_value = []+ service = self._library_service()+ with patch.object(mod, "get_user_db_session") as mock_gs:+ mock_gs.return_value.__enter__.return_value = session+ mock_gs.return_value.__exit__.return_value = False+ details = service.get_document_by_id("d1")++ assert details["domain"] == ""++ @pytest.mark.parametrize("url", AMBIGUOUS_AUTHORITY_URLS)+ def test_pdf_previews_domain(self, url):+ from local_deep_research.research_library.services import (+ library_service as mod,+ )++ doc = MagicMock(+ id="d1",+ research_id="r1",+ file_type="pdf",+ status="completed",+ original_url=url,+ filename="a.pdf",+ )+ session = MagicMock()+ chain = session.query.return_value.outerjoin.return_value+ chain.filter.return_value.order_by.return_value.limit.return_value.all.return_value = [+ (doc, None)+ ]+ service = self._library_service()+ with patch.object(mod, "get_user_db_session") as mock_gs:+ mock_gs.return_value.__enter__.return_value = session+ mock_gs.return_value.__exit__.return_value = False+ previews = service.get_pdf_previews_batch(["r1"])++ assert list(previews["r1"]["domains"]) == ["unknown"]+ assert "hunter2-secret" not in repr(previews)++ @pytest.mark.parametrize("url", AMBIGUOUS_AUTHORITY_URLS)+ def test_collection_search_domain(self, url):+ from local_deep_research.web.routers.library_search import (+ _enrich_with_document_metadata,+ )++ row = MagicMock(+ document_id="d1", file_type="pdf", original_url=url, created_at=None+ )+ session = MagicMock()+ session.query.return_value.filter.return_value.all.return_value = [row]+ results = [{"document_id": "d1"}]+ with patch(+ "local_deep_research.database.session_context.get_user_db_session"+ ) as mock_gs:+ mock_gs.return_value.__enter__.return_value = session+ mock_gs.return_value.__exit__.return_value = False+ _enrich_with_document_metadata(results, "alice", "pw")++ assert results[0]["domain"] == ""++ @pytest.mark.parametrize("url", AMBIGUOUS_AUTHORITY_URLS)+ def test_classifier_key(self, url, captured_logs):+ session = TestDomainKeyDropsUserinfo._session([(url,)])+ llm = MagicMock()++ results, progress = TestDomainKeyDropsUserinfo._run(session, llm)++ assert results["total"] == 0+ assert not session.add.called+ assert not llm.invoke.called+ assert "hunter2-secret" not in repr((results, progress))+ _assert_no_secret(captured_logs)++ @pytest.mark.parametrize("url", AMBIGUOUS_AUTHORITY_URLS)+ def test_failure_classifier_rate_limit_domain(self, url, captured_logs):+ from local_deep_research.library.download_management.failure_classifier import (+ FailureClassifier,+ )++ failure = FailureClassifier().classify_failure(+ error_type="http_error", status_code=429, url=url+ )++ assert failure.domain == ""+ assert "hunter2-secret" not in failure.message+ _assert_no_secret(captured_logs)++ @pytest.mark.parametrize("url", AMBIGUOUS_AUTHORITY_URLS)+ def test_llm_rate_limit_key(self, url):+ from types import SimpleNamespace++ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ create_rate_limited_llm_wrapper,+ )++ llm = SimpleNamespace(base_url=url, model_name="m")+ key = create_rate_limited_llm_wrapper(+ llm, provider="openai"+ )._get_rate_limit_key()++ assert key == "openai-unknown-m"++ def test_llm_rate_limit_key_schemeless_userinfo(self):+ from types import SimpleNamespace++ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (+ create_rate_limited_llm_wrapper,+ )++ llm = SimpleNamespace(+ base_url="user:[email protected]", model_name="m"+ )+ key = create_rate_limited_llm_wrapper(+ llm, provider="openai"+ )._get_rate_limit_key()++ assert "hunter2-secret" not in key+++#: The retry reason for a row permanently failed before the domain fix:+#: ``RateLimitFailure`` used ``urlparse(url).netloc``, userinfo included,+#: and ``status_tracker.can_retry`` embeds the stored message.+LEGACY_RETRY_REASON = (+ "Permanently failed: Rate limited by user:hunter2-secret@"+ "papers.example.com - Unable to access article - server returned "+ "error code 429"+)+++class TestLegacyRetryReasonsAreWithheld:+ """Rows written before this change still hold credentialed+ ``failure_message`` text; the retry-refusal log lines withhold it,+ while the value returned to the caller is unchanged (the user's own+ data)."""++ @staticmethod+ def _service_with_retry_refusal():+ from types import SimpleNamespace++ from local_deep_research.research_library.services import (+ download_service as ds,+ )++ service = ds.DownloadService.__new__(ds.DownloadService)+ service.username = "alice"+ service.password = "pw"+ service.retry_manager = MagicMock()+ service.retry_manager.should_retry_resource.return_value = (+ SimpleNamespace(can_retry=False, reason=LEGACY_RETRY_REASON)+ )+ return ds, service++ def test_download_as_text_retry_refusal(self, captured_logs):+ ds, service = self._service_with_retry_refusal()+ resource = MagicMock(+ source_type="web", url="https://papers.example.com/a.pdf"+ )+ session = MagicMock()+ session.query.return_value.filter_by.return_value.first.return_value = (+ resource+ )+ with (+ patch.object(ds, "get_user_db_session") as mock_gs,+ patch.object(service, "_try_existing_text", return_value=None),+ patch.object(service, "_try_legacy_text_file", return_value=None),+ patch.object(+ service, "_try_arxiv_text_extraction", return_value=None+ ),+ patch.object(+ service, "_try_existing_pdf_extraction", return_value=None+ ),+ ):+ mock_gs.return_value.__enter__.return_value = session+ mock_gs.return_value.__exit__.return_value = False+ result = service.download_as_text(7)++ assert result == (False, LEGACY_RETRY_REASON)+ joined = _assert_no_secret(captured_logs)+ assert "Skipping resource 7" in joined, joined[-400:]++ def test_arxiv_text_retry_refusal(self, captured_logs):+ _, service = self._service_with_retry_refusal()+ resource = MagicMock(id=7, url="https://arxiv.org/abs/2301.00001")++ assert service._try_arxiv_text_extraction(MagicMock(), resource) is None+ joined = _assert_no_secret(captured_logs)+ assert "Skipping canonical arXiv text for resource 7" in joined++ def test_queue_all_retry_refusal(self, captured_logs):+ from contextlib import contextmanager+ from types import SimpleNamespace++ from starlette.requests import Request++ from local_deep_research.web.routers import library as library_module++ row = SimpleNamespace(+ id=7, url="https://papers.example.com/a.pdf", research_id="r1"+ )+ session = MagicMock()+ session.query.return_value.outerjoin.return_value.filter.return_value.all.return_value = [+ row+ ]+ resource_filter = MagicMock()+ resource_filter.filter_downloadable_resources.return_value = [+ SimpleNamespace(+ resource_id=7, can_retry=False, reason=LEGACY_RETRY_REASON+ )+ ]+ summary = MagicMock(+ permanently_failed_count=1, temporarily_failed_count=0+ )+ summary.to_dict.return_value = {}+ resource_filter.get_filter_summary.return_value = summary+ resource_filter.get_skipped_resources_info.return_value = []++ @contextmanager+ def fake_db_session(*args, **kwargs):+ yield session++ request = Request(+ {+ "type": "http",+ "method": "POST",+ "path": "/library/api/queue-all-undownloaded",+ "headers": [],+ "query_string": b"",+ }+ )+ with (+ patch.object(+ library_module,+ "get_user_db_session",+ side_effect=fake_db_session,+ ),+ patch.object(+ library_module,+ "get_authenticated_user_password",+ return_value="pw",+ ),+ patch.object(+ library_module, "ResourceFilter", return_value=resource_filter+ ),+ ):+ result = library_module.queue_all_undownloaded(+ request, username="alice"+ )++ assert result["skipped"] == 1+ joined = _assert_no_secret(captured_logs)+ assert "Skipping resource 7 due to retry policy" in joined+++class TestFailedTextExtractionRecordLogs:+ """``_record_failed_text_extraction`` stores the reason unchanged but+ logs it through ``failure_reason_for_log``."""++ @pytest.mark.parametrize("existing_doc", [True, False])+ def test_reason_is_withheld(self, captured_logs, existing_doc):+ from local_deep_research.research_library.services import (+ download_service as ds,+ )++ service = ds.DownloadService.__new__(ds.DownloadService)+ service.username = "alice"+ service.password = "pw"+ doc = MagicMock(id="d1") if existing_doc else None+ session = MagicMock()+ resource = MagicMock(+ id=7, url="https://papers.example.com/a.pdf", research_id="r1"+ )+ with (+ patch.object(ds, "get_document_for_resource", return_value=doc),+ patch.object(ds, "get_source_type_id", return_value="st"),+ patch.object(ds, "Document") as document_cls,+ ):+ service._record_failed_text_extraction(+ session, resource, PRESIGNED_REASON+ )++ joined = _assert_no_secret(captured_logs)+ if existing_doc:+ assert doc.error_message == PRESIGNED_REASON+ assert "Recorded failed text extraction for document d1" in joined+ else:+ kwargs = document_cls.call_args.kwargs+ assert kwargs["error_message"] == PRESIGNED_REASON+ assert "resource 7" in joined, joined[-400:]+++class TestDocSchedulerTextExtractionLogs:+ """The document scheduler's per-resource text extraction logs the+ returned failure reason through ``failure_reason_for_log`` and an+ escaping exception by type only (its text can carry the resource URL+ via SQLAlchemy ``[parameters: ...]``; ``password`` is in scope)."""++ def test_reason_and_exception_text_are_withheld(self, captured_logs):+ from contextlib import contextmanager+ from datetime import UTC, datetime++ from local_deep_research.scheduler import background as bg++ saved_instance = bg.BackgroundJobScheduler._instance+ bg.BackgroundJobScheduler._instance = None+ try:+ with patch.object(bg, "BackgroundScheduler"):+ scheduler = bg.BackgroundJobScheduler()+ scheduler.user_sessions["testuser"] = {+ "scheduled_jobs": set(),+ "last_activity": datetime.now(UTC),+ }+ scheduler._credential_store.store("testuser", "testpass")+ settings = bg.DocumentSchedulerSettings(+ download_pdfs=False,+ extract_text=True,+ generate_rag=False,+ last_run="",+ )+ research = MagicMock(id="research-1", title="T", completed_at=None)+ resources = [+ MagicMock(id=1, url="https://papers.example.com/a.pdf"),+ MagicMock(id=2, url="https://papers.example.com/b.pdf"),+ ]+ db = MagicMock()+ research_query = MagicMock()+ research_query.filter.return_value = research_query+ research_query.order_by.return_value = research_query+ research_query.limit.return_value = research_query+ research_query.all.return_value = [research]+ resource_query = MagicMock()+ resource_query.filter_by.return_value = resource_query+ resource_query.all.return_value = resources+ db.query.side_effect = [research_query, resource_query]++ @contextmanager+ def fake_get_user_db_session(*a, **kw):+ yield db++ download_service = MagicMock()+ download_service.__enter__ = MagicMock(+ return_value=download_service+ )+ download_service.__exit__ = MagicMock(return_value=False)+ download_service.download_as_text.side_effect = [+ (False, PRESIGNED_REASON),+ RuntimeError(f"[parameters: ('{PUBLIC_SECRET_URL}',)]"),+ ]+ settings_manager = MagicMock()+ settings_manager.get_settings_snapshot.return_value = {+ "search.tool": "searxng"+ }+ with (+ patch.object(+ scheduler,+ "_get_document_scheduler_settings",+ return_value=settings,+ ),+ patch(+ "local_deep_research.database.session_context.get_user_db_session",+ side_effect=fake_get_user_db_session,+ ),+ patch(+ "local_deep_research.settings.manager.SettingsManager",+ return_value=settings_manager,+ ),+ patch(+ "local_deep_research.research_library.services.download_service.DownloadService",+ return_value=download_service,+ ),+ patch(+ "local_deep_research.research_library.utils.is_downloadable_url",+ return_value=True,+ ),+ ):+ scheduler._process_user_documents("testuser")+ finally:+ bg.BackgroundJobScheduler._instance = saved_instance++ assert download_service.download_as_text.call_count == 2+ joined = _assert_no_secret(captured_logs)+ assert "Failed to extract text for resource 1" in joined, joined[-600:]+ assert "Error processing resource 2: RuntimeError" in joined, joined[+ -600:+ ]diff --git a/tests/security/test_ssrf_egress_policy.py b/tests/security/test_ssrf_egress_policy.pyindex e49d2fed1c..8c78fc37d1 100644--- a/tests/security/test_ssrf_egress_policy.py+++ b/tests/security/test_ssrf_egress_policy.py@@ -564,7 +564,10 @@ def test_redirect_from_public_host_to_metadata_is_blocked(stub_http):safe_requests.safe_get(start)assert "Redirect target failed SSRF validation" in str(excinfo.value)- assert target in str(excinfo.value)+ # The refused target is named by origin only (#6541): the exception+ # text reaches caller logs, and a URL path/query can carry tokens.+ assert f"http://{IMDS_HOST}" in str(excinfo.value)+ assert "/latest/meta-data/" not in str(excinfo.value)# The decisive assertion: the second hop was never dialled. A gate# that raises *after* connecting has not prevented the SSRF.assert [url for url, _kw in stub_http["calls"]] == [start]