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(pdf): parse custom_css through the SSRF-guarded url_fetcher (#6437)

LearningCircuit9d5e07110147
diff --git a/changelog.d/6437.security.md b/changelog.d/6437.security.md
new file mode 100644
index 0000000000..586235b0e0
--- /dev/null
+++ b/changelog.d/6437.security.md
@@ -0,0 +1 @@
+PDF export now parses caller-supplied custom CSS through the same SSRF-guarded url_fetcher as the rendered document. Only the references WeasyPrint resolves while parsing a stylesheet (@import and @color-profile src) were exposed to WeasyPrint's default, unguarded fetcher before this fix; property-level url() values (e.g. background-image) were already resolved through the same guarded fetcher when the document renders. A parse-time fetch the guarded fetcher refuses (e.g. a blocked @color-profile src) or that fails while it runs, or a relative @import WeasyPrint cannot resolve without a base URL (a ValueError), now drops the custom stylesheet and renders with default styling instead of aborting the export; a data: URL inside custom CSS is refused like any other non-http(s) scheme, so a data: @color-profile src drops the stylesheet the same way.
diff --git a/src/local_deep_research/web/services/pdf_service.py b/src/local_deep_research/web/services/pdf_service.py
index 5f7da989e3..1114d29c1f 100644
--- a/src/local_deep_research/web/services/pdf_service.py
+++ b/src/local_deep_research/web/services/pdf_service.py
@@ -84,7 +84,17 @@ _WEASYPRINT_DOCS_URL = (
class UnsafePDFResourceURLError(ValueError):
- """Subclasses ValueError so WeasyPrint skips the resource instead of aborting the render."""
+ """Raised to refuse a blocked resource fetch.
+
+ WeasyPrint's ``fetch()`` (``weasyprint/urls.py``) wraps any
+ ``Exception`` the ``url_fetcher`` raises as ``URLFetchingError``;
+ whether that skips the resource or aborts the render depends on the
+ call site. ``@import`` is fetched inside a try/except in
+ ``css/__init__.py`` and is skipped; ``@color-profile`` is fetched
+ outside one, which is why ``markdown_to_pdf`` catches the error
+ around the custom stylesheet itself. Subclassing ``ValueError`` here
+ is a conventional choice, not what triggers the skip.
+ """
# Populated by _ensure_weasyprint() on first PDF use. The URLFetcher preserves
@@ -294,9 +304,15 @@ class PDFService:
def __init__(self):
"""Initialize PDF service with minimal CSS for readability."""
# Defer-load WeasyPrint (lazy import) before using CSS, then
- # build the stylesheet from the module-level MINIMAL_CSS constant.
+ # build the stylesheet from the module-level MINIMAL_CSS
+ # constant. MINIMAL_CSS has no @import/@color-profile/url()
+ # references to fetch, so url_fetcher is passed only for
+ # consistency with every other CSS() construction in this
+ # module -- not because anything here is reachable.
_ensure_weasyprint()
- self.minimal_css = CSS(string=MINIMAL_CSS)
+ self.minimal_css = CSS(
+ string=MINIMAL_CSS, url_fetcher=_safe_url_fetcher
+ )
def markdown_to_pdf(
self,
@@ -345,7 +361,51 @@ class PDFService:
# while still letting them override any default.
css_list = [self.minimal_css]
if custom_css:
- css_list.append(CSS(string=custom_css))
+ # With no font_config passed to CSS() at this call
+ # site, @import and @color-profile src are the
+ # references WeasyPrint fetches while parsing a
+ # stylesheet -- @font-face src would join them if a
+ # FontConfiguration were ever supplied here. Parsing
+ # this stylesheet must go through the same SSRF-guarded
+ # fetcher as the HTML document. Property-level url()
+ # values (e.g. background-image) are not parsed here --
+ # WeasyPrint resolves those later, at render time,
+ # through html_doc's fetcher above, which is already
+ # _safe_url_fetcher regardless of which stylesheet
+ # declared them. A refused parse-time fetch (e.g. an
+ # @color-profile src WeasyPrint resolves outside the
+ # try/except that guards @import) surfaces here as
+ # URLFetchingError; a relative @import WeasyPrint
+ # cannot resolve without a base_url (since
+ # CSS(string=...) has none) raises ValueError directly.
+ # Either way: drop the custom stylesheet and keep
+ # rendering with the default one rather than aborting
+ # the whole export.
+ try:
+ css_list.append(
+ CSS(string=custom_css, url_fetcher=_safe_url_fetcher)
+ )
+ except (URLFetchingError, ValueError) as exc:
+ # URLFetchingError wraps the fetcher's exception
+ # without `from`, so __cause__ is always None; the
+ # original exception (e.g. the
+ # UnsafePDFResourceURLError a refusal raises) is on
+ # __context__ instead. A plain ValueError (a
+ # stylesheet WeasyPrint could not parse) carries
+ # neither -- unless markdown_to_pdf() is itself
+ # called from inside a caller's `except` block, in
+ # which case Python's implicit chaining sets
+ # __context__ to that in-flight exception rather
+ # than the parse failure. The logged type is
+ # therefore a best-effort diagnostic, not a
+ # guarantee.
+ cause = type(
+ exc.__cause__ or exc.__context__ or exc
+ ).__name__
+ logger.warning(
+ "Custom stylesheet rejected ({}); rendering without it",
+ cause,
+ )
# Generate PDF
pdf_bytes = self._render_pdf(html_content, html_doc, css_list)
diff --git a/tests/web/services/test_pdf_custom_css_fetcher.py b/tests/web/services/test_pdf_custom_css_fetcher.py
new file mode 100644
index 0000000000..e7dc4c1a98
--- /dev/null
+++ b/tests/web/services/test_pdf_custom_css_fetcher.py
@@ -0,0 +1,166 @@
+"""Custom-CSS fetcher contracts for the PDF export path.
+
+The rendered HTML already resolves every resource through the
+SSRF-guarded ``_safe_url_fetcher`` (GHSA-fj2m-qvh9-jq4q). Caller-supplied
+``custom_css`` is parsed by a separate ``CSS()`` construction, and
+WeasyPrint fetches a stylesheet's ``@import`` and ``@color-profile src``
+while parsing it — so that construction must resolve through the same
+guarded fetcher, not WeasyPrint's default. (Property-level ``url()``
+values, e.g. ``background-image``, are resolved later, at render time,
+through the HTML document's fetcher, which is already guarded.)
+"""
+
+from __future__ import annotations
+
+from unittest.mock import patch
+
+import pytest
+
+pytest.importorskip("weasyprint")
+
+from local_deep_research.web.services import pdf_service as pdf_module # noqa: E402
+
+
+class TestCustomCssUsesTheGuardedFetcher:
+ def test_custom_css_is_parsed_with_the_ssrf_guarded_fetcher(self):
+ custom_css = "p { color: rebeccapurple; }"
+ service = pdf_module.get_pdf_service()
+ # CSS is populated lazily by _ensure_weasyprint(), so capture the
+ # real callable only after the service has initialised it.
+ real_css = pdf_module.CSS
+ recorded: list[dict] = []
+
+ def recording_css(*args, **kwargs):
+ recorded.append(kwargs)
+ return real_css(*args, **kwargs)
+
+ with patch.object(pdf_module, "CSS", recording_css):
+ service.markdown_to_pdf(
+ "# Title\n\nBody text.\n", title="Title", custom_css=custom_css
+ )
+
+ custom_calls = [kw for kw in recorded if kw.get("string") == custom_css]
+ assert custom_calls, "custom_css must be parsed through CSS()"
+ assert all(
+ kw.get("url_fetcher") is pdf_module._safe_url_fetcher
+ for kw in custom_calls
+ )
+
+
+class TestColorProfileRefusalKeepsRendering:
+ """A refused ``@color-profile`` fetch must not abort the export.
+
+ WeasyPrint resolves an ``@color-profile`` rule's ``src`` outside the
+ try/except that guards ``@import``, so an unwrapped
+ ``CSS(string=custom_css, ...)`` lets the guarded fetcher's refusal
+ surface as ``URLFetchingError`` and abort the whole render. The
+ export must instead drop the custom stylesheet and complete with
+ default styling — and the probe must confirm the fetch never left
+ the process ungated.
+ """
+
+ def test_custom_css_color_profile_refusal_does_not_abort_the_render(
+ self,
+ ):
+ import threading
+ import urllib.request
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+ hits: list[str] = []
+
+ class _Probe(BaseHTTPRequestHandler):
+ def do_GET(self):
+ hits.append(self.path)
+ self.send_response(200)
+ self.send_header("Content-Type", "text/css")
+ self.end_headers()
+ self.wfile.write(b"body { color: blue; }")
+
+ def log_message(self, *args):
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), _Probe)
+ port = server.server_address[1]
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ # Environment canary: prove loopback HTTP works here, so a
+ # broken sandbox cannot turn the assertion below into a
+ # silent pass.
+ with urllib.request.urlopen(
+ f"http://127.0.0.1:{port}/canary", timeout=5
+ ) as response:
+ assert response.status == 200
+ assert hits == ["/canary"]
+ hits.clear()
+
+ service = pdf_module.get_pdf_service()
+ pdf_bytes = service.markdown_to_pdf(
+ "# Probe",
+ # The payload must keep its ``--`` prefixed name and a
+ # ``src: url(...)`` token: WeasyPrint drops an unprefixed
+ # profile or a profile without ``src`` before any fetch,
+ # and the assertion would then pass under a revert of the
+ # guarded fetcher.
+ custom_css=(
+ "@color-profile --p { "
+ f"src: url('http://127.0.0.1:{port}/p.icc'); "
+ "components: 3; }"
+ ),
+ )
+ assert pdf_bytes, (
+ "render must still complete when the color-profile "
+ "fetch is refused"
+ )
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+
+ assert hits == [], (
+ f"custom_css @color-profile reached the network ungated "
+ f"(requests: {hits}); the stylesheet fetch bypassed "
+ "_safe_url_fetcher"
+ )
+
+
+class TestUnparseableCustomCssKeepsRendering:
+ """A custom stylesheet WeasyPrint cannot even parse must not abort
+ the export either -- the same widened ``except`` that covers a
+ refused fetch must also cover a relative ``@import`` WeasyPrint
+ cannot resolve without a base URL (a ``ValueError``).
+
+ A relative ``@import url(theme.css);`` cannot resolve: ``custom_css``
+ is parsed via ``CSS(string=custom_css, ...)`` with no ``base_url``,
+ so WeasyPrint raises ``InvalidValues`` (a ``ValueError``) before any
+ fetch is attempted -- ``URLFetchingError`` is never involved. An
+ ``except URLFetchingError`` alone would let that ``ValueError``
+ escape and abort the export; the render must instead drop the
+ custom stylesheet and complete with default styling, exactly like a
+ refused fetch.
+ """
+
+ def test_unparseable_custom_css_does_not_abort_the_render(self):
+ service = pdf_module.get_pdf_service()
+ seen_css_lists: list[list] = []
+ real_render_pdf = service._render_pdf
+
+ def recording_render_pdf(html_content, html_doc, css_list):
+ seen_css_lists.append(list(css_list))
+ return real_render_pdf(html_content, html_doc, css_list)
+
+ with patch.object(service, "_render_pdf", recording_render_pdf):
+ pdf_bytes = service.markdown_to_pdf(
+ "# Title\n\nBody text.\n",
+ title="Title",
+ custom_css="@import url(theme.css);",
+ )
+
+ assert pdf_bytes.startswith(b"%PDF"), (
+ "render must still complete when the custom stylesheet "
+ "cannot be parsed"
+ )
+ assert seen_css_lists == [[service.minimal_css]], (
+ "the unparseable custom stylesheet must be dropped, "
+ "leaving only the default styling"
+ )
diff --git a/tests/web/services/test_pdf_service.py b/tests/web/services/test_pdf_service.py
index 93a66f1fe2..6f32f09b4c 100644
--- a/tests/web/services/test_pdf_service.py
+++ b/tests/web/services/test_pdf_service.py
@@ -501,10 +501,14 @@ class TestSafeUrlFetcher:
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.
+ Subclassing ValueError here is a conventional choice, not what
+ makes a blocked URL skippable: WeasyPrint's fetch() wraps any
+ exception the url_fetcher raises as URLFetchingError regardless
+ of its type, and whether that is skipped or aborts the render
+ depends on the call site -- @import is fetched inside a
+ try/except in css/__init__.py and is skipped; @color-profile is
+ fetched outside one, which is why markdown_to_pdf catches the
+ error around the custom stylesheet itself.
"""
from local_deep_research.web.services.pdf_service import (
UnsafePDFResourceURLError,