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(security): pin the PDF export fetcher to the validated address (#7785)

LearningCircuit24d82d1388a1
diff --git a/SECURITY.md b/SECURITY.md
index 6d9acba31c..ab093d9933 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -149,6 +149,8 @@ By setting this, the operator acknowledges the residual risk above. To minimise
The general HTTP fetch path (`safe_requests`, used for RAG sources and web scraping) resolves the hostname and connects to that **same** validated address: `security.dns_pinning` pins the resolved IP for the outbound connection (re-resolving and re-validating at connect time, and re-pinning at every redirect hop) so `requests`/`urllib3` cannot connect to a different address than the one the guard checked. The request keeps the original hostname, so TLS SNI and certificate verification are unchanged — only name resolution is pinned. The notification path above reuses this same shim (via `pinned_notification_send`, plus the block-private window for unpinned plugin-endpoint hosts) — but with redirect-following disabled outright rather than validated hop-by-hop, since a notification webhook has no legitimate need to follow redirects. It still does not apply to callers that hand a URL to an external client that re-resolves on its own with no in-thread `getaddrinfo` interception (LLM SDKs — see "LLM Provider URL Validation"); for those, egress restriction remains the primary defense. It also does not apply when `requests` is configured to use a forward proxy (`HTTP(S)_PROXY` / `trust_env`): `urllib3` then resolves the *proxy* host rather than the target, so target-IP selection is delegated to the proxy and the pin is a safe no-op (the pre-connection `validate_url` check still runs).
+The PDF export resource fetcher (`_SafeUrlFetcher` in `web/services/pdf_service.py`) fetches the images, stylesheets and fonts a report references through WeasyPrint's urllib-based `URLFetcher`, with redirects disabled. Each fetch runs inside `dns_pinning.pinned_request` nested with `dns_pinning.block_private_resolution`, both with the policy its `validate_url` call applies (public addresses only; cloud-metadata always blocked). The connection therefore goes only to an address that passed the same policy at connect time. For an ASCII host name it is pinned to the validated address. An IP-literal host is not pinned, because there is no DNS to rebind; its lookup goes through the block window like any other unpinned lookup, such as a non-ASCII host that urllib looks up in a different form from the pin key. Each such lookup is checked against that policy on the answer actually used. urllib connects on the rendering thread, which is the thread the pin and window apply to, and keeps the hostname for TLS SNI and certificate verification. The fetch is refused if the `getaddrinfo` shim is not the active resolver, and resource URLs that carry userinfo (any `@` in the authority) are refused outright, because urllib would look up the whole `user@host` authority rather than the pinned host. If `HTTP(S)_PROXY` is set, urllib connects to the proxy and the proxy resolves the target, so the forward-proxy caveat above applies to the target. The proxy's own lookup is exempted from the public-only policy by exact host and port (taken from the fetcher's proxy configuration, via `dns_pinning.allow_resolution`), so a proxy on a private or loopback address keeps working; cloud-metadata and other link-local addresses are still refused for it, and every other lookup during the fetch keeps the public-only policy. Two proxy setups are not mirrored and fail closed, meaning a private proxy is refused rather than let through: a plain-http resource whose `HTTP_PROXY` has an `https://` scheme while `HTTPS_PROXY` is also set, where urllib tunnels through the `HTTPS_PROXY` host; and a Python without urllib's private `_parse_proxy` helper.
+
### JS-Rendering Browser Redirect SSRF
The static fetch path validates every redirect hop via `SafeSession.send` → `ssrf_validator.validate_url`. The JavaScript-rendering browser path (`PlaywrightHTMLDownloader`, used by both Crawl4AI and plain Playwright) previously did not: a public URL that 302-redirected to `169.254.169.254` (cloud metadata) or an RFC1918 host was followed by headless Chromium unchecked. The fix brings the browser path to parity so that **every subrequest the browser makes — the initial navigation, each redirect hop, and every subresource — is validated or blocked** with the same rules and `allow_private_ips` scope as the static path.
diff --git a/changelog.d/+pdf-fetcher-dns-pinning.security.md b/changelog.d/+pdf-fetcher-dns-pinning.security.md
new file mode 100644
index 0000000000..ea0a37afe3
--- /dev/null
+++ b/changelog.d/+pdf-fetcher-dns-pinning.security.md
@@ -0,0 +1 @@
+PDF export resource fetches (images, stylesheets, fonts) now connect only to an address that passed the same SSRF policy at connect time: the validated address is pinned for the connection, any other lookup during the fetch is checked against that policy, and the fetch is refused if the pinning resolver is not active. Resource URLs that carry userinfo (`user@host`) are no longer fetched. A forward proxy set through `HTTP_PROXY`/`HTTPS_PROXY` keeps working for these fetches even on a private or loopback address; a proxy that resolves to a cloud-metadata or other link-local address is refused.
diff --git a/src/local_deep_research/security/dns_pinning.py b/src/local_deep_research/security/dns_pinning.py
index bc794d9b3c..e3b80f0f81 100644
--- a/src/local_deep_research/security/dns_pinning.py
+++ b/src/local_deep_research/security/dns_pinning.py
@@ -54,6 +54,18 @@ synchronous, in-thread delivery (``AppriseAsset(async_mode=False)``); with
the default async fan-out the send would run in worker threads that carry
no thread-local pin/block and the guard would silently not apply.
+The PDF export resource fetcher (``web/services/pdf_service._SafeUrlFetcher``)
+wraps each WeasyPrint ``URLFetcher`` fetch (urllib, redirects disabled) in
+:func:`pinned_request` nested with :func:`block_private_resolution`, using the
+same default policy as its ``validate_url`` call, and refuses the fetch when
+:func:`_shim_installed` is False. When the fetcher has a forward proxy
+configured for the URL's scheme, the proxy's exact (host, port) lookup is
+relaxed with :func:`allow_resolution` so a private proxy keeps working, while
+metadata addresses stay refused. urllib connects on the calling thread, so the
+thread-local pin applies. The block window covers any lookup that misses the
+pin; the fetcher also refuses URLs with userinfo, since urllib would look up
+``user@host`` rather than the pinned host.
+
Import-order dependency: the pin only works while ``socket.getaddrinfo``
is still THIS module's shim. If something replaces ``socket.getaddrinfo``
wholesale AFTER this module is imported — e.g. ``gevent``/``eventlet``
@@ -293,7 +305,7 @@ def _getaddrinfo_bounded(host, port, family, type, proto, flags):
raise socket.gaierror(
getattr(socket, "EAI_AGAIN", socket.EAI_FAIL),
f"DNS resolution for {host!r} timed out after "
- f"{_RESOLVE_TIMEOUT_SECONDS}s during a pinned send (fail closed)",
+ f"{_RESOLVE_TIMEOUT_SECONDS}s during a pinned resolution (fail closed)",
)
if "error" in result:
# Re-raise the resolver's own error unchanged (e.g. gaierror for
@@ -421,7 +433,7 @@ def _resolve_maybe_block(host, port, family, type, proto, flags):
raise socket.gaierror(
getattr(socket, "EAI_NONAME", getattr(socket, "EAI_FAIL", -1)),
f"DNS resolution for {_host_for_log(host)!r} failed: host is "
- f"not encodable to IDNA (refused during a pinned send window)",
+ f"not encodable to IDNA (refused during a pinned resolution window)",
) from exc
# A ``None`` host is an AF_PASSIVE bind
# (``getaddrinfo(None, port, ..., AI_PASSIVE)`` — a local listening-socket
@@ -437,6 +449,14 @@ def _resolve_maybe_block(host, port, family, type, proto, flags):
return results
host_display = _host_for_log(host)
allow_localhost, allow_private_ips, block_link_local = block
+ # An exact (host, port) exemption registered by :func:`allow_resolution`
+ # swaps in its own (relaxed) policy for that one lookup. The check below
+ # still runs, so the always-blocked metadata addresses stay refused.
+ exemptions = getattr(_thread_state, "block_exemptions", None)
+ if exemptions and isinstance(host, str):
+ relaxed = exemptions.get((host, port))
+ if relaxed is not None:
+ allow_localhost, allow_private_ips, block_link_local = relaxed
for info in results:
ip_str = str(info[4][0])
if ssrf_validator.is_ip_blocked(
@@ -446,8 +466,8 @@ def _resolve_maybe_block(host, port, family, type, proto, flags):
block_link_local=block_link_local,
):
logger.warning(
- "Blocked send-time resolution of {} to internal/private/"
- "metadata IP {} during the pinned notification window "
+ "Blocked resolution of {} to internal/private/metadata IP "
+ "{} during a pinned resolution window "
"(possible SSRF / redirect-to-internal)",
host_display,
ip_str,
@@ -460,7 +480,7 @@ def _resolve_maybe_block(host, port, family, type, proto, flags):
raise socket.gaierror(
getattr(socket, "EAI_FAIL", -1),
"Blocked resolution to an internal/private/metadata IP "
- "during the pinned notification send window",
+ "during a pinned resolution window",
)
return results
@@ -742,6 +762,47 @@ def block_private_resolution(
_thread_state.block_private = prev
+def allow_resolution(
+ host: str,
+ port: int,
+ allow_localhost: bool = True,
+ allow_private_ips: bool = True,
+ block_link_local: bool = True,
+) -> Iterator[None]:
+ """Relax an active block-private window for one exact lookup.
+
+ While this context is active on the calling thread, an UNPINNED lookup
+ inside a :func:`block_private_resolution` window whose ``host`` string
+ and ``port`` exactly equal the given ones is checked with these flags
+ instead of the window's. It is still checked:
+ ``ssrf_validator.ALWAYS_BLOCKED_METADATA_IPS`` stay refused whatever the
+ flags, and ``block_link_local`` (on by default) keeps the rest of the
+ link-local range refused too. Every other lookup keeps the window's
+ policy. Outside a window this has no effect, and a pinned host is
+ unaffected (pins short-circuit before the window is consulted).
+
+ Meant for a connection the caller deliberately makes to a fixed,
+ operator-configured endpoint, e.g. a forward proxy from
+ ``HTTP(S)_PROXY``, whose address may legitimately be private. Match is
+ on the exact host string and port the client passes to
+ ``getaddrinfo`` (no normalisation), so an IP-literal endpoint works
+ the same as a name. Thread-local; contexts nest and restore on exit.
+ """
+ prev = getattr(_thread_state, "block_exemptions", None)
+ exemptions = dict(prev or {})
+ exemptions[(host, port)] = (
+ allow_localhost,
+ allow_private_ips,
+ block_link_local,
+ )
+ _thread_state.block_exemptions = exemptions
+ try:
+ yield
+ finally:
+ _thread_state.block_exemptions = prev
+
+
@contextlib.contextmanager
def pin_hosts(
urls,
diff --git a/src/local_deep_research/security/ssrf_validator.py b/src/local_deep_research/security/ssrf_validator.py
index e0e33f84db..8d48db8b09 100644
--- a/src/local_deep_research/security/ssrf_validator.py
+++ b/src/local_deep_research/security/ssrf_validator.py
@@ -564,11 +564,13 @@ def validate_url(
# Resolve hostname to IP and check.
#
# NOTE: this is the validation-time check. On the ``safe_requests``
- # path it is now backed by ``security.dns_pinning``, which pins the
- # address validated here (or re-resolved+re-validated at connect
- # time) so requests/urllib3 connect to exactly that address rather
- # than re-resolving the hostname independently — closing the
- # resolve-vs-connect gap for that path. Callers that hand the URL to
+ # path and in the PDF export resource fetcher
+ # (``web/services/pdf_service._SafeUrlFetcher``, urllib-based) it is
+ # now backed by ``security.dns_pinning``, which pins the address
+ # validated here (or re-resolved+re-validated at connect time) so
+ # the client connects to exactly that address rather than
+ # re-resolving the hostname independently — closing the
+ # resolve-vs-connect gap for those paths. Callers that hand the URL to
# an external client that re-resolves on its own (e.g. an LLM SDK,
# Apprise) still carry the residual window; see SECURITY.md.
try:
diff --git a/src/local_deep_research/web/services/pdf_service.py b/src/local_deep_research/web/services/pdf_service.py
index 2beed88e23..47917b290f 100644
--- a/src/local_deep_research/web/services/pdf_service.py
+++ b/src/local_deep_research/web/services/pdf_service.py
@@ -9,6 +9,7 @@ production Flask applications due to:
- Good paged media features
"""
+import contextlib
import gzip
import http.client
import io
@@ -21,10 +22,12 @@ import zlib
from contextvars import ContextVar
from html import escape
from typing import Optional, Dict, Any, NoReturn
+from urllib.parse import unquote, urlsplit
+
import markdown # type: ignore[import-untyped]
from loguru import logger
-from ...security import redact_url_for_log, validate_url
+from ...security import dns_pinning, redact_url_for_log, validate_url
from ...utilities.resource_utils import safe_close
@@ -1034,8 +1037,145 @@ class _SafeUrlFetcher:
raise UnsafePDFResourceURLError(
f"Blocked unsafe URL in PDF rendering: {redacted}"
)
+ if _has_userinfo(url):
+ # urllib passes the whole authority (``user@host``) to
+ # getaddrinfo, while the DNS pin is keyed on the host alone, so
+ # such a lookup would miss the pin. These fetches never need
+ # credentials; refuse them.
+ redacted = redact_url_for_log(url)
+ logger.warning(
+ f"Blocked URL with userinfo in PDF rendering: {redacted}"
+ )
+ raise UnsafePDFResourceURLError(
+ f"Blocked URL with userinfo in PDF rendering: {redacted}"
+ )
_ensure_weasyprint()
- return _URL_FETCHER.fetch(url)
+ # validate_url resolved the host, but urllib would resolve it again
+ # at connect time. Pin the validated addresses for this fetch so the
+ # connection goes to an address that passed the same policy (see
+ # security.dns_pinning). The block-private window checks any lookup
+ # during the fetch that misses the pin against the same policy, on
+ # the answer actually used. Both are thread-local, and WeasyPrint
+ # fetches on the calling thread; urllib keeps the hostname for TLS
+ # SNI and certificate checks. Without the shim neither applies, so
+ # refuse rather than fetch unpinned.
+ if not dns_pinning._shim_installed():
+ redacted = redact_url_for_log(url)
+ logger.warning(
+ f"DNS pin unavailable; refusing PDF resource fetch: {redacted}"
+ )
+ raise UnsafePDFResourceURLError(
+ f"DNS pin unavailable; refusing PDF resource fetch: {redacted}"
+ )
+ with (
+ dns_pinning.block_private_resolution(),
+ _allow_proxy_lookup(url),
+ dns_pinning.pinned_request(url),
+ ):
+ return _URL_FETCHER.fetch(url)
+
+
+def _allow_proxy_lookup(url):
+ """Let urllib's lookup of the configured forward proxy pass the window.
+
+ With ``HTTP(S)_PROXY`` set, urllib connects to the proxy, which resolves
+ the target itself; the proxy is operator configuration and is often on
+ a private or loopback address. Its lookup misses the pin, so the
+ block-private window would refuse it. Relax exactly that (host, port)
+ lookup to allow private and loopback addresses; metadata and the rest of
+ link-local stay refused (see ``dns_pinning.allow_resolution``). Returns
+ a no-op context when the URL will not go through a proxy.
+ """
+ endpoint = _proxy_endpoint(url)
+ if endpoint is None:
+ return contextlib.nullcontext()
+ host, port = endpoint
+ return dns_pinning.allow_resolution(
+ host,
+ port,
+ allow_localhost=True,
+ allow_private_ips=True,
+ block_link_local=True,
+ )
+
+
+def _proxy_endpoint(url):
+ """The (host, port) urllib will look up to reach the proxy for ``url``.
+
+ Read from the fetcher's own ``ProxyHandler`` snapshot (what urllib will
+ use), not a fresh ``getproxies()``. Mirrors ``ProxyHandler.proxy_open``
+ (scheme lookup, ``proxy_bypass``, ``_parse_proxy``, ``unquote`` of the
+ host:port) and ``http.client``'s host/port split, so the result is the
+ exact host string and port passed to ``getaddrinfo``. None when no proxy
+ applies or it cannot be worked out; the proxy lookup then gets the
+ window's public-only policy, so a private proxy is refused (fail
+ closed), never let through unchecked.
+
+ Not mirrored, so it fails closed the same way: a plain-http URL whose
+ ``http_proxy`` has an ``https://`` scheme while ``https_proxy`` is also
+ set. urllib then re-enters its opener and tunnels to the first proxy
+ through the ``https_proxy`` one, so the lookup is of the
+ ``https_proxy`` host, which is not exempted.
+ """
+ parse_proxy = getattr(urllib.request, "_parse_proxy", None)
+ if parse_proxy is None:
+ # Private urllib helper; if a future Python drops it, fail closed
+ # (no exemption) with a clear message rather than guessing.
+ logger.warning(
+ "urllib.request._parse_proxy is unavailable; a private forward "
+ "proxy will be refused for PDF resource fetches"
+ )
+ return None
+ proxies = None
+ for handler in getattr(_URL_FETCHER, "handlers", ()):
+ if isinstance(handler, urllib.request.ProxyHandler):
+ proxies = handler.proxies
+ break
+ try:
+ scheme = urlsplit(url).scheme.lower()
+ proxy = (proxies or {}).get(scheme)
+ if not proxy:
+ return None
+ # urllib's ``Request.host``: the authority (userinfo is refused
+ # before this runs, and validate_url refuses percent-escapes).
+ request_host = urlsplit(url).netloc
+ if request_host and urllib.request.proxy_bypass(request_host):
+ return None
+ proxy_type, _user, _password, hostport = parse_proxy(proxy)
+ except ValueError:
+ return None
+ hostport = unquote(hostport) # as ProxyHandler.proxy_open does
+ # The connection class urllib uses: an https URL tunnels through the
+ # proxy over HTTPSConnection; otherwise the proxy URL's scheme decides.
+ conn_scheme = "https" if scheme == "https" else (proxy_type or scheme)
+ port = 443 if conn_scheme == "https" else 80
+ host = hostport
+ i, j = hostport.rfind(":"), hostport.rfind("]")
+ if i > j:
+ host = hostport[:i]
+ if hostport[i + 1 :]:
+ try:
+ port = int(hostport[i + 1 :])
+ except ValueError:
+ return None
+ if host[:1] == "[" and host[-1:] == "]":
+ host = host[1:-1]
+ return (host, port) if host else None
+
+
+def _has_userinfo(url) -> bool:
+ """True if the URL's authority carries userinfo (``@``, or ``%40``).
+
+ The ``%40`` branch is defence in depth: an authority with ``%40`` but
+ no ``@`` has the escape in its host or port, which ``validate_url``
+ already refuses. An authority that cannot be parsed counts as carrying
+ userinfo, so the caller refuses it.
+ """
+ try:
+ netloc = urlsplit(url).netloc
+ except ValueError:
+ return True
+ return "@" in netloc or "%40" in netloc.lower()
_safe_url_fetcher = _SafeUrlFetcher()
@@ -1452,9 +1592,12 @@ class PDFService:
# 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.
+ # which can still carry URL material such as secret query
+ # tokens -- and ``logger.exception`` in the callers would print
+ # that chain. Userinfo URLs are refused by the guard before
+ # urllib parses them (``_has_userinfo``), so an
+ # ``InvalidURL: nonnumeric port: '<password>@host'`` can no
+ # longer arise for a URL the guard allows.
needs_retry = True
if needs_retry:
logger.warning(
diff --git a/tests/web/services/test_pdf_resource_size_limits.py b/tests/web/services/test_pdf_resource_size_limits.py
index 5278dcc16d..6c0f495469 100644
--- a/tests/web/services/test_pdf_resource_size_limits.py
+++ b/tests/web/services/test_pdf_resource_size_limits.py
@@ -14,7 +14,10 @@ body shorter than its ``Content-Length`` fails the fetch too.
Every response comes from an in-process stub behind urllib's real HTTP
parsing (``http.client.HTTPResponse`` over an in-memory stream), patched in
-as ``HTTPHandler.http_open``: no socket is opened and no name is resolved.
+as ``HTTPHandler.http_open``: no socket is opened. The fetcher pins each
+host's DNS answer for the fetch (``security.dns_pinning``), which resolves
+the host once; that lookup goes to a stand-in resolver answering a fixed
+TEST-NET-1 address, so no real name is resolved either.
"""
from __future__ import annotations
@@ -22,6 +25,7 @@ from __future__ import annotations
import gzip
import http.client
import io
+import socket
import struct
import sys
import threading
@@ -38,6 +42,7 @@ from loguru import logger
pytest.importorskip("weasyprint")
+from local_deep_research.security import dns_pinning # noqa: E402
from local_deep_research.web.services import pdf_service # noqa: E402
ORIGIN = "http://pdf-resources.test"
@@ -102,6 +107,10 @@ class _StubOrigin:
self._routes: dict = {}
self.streams: dict[str, _Stream] = {}
self.requested: list[str] = []
+ # Every host the DNS pin looked up, and, per request, whether the
+ # request's host was pinned while it was being served.
+ self.lookups: list[str] = []
+ self.pinned: list[bool] = []
def add(
self,
@@ -132,6 +141,7 @@ class _StubOrigin:
parts = urlsplit(request.full_url)
key = parts.path + (f"?{parts.query}" if parts.query else "")
self.requested.append(key)
+ self.pinned.append(parts.hostname in dns_pinning._get_pins())
body, headers, pieces, chunked, status = self._routes[key]
lines = [f"HTTP/1.1 {status}"]
lines += [f"{name}: {value}" for name, value in headers.items()]
@@ -157,7 +167,15 @@ class _StubOrigin:
@pytest.fixture
def origin():
- """The stub, reachable through the real wired fetcher and nothing else."""
+ """The stub, reachable through the real wired fetcher and nothing else.
+
+ The fetcher refuses to fetch unless ``socket.getaddrinfo`` is still the
+ DNS-pin shim, so the resolver is stubbed one layer down, at the pin's
+ 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``.
+ """
pdf_service._ensure_weasyprint() # build the real _URL_FETCHER first
stub = _StubOrigin()
@@ -167,13 +185,22 @@ def origin():
def only_the_stub(url, *_args, **_kwargs):
return url.startswith(ORIGIN + "/")
- def no_resolution(*_args, **_kwargs):
- raise OSError("name resolution is disabled in this test")
+ def test_net_resolver(host, port, *_args, **_kwargs):
+ stub.lookups.append(host)
+ return [
+ (
+ socket.AF_INET,
+ socket.SOCK_STREAM,
+ socket.IPPROTO_TCP,
+ "",
+ ("192.0.2.10", port or 0),
+ )
+ ]
with (
patch.object(pdf_service, "validate_url", only_the_stub),
patch.object(urllib.request.HTTPHandler, "http_open", http_open),
- patch("socket.getaddrinfo", side_effect=no_resolution),
+ patch.object(dns_pinning, "_real_getaddrinfo", test_net_resolver),
):
yield stub
@@ -766,9 +793,11 @@ class TestExportBudget:
finally:
pdf_service._export_resource_budget.reset(token)
- # Refused before the URL is checked (which resolves its host), so
- # not even a name is looked up, let alone a request made.
+ # Refused before the URL is checked (which resolves its host) and
+ # before the DNS pin (which resolves it again), so not even a name
+ # is looked up, let alone a request made.
assert origin.requested == []
+ assert origin.lookups == []
checked.assert_not_called()
assert "pdf-resources.test" not in str(refused.value)
assert "T0K3N-9QX" not in str(refused.value)
@@ -778,6 +807,30 @@ class TestExportBudget:
assert ORIGIN in warnings[0]
assert "T0K3N-9QX" not in "\n".join(pdf_logs)
+ def test_a_bounded_fetch_is_made_inside_the_dns_pin(self, origin):
+ """The size limits and the DNS pin apply to the same fetch.
+
+ The body is read and charged by `_BoundedBodyProcessor` inside
+ ``_URL_FETCHER.fetch``, which `_SafeUrlFetcher` runs within
+ ``dns_pinning.pinned_request``: the host is looked up once, for the
+ pin, and is pinned while the request is served; the export's budget
+ is charged for the body.
+ """
+ origin.add("/pinned.css", b"p" * 100)
+ budget = pdf_service._ResourceBudget(MIB)
+ token = pdf_service._export_resource_budget.set(budget)
+ try:
+ resource = pdf_service._safe_url_fetcher(ORIGIN + "/pinned.css")
+ resource.close()
+ finally:
+ pdf_service._export_resource_budget.reset(token)
+
+ assert origin.requested == ["/pinned.css"]
+ assert origin.lookups == ["pdf-resources.test"]
+ assert origin.pinned == [True]
+ assert budget.remaining == MIB - 100
+ assert "pdf-resources.test" not in dns_pinning._get_pins()
+
def test_a_read_asks_for_at_most_one_byte_past_what_is_left(self, origin):
# No Content-Length: a body read until the connection closes, which
# the server sends in 1 KiB pieces.
diff --git a/tests/web/services/test_pdf_service.py b/tests/web/services/test_pdf_service.py
index 11b237ca5d..b98d09f8e7 100644
--- a/tests/web/services/test_pdf_service.py
+++ b/tests/web/services/test_pdf_service.py
@@ -10,6 +10,7 @@ Tests cover:
"""
import re
+import warnings
import pytest
from unittest.mock import Mock, patch
@@ -519,15 +520,36 @@ class TestSafeUrlFetcher:
assert issubclass(UnsafePDFResourceURLError, ValueError)
def test_validated_url_delegates_to_url_fetcher(self):
- """Validated URLs are forwarded to the module's URLFetcher instance."""
+ """Validated URLs are forwarded to the module's URLFetcher instance.
+
+ The fetch is wrapped in the DNS pin, which resolves the host once;
+ the resolver seam is patched to a TEST-NET-1 answer (192.0.2.10,
+ which passes the SSRF policy but is not routable), so the cell does
+ no real DNS lookup.
+ """
+ import socket
+
+ from local_deep_research.security import dns_pinning
from local_deep_research.web.services import pdf_service as pdf_module
from local_deep_research.web.services.pdf_service import (
_safe_url_fetcher,
)
+ def _public(host, port, *args, **kwargs):
+ return [
+ (
+ socket.AF_INET,
+ socket.SOCK_STREAM,
+ socket.IPPROTO_TCP,
+ "",
+ ("192.0.2.10", port or 0),
+ )
+ ]
+
pdf_module._ensure_weasyprint() # populate the lazy _URL_FETCHER
with (
patch.object(pdf_module, "validate_url", return_value=True),
+ patch.object(dns_pinning, "_real_getaddrinfo", _public),
patch.object(pdf_module._URL_FETCHER, "fetch") as mock_fetch,
):
mock_fetch.return_value = Mock(
@@ -669,6 +691,598 @@ class TestSafeUrlFetcher:
assert len(pdf_bytes) > 100
+class TestSafeUrlFetcherDnsPin:
+ """The PDF resource fetch connects only to an address that passed the
+ same policy at connect time.
+
+ ``validate_url`` resolves the host, and urllib would resolve it again
+ when it connects. ``_SafeUrlFetcher`` pins the validated answer with
+ ``security.dns_pinning`` for the fetch (for ASCII hosts, whose lookup
+ key matches the pin), and opens a block-private window so any lookup
+ that misses the pin is checked against the same policy on the answer
+ actually used. A resolver that changes its answer between the lookups
+ therefore cannot steer the connection to a blocked address. The one
+ relaxation is the configured forward proxy's exact (host, port), which
+ may be private but never metadata.
+
+ The resolver seam ``dns_pinning._real_getaddrinfo`` is driven with
+ successive answers per host. Two stub HTTP servers share one port: one
+ on 127.0.0.1 (the "validated" address) and one on an internal address
+ (127.0.0.2, or ::1 where 127.0.0.2 cannot be bound). A hit on the second
+ server means the fetch connected to an address that never passed the
+ check. The fetcher uses the default (public-only) policy, which blocks
+ every loopback address, so ``ssrf_validator.is_ip_blocked`` is wrapped
+ to treat 127.0.0.1 alone as a public stand-in; the internal address and
+ everything else keep the real policy.
+ """
+
+ HOST = "pdf-pin.example"
+ USERINFO_URLS = (
+ "http://user@{host}:{port}/x.css",
+ "http://@{host}:{port}/x.css",
+ "http://u%40v@{host}:{port}/x.css",
+ )
+
+ @staticmethod
+ def _resolver(answers, default=None):
+ """Stand-in for ``dns_pinning._real_getaddrinfo``.
+
+ Each lookup of ``host`` consumes the next answer from
+ ``answers[host]``; the last answer then sticks. An IP literal
+ resolves to itself. A host with no entry gets ``default`` when one
+ is given. ``calls`` records every
+ looked-up host, and ``queues`` lets a test change the remaining
+ answers mid-fetch.
+ """
+ import ipaddress
+ import socket
+
+ queues = {h: list(v) for h, v in answers.items()}
+ calls = []
+
+ def resolve(host, port, family=0, type=0, proto=0, flags=0):
+ key = (host or "").lower().rstrip(".")
+ calls.append(key)
+ seq = queues.get(key)
+ try:
+ # An IP literal resolves to itself, as the real resolver does.
+ ipaddress.ip_address(key)
+ seq = [key]
+ except ValueError:
+ pass
+ if seq:
+ ip = seq[0] if len(seq) == 1 else seq.pop(0)
+ elif default is not None:
+ ip = default
+ else:
+ raise socket.gaierror(socket.EAI_NONAME, "no answer")
+ if ":" in ip:
+ fam, sockaddr = socket.AF_INET6, (ip, port or 0, 0, 0)
+ else:
+ fam, sockaddr = socket.AF_INET, (ip, port or 0)
+ return [(fam, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", sockaddr)]
+
+ resolve.calls = calls
+ resolve.queues = queues
+ return resolve
+
+ @staticmethod
+ def _start_server(bind_ip, port, marker, hits):
+ import socket
+ import threading
+ from http.server import BaseHTTPRequestHandler, HTTPServer
+
+ class _Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ hits.append(self.path)
+ self.send_response(200)
+ self.send_header("Content-Type", "text/css")
+ self.send_header("Content-Length", str(len(marker)))
+ self.end_headers()
+ self.wfile.write(marker)
+
+ def log_message(self, *args):
+ pass
+
+ class _Server(HTTPServer):
+ address_family = (
+ socket.AF_INET6 if ":" in bind_ip else socket.AF_INET
+ )
+
+ server = _Server((bind_ip, port), _Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ return server, thread
+
+ @pytest.fixture
+ def servers(self):
+ """A server on 127.0.0.1 and one on an internal address, same port.
+
+ Yields ``(port, validated_hits, internal_hits, internal_ip)``.
+ """
+ validated_hits: list = []
+ internal_hits: list = []
+ validated, t1 = self._start_server(
+ "127.0.0.1", 0, b"VALIDATED", validated_hits
+ )
+ port = validated.server_address[1]
+ internal = None
+ errors = []
+ for internal_ip in ("127.0.0.2", "::1"):
+ try:
+ internal = self._start_server(
+ internal_ip, port, b"INTERNAL", internal_hits
+ )
+ break
+ except OSError as exc:
+ errors.append(f"{internal_ip}: {exc}")
+ if internal is None:
+ validated.shutdown()
+ validated.server_close()
+ t1.join(timeout=5)
+ warnings.warn(
+ "TestSafeUrlFetcherDnsPin: neither 127.0.0.2 nor ::1 could "
+ "be bound, so the PDF fetcher's DNS-pin, block-window and "
+ "proxy-exemption tests did NOT run on this host: "
+ + "; ".join(errors),
+ stacklevel=2,
+ )
+ pytest.skip(
+ "needs a second loopback address on the same port as "
+ "127.0.0.1 to tell the validated address from an internal "
+ "one; neither could be bound: " + "; ".join(errors)
+ )
+ try:
+ yield port, validated_hits, internal_hits, internal_ip
+ finally:
+ for server, thread in ((validated, t1), internal):
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+
+ @staticmethod
+ def _module_fetcher(pdf_module):
+ """A fresh URL fetcher built as ``_ensure_weasyprint`` builds it.
+
+ 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.
+ """
+ fetcher = type(pdf_module._URL_FETCHER)(allow_redirects=False)
+ fetcher.add_handler(pdf_module._BoundedBodyProcessor())
+ return fetcher
+
+ @pytest.fixture
+ def fetcher_env(self, monkeypatch):
+ """Treat 127.0.0.1 as public and use a proxy-free URL fetcher.
+
+ WeasyPrint's ``URLFetcher`` reads proxy settings from the
+ environment when it is built, and a proxy would take the target
+ lookup off this machine. A fresh fetcher with the module's settings
+ (redirects off, size-limiting processor attached; see
+ ``_module_fetcher``) is built with the proxy variables cleared.
+ """
+ from local_deep_research.security import ssrf_validator
+ from local_deep_research.web.services import pdf_service as pdf_module
+
+ for var in (
+ "http_proxy",
+ "https_proxy",
+ "all_proxy",
+ "HTTP_PROXY",
+ "HTTPS_PROXY",
+ "ALL_PROXY",
+ "no_proxy",
+ "NO_PROXY",
+ ):
+ monkeypatch.delenv(var, raising=False)
+ pdf_module._ensure_weasyprint()
+ fetcher = TestSafeUrlFetcherDnsPin._module_fetcher(pdf_module)
+ monkeypatch.setattr(pdf_module, "_URL_FETCHER", fetcher)
+
+ real_is_ip_blocked = ssrf_validator.is_ip_blocked
+
+ def is_ip_blocked(ip, *args, **kwargs):
+ if ip == "127.0.0.1":
+ return False
+ return real_is_ip_blocked(ip, *args, **kwargs)
+
+ monkeypatch.setattr(ssrf_validator, "is_ip_blocked", is_ip_blocked)
+ return pdf_module
+
+ def test_connect_uses_the_validated_address(self, servers, fetcher_env):
+ """The resolver answers 127.0.0.1 for validation and the pin, then
+ switches to the internal address the moment the URL fetcher starts,
+ which is when urllib would look the host up again to connect. The
+ fetch must reach the 127.0.0.1 server."""
+ from local_deep_research.security import dns_pinning
+
+ port, validated_hits, internal_hits, internal_ip = servers
+ resolver = self._resolver({self.HOST: ["127.0.0.1"]})
+ url_fetcher = fetcher_env._URL_FETCHER
+ real_fetch = url_fetcher.fetch
+
+ def fetch_after_rebind(url, *args, **kwargs):
+ # Every lookup from here on answers the internal address.
+ resolver.queues[self.HOST][:] = [internal_ip]
+ return real_fetch(url, *args, **kwargs)
+
+ with (
+ patch.object(dns_pinning, "_real_getaddrinfo", resolver),
+ patch.object(url_fetcher, "fetch", fetch_after_rebind),
+ ):
+ resource = fetcher_env._safe_url_fetcher(
+ f"http://{self.HOST}:{port}/style.css"
+ )
+ try:
+ body = resource.read()
+ finally:
+ resource.close()
+
+ assert internal_hits == [], "the fetch connected to the later answer"
+ assert body == b"VALIDATED"
+ assert validated_hits == ["/style.css"]
+
+ def test_answer_that_changes_before_the_pin_is_refused(
+ self, servers, fetcher_env
+ ):
+ """Validation sees 127.0.0.1, every later lookup the internal
+ address. The pin re-checks its own answer against the same policy
+ and refuses it, so nothing is fetched."""
+ from local_deep_research.security import dns_pinning
+
+ port, validated_hits, internal_hits, internal_ip = servers
+ resolver = self._resolver({self.HOST: ["127.0.0.1", internal_ip]})
+ with (
+ patch.object(dns_pinning, "_real_getaddrinfo", resolver),
+ pytest.raises(ValueError, match="possible SSRF"),
+ ):
+ fetcher_env._safe_url_fetcher(
+ f"http://{self.HOST}:{port}/style.css"
+ )
+
+ assert internal_hits == [], "the fetch connected to the later answer"
+ assert validated_hits == []
+
+ @pytest.mark.parametrize("template", USERINFO_URLS)
+ def test_userinfo_url_is_refused(self, servers, fetcher_env, template):
+ """A URL with userinfo is refused before any fetch. urllib would
+ look up ``user@host``, which the pin (keyed on the host) does not
+ cover."""
+ from local_deep_research.security import dns_pinning
+
+ port, validated_hits, internal_hits, internal_ip = servers
+ resolver = self._resolver(
+ {self.HOST: ["127.0.0.1"]}, default=internal_ip
+ )
+ url = template.format(host=self.HOST, port=port)
+ with (
+ patch.object(dns_pinning, "_real_getaddrinfo", resolver),
+ pytest.raises(
+ fetcher_env.UnsafePDFResourceURLError, match="userinfo"
+ ),
+ ):
+ fetcher_env._safe_url_fetcher(url)
+
+ assert internal_hits == []
+ assert validated_hits == []
+
+ def test_percent_encoded_at_without_userinfo_is_refused(self):
+ """An authority with ``%40`` but no literal ``@`` has the escape in
+ its host, which ``validate_url`` already refuses before any lookup;
+ the ``%40`` branch of ``_has_userinfo`` is defence in depth for it.
+ """
+ from local_deep_research.web.services import pdf_service as pdf_module
+
+ with pytest.raises(
+ pdf_module.UnsafePDFResourceURLError, match="Blocked unsafe URL"
+ ):
+ pdf_module._safe_url_fetcher(f"http://u%40{self.HOST}/x.css")
+
+ @pytest.mark.parametrize("template", USERINFO_URLS)
+ def test_lookup_that_misses_the_pin_is_policy_checked(
+ self, servers, fetcher_env, template
+ ):
+ """With the userinfo check bypassed, urllib's lookup of
+ ``user@host`` misses the pin and resolves to the internal address.
+ The block-private window must refuse that answer, so nothing is
+ fetched. (urllib reports the refused lookup as ``URLError``.)"""
+ import urllib.error
+
+ from local_deep_research.security import dns_pinning
+
+ port, validated_hits, internal_hits, internal_ip = servers
+ resolver = self._resolver(
+ {self.HOST: ["127.0.0.1"]}, default=internal_ip
+ )
+ url = template.format(host=self.HOST, port=port)
+ with (
+ patch.object(dns_pinning, "_real_getaddrinfo", resolver),
+ patch.object(fetcher_env, "_has_userinfo", return_value=False),
+ pytest.raises(urllib.error.URLError),
+ ):
+ fetcher_env._safe_url_fetcher(url)
+
+ assert internal_hits == [], (
+ "a lookup that missed the pin connected to an internal address"
+ )
+ assert validated_hits == []
+ assert any("@" in host for host in resolver.calls), resolver.calls
+
+ @staticmethod
+ def _use_proxy(monkeypatch, pdf_module, proxy_url):
+ """Rebuild the module fetcher with ``http_proxy`` set, so the proxy
+ comes from the fetcher's own ``ProxyHandler`` snapshot, as in
+ production (size-limiting processor included)."""
+ monkeypatch.setenv("http_proxy", proxy_url)
+ fetcher = TestSafeUrlFetcherDnsPin._module_fetcher(pdf_module)
+ monkeypatch.setattr(pdf_module, "_URL_FETCHER", fetcher)
+ return fetcher
+
+ def _fetch_body(self, pdf_module, url):
+ resource = pdf_module._safe_url_fetcher(url)
+ try:
+ return resource.read()
+ finally:
+ resource.close()
+
+ def test_private_proxy_is_used(self, servers, fetcher_env, monkeypatch):
+ """A forward proxy named in ``http_proxy`` that resolves to a
+ private/loopback address still carries the fetch. Its lookup misses
+ the pin, and the block window must let exactly that one through."""
+ from local_deep_research.security import dns_pinning
+
+ port, validated_hits, internal_hits, internal_ip = servers
+ self._use_proxy(
+ monkeypatch, fetcher_env, f"http://proxy.example:{port}"
+ )
+ resolver = self._resolver(
+ {self.HOST: ["127.0.0.1"], "proxy.example": [internal_ip]}
+ )
+ url = f"http://{self.HOST}:{port}/x.css"
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ body = self._fetch_body(fetcher_env, url)
+
+ # The internal server is the proxy here: it gets the absolute URL.
+ assert body == b"INTERNAL"
+ assert internal_hits == [url]
+ assert validated_hits == []
+ # The exemption and the window are restored once the fetch ends.
+ assert (
+ getattr(dns_pinning._thread_state, "block_exemptions", None) is None
+ )
+ assert getattr(dns_pinning._thread_state, "block_private", None) is None
+
+ def test_ip_literal_private_proxy_is_used(
+ self, servers, fetcher_env, monkeypatch
+ ):
+ """The same with the proxy given as an IP literal, which is not
+ pinned but does pass through the window's lookup."""
+ from local_deep_research.security import dns_pinning
+
+ port, validated_hits, internal_hits, internal_ip = servers
+ literal = f"[{internal_ip}]" if ":" in internal_ip else internal_ip
+ self._use_proxy(monkeypatch, fetcher_env, f"http://{literal}:{port}")
+ resolver = self._resolver({self.HOST: ["127.0.0.1"]})
+ url = f"http://{self.HOST}:{port}/x.css"
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ body = self._fetch_body(fetcher_env, url)
+
+ assert body == b"INTERNAL"
+ assert internal_hits == [url]
+ assert validated_hits == []
+
+ @pytest.mark.parametrize(
+ ("proxy_ip", "allowed"),
+ [
+ # RFC1918: the exemption must allow private addresses.
+ ("10.0.0.5", True),
+ # Always-blocked cloud metadata.
+ ("169.254.169.254", False),
+ # Link-local metadata outside the always-blocked set (Scaleway)
+ # and IPv6 link-local: refused only because the exemption keeps
+ # ``block_link_local`` on.
+ ("169.254.42.42", False),
+ ("fe80::1", False),
+ ],
+ )
+ def test_proxy_lookup_policy(
+ self, fetcher_env, monkeypatch, proxy_ip, allowed
+ ):
+ """The proxy exemption relaxes private/loopback only: a proxy name
+ that resolves to an RFC1918 address is connected to, one that
+ resolves to metadata or link-local is still refused.
+
+ ``socket.create_connection`` is replaced by a stand-in that does
+ the same ``getaddrinfo`` call (through the shim and window) and
+ records the answer instead of connecting, so the cell never opens a
+ socket to any of these addresses, whatever the outcome."""
+ import socket
+ import urllib.error
+
+ from local_deep_research.security import dns_pinning
+
+ self._use_proxy(monkeypatch, fetcher_env, "http://proxy.example:3128")
+ resolver = self._resolver(
+ {self.HOST: ["127.0.0.1"], "proxy.example": [proxy_ip]}
+ )
+ connect_targets = []
+
+ def lookup_only(address, *args, **kwargs):
+ host, target_port = address[:2]
+ infos = socket.getaddrinfo(host, target_port, 0, socket.SOCK_STREAM)
+ connect_targets.extend(info[4][0] for info in infos)
+ raise ConnectionRefusedError("connect suppressed in test")
+
+ expected = "connect suppressed" if allowed else "Blocked resolution"
+ with (
+ patch.object(dns_pinning, "_real_getaddrinfo", resolver),
+ patch.object(socket, "create_connection", lookup_only),
+ pytest.raises(urllib.error.URLError, match=expected),
+ ):
+ fetcher_env._safe_url_fetcher(f"http://{self.HOST}:8080/x.css")
+
+ assert connect_targets == ([proxy_ip] if allowed else []), (
+ connect_targets
+ )
+
+ @pytest.mark.parametrize(
+ ("env", "url"),
+ [
+ # https target tunnelled (CONNECT) through a port-less proxy:
+ # HTTPSConnection, so the default port is 443.
+ ({"https_proxy": "http://proxy.example"}, "https://t.example/x"),
+ # http target through an https:// proxy: also 443.
+ ({"http_proxy": "https://proxy.example"}, "http://t.example/x"),
+ # Port-less http proxy for an http target: 80.
+ ({"http_proxy": "http://proxy.example"}, "http://t.example/x"),
+ # Bracketed IPv6 proxy.
+ ({"http_proxy": "http://[::1]:3128"}, "http://t.example/x"),
+ # Percent-escaped host: urllib unquotes it before connecting.
+ ({"http_proxy": "http://pro%78y.corp:3128"}, "http://t.example/x"),
+ # Scheme-less proxy with credentials.
+ ({"http_proxy": "u:[email protected]:3128"}, "http://t.example/x"),
+ # no_proxy bypass: urllib connects to the target directly.
+ (
+ {
+ "http_proxy": "http://proxy.example:3128",
+ "no_proxy": "t.example",
+ },
+ "http://t.example/x",
+ ),
+ ],
+ )
+ def test_proxy_endpoint_matches_urllib_lookup(
+ self, fetcher_env, monkeypatch, env, url
+ ):
+ """``_proxy_endpoint`` must name exactly the (host, port) urllib
+ passes to ``getaddrinfo`` for the proxy, or None when urllib does
+ not use one. The lookup is recorded and refused, so nothing
+ connects."""
+ import socket
+ import urllib.error
+
+ for name, value in env.items():
+ monkeypatch.setenv(name, value)
+ fetcher = self._module_fetcher(fetcher_env)
+ monkeypatch.setattr(fetcher_env, "_URL_FETCHER", fetcher)
+ seen = []
+
+ def record(host, port, *args, **kwargs):
+ seen.append((host, port))
+ raise socket.gaierror(socket.EAI_NONAME, "recorded only")
+
+ with patch.object(socket, "getaddrinfo", record):
+ with pytest.raises(urllib.error.URLError, match="recorded only"):
+ fetcher.fetch(url)
+
+ endpoint = fetcher_env._proxy_endpoint(url)
+ target = (url.split("/")[2], 443 if url.startswith("https") else 80)
+ if "no_proxy" in env:
+ assert endpoint is None
+ assert seen == [target], seen
+ else:
+ assert seen and seen[0] == endpoint, (seen, endpoint)
+
+ def test_other_private_lookups_stay_refused_with_a_proxy(
+ self, servers, fetcher_env, monkeypatch
+ ):
+ """The exemption is the proxy's exact (host, port) only. During a
+ proxied fetch, a private answer for another host, for the proxy
+ host on another port, or for the proxy's address on another port
+ is still refused; the proxied fetch itself still works."""
+ import socket
+
+ from local_deep_research.security import dns_pinning
+
+ port, validated_hits, internal_hits, internal_ip = servers
+ url_fetcher = self._use_proxy(
+ monkeypatch, fetcher_env, f"http://proxy.example:{port}"
+ )
+ resolver = self._resolver(
+ {
+ self.HOST: ["127.0.0.1"],
+ "proxy.example": [internal_ip],
+ "other.example": [internal_ip],
+ }
+ )
+ probes = [
+ ("other.example", port),
+ ("proxy.example", port + 1),
+ (internal_ip, port + 1),
+ ]
+ outcomes = {}
+ real_fetch = url_fetcher.fetch
+
+ def probe_then_fetch(url, *args, **kwargs):
+ for host, probe_port in probes:
+ try:
+ socket.getaddrinfo(host, probe_port)
+ outcomes[(host, probe_port)] = "resolved"
+ except socket.gaierror:
+ outcomes[(host, probe_port)] = "refused"
+ return real_fetch(url, *args, **kwargs)
+
+ url = f"http://{self.HOST}:{port}/x.css"
+ with (
+ patch.object(dns_pinning, "_real_getaddrinfo", resolver),
+ patch.object(url_fetcher, "fetch", probe_then_fetch),
+ ):
+ body = self._fetch_body(fetcher_env, url)
+
+ assert outcomes == dict.fromkeys(probes, "refused"), outcomes
+ assert body == b"INTERNAL"
+ assert internal_hits == [url]
+
+ def test_public_resource_still_fetches(self, servers, fetcher_env):
+ """Positive control: a host with a stable public answer is fetched
+ normally through the pin and the block-private window."""
+ from local_deep_research.security import dns_pinning
+
+ port, validated_hits, internal_hits, _ = servers
+ resolver = self._resolver({self.HOST: ["127.0.0.1"]})
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ resource = fetcher_env._safe_url_fetcher(
+ f"http://{self.HOST}:{port}/img.css"
+ )
+ try:
+ body = resource.read()
+ finally:
+ resource.close()
+
+ assert body == b"VALIDATED"
+ assert validated_hits == ["/img.css"]
+ assert internal_hits == []
+
+ def test_refuses_when_the_pin_shim_is_not_installed(self):
+ """If ``socket.getaddrinfo`` is no longer the pin shim, a pin has no
+ effect, so the fetcher refuses instead of fetching unpinned.
+
+ Both resolvers are a fixed public stand-in, so the cell does no
+ real DNS even if the refusal is removed."""
+ import socket
+
+ from local_deep_research.security import dns_pinning
+ from local_deep_research.web.services import pdf_service as pdf_module
+
+ public = self._resolver({}, default="192.0.2.10")
+ pdf_module._ensure_weasyprint()
+ with (
+ patch.object(pdf_module, "validate_url", return_value=True),
+ patch.object(pdf_module._URL_FETCHER, "fetch") as mock_fetch,
+ patch.object(dns_pinning, "_real_getaddrinfo", public),
+ patch.object(socket, "getaddrinfo", public),
+ ):
+ assert not dns_pinning._shim_installed()
+ with pytest.raises(
+ pdf_module.UnsafePDFResourceURLError, match="DNS pin"
+ ):
+ pdf_module._safe_url_fetcher("https://example.com/x.png")
+
+ mock_fetch.assert_not_called()
+
+
class TestRenderPdfRetryHardening:
"""Retry-path hardening pins (#6588)."""
@@ -764,11 +1378,15 @@ class TestRenderPdfRetryHardening:
"""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.
+ exception's text, which can carry URL material such as secret query
+ tokens. The ``InvalidURL: nonnumeric port: '<password>@host'`` text
+ used below is fabricated for this test, not a live example: userinfo
+ URLs are refused by the guard before urllib parses them
+ (``_has_userinfo``), so that exact text cannot arise for a URL the
+ guard allows. 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 secret material.
"""
import traceback
diff --git a/tests/web_services/test_pdf_service.py b/tests/web_services/test_pdf_service.py
index 243341ccf0..5ed6f19f03 100644
--- a/tests/web_services/test_pdf_service.py
+++ b/tests/web_services/test_pdf_service.py
@@ -525,9 +525,17 @@ class TestRefusedResourceDoesNotAbortTheExport:
the fetcher's blanket except (#6589). WeasyPrint is loaded first:
a cold ``_ensure_weasyprint`` inside the call would replace the
patched ``_URL_FETCHER`` with the real one, so the cell only passed
- when an earlier test had loaded it. The raising ``getaddrinfo``
- guard makes any real lookup fail the cell deterministically instead of reaching out.
+ when an earlier test had loaded it. The fetch is wrapped in the DNS
+ pin, which resolves the host once through the resolver seam
+ ``dns_pinning._real_getaddrinfo``; that seam is patched to a fixed
+ TEST-NET-1 answer (192.0.2.10, which passes the SSRF policy but is
+ not routable), so no real lookup happens. ``socket.getaddrinfo``
+ itself is left alone: replacing it would remove the pin shim, and
+ the fetcher refuses to fetch without it.
"""
+ import socket
+
+ from local_deep_research.security import dns_pinning
from local_deep_research.web.services import pdf_service
payload = {"string": b"body", "mime_type": "text/css"}
@@ -538,13 +546,21 @@ class TestRefusedResourceDoesNotAbortTheExport:
pdf_service._ensure_weasyprint() # populate the lazy _URL_FETCHER
- def _no_resolution(*_args, **_kwargs):
- raise OSError("getaddrinfo disabled: no network in unit tests")
+ def _public(host, port, *_args, **_kwargs):
+ return [
+ (
+ socket.AF_INET,
+ socket.SOCK_STREAM,
+ socket.IPPROTO_TCP,
+ "",
+ ("192.0.2.10", port or 0),
+ )
+ ]
with (
patch.object(pdf_service, "validate_url", return_value=True),
patch.object(pdf_service, "_URL_FETCHER", _Fetcher()),
- patch("socket.getaddrinfo", side_effect=_no_resolution),
+ patch.object(dns_pinning, "_real_getaddrinfo", _public),
):
assert (
pdf_service._SkippingUrlFetcher()("https://example.com/x.css")
@@ -721,8 +737,11 @@ class TestRetriedRenderEndToEnd:
HOSTILE = "https://attacker.example/bad.icc"
def _render(self):
+ import socket
+
from loguru import logger as loguru_logger
+ from local_deep_research.security import dns_pinning
from local_deep_research.web.services import pdf_service
pdf_service._ensure_weasyprint()
@@ -744,6 +763,20 @@ class TestRetriedRenderEndToEnd:
# the stand-in public host is allowed without a DNS lookup.
return "169.254.169.254" not in url
+ def public_resolver(host, port, *args, **kwargs):
+ # The DNS pin around each fetch resolves the host once through
+ # this seam; a fixed TEST-NET-1 answer (passes the SSRF policy,
+ # not routable) keeps the cell offline.
+ return [
+ (
+ socket.AF_INET,
+ socket.SOCK_STREAM,
+ socket.IPPROTO_TCP,
+ "",
+ ("192.0.2.10", port or 0),
+ )
+ ]
+
# The hostile resource comes first, so it is what aborts the first
# pass; the refused one is then reached only by the retry.
markdown = (
@@ -772,6 +805,7 @@ class TestRetriedRenderEndToEnd:
with (
patch.object(pdf_service, "_URL_FETCHER", _SpyFetcher()),
patch.object(pdf_service, "validate_url", fake_validate_url),
+ patch.object(dns_pinning, "_real_getaddrinfo", public_resolver),
patch.object(pdf_service, "HTML", recording_html),
):
pdf = pdf_service.PDFService().markdown_to_pdf(