~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(security): check only the first page of an uploaded PDF (#6782)
Lukas94ce86c40877
diff --git a/changelog.d/6771.security.md b/changelog.d/6771.security.mdnew file mode 100644index 0000000000..c65fc45eab--- /dev/null+++ b/changelog.d/6771.security.md@@ -0,0 +1 @@+PDF upload validation (`FileUploadValidator.validate_pdf_structure`) now inspects only the first page instead of building every page the file declares. pdfplumber's `PDF.pages`, which its `close()` also walks, parsed and constructed every page object before page 0 was looked at: a 10.5 MB upload declaring 100,000 pages measured 7.2 s and 423 MB RSS in the validator, and now measures 0.7 s and 154 MB. The first page is still built with pdfplumber, so its boxes are validated exactly as before. Scope, so this is not read as broader than it is: later pages are no longer checked at upload time (text extraction still reads them), and a page tree whose root `/Kids` array is itself huge is still parsed in full, because pdfminer reads that array as one object; that cost grows with the array's size in bytes, not with the number of pages built.diff --git a/src/local_deep_research/security/file_upload_validator.py b/src/local_deep_research/security/file_upload_validator.pyindex 58ce773401..34de24a035 100644--- a/src/local_deep_research/security/file_upload_validator.py+++ b/src/local_deep_research/security/file_upload_validator.py@@ -13,6 +13,8 @@ from typing import Optional, Tupleimport pdfplumberfrom loguru import logger+from pdfminer.pdfpage import PDFPage+from pdfplumber.page import Pagefrom ..settings.manager import check_env_setting@@ -176,7 +178,8 @@ class FileUploadValidator:Validate PDF structure to detect malicious or corrupted files.This goes beyond just checking the magic bytes and actually attempts- to parse the PDF structure.+ to parse the PDF structure. Only the first page is inspected, so the+ cost does not grow with the number of pages the file declares.Args:filename: Original filename@@ -186,16 +189,22 @@ class FileUploadValidator:Tuple of (is_valid, error_message)"""try:- # Attempt to open and parse the PDF structure- with pdfplumber.open(io.BytesIO(file_content)) as pdf:- # Check if PDF has pages- if not pdf.pages or len(pdf.pages) == 0:- return False, f"Invalid PDF: {filename}. No pages found"-- # Try to access first page metadata to ensure it's parseable- first_page = pdf.pages[0]- _ = first_page.width # Access basic metadata- _ = first_page.height+ # Not a ``with`` block: pdfplumber's ``PDF.pages`` -- which+ # ``PDF.close()`` walks too -- parses and builds every page up+ # front, so an 11 MB upload declaring 100,000 pages cost hundreds+ # of MB and over ten seconds here (#6771). The page tree is walked+ # lazily instead and stops at the first page; nothing needs+ # closing for an in-memory stream.+ pdf = pdfplumber.open(io.BytesIO(file_content))+ page_obj = next(PDFPage.create_pages(pdf.doc), None)+ if page_obj is None:+ return False, f"Invalid PDF: {filename}. No pages found"++ # pdfplumber's Page validates the first page's boxes exactly as+ # building ``pdf.pages`` would.+ first_page = Page(pdf, page_obj, page_number=1)+ _ = first_page.width # Access basic metadata+ _ = first_page.heightreturn True, Nonediff --git a/tests/security/test_file_upload_validator.py b/tests/security/test_file_upload_validator.pyindex 2ff391a731..4c9c45f687 100644--- a/tests/security/test_file_upload_validator.py+++ b/tests/security/test_file_upload_validator.py@@ -2,12 +2,40 @@Tests for FileUploadValidator security module."""-from unittest.mock import Mock, patch+from unittest.mock import patch++from pdfminer.pdfpage import PDFPagefrom local_deep_research.security.file_upload_validator import (FileUploadValidator,)+_PAGE = b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"+++def _pdf(*objects: bytes) -> bytes:+ """Hand-roll a PDF from its numbered objects; object 1 is the catalog."""+ out = bytearray(b"%PDF-1.4\n")+ offsets = []+ for number, body in enumerate(objects, 1):+ offsets.append(len(out))+ out += b"%d 0 obj\n%s\nendobj\n" % (number, body)+ xref_at = len(out)+ out += b"xref\n0 %d\n0000000000 65535 f \n" % (len(objects) + 1)+ out += b"".join(b"%010d 00000 n \n" % offset for offset in offsets)+ out += b"trailer\n<< /Size %d /Root 1 0 R >>\n" % (len(objects) + 1)+ return bytes(out) + b"startxref\n%d\n%%%%EOF\n" % xref_at+++def _pdf_with_pages(count: int, page: bytes = _PAGE) -> bytes:+ """A PDF whose flat page tree holds ``count`` distinct page objects."""+ kids = b" ".join(b"%d 0 R" % number for number in range(3, count + 3))+ return _pdf(+ b"<< /Type /Catalog /Pages 2 0 R >>",+ b"<< /Type /Pages /Kids [%s] /Count %d >>" % (kids, count),+ *[page] * count,+ )+class TestFileUploadValidatorConstants:"""Tests for FileUploadValidator constants."""@@ -247,46 +275,23 @@ class TestValidatePdfStructure:def test_valid_pdf_structure(self, mock_pdf_content):"""Accepts valid PDF structure."""- with patch(- "local_deep_research.security.file_upload_validator.pdfplumber"- ) as mock_pdfplumber:- mock_pdf = Mock()- mock_page = Mock()- mock_page.width = 612- mock_page.height = 792- mock_pdf.pages = [mock_page]- mock_pdfplumber.open.return_value.__enter__ = Mock(- return_value=mock_pdf- )- mock_pdfplumber.open.return_value.__exit__ = Mock(- return_value=False- )-- is_valid, error = FileUploadValidator.validate_pdf_structure(- "document.pdf", mock_pdf_content- )- assert is_valid is True- assert error is None+ is_valid, error = FileUploadValidator.validate_pdf_structure(+ "document.pdf", mock_pdf_content+ )+ assert is_valid is True+ assert error is None- def test_pdf_no_pages(self, mock_pdf_content):+ def test_pdf_no_pages(self):"""Rejects PDF with no pages."""- with patch(- "local_deep_research.security.file_upload_validator.pdfplumber"- ) as mock_pdfplumber:- mock_pdf = Mock()- mock_pdf.pages = []- mock_pdfplumber.open.return_value.__enter__ = Mock(- return_value=mock_pdf- )- mock_pdfplumber.open.return_value.__exit__ = Mock(- return_value=False- )-- is_valid, error = FileUploadValidator.validate_pdf_structure(- "document.pdf", mock_pdf_content- )- assert is_valid is False- assert "no pages" in error.lower()+ empty = _pdf(+ b"<< /Type /Catalog /Pages 2 0 R >>",+ b"<< /Type /Pages /Kids [] /Count 0 >>",+ )+ is_valid, error = FileUploadValidator.validate_pdf_structure(+ "document.pdf", empty+ )+ assert is_valid is False+ assert "no pages" in error.lower()def test_pdf_parse_error(self, mock_pdf_content):"""Rejects PDF that cannot be parsed."""@@ -301,25 +306,30 @@ class TestValidatePdfStructure:assert is_valid is Falseassert "invalid" in error.lower() or "corrupted" in error.lower()- def test_pdf_none_pages(self, mock_pdf_content):- """Rejects PDF with None pages."""- with patch(- "local_deep_research.security.file_upload_validator.pdfplumber"- ) as mock_pdfplumber:- mock_pdf = Mock()- mock_pdf.pages = None- mock_pdfplumber.open.return_value.__enter__ = Mock(- return_value=mock_pdf- )- mock_pdfplumber.open.return_value.__exit__ = Mock(- return_value=False- )+ def test_first_page_without_media_box_is_rejected(self):+ """The first page's boxes are checked the way pdfplumber builds pages."""+ is_valid, error = FileUploadValidator.validate_pdf_structure(+ "document.pdf",+ _pdf_with_pages(1, page=b"<< /Type /Page /Parent 2 0 R >>"),+ )+ assert is_valid is False+ assert "corrupted" in error.lower()- is_valid, error = FileUploadValidator.validate_pdf_structure(- "document.pdf", mock_pdf_content- )- assert is_valid is False- assert "no pages" in error.lower()+ def test_only_the_first_page_is_built(self, monkeypatch):+ """A file declaring many pages costs one page here, not all (#6771)."""+ built = []+ original_init = PDFPage.__init__++ def counting_init(page, *args, **kwargs):+ built.append(page)+ original_init(page, *args, **kwargs)++ monkeypatch.setattr(PDFPage, "__init__", counting_init)+ is_valid, error = FileUploadValidator.validate_pdf_structure(+ "document.pdf", _pdf_with_pages(2000)+ )+ assert (is_valid, error) == (True, None)+ assert len(built) == 1class TestValidateUpload:@@ -327,26 +337,11 @@ class TestValidateUpload:def test_valid_upload(self, mock_pdf_content):"""Accepts valid file upload."""- with patch(- "local_deep_research.security.file_upload_validator.pdfplumber"- ) as mock_pdfplumber:- mock_pdf = Mock()- mock_page = Mock()- mock_page.width = 612- mock_page.height = 792- mock_pdf.pages = [mock_page]- mock_pdfplumber.open.return_value.__enter__ = Mock(- return_value=mock_pdf- )- mock_pdfplumber.open.return_value.__exit__ = Mock(- return_value=False- )-- is_valid, error = FileUploadValidator.validate_upload(- "document.pdf", mock_pdf_content- )- assert is_valid is True- assert error is None+ is_valid, error = FileUploadValidator.validate_upload(+ "document.pdf", mock_pdf_content+ )+ assert is_valid is True+ assert error is Nonedef test_upload_file_too_large(self):"""Rejects upload that's too large."""@@ -390,28 +385,13 @@ class TestValidateUpload:def test_upload_with_content_length(self, mock_pdf_content):"""Validates with content length header."""- with patch(- "local_deep_research.security.file_upload_validator.pdfplumber"- ) as mock_pdfplumber:- mock_pdf = Mock()- mock_page = Mock()- mock_page.width = 612- mock_page.height = 792- mock_pdf.pages = [mock_page]- mock_pdfplumber.open.return_value.__enter__ = Mock(- return_value=mock_pdf- )- mock_pdfplumber.open.return_value.__exit__ = Mock(- return_value=False- )-- is_valid, error = FileUploadValidator.validate_upload(- "document.pdf",- mock_pdf_content,- content_length=len(mock_pdf_content),- )- assert is_valid is True- assert error is None+ is_valid, error = FileUploadValidator.validate_upload(+ "document.pdf",+ mock_pdf_content,+ content_length=len(mock_pdf_content),+ )+ assert is_valid is True+ assert error is Nonedef test_upload_content_length_mismatch_large(self, mock_pdf_content):"""Rejects when content length indicates too large."""