Skip to content

~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.

fix(arxiv): close live-network test, redirect, gzip, and directory-containment gaps from #5807 (#6199)

LearningCircuitb07d3308304b
diff --git a/.github/scripts/check-file-writes.sh b/.github/scripts/check-file-writes.sh
index fdffe9f1e8..e6a41f818c 100755
--- a/.github/scripts/check-file-writes.sh
+++ b/.github/scripts/check-file-writes.sh
@@ -252,14 +252,45 @@ if [ -n "$ALL_MATCHES" ]; then
# - vector_stores/legacy_cleanup.py — writes the text-free
# ``.idmap.json`` migration sidecar (plain position->uuid JSON map,
# no chunk text; see the module docstring / `_ID_RE`)
- # - web_search_engines/engines/search_engine_arxiv.py — writes the
- # downloaded PDF of a public arXiv paper into the caller-provided
- # download dir (public published document, no PII/secrets; the fetch
- # itself goes through the SSRF-validated SafeSession egress gate)
+ # web_search_engines/engines/search_engine_arxiv.py is NOT listed here:
+ # its one write (the downloaded PDF of a public arXiv paper) carries an
+ # inline `# Safe: ...` marker on the write line itself instead of a
+ # blanket file-level exemption -- that marker is intended as the
+ # belt-and-suspenders exemption for whichever SUSPICIOUS_PATTERNS entry
+ # fires on that line. CORRECTION (this comment previously claimed the
+ # marker is what currently satisfies the check for this file -- false):
+ # as written today (`tmp_path.open("wb") # Safe: public PDF`), the
+ # marker is never actually consulted for this line. SAFE_USAGE_PATTERNS
+ # contains the bare identifier `tmp_path`, and that loop runs BEFORE
+ # the `# Safe:` marker check below -- `tmp_path` matches this line's
+ # variable name first, so skip_line is already 1 by the time the
+ # marker check would run. This is weaker than "any other write later
+ # added to that file still gets flagged" for two independent reasons,
+ # not one: first, the bare `tmp_path` entry exempts ANY line in src/
+ # mentioning that identifier, whatever it does, not just this write;
+ # second, the SUSPICIOUS_PATTERNS loop above runs `grep` in POSIX
+ # basic-regex mode (no `-E`), where most of these patterns' trailing
+ # `\(` opens an unterminated group and errors out (silently swallowed
+ # by `2>/dev/null`), so patterns like `\.write\(`,
+ # `Path.*\.write_bytes\(`, and `with.*open\(...` never fire at all.
+ # Only patterns with a *balanced* `\(...\)` pair, e.g.
+ # `open\(.*['"]wb['"].*\)`, actually match under this grep call -- and
+ # it is `tmp_path`, not the marker, that currently exempts that match.
+ # A write shape that only matches one of the dead patterns (a bare
+ # `.write(`, `Path(...).write_bytes(...)`, etc.) added elsewhere in
+ # this file would NOT be caught, marker or no marker. Treat this as a
+ # per-line exemption for the one pattern that does fire, not a
+ # file-wide guarantee, and not evidence that the `# Safe:` marker
+ # mechanism is actually wired up for this file today. Whether the bare
+ # `tmp_path` entry in SAFE_USAGE_PATTERNS is sound at all (it exempts
+ # by variable name, not by review) is out of scope for this comment
+ # fix and tracked instead in #6208, alongside the ~26 other
+ # SAFE_USAGE_PATTERNS/dead-pattern violations tightening it would
+ # surface.
# If you add an entry here, document WHY the file's writes are safe
# (public data, not user-specific, not encrypted at rest by design).
if [ "$skip_line" -eq 0 ]; then
- if echo "$line" | grep -qE "web/app_factory\.py|document_loaders/bytes_loader\.py|journal_quality/downloader\.py|journal_quality/data_sources/.+\.py|vector_stores/implementations/faiss_store\.py|vector_stores/legacy_cleanup\.py|web_search_engines/engines/search_engine_arxiv\.py"; then
+ if echo "$line" | grep -qE "web/app_factory\.py|document_loaders/bytes_loader\.py|journal_quality/downloader\.py|journal_quality/data_sources/.+\.py|vector_stores/implementations/faiss_store\.py|vector_stores/legacy_cleanup\.py"; then
skip_line=1
fi
fi
diff --git a/changelog.d/5807.security.md b/changelog.d/5807.security.md
index b95aa9171d..25d0faf72b 100644
--- a/changelog.d/5807.security.md
+++ b/changelog.d/5807.security.md
@@ -1,20 +1,54 @@
-arXiv PDF downloads now go through the same SSRF-validated session
-(with SSRF pre-validation and DNS pinning) as the rest of the arXiv
-integration, instead of the arxiv library's built-in download path, and
-fetch from export.arxiv.org (arXiv's designated host for automated
-access, matching the arxiv library's own default `download_domain` and
-the host already used for the metadata API) rather than the public
-arxiv.org host.
-This fetch now also passes `stream=True`, so SafeSession's response-size
-cap runs before the body is buffered rather than after: an oversized
-response with a `Content-Length` header is now rejected immediately,
-instead of being fully read into memory first and only then discarded.
-When `Content-Length` is absent, the cap's guard now correctly bounds
-memory for a connection-close-delimited body, but not for one sent with
-`Transfer-Encoding: chunked` (the common case for a CDN of unknown
-length) -- `urllib3` reads chunked bodies through a path that bypasses
-the guard. That remaining gap lives in SafeSession's response-size cap
-itself (`_check_response_size`/`_install_body_guard` in
-`safe_requests.py`), affects every `SafeSession` caller that already
-streams, and needs its own follow-up; it is not the same issue as
-#6172, which tracks callers that don't set `stream=True` at all.
+arXiv PDF downloads now go through a SSRF-validated `SafeSession`
+(with SSRF pre-validation and DNS pinning) instead of the arxiv
+library's built-in download path (`urllib.request.urlretrieve`).
+This is narrower than "the same session as the rest of the arXiv
+integration": this engine's metadata queries (`arxiv.Client()`) still
+use the `arxiv` package's own bare `requests.Session()`, unvalidated
+and untimed -- only the PDF fetch is gated here.
+The fetch continues to go to export.arxiv.org -- that host did not
+change; the `arxiv` library (2.4.1) already defaulted
+`download_domain="export.arxiv.org"`, the same host already used for
+the metadata API.
+The request URL no longer appends a `.pdf` suffix (arxiv 2.4.1's own
+`pdf_url` has none), which also removes a 301 redirect hop that
+`export.arxiv.org` was adding for the suffixed form -- a redirect
+response's body was being drained by `requests`' internal redirect
+handling before it ever reached the size check below, undermining that
+check for exactly the request this change makes.
+This fetch now passes `stream=True` and writes the body to disk in
+bounded chunks (instead of buffering the whole response via
+`.content`) with `Accept-Encoding: identity`: `requests` sends
+`Accept-Encoding: gzip` by default where the old `urllib`-based path
+did not, and a valid, under-cap `Content-Length` installs no body
+guard in `SafeSession` at all, so a small compressed response could
+otherwise decompress far past that check.
+Since this change, `download_dir` -- reachable through per-user web
+settings, e.g. `search.engine.web.arxiv.default_params.download_dir`
+-- is created (including any missing parent directories) rather than
+raising if it does not already exist. Two behavior changes from that
+were not previously called out: a `download_dir` containing a `..`
+traversal segment now raises (caught, so the result silently has no
+`pdf_path` rather than an actionable error), and a `download_dir`
+starting with `~` is not expanded by this code, so it is treated as a
+literal `~` path segment rather than the user's home directory.
+A follow-up now additionally contains directory creation to a
+dedicated subtree of the local-deep-research data directory, since
+`download_dir` is user-influenced input rather than a trusted
+constant -- as of that follow-up, an unexpanded `~`-prefixed
+`download_dir` resolves relative to the process's working directory
+and (outside the unusual case of that directory being the contained
+subtree itself) is now rejected by that containment check rather than
+silently creating a literal `~` directory.
+The saved filename also changed, from `<id>.<sanitized title>.pdf` to
+`<id>.pdf`.
+When `Content-Length` is absent, `SafeSession`'s guard correctly
+bounds memory for a connection-close-delimited body, but not for one
+sent with `Transfer-Encoding: chunked` (the common case for a CDN of
+unknown length) -- `urllib3` reads chunked bodies through a path that
+bypasses the guard, which is why this fetch enforces its own running
+byte cap while streaming rather than relying on that guard alone. The
+`urllib3` gap itself lives in SafeSession's response-size cap
+(`_check_response_size`/`_install_body_guard` in `safe_requests.py`),
+affects every `SafeSession` caller that already streams, and needs
+its own follow-up; it is not the same issue as #6172, which tracks
+callers that don't set `stream=True` at all.
diff --git a/changelog.d/6199.security.md b/changelog.d/6199.security.md
new file mode 100644
index 0000000000..2c9422c3ee
--- /dev/null
+++ b/changelog.d/6199.security.md
@@ -0,0 +1,18 @@
+Follow-up to #5807's arXiv PDF egress hardening. arXiv PDF downloads no
+longer append a `.pdf` suffix to the request URL, which removed a 301
+redirect hop whose body was being drained by `requests` before
+`SafeSession`'s response-size check ever ran on it. The body is now
+streamed to disk in bounded chunks with its own running byte cap (instead
+of being read whole via `.content`) and `Accept-Encoding: identity` is
+sent as a best-effort measure, though the running byte cap over the
+already-decoded stream is what actually bounds a decompression bomb
+regardless of what encoding the origin sends. Directory creation for
+the (per-user-settable) `download_dir` is now contained to a dedicated
+`arxiv_downloads` subtree of the local-deep-research data directory,
+rather than the data directory itself, which also holds secrets and
+per-user encrypted databases.
+Also fixed: three unit tests that were making live HTTPS requests to
+export.arxiv.org in CI (`test_pdf_download_pypdf2_empty_falls_back_to_summary`,
+`test_pypdf2_fails_pdfplumber_succeeds`, `test_both_pdf_extractors_fail`),
+and a fourth (`test_pdf_limit_reached`) whose ids never exercised the
+branch it named.
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
index ffe30a534a..0b79f517b2 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
@@ -1,14 +1,21 @@
+import os
import re
+import uuid
from pathlib import Path
from typing import Any, Dict, List, Optional
import arxiv
from langchain_core.language_models import BaseLLM
+from requests.exceptions import RequestException
+from ...config.paths import get_data_directory
from ...constants import SNIPPET_LENGTH_SHORT
from ...security import SafeSession
-from ...security.directory_creation import create_directory
-from ...security.safe_requests import DEFAULT_TIMEOUT
+from ...security.directory_creation import (
+ DirectoryCreationSecurityError,
+ create_directory,
+)
+from ...security.safe_requests import DEFAULT_TIMEOUT, MAX_RESPONSE_SIZE
from ...security.secure_logging import logger
from ..rate_limiting import RateLimitError
from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
@@ -153,27 +160,107 @@ class ArXivSearchEngine(BaseSearchEngine):
return candidate
return None
+ @staticmethod
+ def _enforce_response_size_cap(written: int) -> None:
+ """Raise if a streamed PDF body has grown past ``MAX_RESPONSE_SIZE``.
+
+ Split out from ``_download_pdf_safely``'s streaming loop so the
+ ``raise`` isn't directly inside that loop's own cleanup
+ ``try``/``except`` block.
+ """
+ if written > MAX_RESPONSE_SIZE:
+ raise ValueError(
+ f"arXiv PDF body exceeded {MAX_RESPONSE_SIZE} bytes "
+ "while streaming"
+ )
+
def _download_pdf_safely(self, paper: Any, dirpath: str) -> str:
"""Download a paper PDF through the SSRF-validated ``SafeSession``.
- Invariant: every arXiv PDF fetch goes through the same egress gate
- the rest of the arXiv integration uses. ``SafeSession`` applies SSRF
- pre-validation and DNS pinning to this fetch. This replaces
- ``arxiv.Result.download_pdf``, which fetches via
+ Invariant: every arXiv PDF fetch made *by this engine*
+ (``ArXivSearchEngine``) goes through this gate. ``SafeSession``
+ applies SSRF pre-validation and DNS pinning to this fetch. This
+ replaces ``arxiv.Result.download_pdf``, which fetches via
``urllib.request.urlretrieve`` and therefore bypasses all of those
- controls. Behavior is preserved: the PDF is written into ``dirpath``
- and the resulting path is returned.
-
- Note: this call passes ``stream=True``, so ``requests.Session.send()``
- does *not* drain the body itself (it only does that when
- ``stream`` is falsy — see ``requests.sessions.Session.send``);
- ``SafeSession``'s response-size cap (``_check_response_size``) runs
- while the connection is still open, before the call site reads
- ``response.content``. That fixes the case this note used to
- describe: with ``Content-Length`` present and over the limit, the
- cap now rejects immediately after the headers arrive, before any
- body bytes are buffered, instead of buffering the whole oversized
- body first and only then discarding it.
+ controls. This is narrower than "the same session as the rest of
+ the arXiv integration": the metadata queries this engine makes
+ elsewhere (``arxiv.Client()`` in ``_get_search_results`` and
+ ``get_paper_details``) still go through the ``arxiv`` package's own
+ bare ``requests.Session()`` — unvalidated and untimed. Gating those
+ too is out of scope here.
+
+ It is also narrower than "every arXiv PDF fetch in this codebase":
+ ``research_library/downloaders/arxiv.py``'s ``ArxivDownloader``
+ (via ``BaseDownloader._download_pdf``) independently fetches
+ ``https://arxiv.org/pdf/{id}.pdf`` — the public host, with the
+ ``.pdf`` suffix this module omits specifically to dodge the
+ redirect-drain gap described below. It does use ``SafeSession``,
+ but sends ``Accept-Encoding: gzip, deflate, br`` and reads
+ ``response.content`` with no ``stream=True``, so it has neither
+ this call site's running-byte-count cap nor its identity-encoding
+ best-effort measure. That is a separate, untouched call site —
+ fixing it is out of scope here.
+
+ The filename changes from the old path's ``<id>.<sanitized
+ title>.pdf`` (``arxiv.Result._get_default_filename``) to
+ ``<id>.pdf`` here — a behavior change worth knowing about even
+ though nothing in this codebase parses the filename back apart.
+
+ No ``.pdf`` suffix is appended to the request URL: arxiv 2.4.1's
+ own Atom ``pdf_url`` (what ``arxiv.Result.download_pdf`` fetches)
+ has none either, e.g. ``"http://arxiv.org/pdf/2101.00001v1"``.
+ Appending ``.pdf`` makes ``export.arxiv.org`` answer with a 301 to
+ the suffix-less path, and that redirect response's own body is
+ drained by ``requests.Session.send()``'s internal
+ ``resolve_redirects()`` (``resp.content # Consume socket``)
+ *before* it is ever handed to ``SafeSession.send()`` for a size
+ check — so an oversized redirect body would be read into memory
+ unchecked. Omitting the suffix removes that hop entirely, which is
+ the minimal fix; it is not a fix to ``SafeSession`` itself (every
+ redirect hop has this gap, not just this call site). This
+ redirect-drain gap in ``SafeSession.send()`` has no tracking issue
+ filed for it yet — it is untracked, and distinct from the
+ chunked-body gap discussed below (which does have one, #6180).
+
+ This call passes ``stream=True`` and writes the body to
+ ``target_path`` in bounded chunks via ``iter_content`` rather than
+ reading ``response.content`` — unlike what an earlier version of
+ this comment claimed, ``stream=True`` alone does not bound memory;
+ `research_library/downloaders/generic.py`'s ``stream=True`` usage
+ is not a precedent for this pattern, since it never reads the body
+ at all (a status-code-only diagnostic probe). The running byte
+ count enforced while streaming is also the actual guard against a
+ gzip/deflate decompression bomb here: for a valid, under-cap
+ ``Content-Length``, ``SafeSession._check_response_size`` installs
+ no body guard at all (see ``safe_requests.py``), and ``requests``
+ (unlike the old ``urllib``-based path) sends
+ ``Accept-Encoding: gzip`` by default, so a small compressed
+ response could otherwise decompress far past any header-level
+ check. This fetch instead sends ``Accept-Encoding: identity`` —
+ matching what the old ``urlretrieve``-based path effectively did
+ (``urllib`` does not request compression) — as a best-effort
+ signal, since a PDF is already-compressed binary and gains
+ nothing from gzip transfer. This does not remove the
+ decompression-bomb vector outright: ``urllib3`` decodes based on
+ the *response*'s ``Content-Encoding`` header, not the request's
+ ``Accept-Encoding`` one, so a server that ignores the request
+ header and gzips the body anyway would still be transparently
+ decoded by ``iter_content`` here. What actually bounds a
+ decompression bomb, with or without gzip, is the running byte
+ count enforced while streaming above — it is computed over the
+ already-decoded chunks ``iter_content`` yields, so it caps the
+ decompressed size regardless of what encoding the origin used.
+
+ Connection release: if ``SafeSession``'s response-size cap rejects
+ an over-limit ``Content-Length`` response, that ``ValueError`` is
+ raised *inside* ``SafeSession.send()`` — i.e. inside the
+ ``session.get(...)`` call itself, before the ``with ... as
+ response:`` statement below ever binds. So on that path the
+ connection is released by ``_check_response_size`` calling
+ ``response.close()`` internally, not by this function's context
+ manager; the context manager only covers releasing the connection
+ for responses that *do* make it past that check (including this
+ function's own errors raised while streaming the body).
It does not fully fix the ``Content-Length``-absent case. The cap
installs a guard on ``response.raw.read()``
@@ -190,16 +277,19 @@ class ArXivSearchEngine(BaseSearchEngine):
(2.7.0) source and confirming with a live chunked-response
server: the patched ``read()`` recorded zero calls while a full
chunked body was consumed. So for a genuinely chunked response,
- peak memory is still unbounded here, same as before this change.
-
- That gap is a defect in ``_check_response_size``/
- ``_install_body_guard`` in ``safe_requests.py`` itself — every
- ``SafeSession`` caller that already uses ``stream=True`` (e.g.
- ``research_library/downloaders/generic.py``) has the same
- exposure for chunked responses. It is independent of whether this
- call streams and is not the same issue as #6172, which is about
- callers that never set ``stream=True`` at all (this one now
- does). It needs its own follow-up rather than being fixed here.
+ ``_check_response_size`` still cannot bound memory on its own here
+ — this function's own running byte count during streaming is what
+ does that instead.
+
+ The ``_check_response_size`` chunked-body gap is a defect in
+ ``safe_requests.py`` itself (``_check_response_size``/
+ ``_install_body_guard``) — every ``SafeSession`` caller that
+ already uses ``stream=True`` has the same exposure for chunked
+ responses. It is independent of whether this call streams and is
+ not the same issue as #6172, which is about callers that never
+ set ``stream=True`` at all (this one now does). It has its own
+ tracking issue, #6180, and needs its own follow-up rather than
+ being fixed here.
"""
arxiv_id = self._validated_arxiv_id(paper)
if not arxiv_id:
@@ -209,6 +299,7 @@ class ArXivSearchEngine(BaseSearchEngine):
# Build the download URL from the validated id rather than trusting
# an arbitrary attribute value; SafeSession re-validates it anyway.
+ # No ".pdf" suffix -- see the docstring note above for why.
# Use export.arxiv.org (not the public arxiv.org CDN-fronted host)
# to match arxiv.Result.download_pdf's default `download_domain`
# (see the installed `arxiv` package, ~v2.4) and the host
@@ -217,41 +308,131 @@ class ArXivSearchEngine(BaseSearchEngine):
# export.arxiv.org is arXiv's designated host for automated/scripted
# access; the public arxiv.org host is rate-limited and
# bot-challenged for that traffic.
- pdf_url = f"https://export.arxiv.org/pdf/{arxiv_id}.pdf"
+ pdf_url = f"https://export.arxiv.org/pdf/{arxiv_id}"
directory = Path(dirpath)
- create_directory(directory, context="arXiv PDF download directory")
+ # `dirpath` (== self.download_dir) is reachable from per-user web
+ # settings ("search." is an allowed settings prefix; the factory
+ # splats `search.engine.web.arxiv.default_params.download_dir`
+ # straight into this engine's constructor kwargs) as well as
+ # `LDR_SEARCH_ENGINE_WEB_ARXIV_DEFAULT_PARAMS_DOWNLOAD_DIR`, so it
+ # is untrusted/user-influenced input, not a trusted constant --
+ # containment is required per directory_creation.py's own
+ # opt-in-root guidance. Contain it to a dedicated subtree of the
+ # LDR-managed data directory rather than the data directory
+ # itself: the data directory root also holds `.secret_key`
+ # (fastapi_app.py), `encrypted_databases/` (per-user encrypted DB
+ # files + `.salt`), and backups, and `create_directory` is called
+ # with `parents=True, exist_ok=True` -- with the bare data
+ # directory as root, an authenticated user could `mkdir` any
+ # not-yet-existing path under it, including pre-occupying the
+ # (computable) encrypted-DB path of a username that has not
+ # registered yet. Scoping the root to a download-only subtree
+ # keeps the blast radius of that primitive to the download area.
+ arxiv_downloads_root = get_data_directory() / "arxiv_downloads"
+ create_directory(
+ directory,
+ context="arXiv PDF download directory",
+ root=arxiv_downloads_root,
+ )
target_path = directory / f"{arxiv_id.replace('/', '_')}.pdf"
with SafeSession() as session:
- # stream=True is intentional here — DO NOT remove it. It lets
- # SafeSession's response-size cap (_check_response_size) run
- # while the connection is still open, instead of after
- # `requests` has already buffered the whole body (see the
- # docstring note above). The `with ... as response:` ensures
- # the connection is released on every path, including a
- # rejection raised by the cap itself, mirroring the same
- # stream=True + context-manager pattern already used in
- # research_library/downloaders/generic.py.
+ # stream=True is intentional here — DO NOT remove it: it lets
+ # the body be written to disk in bounded chunks below instead
+ # of buffered whole in memory (see the docstring note above).
+ # Accept-Encoding: identity mirrors what the old
+ # urlretrieve-based path effectively sent -- a best-effort
+ # signal only; it does NOT rule out a decompression bomb on
+ # its own (a server that ignores this header and gzips the
+ # body anyway is still transparently decoded downstream). The
+ # running byte count enforced while streaming below, over the
+ # already-decoded chunks, is what actually bounds that (see
+ # the docstring note above).
with session.get(
pdf_url,
timeout=DEFAULT_TIMEOUT,
allow_redirects=True,
stream=True,
+ headers={"Accept-Encoding": "identity"},
) as response:
response.raise_for_status()
- # `.content` still returns the full body unchanged — see
- # the docstring note above for what moving the read here
- # (rather than inside `send()`) does and does not fix.
- pdf_bytes = response.content
-
- # Public arXiv PDF (a published paper, no PII/secrets) written into the
- # caller-provided download dir; see the allowlist note in
- # .github/scripts/check-file-writes.sh.
- target_path.write_bytes(pdf_bytes)
+ self._stream_response_to_file(response, target_path)
return str(target_path)
+ def _stream_response_to_file(
+ self, response: Any, target_path: Path
+ ) -> None:
+ """Write ``response``'s body to ``target_path`` in bounded chunks.
+
+ Streams via ``iter_content`` rather than reading ``response.content``
+ (which would materialise the whole body in memory) -- see
+ ``_download_pdf_safely``'s docstring. ``written`` is an independent
+ running cap: it is what actually bounds this fetch's memory/disk
+ use, not the ``Content-Length`` check in ``SafeSession`` (see that
+ docstring for why the check alone is not enough here).
+
+ The body is streamed to a per-call-unique ``<target
+ name>.<uuid4 hex>.part`` sibling and only ``os.replace()``d onto
+ ``target_path`` after a full, under-cap, *non-empty* write -- never
+ streamed directly into ``target_path``. Two concurrent downloads of
+ the same arXiv id into the same directory each get their own
+ ``.part`` file, so one failing (e.g. tripping the size cap) can
+ only ever remove *its own* partial file, never a sibling
+ download's already-completed ``target_path``.
+
+ A response body that streams zero bytes (e.g. a ``200`` with an
+ empty body) is rejected before ``os.replace()`` runs, specifically
+ so it can never silently overwrite an already-completed
+ ``target_path`` from an earlier download of the same id with a
+ 0-byte file while still reporting success.
+
+ Cleanup runs in a ``finally``, not an ``except Exception`` --
+ ``except Exception`` does not catch ``KeyboardInterrupt`` /
+ ``SystemExit`` (or a raw thread-kill), which would otherwise leave
+ an unpredictably-named, up-to-``MAX_RESPONSE_SIZE``-byte ``.part``
+ file orphaned in this shared root with no sweeper to reclaim it.
+ On success ``os.replace()`` has already moved ``tmp_path`` onto
+ ``target_path`` by the time ``finally`` runs, so the same
+ unconditional ``unlink(missing_ok=True)`` call is a no-op then;
+ on any failure -- including the cap being exceeded, an empty body,
+ or an interrupt -- it removes that call's own ``.part`` file. The
+ unlink itself is best-effort and never allowed to replace (mask)
+ whatever exception is already propagating.
+ """
+ written = 0
+ tmp_path = target_path.with_name(
+ f"{target_path.name}.{uuid.uuid4().hex}.part"
+ )
+ try:
+ # Public arXiv PDF (a published paper, no PII/secrets) fetched
+ # through the SSRF-validated SafeSession and written into the
+ # caller-provided, containment-checked download dir.
+ with tmp_path.open("wb") as pdf_file: # Safe: public PDF
+ for chunk in response.iter_content(chunk_size=1024 * 1024):
+ if not chunk:
+ continue
+ written += len(chunk)
+ self._enforce_response_size_cap(written)
+ pdf_file.write(chunk)
+ if written == 0:
+ raise ValueError(
+ "arXiv PDF body was empty; refusing to write a "
+ "0-byte file over any existing download at the "
+ "target path"
+ )
+ os.replace(tmp_path, target_path)
+ finally:
+ try:
+ tmp_path.unlink(missing_ok=True)
+ except OSError:
+ # Never let a failure to clean up the partial file mask
+ # whatever exception (if any) is already propagating.
+ logger.debug(
+ f"Failed to remove partial download file {tmp_path.name}"
+ )
+
def _get_previews(self, query: str) -> List[Dict[str, Any]]:
"""
Get preview information for arXiv papers.
@@ -463,6 +644,53 @@ class ArXivSearchEngine(BaseSearchEngine):
logger.info(
"Using paper summary as content instead"
)
+ except RequestException as e:
+ # ORDER MATTERS: this clause must precede the
+ # (DirectoryCreationSecurityError, OSError)
+ # clause below. requests' RequestException
+ # subclasses IOError, which *is* OSError, so a
+ # bare OSError catch would otherwise swallow
+ # every ConnectionError/Timeout/HTTPError and
+ # relabel a routine network failure as a
+ # containment error. Network errors carry no
+ # local path, so the normal scrubbed message is
+ # both safe and far more useful here.
+ safe_msg = self._scrub_error(e)
+ logger.exception(
+ f"Error downloading paper {paper.title} ({type(e).__name__}): {safe_msg}"
+ )
+ result["pdf_path"] = None
+ pdf_count -= 1 # Decrement counter if download fails
+ except (DirectoryCreationSecurityError, OSError) as e:
+ # Never interpolate either exception's message or
+ # any path -- only its type name, which is
+ # path-free and safe to include (unlike str(e)).
+ # DirectoryCreationSecurityError embeds the
+ # resolved data-directory path
+ # (directory_creation.py). OSError (e.g.
+ # FileExistsError/NotADirectoryError) is what
+ # create_directory's own `p.mkdir()` raises
+ # uncaught -- with the *same* resolved, absolute
+ # path in its message -- when download_dir
+ # collides with an existing file or has one as a
+ # parent component; a filesystem error surfacing
+ # from the streaming write below (e.g. a disk-full
+ # OSError) can carry a path too. logger.exception
+ # here reaches the research owner's browser via
+ # frontend_progress_sink -- _scrub_error does not
+ # scrub filesystem paths, so a static, path-free
+ # message is used for this whole exception family
+ # instead; the type name alone lets an operator
+ # tell a containment rejection apart from e.g. a
+ # disk-full OSError (a cert_verify OSError from a
+ # missing REQUESTS_CA_BUNDLE, say).
+ logger.exception(
+ f"Error downloading paper {paper.title} "
+ f"({type(e).__name__}): a filesystem or "
+ "directory-containment error occurred"
+ )
+ result["pdf_path"] = None
+ pdf_count -= 1 # Decrement counter if download fails
except Exception as e:
safe_msg = self._scrub_error(e)
logger.exception(
@@ -590,6 +818,47 @@ class ArXivSearchEngine(BaseSearchEngine):
paper, self.download_dir
)
result["pdf_path"] = str(paper_path)
+ except RequestException as e:
+ # ORDER MATTERS: this clause must precede the
+ # (DirectoryCreationSecurityError, OSError)
+ # clause below. requests' RequestException
+ # subclasses IOError, which *is* OSError, so a
+ # bare OSError catch would otherwise swallow
+ # every ConnectionError/Timeout/HTTPError and
+ # relabel a routine network failure as a
+ # containment error. Network errors carry no
+ # local path, so the normal scrubbed message is
+ # both safe and far more useful here.
+ safe_msg = self._scrub_error(e)
+ logger.exception(
+ f"Error downloading paper ({type(e).__name__}): {safe_msg}"
+ )
+ except (DirectoryCreationSecurityError, OSError) as e:
+ # Never interpolate either exception's message or any
+ # path -- only its type name, which is path-free and
+ # safe to include (unlike str(e)).
+ # DirectoryCreationSecurityError embeds the resolved
+ # data-directory path (directory_creation.py). OSError
+ # (e.g. FileExistsError/NotADirectoryError) is what
+ # create_directory's own `p.mkdir()` raises uncaught
+ # -- with the *same* resolved, absolute path in its
+ # message -- when download_dir collides with an
+ # existing file or has one as a parent component; a
+ # filesystem error surfacing from the streaming write
+ # below (e.g. a disk-full OSError) can carry a path
+ # too. logger.exception here reaches the research
+ # owner's browser via frontend_progress_sink --
+ # _scrub_error does not scrub filesystem paths, so a
+ # static, path-free message is used for this whole
+ # exception family instead; the type name alone lets
+ # an operator tell a containment rejection apart from
+ # e.g. a disk-full OSError (a cert_verify OSError from
+ # a missing REQUESTS_CA_BUNDLE, say).
+ logger.exception(
+ f"Error downloading paper ({type(e).__name__}): "
+ "a filesystem or directory-containment error "
+ "occurred"
+ )
except Exception as e:
safe_msg = self._scrub_error(e)
logger.exception(
diff --git a/tests/web_search_engines/engines/test_arxiv_coverage.py b/tests/web_search_engines/engines/test_arxiv_coverage.py
index 3691aa17e9..f5b6499e23 100644
--- a/tests/web_search_engines/engines/test_arxiv_coverage.py
+++ b/tests/web_search_engines/engines/test_arxiv_coverage.py
@@ -14,7 +14,7 @@ Targets uncovered paths in search_engine_arxiv.py including:
"""
from datetime import datetime
-from unittest.mock import MagicMock, Mock, patch, mock_open
+from unittest.mock import MagicMock, Mock, PropertyMock, patch, mock_open
import pytest
@@ -107,6 +107,39 @@ def engine_with_pdf():
yield eng
+def log_sink():
+ """Capture rendered loguru output for the path-leak assertions below.
+
+ A dedicated sink rather than ``loguru_caplog``: this module wants a
+ plain rendered string per record and its own local control over the
+ sink level/format, so it follows the same "enable, add, yield,
+ remove, disable" dance as
+ ``tests/research_library/test_download_service_contracts.py``'s
+ ``log_sink`` fixture. ``local_deep_research/__init__.py`` calls
+ ``logger.disable("local_deep_research")`` at import time, so package
+ logging is invisible to any sink until re-enabled -- and the
+ disabled state is restored afterwards so this fixture doesn't leak
+ logging-enabled into later tests.
+ """
+ from local_deep_research.security.secure_logging import logger
+
+ captured = []
+ logger.enable("local_deep_research")
+ sink_id = logger.add(
+ captured.append,
+ level="TRACE",
+ format="{level} | {name} | {message}",
+ diagnose=False,
+ backtrace=True,
+ )
+ try:
+ yield captured
+ finally:
+ logger.remove(sink_id)
+ logger.disable("local_deep_research")
+
+
# ===========================================================================
# __init__ tests
# ===========================================================================
@@ -456,6 +489,11 @@ class TestGetFullContent:
with (
patch("builtins.open", mock_open()),
+ patch.object(
+ engine_with_pdf,
+ "_download_pdf_safely",
+ return_value="/tmp/paper.pdf",
+ ),
):
import sys
@@ -485,6 +523,11 @@ class TestGetFullContent:
with (
patch("builtins.open", mock_open()),
+ patch.object(
+ engine_with_pdf,
+ "_download_pdf_safely",
+ return_value="/tmp/paper.pdf",
+ ),
):
import sys
@@ -512,6 +555,11 @@ class TestGetFullContent:
with (
patch("builtins.open", mock_open()),
+ patch.object(
+ engine_with_pdf,
+ "_download_pdf_safely",
+ return_value="/tmp/paper.pdf",
+ ),
):
import sys
@@ -546,10 +594,51 @@ class TestGetFullContent:
assert result[0]["pdf_path"] is None
def test_pdf_limit_reached(self, engine_with_pdf):
- """Once max_full_text PDFs processed, remaining use summary."""
+ """Once max_full_text PDFs processed, remaining use summary.
+
+ Uses valid arXiv ids (unlike the ``abs/1``/``abs/2`` ids this test
+ used to use) so the first download actually succeeds and
+ ``pdf_count`` reaches ``max_full_text`` for real, exercising the
+ "Reached PDF limit" ``elif`` branch in
+ ``_get_full_content``. With invalid ids ``_download_pdf_safely``
+ raised before that branch could ever be reached: the except-path
+ decrements ``pdf_count`` right back down, so the second paper
+ re-entered the *download* branch instead of the limit branch, and
+ the branch this test names went uncovered while the test stayed
+ green.
+
+ The elif's own body (``result["content"] = paper.summary`` /
+ ``result["full_content"] = paper.summary``) re-assigns the exact
+ same attribute the *default* assignment a few lines above already
+ set for every item, so a plain ``result[1]["content"] ==
+ paper2.summary`` equality check can't tell "the elif body ran"
+ from "the elif body was deleted" -- both read the same static
+ value. This is pinned instead with a ``PropertyMock`` installed
+ on ``type(paper2)`` with a ``side_effect`` list, so each of the
+ five reads ``_get_full_content`` makes of ``paper2.summary`` for
+ this item -- the ``"summary"`` field in the initial
+ ``result.update(...)``, the default ``content``/``full_content``
+ assignment, then the elif's own ``content``/``full_content``
+ reassignment -- returns a distinct value; ``result[1]["content"]``
+ and ``["full_content"]`` can then only equal the 4th/5th value if
+ the elif body actually executed.
+
+ Installing the ``PropertyMock`` on ``type(paper2)`` (a
+ class-level data descriptor) rather than on ``paper2`` itself is
+ safe here specifically because ``paper1`` and ``paper2`` do NOT
+ share a class: ``NonCallableMock.__new__`` gives every ``Mock()``
+ instance its own freshly-created subclass, so ``type(paper1) is
+ type(paper2)`` is ``False`` and this patch cannot bleed onto
+ ``paper1.summary`` reads. (An earlier version of this docstring
+ claimed the opposite -- that ``paper1``/``paper2`` "share the
+ same ``Mock`` class" and a ``type(paper2)`` patch would therefore
+ leak onto ``paper1`` -- which is false; verified directly by
+ patching ``type(paper2).summary`` via ``PropertyMock`` and
+ observing ``paper1.summary`` unaffected.)
+ """
engine_with_pdf.max_full_text = 1
- paper1 = _make_mock_paper(entry_id="http://arxiv.org/abs/1")
- paper2 = _make_mock_paper(entry_id="http://arxiv.org/abs/2")
+ paper1 = _make_mock_paper(entry_id="http://arxiv.org/abs/2101.00001")
+ paper2 = _make_mock_paper(entry_id="http://arxiv.org/abs/2101.00002")
engine_with_pdf._papers = {
paper1.entry_id: paper1,
paper2.entry_id: paper2,
@@ -564,9 +653,29 @@ class TestGetFullContent:
mock_reader = Mock()
mock_reader.pages = [mock_page]
+ summary_reads = [
+ "summary-read-1-field",
+ "summary-read-2-default-content",
+ "summary-read-3-default-full-content",
+ "summary-read-4-elif-content",
+ "summary-read-5-elif-full-content",
+ ]
+
with (
patch("builtins.open", mock_open()),
+ patch.object(
+ engine_with_pdf,
+ "_download_pdf_safely",
+ return_value="/tmp/paper1.pdf",
+ ) as mock_download,
+ patch.object(
+ type(paper2),
+ "summary",
+ new_callable=PropertyMock,
+ create=True,
+ ) as paper2_summary,
):
+ paper2_summary.side_effect = summary_reads
import sys
mock_pypdf2 = MagicMock()
@@ -575,8 +684,23 @@ class TestGetFullContent:
try:
result = engine_with_pdf._get_full_content(items)
- # Second paper should still have content (summary)
- assert result[1]["content"] == paper2.summary
+ # Only the first paper triggers a download; the second
+ # must hit the "limit reached" branch and fall back to
+ # the summary without calling the download helper again
+ # (and therefore without ever touching the network).
+ mock_download.assert_called_once()
+ assert result[0]["pdf_path"] == "/tmp/paper1.pdf"
+ assert "pdf_path" not in result[1]
+ # These can only hold if the elif body's own reassignment
+ # ran: deleting those two lines would leave
+ # result[1]["content"]/["full_content"] at the 2nd/3rd
+ # (default-assignment) read instead of the 4th/5th.
+ assert result[1]["content"] == "summary-read-4-elif-content"
+ assert (
+ result[1]["full_content"]
+ == "summary-read-5-elif-full-content"
+ )
+ assert paper2_summary.call_count == 5
finally:
del sys.modules["pypdf"]
@@ -748,6 +872,205 @@ class TestGetPaperDetails:
assert result["snippet"] == "Short"
+# ===========================================================================
+# PDF-download error handling: path-free logging + exception ordering
+# ===========================================================================
+
+
+class TestDownloadErrorLoggingOmitsPaths:
+ """The path-free logging invariant for the two containment/OSError
+ handlers -- ``except (DirectoryCreationSecurityError, OSError)`` in
+ both ``_get_full_content``'s download branch and
+ ``get_paper_details``.
+
+ Both handlers catch that pair and log a static, path-free message
+ instead of interpolating the exception, because either exception
+ type can carry the resolved, absolute download path in its own
+ ``str()``: ``DirectoryCreationSecurityError`` embeds it directly,
+ and an ``OSError`` such as ``FileExistsError`` (what
+ ``create_directory``'s own ``p.mkdir()`` raises uncaught on a
+ collision) embeds it via ``strerror``/``filename`` too. The message
+ does interpolate ``type(e).__name__`` -- that alone is path-free, and
+ lets an operator tell a containment rejection apart from e.g. a
+ disk-full ``OSError``. Deleting either handler (letting the generic
+ ``except Exception`` below it catch instead, which interpolates
+ ``str(e)`` in full) produces the exact same ``pdf_path``/``pdf_count``
+ end state -- nothing but the rendered log text itself tells the two
+ apart, so that's what these tests inspect: each asserts both that the
+ static "filesystem or directory-containment error" text (plus the
+ type name) is present, and that the path is absent -- a sink that
+ silently swallowed the record would fail the first assertion instead
+ of passing vacuously.
+ """
+
+ def test_get_full_content_containment_error_log_omits_path(
+ self, engine_with_pdf, log_sink
+ ):
+ """Catches deleting the ``(DirectoryCreationSecurityError,
+ OSError)`` handler in ``_get_full_content``'s download branch: with
+ only the generic ``except Exception`` left, the log line would
+ interpolate ``str(e)``, which for ``DirectoryCreationSecurityError``
+ embeds the resolved path."""
+ from local_deep_research.security.directory_creation import (
+ DirectoryCreationSecurityError,
+ )
+
+ paper = _make_mock_paper()
+ engine_with_pdf._papers = {paper.entry_id: paper}
+ items = [{"id": paper.entry_id, "title": "T"}]
+
+ secret_path = "/home/researcher/.secret_key_dir/zzqleak4711"
+ with patch.object(
+ engine_with_pdf,
+ "_download_pdf_safely",
+ side_effect=DirectoryCreationSecurityError(
+ f"Path {secret_path} escapes the containment root"
+ ),
+ ):
+ result = engine_with_pdf._get_full_content(items)
+
+ assert result[0]["pdf_path"] is None
+ rendered = "\n".join(str(m) for m in log_sink)
+ # Positive: the static log line was actually emitted (a sink that
+ # captured nothing would fail here instead of passing vacuously),
+ # and it names the exception type.
+ assert "a filesystem or directory-containment error" in rendered
+ assert "DirectoryCreationSecurityError" in rendered
+ # Negative: but never the path it carries.
+ assert secret_path not in rendered
+
+ def test_get_full_content_oserror_log_omits_path(
+ self, engine_with_pdf, log_sink
+ ):
+ """Same property, ``OSError`` branch -- e.g. ``create_directory``'s
+ own ``p.mkdir()`` raising ``FileExistsError`` uncaught, whose
+ message also embeds the same resolved path."""
+ paper = _make_mock_paper()
+ engine_with_pdf._papers = {paper.entry_id: paper}
+ items = [{"id": paper.entry_id, "title": "T"}]
+
+ secret_path = "/home/researcher/.secret_key_dir/zzqleak8822"
+ with patch.object(
+ engine_with_pdf,
+ "_download_pdf_safely",
+ side_effect=FileExistsError(17, f"File exists: '{secret_path}'"),
+ ):
+ result = engine_with_pdf._get_full_content(items)
+
+ assert result[0]["pdf_path"] is None
+ rendered = "\n".join(str(m) for m in log_sink)
+ # Positive: the static log line was actually emitted, and it
+ # names the exception type.
+ assert "a filesystem or directory-containment error" in rendered
+ assert "FileExistsError" in rendered
+ # Negative: but never the path it carries.
+ assert secret_path not in rendered
+
+ def test_get_paper_details_containment_error_log_omits_path(
+ self, engine_with_pdf, log_sink
+ ):
+ """Catches deleting the ``(DirectoryCreationSecurityError,
+ OSError)`` handler in ``get_paper_details``."""
+ import arxiv
+
+ from local_deep_research.security.directory_creation import (
+ DirectoryCreationSecurityError,
+ )
+
+ paper = _make_mock_paper()
+ secret_path = "/home/researcher/.secret_key_dir/zzqleak9933"
+ with (
+ patch.object(arxiv, "Client") as mock_client_cls,
+ patch.object(arxiv, "Search"),
+ patch.object(
+ engine_with_pdf,
+ "_download_pdf_safely",
+ side_effect=DirectoryCreationSecurityError(
+ f"Path {secret_path} escapes the containment root"
+ ),
+ ),
+ ):
+ mock_client = Mock()
+ mock_client.results.return_value = [paper]
+ mock_client_cls.return_value = mock_client
+
+ result = engine_with_pdf.get_paper_details("2101.00001")
+
+ assert "pdf_path" not in result
+ rendered = "\n".join(str(m) for m in log_sink)
+ # Positive: the static log line was actually emitted, and it
+ # names the exception type.
+ assert "a filesystem or directory-containment error" in rendered
+ assert "DirectoryCreationSecurityError" in rendered
+ # Negative: but never the path it carries.
+ assert secret_path not in rendered
+
+
+class TestRequestExceptionOrderingBeforeContainmentHandler:
+ """``RequestException`` must be caught -- and produce the scrubbed
+ diagnostic message -- before ``(DirectoryCreationSecurityError,
+ OSError)``. ``requests``' ``RequestException`` subclasses ``IOError``,
+ which *is* ``OSError``, so reordering the two ``except`` clauses (or
+ merging them) would silently swallow every
+ ``ConnectionError``/``Timeout``/``HTTPError`` under the static,
+ path-free containment message instead of the normal scrubbed network
+ diagnostic -- exactly the regression the ``# ORDER MATTERS`` comments
+ at both call sites warn about.
+ """
+
+ def test_connection_error_in_get_full_content_produces_scrubbed_message(
+ self, engine_with_pdf, log_sink
+ ):
+ from requests.exceptions import (
+ ConnectionError as RequestsConnectionError,
+ )
+
+ paper = _make_mock_paper()
+ engine_with_pdf._papers = {paper.entry_id: paper}
+ items = [{"id": paper.entry_id, "title": "T"}]
+
+ with patch.object(
+ engine_with_pdf,
+ "_download_pdf_safely",
+ side_effect=RequestsConnectionError("zzqnetfail1234"),
+ ):
+ result = engine_with_pdf._get_full_content(items)
+
+ assert result[0]["pdf_path"] is None
+ rendered = "\n".join(str(m) for m in log_sink)
+ assert "zzqnetfail1234" in rendered
+ assert "filesystem or directory-containment error" not in rendered
+
+ def test_connection_error_in_get_paper_details_produces_scrubbed_message(
+ self, engine_with_pdf, log_sink
+ ):
+ import arxiv
+ from requests.exceptions import (
+ ConnectionError as RequestsConnectionError,
+ )
+
+ paper = _make_mock_paper()
+ with (
+ patch.object(arxiv, "Client") as mock_client_cls,
+ patch.object(arxiv, "Search"),
+ patch.object(
+ engine_with_pdf,
+ "_download_pdf_safely",
+ side_effect=RequestsConnectionError("zzqnetfail5678"),
+ ),
+ ):
+ mock_client = Mock()
+ mock_client.results.return_value = [paper]
+ mock_client_cls.return_value = mock_client
+
+ result = engine_with_pdf.get_paper_details("2101.00001")
+
+ assert "pdf_path" not in result
+ rendered = "\n".join(str(m) for m in log_sink)
+ assert "zzqnetfail5678" in rendered
+ assert "filesystem or directory-containment error" not in rendered
+
+
# ===========================================================================
# search_by_author
# ===========================================================================
diff --git a/tests/web_search_engines/engines/test_arxiv_pdf_egress_gating.py b/tests/web_search_engines/engines/test_arxiv_pdf_egress_gating.py
index de67c06f4c..f702812fd5 100644
--- a/tests/web_search_engines/engines/test_arxiv_pdf_egress_gating.py
+++ b/tests/web_search_engines/engines/test_arxiv_pdf_egress_gating.py
@@ -8,27 +8,46 @@ than ``arxiv.Result.download_pdf``, which fetches via
fetch targets ``export.arxiv.org`` (arXiv's designated host for automated
access — the same default ``arxiv.Result.download_pdf`` uses and the host
already used for the metadata API), not the public ``arxiv.org`` host.
-
-Note: this fetch passes ``stream=True``, so ``SafeSession``'s
-response-size cap (``_check_response_size``) runs while the connection
-is still open rather than after ``requests`` has already buffered the
-whole body. An oversized response with a ``Content-Length`` header is
-now rejected immediately, before any body bytes are read. When
-``Content-Length`` is absent, the cap's guard correctly bounds memory
-for a connection-close-delimited body, but not for one sent with
-``Transfer-Encoding: chunked`` (the common case for a CDN of unknown
-length): ``urllib3`` reads chunked bodies through ``read_chunked()``,
-which bypasses the guard's patched ``read()``. That gap lives in the
-cap itself (``_check_response_size``/``_install_body_guard`` in
-``safe_requests.py``), not in this call site, and is unrelated to
-#6172 (which tracks callers that never set ``stream=True`` at all —
-this one now does).
+This is narrower than "the same session as the rest of the arXiv
+integration": this engine's metadata queries (``arxiv.Client()``) still go
+through the ``arxiv`` package's own bare, unvalidated ``requests.Session()``
+— only the PDF fetch is gated.
+
+The request URL carries no ``.pdf`` suffix (arxiv 2.4.1's own ``pdf_url``
+has none either) — appending one makes ``export.arxiv.org`` answer with a
+301 whose body is drained by ``requests``' internal redirect handling
+before any size check runs, so the suffix-less form is load-bearing, not
+cosmetic.
+
+Note: this fetch passes ``stream=True`` and writes the body to disk in
+bounded chunks via ``iter_content`` (never ``.content``, which would
+buffer the whole body in memory) with ``Accept-Encoding: identity``. A
+running byte count enforced while streaming — not ``SafeSession``'s
+``Content-Length`` check alone — is what bounds this fetch: for a valid,
+under-cap ``Content-Length`` header, ``_check_response_size`` installs no
+body guard at all, and a ``Transfer-Encoding: chunked`` body bypasses the
+guard it does install in the no-``Content-Length`` case (``urllib3`` reads
+chunked bodies through ``read_chunked()``, which does not call the patched
+``read()``). That gap lives in the cap itself
+(``_check_response_size``/``_install_body_guard`` in ``safe_requests.py``),
+not in this call site, and is unrelated to #6172 (which tracks callers
+that never set ``stream=True`` at all — this one now does).
+
+``download_dir`` is reachable from per-user web settings, so directory
+creation is contained to a dedicated ``arxiv_downloads`` subtree of the
+local-deep-research data directory (see ``get_data_directory``) rather
+than the data directory itself -- the data directory root also holds
+``.secret_key``, the per-user encrypted databases, and backups, and
+``download_dir`` is untrusted input, so containing it to a
+download-only subtree keeps the blast radius of an accepted
+``download_dir`` to that subtree. These tests patch ``get_data_directory``
+to return ``tmp_path`` so the real, platform-specific data directory is
+never touched.
These tests mock ``SafeSession`` wholesale, so they don't exercise
``_check_response_size`` — they only pin that the call site asks for
-``stream=True`` and handles the response as a context manager.
-
-These tests are written to be run by CI; they are not executed here.
+``stream=True``/``Accept-Encoding: identity`` and handles the response as
+a context manager.
"""
from pathlib import Path
@@ -54,19 +73,78 @@ def _make_engine(**kwargs):
return ArXivSearchEngine(**kwargs)
+def data_dir(tmp_path):
+ """Patch get_data_directory() to tmp_path for the duration of a test.
+
+ ``_download_pdf_safely`` contains directory creation to a dedicated
+ ``arxiv_downloads`` subtree of ``get_data_directory()`` (not the data
+ directory root itself) because ``download_dir`` is reachable from
+ per-user web settings. Patching it to ``tmp_path`` keeps these tests
+ off the real, platform-specific data directory while still exercising
+ the real containment check (a ``download_dir`` outside the patched
+ root, or inside it but outside the ``arxiv_downloads`` subtree, is
+ still rejected -- see
+ ``test_download_dir_outside_data_directory_is_rejected`` and
+ ``test_download_dir_inside_data_dir_but_outside_subtree_is_rejected``).
+ """
+ with patch(f"{ENGINE_MODULE}.get_data_directory", return_value=tmp_path):
+ yield tmp_path
+
+
+def download_dir(data_dir):
+ """The accepted download directory: inside the contained subtree.
+
+ ``_download_pdf_safely`` requires ``download_dir`` to resolve inside
+ ``get_data_directory() / "arxiv_downloads"``; the bare data directory
+ itself (what these tests used to pass directly) is now outside that
+ root and would be rejected -- see ``download_dir`` usages below.
+ """
+ return data_dir / "arxiv_downloads"
+
+
def _mock_safe_session(pdf_bytes=b"%PDF-1.4 test"):
- """Return (SafeSession class mock, session instance mock, response mock)."""
+ """Return (SafeSession class mock, session instance mock, response mock).
+
+ ``response`` (what a correct call site sees via
+ ``with session.get(...) as response:``) is deliberately a *different*
+ object from ``session.get.return_value`` (what a buggy call site would
+ see if it dropped the ``with`` and just did
+ ``response = session.get(...)``). Only entering the context manager
+ yields ``response``, whose ``raise_for_status``/``iter_content`` are
+ configured below; the bare return value's methods are unconfigured
+ ``MagicMock`` attributes. Iterating an unconfigured ``MagicMock`` does
+ *not* raise -- ``MagicMock`` pre-configures ``__iter__`` with a
+ default of ``iter([])``, so a call site that dropped the ``with`` and
+ iterated the bare return value's ``iter_content()`` result would get
+ zero chunks back from that call rather than erroring there. What
+ actually pins the "DO NOT remove the ``with``" invariant the call
+ site's own comment relies on is that ``response`` and ``get_result``
+ are different objects: a dropped ``with`` calls methods on
+ ``get_result``, never on ``response``, and streaming zero chunks
+ trips ``_stream_response_to_file``'s own empty-body check (``if
+ written == 0: raise ValueError(...)``) -- so the call to
+ ``_download_pdf_safely`` itself raises before any of the assertions
+ below run. It is *not* the ``response.raise_for_status``/
+ ``response.iter_content`` assertions (e.g. ``assert_called_once()``)
+ that catch a dropped ``with``: those never execute on that path,
+ because the ``ValueError`` propagates out of the call first. With the
+ old version of this helper, ``response.__enter__.return_value =
+ response`` made the two forms indistinguishable, so dropping the
+ ``with`` (or dropping ``raise_for_status()``) still passed every
+ assertion below.
+ """
response = MagicMock()
- response.content = pdf_bytes
response.raise_for_status = Mock()
- # The response is used as a context manager (`with session.get(...) as
- # response:`), same as a real requests.Response, whose __enter__
- # returns self.
- response.__enter__.return_value = response
- response.__exit__.return_value = False
+ response.iter_content = Mock(return_value=[pdf_bytes])
+
+ get_result = MagicMock(name="bare_get_result_not_a_context_manager")
+ get_result.__enter__.return_value = response
+ get_result.__exit__.return_value = False
session = MagicMock()
- session.get.return_value = response
+ session.get.return_value = get_result
session_cls = MagicMock()
session_cls.return_value.__enter__.return_value = session
@@ -120,59 +198,76 @@ class TestValidatedArxivId:
class TestDownloadPdfSafely:
"""The download helper must use SafeSession and never download_pdf."""
- def test_routes_through_safe_session(self, tmp_path):
+ def test_routes_through_safe_session(self, download_dir):
engine = _make_engine()
paper = Mock()
paper.entry_id = "https://arxiv.org/abs/2101.12345"
- session_cls, session, _ = _mock_safe_session(b"%PDF-1.4 payload")
+ session_cls, session, response = _mock_safe_session(b"%PDF-1.4 payload")
with patch(f"{ENGINE_MODULE}.SafeSession", session_cls):
- path = engine._download_pdf_safely(paper, str(tmp_path))
+ path = engine._download_pdf_safely(paper, str(download_dir))
# SafeSession was constructed and used as the fetch transport.
assert session_cls.called
session.get.assert_called_once()
called_url = session.get.call_args.args[0]
- assert called_url == "https://export.arxiv.org/pdf/2101.12345.pdf"
+ # No ".pdf" suffix -- see the module docstring for why that matters.
+ assert called_url == "https://export.arxiv.org/pdf/2101.12345"
+
+ # The response was consumed via the context manager, not the bare
+ # session.get() return value (see _mock_safe_session's docstring).
+ response.raise_for_status.assert_called_once()
+ response.iter_content.assert_called_once()
# arxiv.Result.download_pdf (the ungated urlretrieve path) is never used.
assert not paper.download_pdf.called
- # Bytes were written to the returned path inside dirpath.
- assert Path(path).parent == tmp_path
+ # Bytes were written to the returned path inside dirpath, and no
+ # ".part" temp sibling is left behind after a successful download.
+ assert Path(path).parent == download_dir
assert Path(path).is_file()
+ assert Path(path).name == "2101.12345.pdf"
+ assert list(download_dir.iterdir()) == [Path(path)]
with open(path, "rb") as fh:
assert fh.read() == b"%PDF-1.4 payload"
- def test_uses_streaming_get(self, tmp_path):
- """stream=True lets SafeSession's response-size cap run before the
- body is buffered instead of after — see the module docstring."""
+ def test_uses_streaming_get_with_identity_encoding(self, download_dir):
+ """stream=True lets the body be written to disk in bounded chunks
+ instead of buffered whole via `.content` — see the module
+ docstring. Accept-Encoding: identity is a best-effort measure
+ against a gzip/deflate decompression bomb on this fetch; the
+ running byte cap over the decoded stream is the actual backstop
+ (see the module docstring for why identity alone isn't enough)."""
engine = _make_engine()
paper = Mock()
paper.entry_id = "https://arxiv.org/abs/2101.12345"
session_cls, session, _ = _mock_safe_session()
with patch(f"{ENGINE_MODULE}.SafeSession", session_cls):
- engine._download_pdf_safely(paper, str(tmp_path))
+ engine._download_pdf_safely(paper, str(download_dir))
assert session.get.call_args.kwargs["stream"] is True
+ assert (
+ session.get.call_args.kwargs["headers"]["Accept-Encoding"]
+ == "identity"
+ )
- def test_url_is_built_from_validated_id(self, tmp_path):
+ def test_url_is_built_from_validated_id(self, download_dir):
engine = _make_engine()
paper = Mock()
paper.entry_id = "http://arxiv.org/abs/2301.12345v3"
session_cls, session, _ = _mock_safe_session()
with patch(f"{ENGINE_MODULE}.SafeSession", session_cls):
- engine._download_pdf_safely(paper, str(tmp_path))
+ engine._download_pdf_safely(paper, str(download_dir))
assert (
session.get.call_args.args[0]
- == "https://export.arxiv.org/pdf/2301.12345v3.pdf"
+ == "https://export.arxiv.org/pdf/2301.12345v3"
)
- def test_raises_and_makes_no_request_for_bad_id(self, tmp_path):
+ def test_raises_and_makes_no_request_for_bad_id(self, download_dir):
engine = _make_engine()
paper = Mock()
paper.entry_id = "https://evil.example.com/abs/2101.12345"
@@ -180,26 +275,295 @@ class TestDownloadPdfSafely:
session_cls, session, _ = _mock_safe_session()
with patch(f"{ENGINE_MODULE}.SafeSession", session_cls):
with pytest.raises(ValueError):
- engine._download_pdf_safely(paper, str(tmp_path))
+ engine._download_pdf_safely(paper, str(download_dir))
# No egress attempted for an id that fails validation.
assert not session.get.called
assert not session_cls.called
+ def test_oversized_streamed_body_is_rejected_and_not_left_on_disk(
+ self, download_dir
+ ):
+ """A body that grows past MAX_RESPONSE_SIZE while being streamed
+ must be rejected, and no partial file left behind -- this is the
+ guard that actually bounds a decompressed/chunked body, since
+ SafeSession's own Content-Length check installs no guard at all
+ for a valid, under-cap header (see the module docstring).
+
+ The body is streamed to a unique ``.part`` sibling and only
+ ``os.replace()``d onto the final path on success (see
+ ``_stream_response_to_file``'s docstring), so a rejected download
+ must leave that ``.part`` file removed too, not just the final
+ ``<id>.pdf`` path absent.
+
+ Patches the module's ``MAX_RESPONSE_SIZE`` down to a few bytes
+ instead of allocating a real ~1GB chunk, which would needlessly
+ pressure memory for a check that only cares about the comparison,
+ not the actual cap value.
+ """
+ engine = _make_engine()
+ paper = Mock()
+ paper.entry_id = "https://arxiv.org/abs/2101.12345"
+
+ oversized_chunk = b"x" * 32
+ session_cls, session, response = _mock_safe_session()
+ response.iter_content = Mock(return_value=[oversized_chunk])
+
+ with (
+ patch(f"{ENGINE_MODULE}.SafeSession", session_cls),
+ patch(f"{ENGINE_MODULE}.MAX_RESPONSE_SIZE", 8),
+ ):
+ with pytest.raises(ValueError):
+ engine._download_pdf_safely(paper, str(download_dir))
+
+ # No leftover partial PDF (nor its ".part" temp sibling) for a
+ # rejected download.
+ assert list(download_dir.iterdir()) == []
+
+ def test_download_dir_outside_data_directory_is_rejected(
+ self, data_dir, tmp_path_factory
+ ):
+ """download_dir is untrusted (reachable from per-user settings), so
+ directory creation must stay contained to the arxiv_downloads
+ subtree of get_data_directory() -- a sibling directory entirely
+ outside the data directory must be rejected rather than silently
+ created."""
+ from local_deep_research.security.directory_creation import (
+ DirectoryCreationSecurityError,
+ )
+
+ engine = _make_engine()
+ paper = Mock()
+ paper.entry_id = "https://arxiv.org/abs/2101.12345"
+
+ outside_dir = tmp_path_factory.mktemp("outside_data_dir")
+ session_cls, session, _ = _mock_safe_session()
+
+ with patch(f"{ENGINE_MODULE}.SafeSession", session_cls):
+ with pytest.raises(DirectoryCreationSecurityError):
+ engine._download_pdf_safely(paper, str(outside_dir))
+
+ # Rejected before any egress was attempted.
+ assert not session.get.called
+
+ def test_download_dir_inside_data_dir_but_outside_subtree_is_rejected(
+ self, data_dir
+ ):
+ """A download_dir that resolves inside get_data_directory() but
+ outside its arxiv_downloads subtree must still be rejected --
+ this is the containment-root-too-broad regression this subtree
+ exists to close. Before the subtree narrowing, any path under the
+ bare data directory (including e.g. a not-yet-existing per-user
+ encrypted-DB path, since the username hash is computable) was
+ accepted; now only paths under arxiv_downloads are."""
+ from local_deep_research.security.directory_creation import (
+ DirectoryCreationSecurityError,
+ )
+
+ engine = _make_engine()
+ paper = Mock()
+ paper.entry_id = "https://arxiv.org/abs/2101.12345"
+
+ # A sibling of arxiv_downloads, still inside data_dir.
+ sibling_dir = data_dir / "encrypted_databases"
+ session_cls, session, _ = _mock_safe_session()
+
+ with patch(f"{ENGINE_MODULE}.SafeSession", session_cls):
+ with pytest.raises(DirectoryCreationSecurityError):
+ engine._download_pdf_safely(paper, str(sibling_dir))
+
+ # Rejected before any egress was attempted, and nothing was created.
+ assert not session.get.called
+ assert not sibling_dir.exists()
+
+
+class TestStreamResponseToFileIntermediateState:
+ """The body must never be visible at ``target_path`` until the fetch
+ fully completes -- it is streamed to a per-call ``.part`` sibling and
+ only ``os.replace()``d onto ``target_path`` afterwards (see
+ ``_stream_response_to_file``'s docstring).
+
+ Both existing assertions in ``TestDownloadPdfSafely`` only inspect the
+ directory listing *after* ``_download_pdf_safely`` has already
+ returned -- ``test_routes_through_safe_session``'s
+ ``list(download_dir.iterdir()) == [Path(path)]`` and the
+ oversized-body test's ``== []`` -- so a revert straight back to
+ streaming directly into ``target_path`` (dropping the ``.part`` +
+ ``os.replace()`` indirection entirely) still satisfies both of them:
+ the *final* directory state is identical either way (one completed
+ file, or none). These tests instead inspect the state *while the body
+ is still streaming*, which is the only place that revert actually
+ differs.
+ """
+
+ def test_target_path_does_not_exist_mid_stream(self, download_dir):
+ """Catches a revert of ``_stream_response_to_file`` to opening
+ ``target_path`` itself for writing (no ``.part`` sibling, no
+ rename): on that revert, ``target_path`` would already exist
+ (partially written) by the time a later chunk is requested, and
+ no ``.part``-suffixed file would exist at all.
+ """
+ engine = _make_engine()
+ paper = Mock()
+ paper.entry_id = "https://arxiv.org/abs/2101.12345"
+ target_name = "2101.12345.pdf"
+ observed = {}
+
+ def chunks():
+ yield b"first-chunk-bytes"
+ # Mid-stream: the first chunk has already been written to
+ # disk, but the response body has not finished streaming.
+ observed["target_exists"] = (download_dir / target_name).exists()
+ observed["part_files"] = [
+ p.name
+ for p in download_dir.iterdir()
+ if p.name.startswith(target_name + ".")
+ and p.name.endswith(".part")
+ ]
+ yield b"second-chunk-bytes"
+
+ session_cls, session, response = _mock_safe_session()
+ response.iter_content = Mock(return_value=chunks())
+
+ with patch(f"{ENGINE_MODULE}.SafeSession", session_cls):
+ engine._download_pdf_safely(paper, str(download_dir))
+
+ assert observed["target_exists"] is False
+ assert len(observed["part_files"]) == 1
+
+ def test_part_suffix_is_unique_per_call(self, download_dir):
+ """Catches unpinning the ``uuid4().hex`` component of the
+ ``.part`` filename (reverting ``_stream_response_to_file`` to a
+ fixed ``<target_name>.part`` sibling with no per-call-unique
+ suffix). ``test_target_path_does_not_exist_mid_stream`` above only
+ checks that *a* name matching ``startswith(name + ".") and
+ endswith(".part")`` exists mid-stream -- a fixed ``<name>.part``
+ satisfies that filter just as well as a uuid-suffixed one, so it
+ can't tell the two apart. The whole point of the per-call-unique
+ suffix, per the function's docstring, is that two concurrent
+ downloads of the same arXiv id can only ever remove *their own*
+ partial file; this test drives the streaming write twice for the
+ same id and captures the generated ``.part`` name each time --
+ under a fixed-suffix revert both calls would produce the
+ identical name.
+ """
+ engine = _make_engine()
+ target_name = "2101.12345.pdf"
+ observed_names = []
+
+ def make_chunks():
+ def chunks():
+ yield b"first-chunk-bytes"
+ names = [
+ p.name
+ for p in download_dir.iterdir()
+ if p.name.startswith(target_name + ".")
+ and p.name.endswith(".part")
+ ]
+ assert len(names) == 1
+ observed_names.append(names[0])
+ yield b"second-chunk-bytes"
+
+ return chunks()
+
+ for _ in range(2):
+ paper = Mock()
+ paper.entry_id = "https://arxiv.org/abs/2101.12345"
+ session_cls, session, response = _mock_safe_session()
+ response.iter_content = Mock(return_value=make_chunks())
+
+ with patch(f"{ENGINE_MODULE}.SafeSession", session_cls):
+ engine._download_pdf_safely(paper, str(download_dir))
+
+ assert len(observed_names) == 2
+ assert observed_names[0] != observed_names[1]
+ assert observed_names[0] != f"{target_name}.part"
+ assert observed_names[1] != f"{target_name}.part"
+
+ def test_keyboard_interrupt_mid_stream_cleans_up_part_file(
+ self, download_dir
+ ):
+ """Catches rewriting ``_stream_response_to_file``'s cleanup from a
+ ``finally`` block to ``except Exception: unlink(...); raise``.
+ Every other test in this module only ever raises ``Exception``
+ subclasses (``ValueError``, an oversized-chunk rejection, etc.),
+ so an ``except Exception``-based rewrite would pass all of them
+ too. ``KeyboardInterrupt`` does not subclass ``Exception`` (it
+ subclasses ``BaseException`` directly), so that rewrite would let
+ it propagate straight past the cleanup, orphaning the ``.part``
+ file -- up to ``MAX_RESPONSE_SIZE`` bytes -- in the shared
+ ``arxiv_downloads`` root with no sweeper to reclaim it. This test
+ must let the ``KeyboardInterrupt`` propagate out of
+ ``_download_pdf_safely`` and catch it explicitly (a bare
+ ``except Exception`` in the test itself would just as wrongly
+ swallow it).
+ """
+ engine = _make_engine()
+ paper = Mock()
+ paper.entry_id = "https://arxiv.org/abs/2101.12345"
+
+ def chunks():
+ yield b"first-chunk-bytes"
+ raise KeyboardInterrupt()
+
+ session_cls, session, response = _mock_safe_session()
+ response.iter_content = Mock(return_value=chunks())
+
+ with patch(f"{ENGINE_MODULE}.SafeSession", session_cls):
+ with pytest.raises(KeyboardInterrupt):
+ engine._download_pdf_safely(paper, str(download_dir))
+
+ # `finally` (not `except Exception`) ran the cleanup: no orphaned
+ # `.part` file -- or anything else -- is left behind.
+ assert list(download_dir.iterdir()) == []
+
+ def test_empty_body_does_not_replace_existing_complete_download(
+ self, download_dir
+ ):
+ """A ``200`` with a zero-byte body must be rejected before
+ ``os.replace()`` runs, and must never overwrite an
+ already-completed ``target_path`` left by an earlier, separate
+ download of the same id.
+
+ Catches dropping (or reordering after ``os.replace()``) the
+ ``written == 0`` check in ``_stream_response_to_file``: on that
+ revert this test's pre-seeded, already-complete ``target_path``
+ would be silently replaced by a 0-byte file while the call still
+ reported success (no exception raised).
+ """
+ engine = _make_engine()
+ paper = Mock()
+ paper.entry_id = "https://arxiv.org/abs/2101.12345"
+
+ download_dir.mkdir(parents=True, exist_ok=True)
+ target_path = download_dir / "2101.12345.pdf"
+ target_path.write_bytes(b"%PDF-1.4 already complete")
+
+ session_cls, session, response = _mock_safe_session()
+ response.iter_content = Mock(return_value=[]) # zero bytes streamed
+
+ with patch(f"{ENGINE_MODULE}.SafeSession", session_cls):
+ with pytest.raises(ValueError):
+ engine._download_pdf_safely(paper, str(download_dir))
+
+ assert target_path.read_bytes() == b"%PDF-1.4 already complete"
+ # No leftover ".part" sibling either.
+ assert list(download_dir.iterdir()) == [target_path]
+
class TestFullContentUsesGatedPath:
"""The higher-level full-content path must also avoid download_pdf."""
- def test_get_full_content_uses_safe_session(self, tmp_path):
+ def test_get_full_content_uses_safe_session(self, download_dir):
engine = _make_engine(
include_full_text=True,
- download_dir=str(tmp_path),
+ download_dir=str(download_dir),
max_full_text=1,
)
paper = Mock()
paper.entry_id = "https://arxiv.org/abs/2101.12345"
- paper.pdf_url = "https://arxiv.org/pdf/2101.12345.pdf"
+ paper.pdf_url = "https://arxiv.org/pdf/2101.12345"
paper.authors = []
paper.published = None
paper.updated = None