~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): gate PDF WeasyPrint url_fetcher with SSRF validator (#3613)
LearningCircuit15f13d5c7984
diff --git a/src/local_deep_research/web/services/pdf_service.py b/src/local_deep_research/web/services/pdf_service.pyindex 05566ba59f..3ae2a54fcf 100644--- a/src/local_deep_research/web/services/pdf_service.py+++ b/src/local_deep_research/web/services/pdf_service.py@@ -17,21 +17,50 @@ import markdown # type: ignore[import-untyped]from loguru import loggertry:- from weasyprint import HTML, CSS+ from weasyprint import HTML, CSS, default_url_fetcherWEASYPRINT_AVAILABLE = Trueexcept (OSError, ImportError) as _weasyprint_err:HTML = None # type: ignore[assignment,misc]CSS = None # type: ignore[assignment,misc]+ default_url_fetcher = None # type: ignore[assignment]WEASYPRINT_AVAILABLE = Falselogger.warning("WeasyPrint not available — PDF export will be disabled")+from ...security import validate_url+_WEASYPRINT_DOCS_URL = ("https://doc.courtbouillon.org/weasyprint/stable/first_steps.html")+class UnsafePDFResourceURLError(ValueError):+ """Subclasses ValueError so WeasyPrint skips the resource instead of aborting the render."""+++def _safe_url_fetcher(+ url,+ timeout=10,+ ssl_context=None,+ http_headers=None,+ allowed_protocols=None,+):+ """WeasyPrint url_fetcher that blocks SSRF targets (GHSA-fj2m-qvh9-jq4q)."""+ if not validate_url(url):+ logger.warning(f"Blocked unsafe URL in PDF rendering: {url}")+ raise UnsafePDFResourceURLError(+ f"Blocked unsafe URL in PDF rendering: {url}"+ )+ return default_url_fetcher(+ url,+ timeout=timeout,+ ssl_context=ssl_context,+ http_headers=http_headers,+ allowed_protocols=allowed_protocols,+ )++class MissingPDFDependencyError(RuntimeError):"""Raised when WeasyPrint system libraries are unavailable.@@ -158,8 +187,8 @@ class PDFService:markdown_content, title, metadata)- # Create HTML document with WeasyPrint- html_doc = HTML(string=html_content)+ # url_fetcher blocks SSRF targets reachable via body/citation URLs.+ html_doc = HTML(string=html_content, url_fetcher=_safe_url_fetcher)# Apply CSS (custom or minimal default)css_list = []diff --git a/tests/web/services/test_pdf_service.py b/tests/web/services/test_pdf_service.pyindex ac83d775ab..2d7e607a10 100644--- a/tests/web/services/test_pdf_service.py+++ b/tests/web/services/test_pdf_service.py@@ -338,3 +338,139 @@ class TestMissingPDFDependencyError:with patch.object(pdf_module, "WEASYPRINT_AVAILABLE", False):with pytest.raises(MissingPDFDependencyError):get_pdf_service()+++class TestSafeUrlFetcher:+ """Tests for the SSRF-guarded WeasyPrint url_fetcher (GHSA-fj2m-qvh9-jq4q).++ The custom fetcher blocks outbound requests to internal/private IPs and+ non-http(s) schemes, so URLs that reach the rendered HTML via the+ markdown body, citations, or any other channel cannot be weaponised+ into SSRF against cloud metadata or internal services.+ """++ def test_blocks_aws_metadata_endpoint(self):+ """AWS metadata IP is always blocked — critical SSRF target."""+ from local_deep_research.web.services.pdf_service import (+ UnsafePDFResourceURLError,+ _safe_url_fetcher,+ )++ with pytest.raises(UnsafePDFResourceURLError):+ _safe_url_fetcher(+ "http://169.254.169.254/latest/meta-data/iam/security-credentials/"+ )++ def test_blocks_loopback_address(self):+ """Loopback addresses are blocked by default."""+ from local_deep_research.web.services.pdf_service import (+ UnsafePDFResourceURLError,+ _safe_url_fetcher,+ )++ with pytest.raises(UnsafePDFResourceURLError):+ _safe_url_fetcher("http://127.0.0.1:8080/admin")++ def test_blocks_rfc1918_private_ip(self):+ """RFC1918 private range is blocked."""+ from local_deep_research.web.services.pdf_service import (+ UnsafePDFResourceURLError,+ _safe_url_fetcher,+ )++ with pytest.raises(UnsafePDFResourceURLError):+ _safe_url_fetcher("http://10.0.0.1/internal-api")++ def test_blocks_non_http_scheme(self):+ """Non-http(s) schemes like file:// are blocked."""+ from local_deep_research.web.services.pdf_service import (+ UnsafePDFResourceURLError,+ _safe_url_fetcher,+ )++ with pytest.raises(UnsafePDFResourceURLError):+ _safe_url_fetcher("file:///etc/passwd")++ def test_unsafe_url_error_subclasses_valueerror(self):+ """UnsafePDFResourceURLError must inherit from ValueError.++ WeasyPrint's url_fetcher contract treats ValueError as a+ retrievable fetch failure — the offending resource is skipped+ and rendering continues. Breaking this subclass relationship+ would turn blocked URLs into hard render failures.+ """+ from local_deep_research.web.services.pdf_service import (+ UnsafePDFResourceURLError,+ )++ assert issubclass(UnsafePDFResourceURLError, ValueError)++ def test_validated_url_delegates_to_default_fetcher(self):+ """Validated URLs are forwarded to weasyprint's default_url_fetcher."""+ from local_deep_research.web.services import pdf_service as pdf_module+ from local_deep_research.web.services.pdf_service import (+ _safe_url_fetcher,+ )++ with (+ patch.object(pdf_module, "validate_url", return_value=True),+ patch.object(pdf_module, "default_url_fetcher") as mock_fetcher,+ ):+ mock_fetcher.return_value = {+ "string": b"fake",+ "mime_type": "image/png",+ }++ _safe_url_fetcher("https://example.com/image.png")++ mock_fetcher.assert_called_once()+ assert (+ mock_fetcher.call_args.args[0]+ == "https://example.com/image.png"+ )++ def test_pdf_html_passes_fetcher_to_weasyprint(self):+ """markdown_to_pdf must wire _safe_url_fetcher into HTML(...).++ Regression guard: if a refactor drops the url_fetcher= kwarg,+ WeasyPrint silently reverts to its default fetcher and the+ SSRF guard disappears.+ """+ from local_deep_research.web.services import pdf_service as pdf_module+ from local_deep_research.web.services.pdf_service import PDFService++ service = PDFService()++ with patch.object(pdf_module, "HTML") as mock_html:+ mock_html.return_value.write_pdf.return_value = None+ service.markdown_to_pdf("content")++ mock_html.assert_called_once()+ assert (+ mock_html.call_args.kwargs.get("url_fetcher")+ is pdf_module._safe_url_fetcher+ )++ def test_render_succeeds_when_body_url_is_blocked(self):+ """End-to-end: a malicious URL in the markdown body doesn't break rendering.++ Covers the full chain (markdown passthrough → WeasyPrint → fetcher →+ ValueError → WeasyPrint skips resource → PDF still renders), which+ is what the SSRF guard relies on. Would fail if a future WeasyPrint+ upgrade changed the ValueError-as-skip contract, if Python-Markdown+ started stripping raw HTML, or if the url_fetcher got unwired.+ """+ from local_deep_research.web.services.pdf_service import PDFService++ service = PDFService()+ markdown = (+ "# Report\n\n"+ "Body text.\n\n"+ '<img src="http://169.254.169.254/latest/meta-data/" alt="x" />\n'+ )++ pdf_bytes = service.markdown_to_pdf(markdown)++ assert isinstance(pdf_bytes, bytes)+ assert pdf_bytes[:4] == b"%PDF"+ assert len(pdf_bytes) > 100