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.

test(pdf): fetcher follow-ups from the #7785 merge review (#8025)

LearningCircuitb15c9a69c6c1
diff --git a/src/local_deep_research/web/services/pdf_service.py b/src/local_deep_research/web/services/pdf_service.py
index 5b59fddc11..ec13c6e00a 100644
--- a/src/local_deep_research/web/services/pdf_service.py
+++ b/src/local_deep_research/web/services/pdf_service.py
@@ -76,9 +76,7 @@ def _ensure_weasyprint() -> None:
URLFetcherResponse = _Response
# Built in full before it is published, so no caller can pick up a
# fetcher that does not have the size limits yet.
- fetcher = URLFetcher(allow_redirects=False)
- fetcher.add_handler(_BoundedBodyProcessor())
- _URL_FETCHER = fetcher
+ _URL_FETCHER = _build_url_fetcher(URLFetcher)
WEASYPRINT_AVAILABLE = True
except (OSError, ImportError):
WEASYPRINT_AVAILABLE = False
@@ -679,9 +677,14 @@ class _FetchCost:
past the limit is charged as if its first read had been made
(`_read_body`), so at most `MAX_PDF_EXPORT_RESOURCE_BYTES` /
`_RESOURCE_READ_CHUNK_BYTES` (1024) of those are fetched per export.
- But a fetch whose body is never read costs nothing (a non-2xx status,
- which ``HTTPErrorProcessor`` raises on before `_BoundedBodyProcessor`
- runs, or an empty body), so the number of such fetches is not limited.
+ But a fetch whose body is never read costs nothing, so the number of
+ such fetches is not limited. That covers a non-2xx status (which
+ ``HTTPErrorProcessor`` raises on before `_BoundedBodyProcessor` runs)
+ and an empty body, and also every fetch that fails before a response
+ arrives: a DNS pin that fails or is refused, a lookup the block-private
+ window refuses, and a connection that fails. Each of those can still
+ spend up to about 5 s on a bounded lookup
+ (``dns_pinning._RESOLVE_TIMEOUT_SECONDS``) before it fails.
"""
__slots__ = ("wire", "decoded", "inflated", "members")
@@ -2241,6 +2244,19 @@ def _has_userinfo(url) -> bool:
_safe_url_fetcher = _SafeUrlFetcher()
+def _build_url_fetcher(fetcher_cls):
+ """A new URL fetcher of WeasyPrint's ``fetcher_cls``, set up for exports.
+
+ Redirects are disabled (see `_URL_FETCHER`) and a `_BoundedBodyProcessor`
+ is attached. `_ensure_weasyprint` builds `_URL_FETCHER` with this, and
+ the tests build their own fetchers with it too, so a handler added here
+ reaches both.
+ """
+ fetcher = fetcher_cls(allow_redirects=False)
+ fetcher.add_handler(_BoundedBodyProcessor())
+ return fetcher
+
+
def _empty_resource_for(url):
"""The empty-resource response a skipped fetch hands WeasyPrint.
diff --git a/tests/web/services/test_pdf_resource_size_limits.py b/tests/web/services/test_pdf_resource_size_limits.py
index 4d8537696f..ee95d1f6f3 100644
--- a/tests/web/services/test_pdf_resource_size_limits.py
+++ b/tests/web/services/test_pdf_resource_size_limits.py
@@ -175,7 +175,9 @@ def origin():
seam ``dns_pinning._real_getaddrinfo``, rather than by replacing
``socket.getaddrinfo`` (which would refuse every fetch here). It
answers TEST-NET-1 (192.0.2.10: passes the SSRF policy, not routable)
- and records each looked-up host in ``stub.lookups``.
+ and records each looked-up host in ``stub.lookups``. Since it answers
+ any host, teardown checks that ``ORIGIN``'s host was the only one
+ looked up, so a stray lookup still fails the test.
"""
pdf_service._ensure_weasyprint() # build the real _URL_FETCHER first
stub = _StubOrigin()
@@ -205,6 +207,9 @@ def origin():
):
yield stub
+ stray = [host for host in stub.lookups if host != urlsplit(ORIGIN).hostname]
+ assert not stray, f"unexpected DNS lookups: {stray}"
+
@pytest.fixture
def pdf_logs():
@@ -3928,3 +3933,122 @@ class TestDocumentedFigures:
assert pixels // (12 * MIB) == 21
# "at most 1024 such requests": 64 KiB charged each
assert per_export // pdf_service._RESOURCE_READ_CHUNK_BYTES == 1024
+
+
+class TestTheFetchWindowIsClosedOnRefusal:
+ """A refusal raised inside the fetch, for an over-cap body or one
+ WeasyPrint would decode unbounded, still removes the DNS pin and closes
+ the block-private window, as a successful fetch does."""
+
+ @pytest.mark.parametrize(
+ ("body", "headers", "refusal"),
+ [
+ (
+ b"",
+ {"Content-Length": str(pdf_service.MAX_PDF_RESOURCE_BYTES + 1)},
+ pdf_service.PDFResourceTooLargeError,
+ ),
+ (
+ b"wOF2" + b"\0" * 512,
+ None,
+ pdf_service.UnsupportedPDFResourceError,
+ ),
+ ],
+ ids=["over-cap", "unsupported"],
+ )
+ def test_the_pin_and_the_window_are_removed(
+ self, origin, body, headers, refusal
+ ):
+ host = urlsplit(ORIGIN).hostname
+ state = dns_pinning._thread_state
+ during = []
+ respond = origin.respond
+
+ def respond_and_record(request):
+ during.append(
+ (
+ host in dns_pinning._get_pins(),
+ getattr(state, "block_private", None) is not None,
+ )
+ )
+ return respond(request)
+
+ origin.respond = respond_and_record
+ origin.add("/resource", body, headers=headers)
+ assert host not in dns_pinning._get_pins()
+ assert getattr(state, "block_private", None) is None
+
+ with pytest.raises(refusal) as refused:
+ pdf_service._safe_url_fetcher(ORIGIN + "/resource")
+
+ assert refused.type is refusal
+ # The refusal was raised inside the pin and the window...
+ assert during == [(True, True)]
+ # ...and both are gone once it has propagated.
+ assert host not in dns_pinning._get_pins()
+ assert getattr(state, "block_private", None) is None
+ assert getattr(state, "block_exemptions", None) is None
+
+
+def _gif_with_frame_past_screen(width: int, height: int) -> bytes:
+ """A 1x1 logical screen whose one frame declares ``width`` x ``height``.
+
+ Pillow's GIF factory enlarges the image to cover such a frame and runs
+ its own decompression-bomb check on the new size while reading the
+ header; no pixel data is decoded.
+ """
+ screen = b"GIF89a" + struct.pack("<HHBBB", 1, 1, 0, 0, 0)
+ frame = b"," + struct.pack("<HHHHB", 0, 0, width, height, 0)
+ return screen + frame + b"\x02\x02\x44\x01\x00" + b";"
+
+
+class TestFollowUpProbeChecks:
+ def test_a_gif_header_probe_leaves_the_warning_filters_alone(self):
+ # The GIF factory warns from inside the probe (past Pillow's
+ # MAX_IMAGE_PIXELS, under twice it). The warning must reach the
+ # caller's own filters, which stay the same list with the same
+ # entries: a probe that changed or replaced the filters, however it
+ # imported ``warnings``, would hide the warning or fail the checks.
+ from PIL import Image
+
+ side = 10000
+ assert Image.MAX_IMAGE_PIXELS < side * side < 2 * Image.MAX_IMAGE_PIXELS
+ body = _gif_with_frame_past_screen(side, side)
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ filters = warnings.filters
+ before = list(filters)
+ pixels = pdf_service._declared_image_pixels(body, "GIF")
+ assert warnings.filters is filters
+ assert list(warnings.filters) == before
+
+ assert pixels == side * side
+ assert [
+ w
+ for w in caught
+ if issubclass(w.category, Image.DecompressionBombWarning)
+ ], caught
+
+ def test_a_header_factory_oserror_is_a_controlled_refusal(
+ self, origin, pdf_logs
+ ):
+ # Image.open propagates an OSError from a header-only factory
+ # rather than trying the next plugin, so the guard treats it as
+ # that format: the resource is refused with the guard's own
+ # warning, not left to escape the fetch.
+ from PIL import Image
+
+ Image.init()
+ factory = Mock(side_effect=OSError("header unavailable"))
+ origin.add("/style.css", b"body { color: red; }\n")
+
+ with (
+ patch.dict(Image.OPEN, {"TGA": (factory, None)}),
+ pytest.raises(pdf_service.UnsupportedPDFResourceError),
+ ):
+ pdf_service._safe_url_fetcher(ORIGIN + "/style.css")
+
+ factory.assert_called_once()
+ refusals = [line for line in pdf_logs if "Refused a TGA image" in line]
+ assert len(refusals) == 1, pdf_logs
+ assert not any("header unavailable" in line for line in pdf_logs)
diff --git a/tests/web/services/test_pdf_service.py b/tests/web/services/test_pdf_service.py
index c6a7a312dd..8703050574 100644
--- a/tests/web/services/test_pdf_service.py
+++ b/tests/web/services/test_pdf_service.py
@@ -1094,16 +1094,14 @@ class TestSafeUrlFetcherDnsPin:
@staticmethod
def _module_fetcher(pdf_module):
- """A fresh URL fetcher built as ``_ensure_weasyprint`` builds it.
+ """A fresh URL fetcher from the builder ``_ensure_weasyprint`` uses.
- Redirects off, plus the ``_BoundedBodyProcessor`` that applies the
- per-resource and per-export size limits (#7248), so these pin tests
- run through the same fetcher shape as production rather than a bare
- one that skips the size limits.
+ ``_build_url_fetcher`` turns redirects off and attaches the
+ ``_BoundedBodyProcessor`` (#7248), so these pin tests run through
+ the same fetcher shape as production, including any handler added
+ there later.
"""
- fetcher = type(pdf_module._URL_FETCHER)(allow_redirects=False)
- fetcher.add_handler(pdf_module._BoundedBodyProcessor())
- return fetcher
+ return pdf_module._build_url_fetcher(type(pdf_module._URL_FETCHER))
@pytest.fixture
def fetcher_env(self, monkeypatch):
@@ -1262,6 +1260,80 @@ class TestSafeUrlFetcherDnsPin:
assert validated_hits == []
assert any("@" in host for host in resolver.calls), resolver.calls
+ IDN_HOST = "ü.pdf-pin.example"
+ IDN_KEY = "xn--tda.pdf-pin.example"
+
+ @pytest.mark.parametrize(
+ ("miss_answer", "expected"),
+ [("internal", "refused"), ("127.0.0.1", "fetched")],
+ )
+ def test_non_ascii_host_lookup_that_misses_the_pin_is_policy_checked(
+ self, servers, fetcher_env, miss_answer, expected
+ ):
+ """A non-ASCII host is validated and pinned under its IDNA form,
+ but urllib looks up the Unicode form, which misses the pin. That
+ lookup is still checked by the block-private window: an internal
+ answer is refused, and an answer that passes the policy is fetched
+ as before."""
+ import urllib.error
+
+ from local_deep_research.security import dns_pinning
+
+ port, validated_hits, internal_hits, internal_ip = servers
+ miss_ip = internal_ip if miss_answer == "internal" else miss_answer
+ resolver = self._resolver(
+ {self.IDN_KEY: ["127.0.0.1"]}, default=miss_ip
+ )
+ validate = Mock(wraps=fetcher_env.validate_url)
+ url = f"http://{self.IDN_HOST}:{port}/x.css"
+ with (
+ patch.object(dns_pinning, "_real_getaddrinfo", resolver),
+ patch.object(fetcher_env, "validate_url", validate),
+ ):
+ if expected == "refused":
+ with pytest.raises(urllib.error.URLError):
+ fetcher_env._safe_url_fetcher(url)
+ else:
+ assert self._fetch_body(fetcher_env, url) == b"VALIDATED"
+
+ # Normal validation ran on the URL, and resolved the IDNA form.
+ validate.assert_called_once_with(url)
+ assert self.IDN_KEY in resolver.calls, resolver.calls
+ # The lookup urllib made missed the pin and reached the resolver.
+ assert self.IDN_HOST in resolver.calls, resolver.calls
+ assert internal_hits == [], (
+ "a non-ASCII host lookup that missed the pin connected to an "
+ "internal address"
+ )
+ if expected == "refused":
+ assert validated_hits == []
+ else:
+ assert validated_hits == ["/x.css"]
+
+ def test_non_ascii_host_is_refused_by_normal_validation(
+ self, servers, fetcher_env
+ ):
+ """A non-ASCII host whose IDNA form resolves to an internal address
+ is refused by ``validate_url`` before any pin or fetch."""
+ from local_deep_research.security import dns_pinning
+
+ port, validated_hits, internal_hits, internal_ip = servers
+ resolver = self._resolver({self.IDN_KEY: [internal_ip]})
+ with (
+ patch.object(dns_pinning, "_real_getaddrinfo", resolver),
+ pytest.raises(
+ fetcher_env.UnsafePDFResourceURLError,
+ match="Blocked unsafe URL",
+ ),
+ ):
+ fetcher_env._safe_url_fetcher(
+ f"http://{self.IDN_HOST}:{port}/x.css"
+ )
+
+ assert resolver.calls == [self.IDN_KEY]
+ assert internal_hits == []
+ assert validated_hits == []
+
@staticmethod
def _use_proxy(monkeypatch, pdf_module, proxy_url):
"""Rebuild the module fetcher with ``http_proxy`` set, so the proxy
@@ -1534,6 +1606,42 @@ class TestSafeUrlFetcherDnsPin:
mock_fetch.assert_not_called()
+ def test_module_fetcher_is_built_by_the_shared_builder(self, monkeypatch):
+ """``_ensure_weasyprint`` builds ``_URL_FETCHER`` through
+ ``_build_url_fetcher``, the builder ``_module_fetcher`` uses, so
+ the fetchers these tests build cannot drift from production's."""
+ from local_deep_research.web.services import pdf_service as pdf_module
+
+ pdf_module._ensure_weasyprint()
+ if not pdf_module.WEASYPRINT_AVAILABLE:
+ pytest.skip("WeasyPrint is not available")
+ # Rebuild the lazily imported globals; monkeypatch restores them.
+ for name in (
+ "HTML",
+ "CSS",
+ "URLFetchingError",
+ "URLFetcherResponse",
+ "_URL_FETCHER",
+ ):
+ monkeypatch.setattr(pdf_module, name, getattr(pdf_module, name))
+ monkeypatch.setattr(pdf_module, "WEASYPRINT_AVAILABLE", None)
+ real_builder = pdf_module._build_url_fetcher
+ built = []
+
+ def builder(fetcher_cls):
+ built.append(real_builder(fetcher_cls))
+ return built[-1]
+
+ monkeypatch.setattr(pdf_module, "_build_url_fetcher", builder)
+ pdf_module._ensure_weasyprint()
+
+ assert len(built) == 1
+ assert pdf_module._URL_FETCHER is built[0]
+ assert any(
+ isinstance(handler, pdf_module._BoundedBodyProcessor)
+ for handler in built[0].handlers
+ )
+
class TestRenderPdfRetryHardening:
"""Retry-path hardening pins (#6588)."""