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(downloads): inspect downloaded PDF body signatures (#7881)

LearningCircuita7fae957395a
diff --git a/changelog.d/5865.bugfix.md b/changelog.d/5865.bugfix.md
new file mode 100644
index 0000000000..8c59de7bec
--- /dev/null
+++ b/changelog.d/5865.bugfix.md
@@ -0,0 +1 @@
+Check downloaded PDF body signatures even when the response declares a PDF content type, while accepting bounded whitespace and UTF-8 BOM prefixes.
diff --git a/src/local_deep_research/research_library/downloaders/base.py b/src/local_deep_research/research_library/downloaders/base.py
index dd77366a3f..5f7a4a6541 100644
--- a/src/local_deep_research/research_library/downloaders/base.py
+++ b/src/local_deep_research/research_library/downloaders/base.py
@@ -322,6 +322,14 @@ class BaseDownloader(ABC):
)
return None
+ @staticmethod
+ def _has_pdf_signature(content: bytes) -> bool:
+ """Allow whitespace and one UTF-8 BOM within a bounded PDF prefix."""
+ header = content[:1024].lstrip()
+ if header.startswith(b"\xef\xbb\xbf"):
+ header = header[3:].lstrip()
+ return len(header) > 4 and header.startswith(b"%PDF")
+
def _is_pdf_content(
self, response: requests.Response, content: bytes | None = None
) -> bool:
@@ -341,25 +349,15 @@ class BaseDownloader(ABC):
Returns:
True if response appears to contain PDF content
"""
- headers = getattr(response, "headers", {}) or {}
- try:
- content_type = headers.get("content-type", "").lower()
- except Exception:
- content_type = ""
-
- # Check content type
- if "pdf" in content_type:
- return True
-
- # Check if content starts with PDF magic bytes
+ # Inspect the body even when the server declares a PDF media type.
if content is not None:
# Caller-supplied bytes: the read already happened and
# succeeded, so there is nothing left to swallow here.
- return len(content) > 4 and content[:4] == b"%PDF"
+ return self._has_pdf_signature(content)
try:
body = getattr(response, "content", b"") or b""
if len(body) > 4:
- return body[:4] == b"%PDF"
+ return self._has_pdf_signature(body)
except Exception:
logger.debug("base.pdf_magic_check_failed")
@@ -505,7 +503,7 @@ class BaseDownloader(ABC):
body = response.content
except ValueError as e:
raise _ResponseBodyTooLarge(str(e)) from e
- if self._is_pdf_content(response):
+ if self._is_pdf_content(response, content=body):
logger.debug(
f"Successfully downloaded PDF from "
f"{redact_url_for_log(url)} on attempt {attempt}"
diff --git a/tests/research_library/downloaders/test_base_downloader.py b/tests/research_library/downloaders/test_base_downloader.py
index a4c8c1741e..82a4d34a95 100644
--- a/tests/research_library/downloaders/test_base_downloader.py
+++ b/tests/research_library/downloaders/test_base_downloader.py
@@ -158,12 +158,12 @@ class TestDownloadWithResult:
class TestIsPdfContent:
"""Tests for _is_pdf_content helper method."""
- def test_is_pdf_content_by_content_type(self, mocker):
- """Detects PDF by content-type header."""
+ def test_is_pdf_content_with_pdf_header_and_signature(self, mocker):
+ """Accepts a declared PDF when its body has the PDF signature."""
downloader = ConcreteDownloader()
response = mocker.Mock()
response.headers = {"content-type": "application/pdf"}
- response.content = b"some content"
+ response.content = b"%PDF-1.4 content"
assert downloader._is_pdf_content(response) is True
def test_is_pdf_content_by_magic_bytes(self, mocker):
@@ -593,6 +593,10 @@ class _FiniteBombRaw:
pass
+class _FinitePdfRaw(_FiniteBombRaw):
+ CHUNK = b"%PDF-1.4\n" + _FiniteBombRaw.CHUNK[9:]
+
+
class TestDownloadPdfBodyCap:
"""The PDF transport must bound the decoded body size while reading."""
@@ -604,7 +608,7 @@ class TestDownloadPdfBodyCap:
# so SafeSession.send (which guards this framing too) never runs:
# the abort can only come from BaseDownloader's own guard install.
response.headers["Content-Length"] = "100"
- response.raw = _FiniteBombRaw(chunks)
+ response.raw = _FinitePdfRaw(chunks)
return response
def test_oversized_decoded_body_aborts_download(self, mocker, monkeypatch):
@@ -612,7 +616,7 @@ class TestDownloadPdfBodyCap:
Red under reverting the _ensure_decoded_body_cap call: without
the guard install the whole finite bomb (4 MiB against a 2 MiB
- cap) is read, passes the content-type PDF check, and is returned
+ cap) is read, passes the PDF signature check, and is returned
as a successful download.
"""
from local_deep_research.security import safe_requests
@@ -655,7 +659,7 @@ class TestDownloadPdfBodyCap:
content = downloader._download_pdf("https://example.com/paper.pdf")
- assert content == _FiniteBombRaw.CHUNK
+ assert content == _FinitePdfRaw.CHUNK
assert record.call_args.kwargs["success"] is True
# stream=True is load-bearing: without it Session.send consumes
# the body before the guard could wrap the reads
diff --git a/tests/research_library/downloaders/test_pdf_body_identification.py b/tests/research_library/downloaders/test_pdf_body_identification.py
new file mode 100644
index 0000000000..026cd4cd8a
--- /dev/null
+++ b/tests/research_library/downloaders/test_pdf_body_identification.py
@@ -0,0 +1,189 @@
+"""Downloaded PDF detection follows body bytes across response media types."""
+
+from io import BytesIO
+
+import pytest
+import requests
+from pypdf import PdfReader, PdfWriter
+
+from local_deep_research.research_library.downloaders.base import (
+ BaseDownloader,
+ ContentType,
+)
+
+
+class _Downloader(BaseDownloader):
+ def can_handle(self, url):
+ return True
+
+ def download(self, url, content_type=ContentType.PDF):
+ return None
+
+
+def downloader():
+ with _Downloader() as instance:
+ yield instance
+
+
+def response_with(body, content_type="application/pdf"):
+ response = requests.Response()
+ response.status_code = 200
+ response.headers["content-type"] = content_type
+ response._content = body
+ return response
+
+
+def readable_pdf_with_prefix(prefix):
+ buffer = BytesIO()
+ with PdfWriter() as writer:
+ writer.add_blank_page(width=72, height=72)
+ writer.pdf_header = prefix + b"%PDF-1.4"
+ writer.write(buffer)
+ return buffer.getvalue()
+
+
+ "prefix",
+ [
+ b"\n",
+ b"\xef\xbb\xbf",
+ b" \t\r\n",
+ b"\xef\xbb\xbf \r\n",
+ b" \xef\xbb\xbf\n",
+ ],
+ ids=["newline", "bom", "whitespace", "bom-whitespace", "whitespace-bom"],
+)
+ "content_type",
+ ["application/pdf", "application/octet-stream"],
+ ids=["pdf_header", "other_header"],
+)
+ "preloaded", [False, True], ids=["response", "preloaded"]
+)
+def test_readable_prefixed_pdf_is_accepted(
+ downloader, prefix, content_type, preloaded
+):
+ body = readable_pdf_with_prefix(prefix)
+ assert len(PdfReader(BytesIO(body)).pages) == 1
+ response = response_with(body, content_type)
+
+ if preloaded:
+ assert downloader._is_pdf_content(response, content=body) is True
+ else:
+ assert downloader._is_pdf_content(response) is True
+
+
+ "body",
+ [
+ b"<html>%PDF-1.4</html>",
+ b"prefix%PDF-1.4",
+ b"\xef\xbb%PDF-1.4",
+ b"\xbb\xbf%PDF-1.4",
+ b"\xef\xbb\xbf\xef\xbb\xbf%PDF-1.4",
+ b"\xef\xbb\xbf",
+ b"\n%PDF",
+ b"\xef\xbb\xbf \nnot a PDF",
+ ],
+)
+ "preloaded", [False, True], ids=["response", "preloaded"]
+)
+def test_unrelated_or_incomplete_pdf_prefix_is_rejected(
+ downloader, body, preloaded
+):
+ response = response_with(body)
+ if preloaded:
+ assert downloader._is_pdf_content(response, content=body) is False
+ else:
+ assert downloader._is_pdf_content(response) is False
+
+
+ ("padding", "accepted"), [(1019, True), (1020, False), (1024, False)]
+)
+ "preloaded", [False, True], ids=["response", "preloaded"]
+)
+def test_pdf_signature_check_is_bounded(
+ downloader, padding, accepted, preloaded
+):
+ body = b" " * padding + b"%PDF-1.4\nbody"
+ response = response_with(body)
+ if preloaded:
+ assert downloader._is_pdf_content(response, content=body) is accepted
+ else:
+ assert downloader._is_pdf_content(response) is accepted
+
+
[email protected]("body", [b"not a PDF", b"", b"%PDF"])
+def test_declared_pdf_still_requires_body_signature(downloader, body):
+ assert downloader._is_pdf_content(response_with(body)) is False
+
+
+ "content_type",
+ ["application/pdf", "application/octet-stream", "text/plain"],
+)
+def test_pdf_signature_is_accepted_independently_of_header(
+ downloader, content_type
+):
+ body = b"%PDF-1.4\nbody"
+ assert downloader._is_pdf_content(response_with(body, content_type)) is True
+
+
[email protected]("body", [b"not a PDF", b"", b"%PDF"])
+def test_preloaded_body_must_also_have_signature(downloader, body):
+ assert (
+ downloader._is_pdf_content(
+ response_with(b"%PDF-1.4\nold"), content=body
+ )
+ is False
+ )
+
+
+def test_preloaded_pdf_does_not_read_the_response_body(downloader):
+ class UnreadResponse:
+ headers = {"content-type": "application/pdf"}
+
+ @property
+ def content(self):
+ raise AssertionError("the caller already read the body")
+
+ assert (
+ downloader._is_pdf_content(UnreadResponse(), content=b"%PDF-1.4\nbody")
+ is True
+ )
+
+
+def test_non_pdf_download_does_not_report_success(downloader, mocker):
+ response = response_with(b"not a PDF")
+ mocker.patch.object(downloader.session, "get", return_value=response)
+ mocker.patch.object(downloader, "_ensure_decoded_body_cap")
+ mocker.patch.object(
+ downloader.rate_tracker, "apply_rate_limit", return_value=0
+ )
+ outcome = mocker.patch.object(downloader.rate_tracker, "record_outcome")
+
+ assert downloader._download_pdf("https://example.com/document.pdf") is None
+ assert outcome.call_args.kwargs["success"] is False
+
+
+ "prefix", [b"\n", b"\xef\xbb\xbf"], ids=["newline", "bom"]
+)
+def test_prefixed_pdf_download_preserves_body(downloader, mocker, prefix):
+ body = readable_pdf_with_prefix(prefix)
+ mocker.patch.object(
+ downloader.session, "get", return_value=response_with(body)
+ )
+ mocker.patch.object(downloader, "_ensure_decoded_body_cap")
+ mocker.patch.object(
+ downloader.rate_tracker, "apply_rate_limit", return_value=0
+ )
+ outcome = mocker.patch.object(downloader.rate_tracker, "record_outcome")
+
+ assert downloader._download_pdf("https://example.com/document.pdf") == body
+ assert outcome.call_args.kwargs["success"] is True
diff --git a/tests/research_library/test_download_service_contracts.py b/tests/research_library/test_download_service_contracts.py
index b60553c151..20d13f5f76 100644
--- a/tests/research_library/test_download_service_contracts.py
+++ b/tests/research_library/test_download_service_contracts.py
@@ -1464,17 +1464,9 @@ def test_a_pdf_url_serving_html_is_rejected():
assert downloader._download_pdf(url) is None
-def test_a_pdf_content_type_header_alone_is_trusted():
- """CHARACTERIZATION of a defect: the header is believed, not the bytes.
-
- ``BaseDownloader._is_pdf_content`` returns True as soon as "pdf"
- appears in the content-type; the ``%PDF`` magic-byte check is only
- reached when the header does NOT claim PDF. So a remote server that
- labels an HTML sign-in page ``application/pdf`` has its HTML accepted
- as PDF content. (A sibling agent found the collection-upload path
- inconsistent about exactly this check.)
- """
- url = "https://evil.example.com/paper"
+def test_a_pdf_content_type_header_requires_matching_body():
+ """The downloader requires PDF bytes even with a PDF content type."""
+ url = "https://example.com/paper"
downloader = _make_downloader(
DirectPDFDownloader,
StubResponse(
@@ -1484,7 +1476,7 @@ def test_a_pdf_content_type_header_alone_is_trusted():
),
)
- assert downloader._download_pdf(url) == HTML_BYTES
+ assert downloader._download_pdf(url) is None
assert not HTML_BYTES.startswith(b"%PDF")