~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
harden(pdf_service): guard the retry path, never let the skip fetcher raise, surface dropped resources (#6801)
LearningCircuit75a4592915ae
diff --git a/changelog.d/6588.security.md b/changelog.d/6588.security.mdnew file mode 100644index 0000000000..0a8782dc4d--- /dev/null+++ b/changelog.d/6588.security.md@@ -0,0 +1 @@+PDF export retry hardening: a render error reached before the lazy WeasyPrint import now surfaces as itself instead of a masking TypeError; the retry renders through a single fetcher class (`_SkippingUrlFetcher`, built fresh per retry) that still runs the SSRF guard before any fetch and skips any failure raised by the fetch itself (unless the WeasyPrint response class itself cannot be constructed; an error while WeasyPrint later reads a streamed response body is not covered); the retry runs outside the first pass's exception handler, so an error it raises does not chain to the first-pass fetch error, whose message can carry a URL's credentials; each skipped resource is logged with its exception type and redacted URL only (never the exception message or a traceback, which can carry URL credentials), a skipped-resource summary lists the count and up to 20 redacted URLs, and the empty resource is always a `URLFetcherResponse` on WeasyPrint 68+, which 69+ requires.diff --git a/src/local_deep_research/web/services/pdf_service.py b/src/local_deep_research/web/services/pdf_service.pyindex 49c7cb7e50..410b472d78 100644--- a/src/local_deep_research/web/services/pdf_service.py+++ b/src/local_deep_research/web/services/pdf_service.py@@ -105,9 +105,9 @@ class UnsafePDFResourceURLError(ValueError):_URL_FETCHER = None# Populated alongside the fetcher; see `_render_pdf` for why it is needed.URLFetchingError = None-# The response type WeasyPrint 68 introduced. A dict still works there and-# warns, and stops working in 69, so the empty resource is built through this-# when it exists and falls back to the dict for an older install.+# The response type WeasyPrint 68 introduced. 69+ accepts nothing else, so the+# empty resource is built through this whenever it exists; the dict shape is+# used only on WeasyPrint < 68 (see `_empty_resource_for`).URLFetcherResponse = None# What the retry hands WeasyPrint in place of a resource it may not have. An@@ -116,6 +116,10 @@ URLFetcherResponse = None# every at-rule but one._EMPTY_RESOURCE_MIME_TYPE = "application/octet-stream"+# How many (redacted) skipped URLs the retry's summary warning lists; the+# rest are counted. Every skipped URL also gets its own warning.+_SKIPPED_SUMMARY_LIMIT = 20+class _SafeUrlFetcher:"""WeasyPrint url_fetcher that blocks SSRF targets (GHSA-fj2m-qvh9-jq4q)."""@@ -136,8 +140,8 @@ class _SafeUrlFetcher:# ``test_fetchers_expose_the_fail_on_errors_contract`` in# ``tests/web/services/test_pdf_service.py``, which asserts# ``getattr(fetcher, "_fail_on_errors", None) is False`` on the wired- # module-level ``_safe_url_fetcher``/``_skipping_url_fetcher``- # objects. ``False`` mirrors the+ # module-level ``_safe_url_fetcher`` and on a ``_SkippingUrlFetcher()``+ # instance as the retry builds one. ``False`` mirrors the# ``URLFetcher(fail_on_errors=False)`` default: the refusal surfaces# as ``URLFetchingError``, which WeasyPrint's callers warn-and-skip.# That keeps the 68.x ValueError-as-skip posture (pinned end-to-end@@ -164,50 +168,131 @@ class _SafeUrlFetcher:_safe_url_fetcher = _SafeUrlFetcher()-class _SkippingUrlFetcher:- """As `_safe_url_fetcher`, but a refusal yields an empty resource.+def _empty_resource_for(url):+ """The empty-resource response a skipped fetch hands WeasyPrint.++ Built through ``URLFetcherResponse`` when WeasyPrint 68+ provides it.+ WeasyPrint 69+ accepts nothing else (``weasyprint.urls.fetch`` asserts+ ``isinstance(resource, URLFetcherResponse)``), so if the full+ construction is refused -- an upstream signature change -- the fallback+ is the bare ``URLFetcherResponse(url)`` (empty body), not a dict. The+ dict is reached only when ``URLFetcherResponse`` does not exist, i.e.+ WeasyPrint < 68, which still reads that shape.++ The full construction (with a body and headers) is guarded so a+ *skipped* resource becomes a render failure only if+ ``URLFetcherResponse`` itself cannot be constructed at all -- the bare,+ no-body fallback below raises too. That bare call is deliberately left+ unguarded rather than caught with a dict as a last resort: on+ WeasyPrint 69+, ``weasyprint.urls.fetch()`` asserts+ ``isinstance(resource, URLFetcherResponse)`` *outside* the+ try/except that turns a raising ``url_fetcher`` into a skippable+ ``URLFetchingError``, so a dict would fail that assertion uncaught --+ strictly worse than letting the original exception propagate, since+ some WeasyPrint call sites (e.g. ``@import``) catch ``URLFetchingError``+ but none catch a bare ``AssertionError``. Letting the bare call's own+ exception propagate keeps it inside that try/except instead, so this+ already-vanishingly-rare double failure is handled exactly like any+ other resource failure (#6588): skipped wherever the caller already+ tolerates one.+ """+ if URLFetcherResponse is not None:+ try:+ return URLFetcherResponse(+ url,+ body=b"",+ headers={"Content-Type": _EMPTY_RESOURCE_MIME_TYPE},+ )+ except Exception as exc:+ # Type name only: the message of an arbitrary exception is not+ # vetted and could echo the URL (with its userinfo) back.+ logger.warning(+ f"URLFetcherResponse construction failed "+ f"({type(exc).__name__}); retrying with an empty body only"+ )+ return URLFetcherResponse(url)+ return {+ "string": b"",+ "mime_type": _EMPTY_RESOURCE_MIME_TYPE,+ "redirected_url": url,+ }+- Used only by the retry in `_render_pdf`. No fetch happens for a URL the- guard refuses -- `validate_url` still runs first and still decides -- so- the SSRF posture is byte for byte the one above. The difference is only- what WeasyPrint is told afterwards: nothing, rather than an exception it- handles inconsistently.+class _SkippingUrlFetcher:+ """As `_safe_url_fetcher`, but any failure yields an empty resource.++ The fetcher the retry in `_render_pdf` renders with: it builds a fresh+ instance per retry, so ``skipped`` lists exactly the URLs that render+ dropped. No fetch happens for a URL the guard refuses -- every call goes+ through `_safe_url_fetcher`, so `validate_url` still runs first and+ still decides, and the SSRF posture is byte for byte the normal path's.+ The difference is only what WeasyPrint is told afterwards: nothing,+ rather than an exception it handles inconsistently.++ ``__call__`` never raises for a resource failure, unless the WeasyPrint+ response class itself cannot be constructed for the empty-resource+ fallback (see `_empty_resource_for`) -- an upstream signature change,+ not a resource failure. The retry exists to skip whatever the first+ pass could not survive, and the failure set of+ a remote fetch is open-ended: besides the refusal+ (`UnsafePDFResourceURLError`) and ``OSError``/``ValueError``, a hostile+ server can make ``http.client`` raise ``HTTPException`` subclasses+ (``BadStatusLine``, ``LineTooLong``, too many headers, ``InvalidURL``)+ and a bad ``deflate`` body raises ``zlib.error``. An exception+ escaping here would abort the retried render -- on WeasyPrint 70 its+ ``fetch()`` would then also read ``_fail_on_errors`` off this object --+ and turn a completed export into a 500 (#6588). A programming error is+ not hidden: its exception *type* is logged at warning level, which is+ what distinguishes an SSRF refusal from an unreachable resource from a+ bug. The exception *message* is never logged -- ``InvalidURL`` and+ friends embed the raw URL, userinfo included.++ Scope: only failures raised *inside* the fetch are skipped. WeasyPrint+ 70 returns an identity or ``gzip`` body as a lazy stream that its+ consumers read after the fetcher has returned, so an ``IncompleteRead``,+ a corrupt gzip stream or a read timeout part-way through the body is+ raised outside this object and can still fail the export."""- # Unlike `_SafeUrlFetcher`, this fetcher's `__call__` never lets an- # exception escape -- it always returns a resource -- so WeasyPrint's- # `fetch()` never hits the except-branch that reads `_fail_on_errors`- # off this instance; it is dead for this class at runtime. Kept as a- # class attribute anyway so both fetchers satisfy the same contract- # test (`test_fetchers_expose_the_fail_on_errors_contract`) and so a- # future edit that makes `__call__` raise again inherits a safe- # default instead of an `AttributeError`.+ # WeasyPrint 70's fetch() context manager reads ``_fail_on_errors`` off+ # the url_fetcher itself when it catches an exception from it. This+ # fetcher never raises, so that branch is dead today; the attribute is+ # kept so a future edit that makes ``__call__`` raise inherits the safe+ # warn-and-skip default instead of an ``AttributeError``, and so both+ # fetchers satisfy the same contract test+ # (``test_fetchers_expose_the_fail_on_errors_contract``). There is+ # deliberately no module-level instance of this class: ``skipped`` is+ # per-render state, and a shared instance would accumulate every+ # skipped URL across requests and users._fail_on_errors = False+ def __init__(self):+ self.skipped: list[str] = []+def __call__(self, url):+ # Settle the lazy import first, so the empty resource below is built+ # as the installed WeasyPrint expects even when the guard refuses+ # the URL before `_safe_url_fetcher` would have imported it.+ _ensure_weasyprint()try:return _safe_url_fetcher(url)- except Exception:- # Same redaction discipline as the fetcher's own block path:- # a refused/unavailable URL is adversarial-shaped and may carry- # credentials in userinfo or secret query tokens.+ except Exception as exc:+ self.skipped.append(url)+ # Same redaction discipline as the fetcher's own block path: a+ # refused/unavailable URL is adversarial-shaped and may carry+ # credentials in userinfo or secret query tokens. Exception type+ # only (see the class docstring); never logger.exception here,+ # whose traceback would carry both the message and the raw URL.logger.warning(- f"Skipping unavailable resource in PDF rendering: {redact_url_for_log(url)}"+ f"Skipping unavailable resource in PDF rendering "+ f"({type(exc).__name__}): {redact_url_for_log(url)}")- if URLFetcherResponse is not None:- return URLFetcherResponse(- url,- body=b"",- headers={"Content-Type": _EMPTY_RESOURCE_MIME_TYPE},- )- return {- "string": b"",- "mime_type": _EMPTY_RESOURCE_MIME_TYPE,- "redirected_url": url,- }---_skipping_url_fetcher = _SkippingUrlFetcher()+ # Built outside the except block so that, if even the bare+ # URLFetcherResponse construction were refused, the new exception+ # does not chain to the fetch error, whose message can carry the raw+ # URL into a later traceback. `_render_pdf` likewise runs the retry+ # outside its own except, so nothing chains to the first pass either.+ return _empty_resource_for(url)class MissingPDFDependencyError(RuntimeError):@@ -464,22 +549,58 @@ class PDFService:The retry restores the behaviour the other at-rules already have,rather than renaming the failure. Nothing about the SSRF guard moves:- `_skipping_url_fetcher` still calls `validate_url` first and still- performs no fetch for a URL it refuses. Only the normal path raises, so- an export that works today is rendered exactly once and unchanged.+ the retry's `_SkippingUrlFetcher` still calls `validate_url` first and+ still performs no fetch for a URL it refuses. Only the normal path+ raises, so an export that works today is rendered exactly once and+ unchanged."""+ # The except below names the lazily-populated URLFetchingError+ # global; ensure the import has run before any except clause+ # evaluates it, or a render error surfaces as TypeError (catching+ # None) instead of the real failure (#6588).+ _ensure_weasyprint()+pdf_buffer = io.BytesIO()+ needs_retry = Falsetry:html_doc.write_pdf(pdf_buffer, stylesheets=css_list)except URLFetchingError:+ # Only record the failure here. The retry runs *after* this+ # block: inside it, any exception the retried render raised+ # would chain (``__context__``) to this first-pass error, whose+ # WeasyPrint-built message embeds the fetch exception's text --+ # e.g. ``InvalidURL: nonnumeric port: '<password>@host'`` for a+ # userinfo URL the guard allows -- and ``logger.exception`` in+ # the callers would print that chain.+ needs_retry = True+ if needs_retry:logger.warning("PDF render aborted on an unavailable resource; retrying with ""unavailable resources skipped")pdf_buffer = io.BytesIO()- HTML(- string=html_content, url_fetcher=_skipping_url_fetcher- ).write_pdf(pdf_buffer, stylesheets=css_list)+ # A fresh fetcher per retry: its `skipped` list is exactly what+ # this render dropped, surfaced below so a subtly incomplete+ # export is diagnosable instead of silent (#6588).+ skipping_fetcher = _SkippingUrlFetcher()+ HTML(string=html_content, url_fetcher=skipping_fetcher).write_pdf(+ pdf_buffer, stylesheets=css_list+ )+ skipped = skipping_fetcher.skipped+ if skipped:+ # Capped: a report with thousands of refused resources would+ # otherwise put all of them on one line (each one already+ # has its own per-resource warning).+ shown = [+ redact_url_for_log(u)+ for u in skipped[:_SKIPPED_SUMMARY_LIMIT]+ ]+ more = len(skipped) - len(shown)+ suffix = f" (+{more} more)" if more else ""+ logger.warning(+ f"PDF render completed with {len(skipped)} skipped "+ f"resource(s): {shown}{suffix}"+ )pdf_bytes = pdf_buffer.getvalue()pdf_buffer.close()return pdf_bytesdiff --git a/tests/security/test_page_route_uuid_fences.py b/tests/security/test_page_route_uuid_fences.pyindex c4b4f0cd21..6951ef59f6 100644--- a/tests/security/test_page_route_uuid_fences.py+++ b/tests/security/test_page_route_uuid_fences.py@@ -35,11 +35,32 @@ fails if either fence call is silently reverted.import inspectfrom uuid import uuid4+from local_deep_research.database import session_contextfrom local_deep_research.web.routers import notes, rag_HOSTILE_ID = 'x"><img src=x onerror=alert(1)>'+def _spy_on_user_db_session(monkeypatch):+ """Patch ``get_user_db_session`` with a pass-through spy; return calls.++ ``view_document_chunks`` resolves its DB session by importing+ ``database.session_context.get_user_db_session`` *inside the+ function body* at call time, so the patchable seam is the source+ module's attribute -- patching ``rag.get_user_db_session`` would+ touch nothing.+ """+ calls = []+ real_factory = session_context.get_user_db_session++ def _spying_factory(*args, **kwargs):+ calls.append((args, kwargs))+ return real_factory(*args, **kwargs)++ monkeypatch.setattr(session_context, "get_user_db_session", _spying_factory)+ return calls++def test_note_page_rejects_malformed_note_id(authenticated_client):"""The notes page must not render for a non-UUID note id.@@ -64,51 +85,94 @@ def test_note_page_renders_for_well_formed_uuid(authenticated_client):def test_document_chunks_page_rejects_malformed_document_id(authenticated_client,+ monkeypatch,):- """The chunks page must 404 malformed ids AT THE FENCE, not via the- route's own missing-row branch.+ """The chunks page must 404 malformed ids AT THE FENCE, before the+ route ever opens its DB session -- not via the route's own+ missing-row branch.- A bare status-code check cannot tell the two apart, and both are- green today: the missing-row branch also answers 404, with body- ``"Document not found"`` (``rag.py``:+ A bare status-code check cannot tell the two apart: the+ missing-row branch also answers 404 (``rag.py``:``return HTMLResponse("Document not found", status_code=404)``).- If the fence call were ever moved after the DB query, this test- would stay green on status code alone while silently losing the+ If the fence call were ever moved after the DB query, a+ status-code-only test would stay green while silently losing the"skips its DB roundtrip" guarantee.- The fence's 404 is different: ``validated_uuid_path_param`` raises- ``HTTPException(404, ...)``, which never reaches the client as- written -- Starlette dispatches by exact status code first, so- ``fastapi_app.py``'s ``@app.exception_handler(404)`` wins over- FastAPI's default ``HTTPException`` handler and, for a browser- (non-API) request, answers with the branded 404 page (#5424), or- with ``HTMLResponse("Not found", status_code=404)`` if rendering- that page fails. Asserting the body pins which branch answered.+ This test originally pinned which branch answered by *body*: the+ fence's 404 arrived as the plain ``"Not found"`` text and the+ missing-row 404 as ``"Document not found"``. That premise changed+ when the branded error pages landed on main (PR #5424): the+ fence's ``HTTPException(404, ...)`` is dispatched by exact status+ code to ``fastapi_app.py``'s ``@app.exception_handler(404)``,+ which now renders ``templates/pages/error.html`` for browser+ requests, so the old plain-body pin went stale and failed CI on+ every branch. Body discrimination is fragile in both directions+ (the missing-row branch could be branded the same way later), so+ the test is body-independent now: it spies on the session factory+ the route resolves at call time and asserts NO DB session was+ created for a hostile id. Nothing else in this request's path+ opens a user session through that seam (``require_auth`` checks+ the connection and the server-side session without it), so a+ recorded call means the fence did not answer first. The+ well-formed companion test below proves the same spy IS reached+ when the fence passes."""+ session_calls = _spy_on_user_db_session(monkeypatch)+response = authenticated_client.get(f"/library/document/{_HOSTILE_ID}/chunks")- assert response.status_code == 404- assert "Document not found" not in response.text- assert (- "<title>Page not found" in response.text or response.text == "Not found"- ), (- "chunks page 404 did not come from the shape fence -- got body "- f"{response.text[:100]!r}. The route's own missing-row branch "- 'answers 404 too, with a different body ("Document not found"), '- "so a fence moved after the DB query would still pass a bare "- "status-code check."+ assert response.status_code == 404, (+ "chunks page did not 404 a malformed document_id; the shape "+ "fence did not answer"+ )+ assert session_calls == [], (+ f"the shape fence did not run before the DB: get_user_db_session "+ f"was called {len(session_calls)} time(s) for a malformed "+ 'document_id -- the fence\'s "skips its DB roundtrip" guarantee '+ "is gone and the 404 came from the route's missing-row branch"+ )+++def test_document_chunks_page_opens_its_db_session_for_well_formed_unknown_id(+ authenticated_client,+ monkeypatch,+):+ """Positive control for the fence test above: the same spy must be+ reached when the fence passes.++ ``get_user_db_session`` never being called proves nothing about a+ fence that has silently moved unless the seam is demonstrably live+ for a well-formed id: a UUID that matches no row must open the+ user's session, because the missing-row 404 answers only after+ the query -- exactly the branch the fence must pre-empt for+ malformed ids. Asserting both directions through one seam keeps+ the pair body-independent: neither test cares which 404 body+ renders, so branding (or un-branding) either page cannot stale+ this file again.+ """+ session_calls = _spy_on_user_db_session(monkeypatch)++ response = authenticated_client.get(f"/library/document/{uuid4()}/chunks")++ assert response.status_code == 404, response.text[:200]+ assert session_calls, (+ "the spy on database.session_context.get_user_db_session was "+ "never reached for a well-formed document_id -- the chunks page "+ "no longer resolves its DB session through that module, so the "+ "fence test above is pinning a dead seam")def test_fenced_page_routes_call_the_uuid_validator():"""The fence call itself must survive a silent revert.- A status-code probe cannot catch deletion of the chunks-page- fence: the route's own missing-row branch 404s a malformed id too,- so the HTTP-level tests above stay green with the fence gone.- Inspecting the route source — the idiom+ A status-code probe alone cannot catch deletion of the chunks-page+ fence: the route's own missing-row branch 404s a malformed id too.+ The DB-session spy above catches that at the HTTP level; this check+ additionally pins the call site for the notes page, and inspecting+ the route source — the idiomtest_both_collection_page_routes_validate uses for the collectionpages (tests/security/test_collection_id_xss.py) — fails themoment either call site disappears.diff --git a/tests/web/services/test_pdf_service.py b/tests/web/services/test_pdf_service.pyindex e4363c9a43..11b237ca5d 100644--- a/tests/web/services/test_pdf_service.py+++ b/tests/web/services/test_pdf_service.py@@ -9,6 +9,8 @@ Tests cover:- Singleton pattern"""+import re+import pytestfrom unittest.mock import Mock, patch@@ -594,17 +596,18 @@ class TestSafeUrlFetcher:all drop it, and ``functools.wraps`` -- which *does* preserve abare function's own attribute -- does not copy an instance's).This test is the actual guard: it asserts the attribute is- present, ``False``, on the wired module-level fetcher objects- (#6685).+ present, ``False``, on the wired module-level ``_safe_url_fetcher``+ and on a ``_SkippingUrlFetcher()`` built the way the retry in+ ``_render_pdf`` builds one -- fresh per retry, since its+ ``skipped`` list is per-render state (#6685, #6588)."""from local_deep_research.web.services.pdf_service import (_SafeUrlFetcher,_SkippingUrlFetcher,_safe_url_fetcher,- _skipping_url_fetcher,)- for fetcher in (_safe_url_fetcher, _skipping_url_fetcher):+ for fetcher in (_safe_url_fetcher, _SkippingUrlFetcher()):assert getattr(fetcher, "_fail_on_errors", None) is False# Intrinsic to the type, not attached to the callable afterwards.assert _SafeUrlFetcher._fail_on_errors is False@@ -664,3 +667,188 @@ class TestSafeUrlFetcher:assert isinstance(pdf_bytes, bytes)assert pdf_bytes[:4] == b"%PDF"assert len(pdf_bytes) > 100+++class TestRenderPdfRetryHardening:+ """Retry-path hardening pins (#6588)."""++ def test_render_error_surfaces_when_error_global_unpopulated(self):+ """`except URLFetchingError:` names a lazily-populated global.++ A caller that reaches ``_render_pdf`` without the lazy import having+ run used to get ``TypeError: catching classes that do not inherit+ from BaseException`` — masking the real render error (#6588). The+ render path now ensures the import first, so the underlying error+ surfaces as itself.+ """+ from local_deep_research.web.services import pdf_service as pdf_module+ from local_deep_research.web.services.pdf_service import PDFService++ pdf_module._ensure_weasyprint()+ real_error = pdf_module.URLFetchingError+ real_available = pdf_module.WEASYPRINT_AVAILABLE++ class _ExplodingDoc:+ def write_pdf(self, buf, stylesheets=None):+ raise RuntimeError("underlying render failure")++ service = PDFService()+ try:+ # Simulate the unpopulated-module state a direct caller can hit.+ pdf_module.URLFetchingError = None+ pdf_module.WEASYPRINT_AVAILABLE = None+ with pytest.raises(RuntimeError, match="underlying render failure"):+ service._render_pdf("<html></html>", _ExplodingDoc(), [])+ finally:+ pdf_module.URLFetchingError = real_error+ pdf_module.WEASYPRINT_AVAILABLE = real_available+ pdf_module._ensure_weasyprint()++ def test_retry_surfaces_skipped_resources(self):+ """The retry must say WHAT it dropped (#6588).++ A subtly incomplete export (missing figures/styles) is otherwise+ indistinguishable from a correct render: the retry now records the+ resources its fetcher skipped and warns with the (redacted) URLs.+ """+ from loguru import logger as loguru_logger++ from local_deep_research.web.services import pdf_service as pdf_module+ from local_deep_research.web.services.pdf_service import PDFService++ pdf_module._ensure_weasyprint()+ urlfetch_error = pdf_module.URLFetchingError++ captured: dict = {}++ class _FakeHTML:+ """Serves as both the first-attempt doc (raises) and the retry's+ reconstructed doc (drives the recording fetcher, then writes)."""++ def __init__(self, string=None, url_fetcher=None):+ captured["fetcher"] = url_fetcher++ def write_pdf(self, buf, stylesheets=None):+ if "attempt" not in captured:+ captured["attempt"] = 1+ raise urlfetch_error("refused @color-profile")+ # Retry attempt: drive the recording fetcher on a URL the+ # SSRF guard always refuses.+ captured["fetcher"]("http://169.254.169.254/dropped.png")+ buf.write(b"%PDF-partial")++ messages: list[str] = []+ handler = loguru_logger.add(+ lambda m: messages.append(str(m)), level="DEBUG"+ )+ loguru_logger.enable("local_deep_research")+ try:+ with patch.object(pdf_module, "HTML", _FakeHTML):+ out = PDFService()._render_pdf("<html></html>", _FakeHTML(), [])+ finally:+ loguru_logger.disable("local_deep_research")+ loguru_logger.remove(handler)++ assert out.startswith(b"%PDF-partial")+ joined = "\n".join(messages)+ # A plain substring also matches "11 skipped resource(s)" etc.;+ # pin the exact count with a word boundary in front.+ assert re.search(r"\b1 skipped resource", joined), joined[-600:]+ # The surface warning lists the redacted form (scheme://host:port),+ # never the path: "http://169.254.169.254" alone is also a substring+ # of the raw, unredacted URL, so pin that the path is gone too.+ assert "http://169.254.169.254" in joined+ assert "dropped.png" not in joined, joined++ def test_a_failing_retry_does_not_chain_to_the_first_pass_error(self):+ """The retry must run outside the first pass's ``except`` (#6588).++ WeasyPrint builds the first-pass ``URLFetchingError`` from the fetch+ exception's text, which for a userinfo URL the guard allows reads+ ``InvalidURL: nonnumeric port: '<password>@host'``. Were the retry+ rendered inside that ``except``, anything it raised would carry the+ first-pass error as ``__context__``, and ``logger.exception`` in+ ``markdown_to_pdf`` would print the password.+ """+ import traceback++ from local_deep_research.web.services import pdf_service as pdf_module+ from local_deep_research.web.services.pdf_service import PDFService++ pdf_module._ensure_weasyprint()+ urlfetch_error = pdf_module.URLFetchingError+ attempts: list[int] = []++ class _FakeHTML:+ def __init__(self, string=None, url_fetcher=None):+ pass++ def write_pdf(self, buf, stylesheets=None):+ attempts.append(1)+ if len(attempts) == 1:+ raise urlfetch_error(+ "InvalidURL: nonnumeric port: '[email protected]'"+ )+ raise RuntimeError("retry layout failure")++ with patch.object(pdf_module, "HTML", _FakeHTML):+ with pytest.raises(+ RuntimeError, match="retry layout failure"+ ) as ei:+ PDFService()._render_pdf("<html></html>", _FakeHTML(), [])++ assert len(attempts) == 2, "the retry must actually have run"+ assert ei.value.__context__ is None, repr(ei.value.__context__)+ assert ei.value.__cause__ is None+ rendered = "".join(traceback.format_exception(ei.value))+ assert "S3CRETPW" not in rendered, rendered++ def test_the_skipped_summary_is_capped(self):+ """A report with many refused resources must not produce one+ unbounded summary line: it lists the first+ ``_SKIPPED_SUMMARY_LIMIT`` (redacted) URLs and counts the rest."""+ from loguru import logger as loguru_logger++ from local_deep_research.web.services import pdf_service as pdf_module+ from local_deep_research.web.services.pdf_service import PDFService++ pdf_module._ensure_weasyprint()+ urlfetch_error = pdf_module.URLFetchingError+ limit = pdf_module._SKIPPED_SUMMARY_LIMIT+ total = limit + 5+ captured: dict = {}++ class _FakeHTML:+ def __init__(self, string=None, url_fetcher=None):+ captured["fetcher"] = url_fetcher++ def write_pdf(self, buf, stylesheets=None):+ if "attempt" not in captured:+ captured["attempt"] = 1+ raise urlfetch_error("refused @color-profile")+ for i in range(total):+ captured["fetcher"](f"http://blocked{i}.invalid/x.png")+ buf.write(b"%PDF-partial")++ messages: list[str] = []+ handler = loguru_logger.add(+ lambda m: messages.append(str(m)), level="DEBUG"+ )+ loguru_logger.enable("local_deep_research")+ try:+ with (+ patch.object(pdf_module, "HTML", _FakeHTML),+ patch.object(pdf_module, "validate_url", return_value=False),+ ):+ PDFService()._render_pdf("<html></html>", _FakeHTML(), [])+ finally:+ loguru_logger.disable("local_deep_research")+ loguru_logger.remove(handler)++ summary = [m for m in messages if "skipped resource(s)" in m]+ assert len(summary) == 1, messages+ line = summary[0]+ assert re.search(rf"\b{total} skipped resource\(s\)", line), line+ assert "(+5 more)" in line, line+ assert f"http://blocked{limit - 1}.invalid" in line, line+ assert f"http://blocked{limit}.invalid" not in line, linediff --git a/tests/web_services/test_pdf_service.py b/tests/web_services/test_pdf_service.pyindex 6572f2d04d..243341ccf0 100644--- a/tests/web_services/test_pdf_service.py+++ b/tests/web_services/test_pdf_service.py@@ -3,8 +3,10 @@ Comprehensive tests for PDFService.Tests PDF generation, markdown conversion, CSS handling, and metadata."""+import http.clientimport ioimport subprocess+import zlibimport pytestfrom unittest.mock import patch@@ -497,7 +499,7 @@ class TestRefusedResourceDoesNotAbortTheExport:return {"string": b"metadata", "mime_type": "text/plain"}with patch.object(pdf_service, "_URL_FETCHER", _WouldServeAnything()):- resource = pdf_service._skipping_url_fetcher(self.BLOCKED)+ resource = pdf_service._SkippingUrlFetcher()(self.BLOCKED)assert fetched == [], "the guard must decide before any request is made"@@ -545,6 +547,315 @@ class TestRefusedResourceDoesNotAbortTheExport:patch("socket.getaddrinfo", side_effect=_no_resolution),):assert (- pdf_service._skipping_url_fetcher("https://example.com/x.css")+ pdf_service._SkippingUrlFetcher()("https://example.com/x.css")is payload), "an allowed URL must reach the (patched) module URL fetcher"+++class TestSkippingFetcherHardening:+ """Pins for `_SkippingUrlFetcher`, the fetcher the retry in+ `_render_pdf` renders with (#6588)."""++ # userinfo, path and query all carry secrets the logs must never see;+ # the host is the metadata address the SSRF guard always refuses.+ CREDENTIALED_BLOCKED = (+ "http://admin:[email protected]/latest/meta.icc?token=TOK123"+ )++ @staticmethod+ def _capture_pdf_service_logs(messages):+ from loguru import logger as loguru_logger++ def sink(message):+ # The formatted line, traceback included: a `logger.exception`+ # would carry the exception's message (which can embed the raw+ # URL) into the log through it.+ record = message.record+ if record["name"].startswith(+ "local_deep_research.web.services.pdf_service"+ ):+ messages.append(str(message))++ return loguru_logger.add(sink, level="DEBUG")++ def test_refusal_reason_reaches_the_log(self):+ """The skip log must say WHY the resource was refused -- by exception+ type, with the URL redacted and no credential text anywhere."""+ from loguru import logger as loguru_logger++ from local_deep_research.web.services import pdf_service++ messages: list[str] = []+ handler = self._capture_pdf_service_logs(messages)+ loguru_logger.enable("local_deep_research")+ fetcher = pdf_service._SkippingUrlFetcher()+ try:+ result = fetcher(self.CREDENTIALED_BLOCKED)+ finally:+ loguru_logger.disable("local_deep_research")+ loguru_logger.remove(handler)++ assert result is not None+ assert fetcher.skipped == [self.CREDENTIALED_BLOCKED]+ skip_lines = [+ m for m in messages if "Skipping unavailable resource" in m+ ]+ assert len(skip_lines) == 1, messages+ assert "UnsafePDFResourceURLError" in skip_lines[0]+ assert "http://169.254.169.254" in skip_lines[0]+ joined = "\n".join(messages)+ for secret in ("S3CRETPW", "admin", "TOK123", "meta.icc"):+ assert secret not in joined, joined++ @pytest.mark.parametrize(+ "error",+ [+ # What a hostile server can make http.client / the decoder raise:+ # none of these is an OSError or ValueError.+ http.client.BadStatusLine("GARBAGE"),+ http.client.LineTooLong("header line"),+ http.client.HTTPException("got more than 100 headers"),+ zlib.error("invalid stored block lengths"),+ TypeError("bad glue"),+ ],+ ids=lambda e: type(e).__name__,+ )+ def test_any_fetch_failure_is_skipped_not_raised(self, error):+ """The retry exists to skip whatever the first pass could not survive,+ so nothing a fetch raises may escape it: an escape aborts the retried+ render (and on WeasyPrint 70 its fetch() then reads+ `_fail_on_errors` off the fetcher) and a completed export becomes a+ 500. A programming error is not hidden -- its type is logged -- but+ its message is not, since `InvalidURL` and friends embed the raw URL.+ """+ from loguru import logger as loguru_logger++ from local_deep_research.web.services import pdf_service++ error.args = error.args + ("S3CRETPW",)+ messages: list[str] = []+ handler = self._capture_pdf_service_logs(messages)+ loguru_logger.enable("local_deep_research")+ fetcher = pdf_service._SkippingUrlFetcher()+ try:+ with patch.object(+ pdf_service, "_safe_url_fetcher", side_effect=error+ ):+ result = fetcher("https://example.com/x.css")+ finally:+ loguru_logger.disable("local_deep_research")+ loguru_logger.remove(handler)++ assert result is not None+ assert fetcher.skipped == ["https://example.com/x.css"]+ joined = "\n".join(messages)+ assert type(error).__name__ in joined+ assert "S3CRETPW" not in joined, joined++ def test_the_empty_resource_survives_a_constructor_change(self):+ """WeasyPrint 69+ asserts the fetcher returned a `URLFetcherResponse`+ -- a dict is rejected -- so when the full construction is refused+ (an upstream signature change) the fallback must still be one. The+ warning naming that failure must log the exception type only: an+ arbitrary upstream exception message is not vetted and could echo+ secrets embedded in headers/body by a caller."""+ from loguru import logger as loguru_logger++ from local_deep_research.web.services import pdf_service++ pdf_service._ensure_weasyprint()+ real = pdf_service.URLFetcherResponse+ if real is None:+ pytest.skip("WeasyPrint < 68 has no URLFetcherResponse")++ class _ChangedSignature(real):+ def __init__(self, *args, **kwargs):+ if "body" in kwargs:+ raise TypeError(+ "unexpected keyword argument 'body' S3CRETPW"+ )+ super().__init__(*args, **kwargs)++ messages: list[str] = []+ handler = self._capture_pdf_service_logs(messages)+ loguru_logger.enable("local_deep_research")+ try:+ with patch.object(+ pdf_service, "URLFetcherResponse", _ChangedSignature+ ):+ resource = pdf_service._empty_resource_for("https://x.test/a")+ finally:+ loguru_logger.disable("local_deep_research")+ loguru_logger.remove(handler)++ assert isinstance(resource, real)+ assert resource.read() == b""+ joined = "\n".join(messages)+ assert "TypeError" in joined, joined+ assert "S3CRETPW" not in joined, joined++ def test_the_fetcher_carries_the_fail_on_errors_contract(self):+ """WeasyPrint 70's fetch() reads `_fail_on_errors` off the fetcher+ when it catches from it; a missing attribute is an AttributeError+ mid-render."""+ from local_deep_research.web.services import pdf_service++ assert (+ getattr(pdf_service._SkippingUrlFetcher(), "_fail_on_errors", None)+ is False+ )+++class TestRetriedRenderEndToEnd:+ """The retry as `_render_pdf` actually runs it, through real WeasyPrint.++ The render is forced into its retry by a refused `@color-profile` (the+ at-rule whose fetch failure aborts the render). `_URL_FETCHER` is+ replaced by a spy, so nothing leaves the process: the assertions are on+ what the spy was *asked* to fetch.+ """++ CREDENTIALED_BLOCKED = (+ "http://admin:[email protected]/latest/meta.icc?token=TOK123"+ )+ HOSTILE = "https://attacker.example/bad.icc"++ def _render(self):+ from loguru import logger as loguru_logger++ from local_deep_research.web.services import pdf_service++ pdf_service._ensure_weasyprint()+ fetched: list[str] = []+ response_type = pdf_service.URLFetcherResponse++ class _SpyFetcher:+ def fetch(self, url):+ fetched.append(url)+ if url == TestRetriedRenderEndToEnd.HOSTILE:+ # A server answering with a garbage status line.+ raise http.client.BadStatusLine("GARBAGE")+ if response_type is not None:+ return response_type(url, body=b"")+ return {"string": b"", "mime_type": "text/plain"}++ def fake_validate_url(url, *args, **kwargs):+ # The metadata host is refused, as the real guard always does;+ # the stand-in public host is allowed without a DNS lookup.+ return "169.254.169.254" not in url++ # The hostile resource comes first, so it is what aborts the first+ # pass; the refused one is then reached only by the retry.+ markdown = (+ "<style>"+ "@color-profile --a { src: url('"+ + self.HOSTILE+ + "'); components: 3; }"+ "@color-profile --b { src: url('"+ + self.CREDENTIALED_BLOCKED+ + "'); components: 3; }"+ "</style>\n\n# Report\n\nBody text.\n"+ )+ html_calls: list = []+ original_html = pdf_service.HTML++ def recording_html(*args, **kwargs):+ html_calls.append(kwargs.get("url_fetcher"))+ return original_html(*args, **kwargs)++ messages: list[str] = []+ handler = TestSkippingFetcherHardening._capture_pdf_service_logs(+ messages+ )+ loguru_logger.enable("local_deep_research")+ try:+ with (+ patch.object(pdf_service, "_URL_FETCHER", _SpyFetcher()),+ patch.object(pdf_service, "validate_url", fake_validate_url),+ patch.object(pdf_service, "HTML", recording_html),+ ):+ pdf = pdf_service.PDFService().markdown_to_pdf(+ markdown, title="t"+ )+ finally:+ loguru_logger.disable("local_deep_research")+ loguru_logger.remove(handler)+ return pdf, fetched, messages, html_calls++ def test_the_retry_runs_and_still_exports(self):+ from local_deep_research.web.services import pdf_service++ pdf, _, _, html_calls = self._render()++ assert pdf.startswith(b"%PDF")+ # First the normal render, then the retry with the skipping fetcher.+ assert html_calls[0] is pdf_service._safe_url_fetcher+ assert isinstance(html_calls[-1], pdf_service._SkippingUrlFetcher)++ def test_a_blocked_url_is_never_fetched_on_the_retry(self):+ _, fetched, _, _ = self._render()++ assert not any("169.254.169.254" in url for url in fetched), fetched+ # The allowed resource did reach the fetcher, so the spy was live.+ assert self.HOSTILE in fetched++ def test_a_hostile_status_line_on_the_retry_is_skipped(self):+ """`BadStatusLine` is neither an OSError nor a ValueError; raised in+ a `@color-profile` fetch on the retry it would abort the retried+ render too, unless the retry fetcher skips it."""+ pdf, fetched, _, _ = self._render()++ assert pdf.startswith(b"%PDF")+ # Once by the first pass (whose abort forced the retry), once by the+ # retry, which skipped it instead of aborting again.+ assert fetched.count(self.HOSTILE) == 2, fetched++ def test_the_skipped_summary_lists_only_redacted_urls(self):+ _, _, messages, _ = self._render()++ summary = [m for m in messages if "skipped resource(s)" in m]+ assert len(summary) == 1, messages+ line = summary[0]+ assert "2 skipped resource(s)" in line+ assert "http://169.254.169.254" in line+ assert "https://attacker.example" in line+ for secret in ("S3CRETPW", "admin", "TOK123", "meta.icc", "bad.icc"):+ assert secret not in line, line+ # And nowhere else in this module's logs either.+ joined = "\n".join(messages)+ assert "S3CRETPW" not in joined, joined++ def test_each_retry_gets_its_own_skipping_fetcher(self):+ """`_render_pdf` must build a fresh `_SkippingUrlFetcher` per retry.++ Nothing else in this module pins that: a module-level shared+ instance whose `skipped` list is cleared at the start of each+ retry would pass every other test here (each render still ends+ up with exactly its own render's skips by the time the summary+ is logged), while mixing skip lists across concurrent renders --+ one render's retry could clear the list out from under another+ render's retry still running against the same instance.++ `_render` already records the exact `url_fetcher` object handed+ to `HTML(...)` for each pass (`html_calls`); its last entry is+ the real `_SkippingUrlFetcher` instance the retry rendered with.+ Two full renders' worth of those instances are compared here.+ """+ from local_deep_research.web.services import pdf_service++ _, _, _, html_calls_one = self._render()+ _, _, _, html_calls_two = self._render()++ fetcher_one = html_calls_one[-1]+ fetcher_two = html_calls_two[-1]++ assert isinstance(fetcher_one, pdf_service._SkippingUrlFetcher)+ assert isinstance(fetcher_two, pdf_service._SkippingUrlFetcher)+ assert fetcher_one is not fetcher_two+ assert fetcher_one.skipped is not fetcher_two.skipped+ # Each render skips the same two (redacted) URLs; a shared+ # instance would show them doubled up on whichever fetcher was+ # captured second instead of each holding only its own render's+ # skips.+ assert len(fetcher_one.skipped) == 2, fetcher_one.skipped+ assert len(fetcher_two.skipped) == 2, fetcher_two.skipped