~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(library): block HTTPS PDF redirect downgrades (#6996)
LearningCircuit1757d7dad56d
diff --git a/changelog.d/6847.security.md b/changelog.d/6847.security.mdnew file mode 100644index 0000000000..8a12d4bcb2--- /dev/null+++ b/changelog.d/6847.security.md@@ -0,0 +1 @@+Research-library downloads now refuse redirects from HTTPS to HTTP. This covers the library's PDF and text downloads and Zotero imports: Zotero API requests, the attachment's redirect to its storage host, and the storage download. A library download whose HTTPS link redirects to HTTP now fails instead of storing what the cleartext hop returned; HTTP-only links still work. The same downloaders also fetch pages for research (the agent's fetch tool and full-page search results), so there too an HTTPS page that redirects to HTTP, as some DOI links do, is no longer fetched; with JavaScript rendering enabled, the browser fallback still follows such a redirect. OpenAlex enrichment keeps its API requests on HTTPS.diff --git a/src/local_deep_research/research_library/downloaders/base.py b/src/local_deep_research/research_library/downloaders/base.pyindex 26714d6905..a67246d12f 100644--- a/src/local_deep_research/research_library/downloaders/base.py+++ b/src/local_deep_research/research_library/downloaders/base.py@@ -135,7 +135,7 @@ class BaseDownloader(ABC):timeout: Request timeout in seconds"""self.timeout = timeout- self.session = SafeSession()+ self.session = SafeSession(block_https_downgrade=True)self.session.headers.update({"User-Agent": USER_AGENT})# Initialize rate limiter for PDF downloadsdiff --git a/src/local_deep_research/research_library/zotero/client.py b/src/local_deep_research/research_library/zotero/client.pyindex aacb1eb0a0..2cd86e2cd5 100644--- a/src/local_deep_research/research_library/zotero/client.py+++ b/src/local_deep_research/research_library/zotero/client.py@@ -3,8 +3,10 @@ Thin client for the Zotero Web API (https://www.zotero.org/support/dev/web_api/vUses the project's :class:`SafeSession` so every request is SSRF-validatedand response sizes are bounded, rather than pulling in ``pyzotero`` (which-would bypass those protections). Only the small slice of the API needed for-import / incremental sync is implemented:+would bypass those protections). A redirect from HTTPS to HTTP is refused,+including the attachment storage redirect that+:meth:`ZoteroClient.download_attachment` follows itself. Only the small slice+of the API needed for import / incremental sync is implemented:- list collections (for the UI picker)- list item *versions* for a collection or the whole library@@ -254,7 +256,13 @@ class ZoteroClient:f"/{quote(self.library_id, safe='')}")# The local API is on the loopback interface; allow it explicitly.- self.session = SafeSession(allow_localhost=local)+ # What this session fetches is imported into the research library+ # (item data, notes, annotations, Zotero's full text), so a redirect+ # from HTTPS to HTTP is refused (#6847). The local API is plain HTTP+ # from the start, which the guard leaves alone.+ self.session = SafeSession(+ allow_localhost=local, block_https_downgrade=True+ )headers = {"Zotero-API-Version": ZOTERO_API_VERSION}# The local desktop API needs no key and is reached over plaintext HTTP# on the loopback; never attach the key there (it would put a real@@ -717,6 +725,18 @@ class ZoteroClient:``allow_redirects=False`` and follow the ``Location`` ourselves using afresh, credential-free :class:`SafeSession` (which still SSRF-validatesthe target).++ Following the ``Location`` ourselves bypasses the session's HTTPS+ downgrade guard, so the same rule is applied here: when the API+ answered over HTTPS (cloud mode), a ``Location`` that is not an+ absolute ``https://`` URL is refused and the method returns None,+ rather than fetching the file in cleartext where an on-path attacker+ could replace the bytes stored in the library (#6847). Any such+ ``Location`` other than ``http://`` was never fetchable here: it is+ not resolved against the API URL, so a relative or scheme-less value,+ like any other scheme, fails the storage session's URL validation.+ Local mode talks to the desktop API over plain HTTP from the start,+ so it has no HTTPS to leave."""try:response = self._request(@@ -751,6 +771,14 @@ class ZoteroClient:)return Nonereturn self._read_local_file(location)+ if self._base.lower().startswith(+ "https://"+ ) and not location.lower().startswith("https://"):+ logger.warning(+ f"Zotero: refusing attachment {attachment_key} redirect "+ "that leaves HTTPS"+ )+ return Nonereturn self._fetch_file_unauthenticated(location)# Some configurations serve the file directly (200, no redirect).@@ -787,15 +815,17 @@ class ZoteroClient:def _fetch_file_unauthenticated(self, url: str) -> Optional[bytes]:"""Fetch a storage URL with a fresh session that carries no Zoterocredentials. SafeSession SSRF-validates the URL (and any further- redirects).+ redirects) and refuses a further redirect from HTTPS to HTTP.Raises :class:`ZoteroTransientError` on a transient failure (networkerror or HTTP 429/5xx from the storage host) so the caller retries next- sync rather than importing the item metadata-only; returns None only- for a genuine "no file here" (other non-2xx / empty body).+ sync rather than importing the item metadata-only; returns None when+ the session refuses the fetch (URL validation, an HTTPS-to-HTTP+ redirect) and for a genuine "no file here" (other non-2xx / empty+ body)."""try:- with SafeSession() as session:+ with SafeSession(block_https_downgrade=True) as session:response = session.get(url, timeout=self.timeout)except (requests.exceptions.Timeout,diff --git a/src/local_deep_research/security/safe_requests.py b/src/local_deep_research/security/safe_requests.pyindex b43878671c..4d3c7a1493 100644--- a/src/local_deep_research/security/safe_requests.py+++ b/src/local_deep_research/security/safe_requests.py@@ -708,9 +708,11 @@ class SafeSession(requests.Session):Raises:ValueError: If a URL (initial or redirect target) fails SSRF- validation, if a 307/308 redirect would re-send the request body- outside the scope of the URL the caller addressed, or if the- response Content-Length exceeds MAX_RESPONSE_SIZE. Note: ``safe_get``/``safe_post`` also raise+ validation, an enabled HTTPS downgrade guard refuses a redirect+ or disabled certificate verification, a 307/308 redirect would+ re-send the request body outside the scope of the URL the caller+ addressed, or the response Content-Length exceeds+ MAX_RESPONSE_SIZE. Note: ``safe_get``/``safe_post`` also raise``ValueError`` for too-many-redirects, but ``SafeSession`` raises``requests.TooManyRedirects`` for that case since it delegatesredirect counting to the ``requests`` library.@@ -722,6 +724,7 @@ class SafeSession(requests.Session):allow_localhost: bool = False,allow_private_ips: bool = False,block_link_local: bool = False,+ block_https_downgrade: bool = False,):"""Initialize SafeSession.@@ -743,12 +746,17 @@ class SafeSession(requests.Session):trusted target that is never link-local (cloud metadata livesthere beyond the always-blocked literals). No effect without``allow_private_ips``; forwarded to ``validate_url``.+ block_https_downgrade: Refuse a redirect from HTTPS to HTTP,+ including a downgrade after earlier redirect hops. HTTP-only+ starting URLs remain supported. HTTPS requests must verify+ their certificates when this is enabled."""super().__init__()self.max_redirects = _MAX_REDIRECTSself.allow_localhost = allow_localhostself.allow_private_ips = allow_private_ipsself.block_link_local = block_link_local+ self.block_https_downgrade = block_https_downgrade# Per-thread, because one session is shared across search engines.self._redirect_local = threading.local()@@ -826,8 +834,19 @@ class SafeSession(requests.Session):caller the 3xx response it asked for; the credential strip still runs,which is what ``Response.next`` needs."""+ following_the_hop = not self._preparing_next_only+ if (+ self.block_https_downgrade+ and following_the_hop+ and (response.request.url or "").lower().startswith("https://")+ and (prepared_request.url or "").lower().startswith("http://")+ ):+ raise ValueError(+ "Redirect would downgrade to cleartext: "+ f"{ssrf_validator.redact_url_for_log(prepared_request.url)}"+ )+if self.should_strip_auth(response.request.url, prepared_request.url):- following_the_hop = not self._preparing_next_onlyif prepared_request.body is not None and following_the_hop:logger.warning(f"Redirect to {_redact(prepared_request.url)} not "@@ -888,6 +907,18 @@ class SafeSession(requests.Session):therefore validated twice (once in ``request()``, once here);this is intentional defense-in-depth."""+ if (+ self.block_https_downgrade+ and request.url+ and request.url.lower().startswith("https://")+ ):+ # Session.send inherits only when the argument is absent.+ # An explicit None reaches the adapter with verification disabled.+ verify = kwargs.get("verify", self.verify)+ if not verify:+ raise ValueError(+ "block_https_downgrade cannot be combined with verify=False"+ )if request.url and not ssrf_validator.validate_url(request.url,allow_localhost=self.allow_localhost,diff --git a/src/local_deep_research/utilities/openalex_enrichment.py b/src/local_deep_research/utilities/openalex_enrichment.pyindex 7cbbf0a08c..d892383532 100644--- a/src/local_deep_research/utilities/openalex_enrichment.py+++ b/src/local_deep_research/utilities/openalex_enrichment.py@@ -444,6 +444,7 @@ def enrich_results_with_source_ids(params=_params,headers=request_headers,timeout=OPENALEX_ENRICHMENT_API_TIMEOUT,+ require_https=True,)try:diff --git a/tests/security/test_safe_session_https_downgrade.py b/tests/security/test_safe_session_https_downgrade.pynew file mode 100644index 0000000000..747d5d9db7--- /dev/null+++ b/tests/security/test_safe_session_https_downgrade.py@@ -0,0 +1,380 @@+"""HTTPS integrity policy for SafeSession-backed library downloads.++Covers ``SafeSession``'s downgrade guard and the research-library paths that+apply it: the library download service's downloaders and the Zotero import.+Every transport is a scripted adapter, so nothing here touches the network.+"""++import io+from unittest.mock import MagicMock++import pytest+import requests++from local_deep_research.research_library.downloaders import base+from local_deep_research.research_library.downloaders.direct_pdf import (+ DirectPDFDownloader,+)+from local_deep_research.research_library.downloaders.playwright_html import (+ AutoHTMLDownloader,+ PlaywrightHTMLDownloader,+)+from local_deep_research.research_library.services import download_service+from local_deep_research.research_library.zotero import (+ client as zotero_client_module,+)+from local_deep_research.research_library.zotero.client import ZoteroClient+from local_deep_research.security.safe_requests import SafeSession+++START = "https://93.184.216.34/paper.pdf"+++class ScriptedAdapter(requests.adapters.BaseAdapter):+ """Answer redirect chains locally and record every attempted transport.++ Each scripted response is ``(status, location)`` or+ ``(status, location, body)``.+ """++ def __init__(self, responses):+ self.responses = list(responses)+ self.sent = []++ def send(self, request, **kwargs):+ self.sent.append(request.url)+ status, location, *body = self.responses.pop(0)+ response = requests.Response()+ response.status_code = status+ response.url = request.url+ response.request = request+ response.raw = io.BytesIO(body[0] if body else b"")+ if location:+ response.headers["Location"] = location+ return response++ def close(self):+ pass+++def session_with_responses(responses, *, block_https_downgrade=True):+ session = SafeSession(block_https_downgrade=block_https_downgrade)+ adapter = ScriptedAdapter(responses)+ session.mount("https://", adapter)+ session.mount("http://", adapter)+ return session, adapter+++ ("location", "expected"),+ [+ ("/next.pdf", "https://93.184.216.34/next.pdf"),+ ("//1.1.1.1/next.pdf", "https://1.1.1.1/next.pdf"),+ ],+)+def test_relative_redirects_remain_on_https(location, expected):+ session, adapter = session_with_responses([(302, location), (200, None)])++ with session:+ response = session.get(START)++ assert response.status_code == 200+ assert adapter.sent == [START, expected]+++ "responses, expected_sent",+ [+ ([(302, "http://1.1.1.1/next.pdf")], [START]),+ (+ [+ (302, "https://1.1.1.1/first.pdf"),+ (302, "http://1.1.1.1/next.pdf"),+ ],+ [START, "https://1.1.1.1/first.pdf"],+ ),+ ],+)+def test_https_to_http_redirect_never_reaches_transport(+ responses, expected_sent+):+ session, adapter = session_with_responses(responses)++ with session:+ with pytest.raises(ValueError, match="downgrade to cleartext"):+ session.get(START)++ assert adapter.sent == expected_sent+++def test_http_starting_url_can_follow_http_redirect():+ session, adapter = session_with_responses([(302, "/next.pdf"), (200, None)])++ with session:+ response = session.get("http://93.184.216.34/paper.pdf")++ assert response.status_code == 200+ assert adapter.sent == [+ "http://93.184.216.34/paper.pdf",+ "http://93.184.216.34/next.pdf",+ ]+++def test_disabled_redirect_following_returns_response_without_fetching_http():+ session, adapter = session_with_responses(+ [(302, "http://1.1.1.1/next.pdf")]+ )++ with session:+ response = session.get(START, allow_redirects=False)++ assert response.status_code == 302+ assert adapter.sent == [START]++[email protected]("disable_at_session", [False, True])+def test_https_policy_rejects_disabled_certificate_verification(+ disable_at_session,+):+ session, adapter = session_with_responses([(200, None)])+ if disable_at_session:+ session.verify = False++ with session:+ with pytest.raises(ValueError, match="verify=False"):+ session.get(+ START, **({} if disable_at_session else {"verify": False})+ )++ assert adapter.sent == []+++def test_prepared_https_request_rejects_none_verification():+ session, adapter = session_with_responses([(200, None)])+ prepared = session.prepare_request(requests.Request("GET", START))++ with session:+ with pytest.raises(ValueError, match="verify=False"):+ session.send(prepared, verify=None)++ assert adapter.sent == []++[email protected]("verify_options", [{}, {"verify": True}])+def test_prepared_https_request_keeps_verified_transport(verify_options):+ session, adapter = session_with_responses([(200, None)])+ prepared = session.prepare_request(requests.Request("GET", START))++ with session:+ response = session.send(prepared, **verify_options)++ assert response.status_code == 200+ assert adapter.sent == [START]+++def test_default_session_retains_legacy_redirect_behavior():+ session, adapter = session_with_responses(+ [(302, "http://1.1.1.1/next.pdf"), (200, None)],+ block_https_downgrade=False,+ )++ with session:+ response = session.get(START)++ assert response.status_code == 200+ assert adapter.sent == [START, "http://1.1.1.1/next.pdf"]+++def test_research_library_pdf_downloader_enables_https_policy(monkeypatch):+ tracker = MagicMock()+ tracker.apply_rate_limit.return_value = 0+ monkeypatch.setattr(base, "AdaptiveRateLimitTracker", lambda **_: tracker)+ adapter = ScriptedAdapter([(302, "http://1.1.1.1/next.pdf")])++ with DirectPDFDownloader() as downloader:+ assert downloader.session.block_https_downgrade is True+ downloader.session.mount("https://", adapter)+ downloader.session.mount("http://", adapter)+ assert downloader._download_pdf(START) is None++ assert adapter.sent == [START]+ tracker.record_outcome.assert_called_once()+++def library_download_service(monkeypatch, tmp_path):+ """The research library's DownloadService, built without a user database."""+ tracker = MagicMock()+ tracker.apply_rate_limit.return_value = 0+ monkeypatch.setattr(base, "AdaptiveRateLimitTracker", lambda **_: tracker)+ settings = MagicMock()+ settings.get_setting.side_effect = lambda key, default=None: (+ str(tmp_path) if key == "research_library.storage_path" else default+ )+ monkeypatch.setattr(+ download_service, "get_settings_manager", lambda **_: settings+ )+ monkeypatch.setattr(+ download_service, "get_library_directory", lambda: tmp_path+ )+ monkeypatch.setattr(download_service, "RetryManager", MagicMock())+ service = download_service.DownloadService("library_user", "pw")+ yield service+ service.close()+++def test_every_library_download_service_downloader_refuses_the_downgrade(+ library_download_service,+):+ """Every downloader the library downloads through refuses HTTPS to HTTP.++ None of them may be a browser downloader: the Playwright and Crawl4AI+ route guards follow redirects without a scheme check.+ """+ downloaders = library_download_service.downloaders+ assert downloaders+ for downloader in downloaders:+ name = type(downloader).__name__+ assert not isinstance(+ downloader, (AutoHTMLDownloader, PlaywrightHTMLDownloader)+ ), name+ adapter = ScriptedAdapter([(302, "http://1.1.1.1/next.pdf")])+ downloader.session.mount("https://", adapter)+ downloader.session.mount("http://", adapter)++ with pytest.raises(ValueError, match="downgrade to cleartext"):+ downloader.session.get(START)++ assert adapter.sent == [START], name+++ZOTERO_PDF = b"%PDF-1.7 attachment bytes"+++def scripted_zotero_client(+ monkeypatch, *, base_url, api_responses, storage_responses, local=False+):+ """A ZoteroClient whose API and storage sessions answer from scripts.++ ``base_url`` replaces the API base with an IP literal, so URL validation+ needs no DNS lookup.+ """+ client = ZoteroClient(+ api_key="" if local else "KEY",+ library_type="user",+ library_id="1",+ local=local,+ )+ client._base = base_url+ api = ScriptedAdapter(api_responses)+ client.session.mount("https://", api)+ client.session.mount("http://", api)+ storage = ScriptedAdapter(storage_responses)++ def storage_session(*args, **kwargs):+ session = SafeSession(*args, **kwargs)+ session.mount("https://", storage)+ session.mount("http://", storage)+ return session++ monkeypatch.setattr(zotero_client_module, "SafeSession", storage_session)+ return client, api, storage+++ (+ "base_url",+ "local",+ "location",+ "storage_responses",+ "imported",+ "storage_sent",+ ),+ [+ pytest.param(+ "https://93.184.216.34",+ False,+ "http://1.1.1.1/file.pdf",+ [(200, None, ZOTERO_PDF)],+ None,+ [],+ id="api-redirects-to-http",+ ),+ pytest.param(+ "https://93.184.216.34",+ False,+ "HTTP://1.1.1.1/file.pdf",+ [(200, None, ZOTERO_PDF)],+ None,+ [],+ id="api-redirects-to-uppercase-http",+ ),+ pytest.param(+ "https://93.184.216.34",+ False,+ "https://1.1.1.1/file.pdf",+ [(302, "http://1.1.1.1/plain.pdf"), (200, None, ZOTERO_PDF)],+ None,+ ["https://1.1.1.1/file.pdf"],+ id="storage-redirects-to-http",+ ),+ pytest.param(+ "https://93.184.216.34",+ False,+ "https://1.1.1.1/file.pdf",+ [(200, None, ZOTERO_PDF)],+ ZOTERO_PDF,+ ["https://1.1.1.1/file.pdf"],+ id="https-storage-is-fetched",+ ),+ pytest.param(+ "http://93.184.216.34/api",+ True,+ "http://1.1.1.1/file.pdf",+ [(200, None, ZOTERO_PDF)],+ ZOTERO_PDF,+ ["http://1.1.1.1/file.pdf"],+ id="local-http-api-has-no-https-to-leave",+ ),+ ],+)+def test_zotero_attachment_import_refuses_https_to_http(+ monkeypatch,+ base_url,+ local,+ location,+ storage_responses,+ imported,+ storage_sent,+):+ client, api, storage = scripted_zotero_client(+ monkeypatch,+ base_url=base_url,+ local=local,+ api_responses=[(302, location)],+ storage_responses=storage_responses,+ )++ with client:+ assert client.download_attachment("ATT1") == imported++ assert api.sent == [f"{base_url}/users/1/items/ATT1/file"]+ assert storage.sent == storage_sent+++def test_zotero_api_redirect_from_https_to_http_is_refused(monkeypatch):+ """Text-only imports store Zotero's full text instead of the PDF."""+ client, api, _ = scripted_zotero_client(+ monkeypatch,+ base_url="https://93.184.216.34",+ api_responses=[+ (302, "http://1.1.1.1/fulltext"),+ (200, None, b'{"content": "replaced text"}'),+ ],+ storage_responses=[],+ )++ with client:+ assert client.get_attachment_fulltext("ATT1") is None++ assert api.sent == ["https://93.184.216.34/users/1/items/ATT1/fulltext"]diff --git a/tests/utilities/test_openalex_enrichment.py b/tests/utilities/test_openalex_enrichment.pyindex 4105064960..53774a20d5 100644--- a/tests/utilities/test_openalex_enrichment.py+++ b/tests/utilities/test_openalex_enrichment.py@@ -206,10 +206,11 @@ class TestEnrichResultsWithSourceIds:with patch("local_deep_research.utilities.openalex_enrichment.safe_get",return_value=bad_resp,- ):+ ) as mock_get:out = enrich_results_with_source_ids(results)assert "openalex_source_id" not in results[0]assert out is results+ assert mock_get.call_args.kwargs["require_https"] is Truedef test_network_exception_swallowed_graceful(self):"""``safe_get`` itself can raise on network errors. The function