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.

harden(fetch): pin the validated IP for the actual connection (#5561)

LearningCircuit744d44a217e5
diff --git a/SECURITY.md b/SECURITY.md
index 0e3d8fe708..ce9ffff899 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -127,7 +127,7 @@ By setting this, the operator acknowledges the residual risk above. To minimise
- **Prefer plugin schemes over raw `http(s)://`.** Apprise plugin schemes (`discord://`, `slack://`, `ntfy://`, `ntfys://`, `gotify://`, `telegram://`, `mattermost://`, `rocketchat://`, `teams://`, `matrix://`, `mailto://`, etc.) hardcode their endpoints internally and have no user-controllable hostname — no SSRF surface. Use them whenever the target service supports them.
- **Restrict egress** if private-network exposure is a concern: deploy LDR behind an egress-restricted network so that even a successful rebinding cannot reach internal services.
-The same DNS-rebinding caveat applies to `safe_requests` / `ssrf_validator.validate_url`, used for general HTTP fetches (RAG sources, web scraping). Egress restriction is the primary defense for that path as well.
+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. This does not apply to callers that hand a URL to an external client that re-resolves on its own (Apprise above; 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).
### Parser-Differential URL Bypass (GHSA-g23j-2vwm-5c25)
@@ -213,7 +213,7 @@ Operators needing a hard boundary **must** layer OS-level controls: network name
#### Caveats
-- **DNS rebinding TOCTOU**: `_classify_host` resolves once at evaluation time; the actual HTTP request resolves again at connect time. Closing this race would require pinning the resolved IP into the outbound connection, which is HTTPS-only and doesn't follow redirects cleanly. See the "Notification Webhook SSRF" subsection for the accepted-risk rationale (the same caveat applies here).
+- **DNS rebinding TOCTOU**: `_classify_host` resolves the hostname once at evaluation time; the actual HTTP request resolves again at connect time. Unlike the `safe_requests` fetch path — which pins its validated address via `security.dns_pinning` (for both `http` and `https`, re-pinning at every redirect hop) so the connection cannot be re-steered — this classification path resolves DNS independently (its own `getaddrinfo`, on a policy worker thread that carries no pin), so it is not covered by that pin and the resolve-vs-connect window remains. Accepted residual; egress restriction at the firewall is the operator-side mitigation.
- **Settings tampering**: `unprotected` is unavailable unless the operator explicitly sets `LDR_POLICY_ALLOW_UNPROTECTED_EGRESS=true`. When enabled, an adversary with write access to a user's per-user settings DB can flip `policy.egress_scope` to that escape hatch and disable normal egress enforcement (the retired `both` value no longer does this — it is coerced to the protective `adaptive` scope). Migration `0027` likewise rewrites legacy stored and queued `unprotected` selections to `adaptive` on upgrade, so turning the gate on later doesn't silently reactivate choices made before the capability boundary existed; while it stays off, new `unprotected` writes are rejected and any residual or tampered queued value is coerced to `adaptive` at dispatch with a `policy_audit` warning. Per-user SQLCipher databases mean one user can't trivially tamper with another's policy, but an attacker who can read/write a user's DB can change anything about that user's runtime. Policy-key changes emit `policy_audit=True` log lines so admins can audit changes after the fact.
- **Audit log routing**: `policy_audit=True` log lines are filtered from the WebSocket sink (`frontend_progress_sink`), so they never reach a CORS-permissive browser observer. They are written to the loguru file/console sinks and persisted to the encrypted research-log DB if a research is active.
- **LLM/embeddings endpoint locality is best-effort**: the "stays local" guarantee is *strong* for named cloud providers (OpenAI, Anthropic, Google, OpenRouter, etc.) and localhost-default providers (Ollama/LM Studio/llama.cpp) — those are classified by name and reliably blocked/allowed. It is *weaker* for configurable-URL providers (`openai_endpoint`): the endpoint is classified by resolving its host, so an OpenAI-compatible endpoint pointed at a private-looking IP (split-horizon DNS, a tunnel, a proxy) is **trusted as local**. A user who wants to process private-collection data with a cloud LLM is expected to mark the collection **public** (the explicit opt-in); the policy prevents *accidental/silent* egress, not a determined user who deliberately points "local" inference at a cloud endpoint. This is consistent with the guardrail-not-boundary model above.
diff --git a/changelog.d/+fetch-pin-resolved-ip.security.md b/changelog.d/+fetch-pin-resolved-ip.security.md
new file mode 100644
index 0000000000..ea74149006
--- /dev/null
+++ b/changelog.d/+fetch-pin-resolved-ip.security.md
@@ -0,0 +1,7 @@
+Hardened outbound HTTP fetches (RAG source and web-scraping requests via
+`safe_get`/`safe_post`/`SafeSession`) so the connection targets the exact
+IP address the SSRF guard validated, instead of letting the HTTP client
+re-resolve the hostname independently at connect time. The validated
+address is now pinned for the connection and re-checked at every redirect
+hop, while the original hostname is preserved for TLS SNI and certificate
+verification.
diff --git a/src/local_deep_research/security/dns_pinning.py b/src/local_deep_research/security/dns_pinning.py
new file mode 100644
index 0000000000..9094347518
--- /dev/null
+++ b/src/local_deep_research/security/dns_pinning.py
@@ -0,0 +1,350 @@
+"""Pin the validated IP for the actual outbound connection.
+
+Closes the resolve-vs-connect gap in the SSRF guard. ``validate_url``
+resolves a hostname via ``socket.getaddrinfo`` and checks the resulting
+addresses against the private/internal/metadata block lists, but
+``requests``/``urllib3`` then resolve the hostname *again, independently*
+at connect time. An attacker who controls a DNS authority can answer with
+a public address while the guard is looking and a private / cloud-metadata
+address a moment later at connect — so the address that was validated is
+not the address that gets connected to.
+
+This module makes the fetch connect to the SAME address that was
+validated. A thread-local registry of pinned ``host -> addrinfo`` entries
+is consulted by a process-wide ``socket.getaddrinfo`` shim installed once
+at import. While a host is pinned (for the duration of a single request,
+re-established at each redirect hop), the shim returns ONLY the
+pre-validated addresses for that host; every other lookup falls through to
+the real resolver untouched.
+
+Why a ``getaddrinfo`` shim rather than a custom ``HTTPAdapter``:
+
+* It covers BOTH sinks uniformly — the module-level ``requests.get`` /
+ ``requests.post`` used by ``safe_get`` / ``safe_post`` AND the
+ ``SafeSession.send`` path — without threading a mounted adapter through
+ every call site or per-request session.
+* TLS is preserved for free. The request URL keeps the original hostname,
+ so ``urllib3`` still sets the TLS SNI and verifies the server
+ certificate against that hostname. Only name resolution is redirected,
+ so there is NO certificate-verification bypass and no
+ ``server_hostname`` / ``assert_hostname`` plumbing to get wrong.
+* It behaves identically for ``http`` and ``https`` and re-pins cleanly at
+ every redirect hop.
+* Thread safety: the pin registry is thread-local, so concurrent requests
+ in LDR's thread pools never observe each other's pins, and every
+ unpinned lookup is an untouched pass-through. This mirrors the existing
+ ``security/egress`` ``socket.connect`` audit hook, which also installs a
+ process-wide, thread-local-gated interposition.
+
+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``
+monkey-patching, or any other socket shim — that later patch silently
+overwrites ours and the pin is dropped fail-open (validation still runs,
+but the connect-time re-resolution it is meant to catch goes unguarded
+again). LDR runs Socket.IO in threading ``async_mode`` and does not
+monkeypatch sockets, so this does not currently apply — but if that ever
+changes, any such monkeypatching must happen BEFORE this module (or
+``security.safe_requests``, which imports it) is first imported.
+"""
+
+import contextlib
+import ipaddress
+import socket
+import threading
+from typing import Iterator, List, Optional, Tuple
+
+import requests
+from loguru import logger
+from urllib3.exceptions import LocationParseError
+from urllib3.util import parse_url
+
+from . import ssrf_validator
+
+# Attribute stamped on our shim (see below) so any later capture of the
+# "real" resolver can recognize it and refuse to capture the shim as if it
+# were the genuine resolver.
+_SHIM_MARKER = "_ldr_dns_pin_shim"
+
+
+def _capture_real_getaddrinfo():
+ """Return the genuine resolver, never our own shim.
+
+ On a normal import ``socket.getaddrinfo`` is still the stdlib resolver
+ and is captured as-is. But if this module is *reloaded*
+ (``importlib.reload``) after :func:`install` has already swapped in our
+ shim, ``socket.getaddrinfo`` is that shim — capturing it here would make
+ the shim's pass-through call itself, recursing forever (``RecursionError``)
+ on every unpinned lookup process-wide. In that case fall back to the real
+ resolver captured by the previous load, which survives in this module's
+ globals across a reload.
+ """
+ current = socket.getaddrinfo
+ if not getattr(current, _SHIM_MARKER, False):
+ return current
+ # Reload after install(): don't re-capture our own shim. Reuse the real
+ # resolver the previous load already captured (guaranteed not to be a
+ # shim, thanks to this very guard).
+ previous = globals().get("_real_getaddrinfo")
+ if previous is not None and not getattr(previous, _SHIM_MARKER, False):
+ return previous
+ return current
+
+
+# The genuine resolver, captured at import BEFORE the shim is installed.
+# Referenced by module-global name at call time (never closed over) so a
+# test can patch this single seam to control what BOTH the validation-time
+# resolution and the pin-time resolution observe. Captured via the guard
+# above so a reload cannot make the shim call itself.
+_real_getaddrinfo = _capture_real_getaddrinfo()
+
+# host (normalized) -> list of addrinfo 5-tuples that are safe to connect
+# to. Thread-local so concurrent fetches in different worker threads cannot
+# see one another's pins.
+_thread_state = threading.local()
+
+_installed = False
+
+
+def _normalize_host(host: Optional[str]) -> Optional[str]:
+ """Normalize a host into the key form used by the pin registry.
+
+ Lower-cases (DNS is case-insensitive, and both ``urllib3.parse_url``
+ and ``urllib3``'s connection layer already lower-case the host before
+ it reaches ``getaddrinfo``), strips IPv6 brackets, and drops the
+ trailing root dot (``urllib3`` calls ``self._dns_host.rstrip(".")``
+ before resolving). Applying the same transform on both the pinning and
+ the lookup side guarantees the key matches.
+ """
+ if not host:
+ return None
+ host = host.strip().lower()
+ if host.startswith("[") and host.endswith("]"):
+ host = host[1:-1]
+ host = host.rstrip(".")
+ return host or None
+
+
+def _get_pins() -> dict:
+ pins = getattr(_thread_state, "pins", None)
+ if pins is None:
+ pins = {}
+ _thread_state.pins = pins
+ return pins
+
+
+def _pinned_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
+ """Process-wide ``socket.getaddrinfo`` replacement.
+
+ Returns the pinned addresses when the calling thread has an active pin
+ for ``host``; otherwise delegates unchanged to the real resolver, so
+ this is a transparent pass-through for every lookup that is not part of
+ a pinned request.
+ """
+ key = _normalize_host(host) if isinstance(host, str) else None
+ if key is not None:
+ entry = _get_pins().get(key)
+ if entry is not None:
+ results = []
+ for fam, socktype, sockproto, canon, sockaddr in entry:
+ # Honor a caller-requested address family (AF_UNSPEC == 0
+ # means "any").
+ if family not in (0, socket.AF_UNSPEC, fam):
+ continue
+ # Honor a caller-requested socket type (0 == "any"). Every
+ # pinned entry is resolved as SOCK_STREAM (see
+ # _resolve_and_validate), which is also what urllib3's own
+ # connection lookups always request explicitly — so this
+ # never filters anything out of the normal HTTP(S) path. It
+ # only guards a hypothetical caller-requested SOCK_DGRAM (or
+ # other non-stream) lookup for a host that happens to be
+ # mid-pin, which would otherwise get back a SOCK_STREAM /
+ # IPPROTO_TCP entry mislabeled with the caller's requested
+ # type.
+ if type not in (0, socktype):
+ continue
+ # Rewrite the port from THIS lookup while preserving the
+ # IPv6 flowinfo / scope_id captured at pin time.
+ new_sockaddr = (sockaddr[0], port) + tuple(sockaddr[2:])
+ results.append(
+ (
+ fam,
+ type or socktype,
+ proto or sockproto,
+ canon,
+ new_sockaddr,
+ )
+ )
+ if results:
+ return results
+ # A pin exists but nothing matches the requested family/type.
+ # Fail closed rather than silently falling through to a fresh
+ # (attacker-controllable) resolution.
+ raise socket.gaierror(
+ getattr(socket, "EAI_ADDRFAMILY", socket.EAI_FAIL),
+ "No pinned address for the requested family/socktype",
+ )
+ return _real_getaddrinfo(host, port, family, type, proto, flags)
+
+
+# Stamp our shim so a later capture (e.g. after ``importlib.reload``) can tell
+# it apart from the genuine resolver and refuse to capture it as the "real"
+# one — see :func:`_capture_real_getaddrinfo`.
+setattr(_pinned_getaddrinfo, _SHIM_MARKER, True)
+
+
+def install() -> None:
+ """Install the process-wide ``getaddrinfo`` shim (idempotent).
+
+ A no-op after the first call. The shim is transparent until a thread
+ activates a pin via :func:`pinned_request`, so importing this module
+ has no behavioral effect on code that does not fetch through the safe
+ request helpers.
+
+ Idempotent under module reload too: if a shim (this load's or a prior
+ load's) is already the active resolver, it is not stacked on top of
+ itself.
+ """
+ global _installed
+ if _installed:
+ return
+ # A reload resets ``_installed`` to False, so also refuse to reinstall
+ # when our shim is already the active resolver. Combined with the capture
+ # guard above, this keeps a reload from ever chaining shim-onto-shim.
+ if not getattr(socket.getaddrinfo, _SHIM_MARKER, False):
+ socket.getaddrinfo = _pinned_getaddrinfo
+ _installed = True
+
+
+def _extract_host(url: Optional[str]) -> Tuple[Optional[str], bool]:
+ """Return ``(normalized_host, is_ip_literal)`` for ``url``.
+
+ ``host`` is ``None`` when the URL is empty or the parser rejects it.
+ Uses ``urllib3.util.parse_url`` — the same parser ``requests`` uses
+ internally and the same one ``ssrf_validator.validate_url`` validates
+ against — so the host we pin is the host the client will resolve.
+ """
+ if not url:
+ return None, False
+ try:
+ parsed = parse_url(url)
+ except (LocationParseError, ValueError):
+ return None, False
+ host = _normalize_host(parsed.host)
+ if host is None:
+ return None, False
+ try:
+ ipaddress.ip_address(host)
+ return host, True # IP literal — no DNS to rebind
+ except ValueError:
+ return host, False
+
+
+def _resolve_and_validate(
+ host: str,
+ allow_localhost: bool,
+ allow_private_ips: bool,
+) -> List[tuple]:
+ """Resolve ``host`` once and validate every returned address.
+
+ Uses the real resolver (never the shim, to avoid recursion and to
+ ignore any pin) and applies exactly the ``is_ip_blocked`` policy that
+ ``validate_url`` applies — honoring ``allow_localhost`` /
+ ``allow_private_ips`` while the ``ALWAYS_BLOCKED_METADATA_IPS`` set
+ keeps firing regardless. This is the connect-time re-validation that
+ the pin adds: an answer that changed since ``validate_url`` ran is
+ caught here.
+
+ Returns the addrinfo list to pin (all entries validated safe).
+
+ Raises:
+ ValueError: if any resolved address is blocked. SSRF-style message
+ so existing callers/tests catch it uniformly.
+ requests.ConnectionError: if the host no longer resolves at pin
+ time — fail closed as an ordinary transport error so the
+ existing retry / ``RequestException`` handling stays intact.
+ """
+ try:
+ addr_info = _real_getaddrinfo(
+ host, None, socket.AF_UNSPEC, socket.SOCK_STREAM
+ )
+ except socket.gaierror as exc:
+ raise requests.ConnectionError(
+ f"DNS resolution failed while pinning host {host}"
+ ) from exc
+ if not addr_info:
+ raise requests.ConnectionError(
+ f"No addresses resolved while pinning host {host}"
+ )
+
+ for info in addr_info:
+ ip_str = str(info[4][0])
+ if ssrf_validator.is_ip_blocked(
+ ip_str,
+ allow_localhost=allow_localhost,
+ allow_private_ips=allow_private_ips,
+ ):
+ logger.warning(
+ "Blocked connect-time address for host {}: resolves to "
+ "internal/private/metadata IP {} "
+ "(resolve-vs-connect guard)",
+ host,
+ ip_str,
+ )
+ raise ValueError(
+ "URL failed security validation (possible SSRF): "
+ f"host {host} resolved to blocked IP {ip_str} at connect time"
+ )
+ return addr_info
+
+
+def pinned_request(
+ url: str,
+ allow_localhost: bool = False,
+ allow_private_ips: bool = False,
+) -> Iterator[None]:
+ """Pin DNS for the duration of a single outbound request to ``url``.
+
+ Resolves the URL host ONCE, validates every returned address against
+ the SSRF policy, and pins those addresses so the connection made by
+ ``requests`` / ``urllib3`` inside this context cannot be steered to a
+ rebind target: the address validated here is the address connected to.
+
+ Yields without pinning when the host is an IP literal (no DNS to
+ rebind — the caller's ``validate_url`` already vetted the literal) or
+ when the URL host cannot be extracted.
+
+ Must wrap every outbound request AND every redirect hop, so each hop
+ re-resolves, re-validates, and re-pins.
+
+ Raises:
+ ValueError: if the host resolves to a blocked address at connect
+ time.
+ requests.ConnectionError: if the host fails to resolve at pin time.
+ """
+ host, is_literal = _extract_host(url)
+ if host is None or is_literal:
+ yield
+ return
+
+ entry = _resolve_and_validate(host, allow_localhost, allow_private_ips)
+
+ pins = _get_pins()
+ # Save/restore any prior pin for this host so nested contexts (e.g. a
+ # redirect chain that loops back to the same host) are safe.
+ had_previous = host in pins
+ previous = pins.get(host)
+ pins[host] = entry
+ try:
+ yield
+ finally:
+ if had_previous:
+ pins[host] = previous
+ else:
+ pins.pop(host, None)
+
+
+# Install on import: safe_requests imports this module, so the shim is in
+# place before any fetch. Transparent until a pin is active.
+install()
diff --git a/src/local_deep_research/security/notification_validator.py b/src/local_deep_research/security/notification_validator.py
index 2795942a85..743068810d 100644
--- a/src/local_deep_research/security/notification_validator.py
+++ b/src/local_deep_research/security/notification_validator.py
@@ -123,6 +123,16 @@ class NotificationURLValidator:
# DNS hook to close this in code without fragile monkey-patching
# of its plugin internals.
#
+ # RESIDUAL RISK (documented, not closed here): the ``safe_requests``
+ # fetch path now pins the validated address for the actual
+ # connection (``security.dns_pinning``). That pin is NOT reused for
+ # Apprise: a single ``notify()`` can fan out to multiple service
+ # URLs and Apprise's plugins re-resolve — and may follow redirects
+ # to further hosts — inside their own request stack, so a partial
+ # pin here would give false confidence rather than a guarantee.
+ # The env-only master switch below remains the boundary; pinning
+ # the full Apprise delivery path is a tracked follow-up.
+ #
# Because the window cannot be closed cleanly in code, the
# whole outbound-notification path is gated behind an env-only
# master switch (LDR_NOTIFICATIONS_ALLOW_OUTBOUND, default off);
diff --git a/src/local_deep_research/security/safe_requests.py b/src/local_deep_research/security/safe_requests.py
index 038c4d630d..580dd0d2cd 100644
--- a/src/local_deep_research/security/safe_requests.py
+++ b/src/local_deep_research/security/safe_requests.py
@@ -13,6 +13,7 @@ from urllib.parse import urljoin
import requests
from loguru import logger
+from . import dns_pinning
from . import ssrf_validator
from ..constants import USER_AGENT
from ..utilities.resource_utils import safe_close
@@ -202,7 +203,14 @@ def safe_get(
current_url = url
try:
- response = requests.get(url, params=params, **kwargs)
+ # Pin the validated IP for the actual connection: the request below
+ # connects to the address resolved+validated here, closing the
+ # resolve-vs-connect gap where requests/urllib3 would otherwise
+ # re-resolve the hostname independently.
+ with dns_pinning.pinned_request(
+ url, allow_localhost, allow_private_ips
+ ):
+ response = requests.get(url, params=params, **kwargs)
# Follow redirects manually with SSRF validation on each hop.
# Each hop uses a fresh requests.get() call without a session,
@@ -246,7 +254,12 @@ def safe_get(
# hops. Per HTTP spec, the server's Location header contains
# the complete target URL. Re-appending original query params
# would corrupt it.
- response = requests.get(redirect_url, **kwargs)
+ # Re-pin per hop: the address validated for this redirect
+ # target is the address connected to.
+ with dns_pinning.pinned_request(
+ redirect_url, allow_localhost, allow_private_ips
+ ):
+ response = requests.get(redirect_url, **kwargs)
redirects_followed += 1
if (
@@ -339,7 +352,11 @@ def safe_post(
current_url = url
try:
- response = requests.post(url, data=data, json=json, **kwargs)
+ # Pin the validated IP for the actual connection (see safe_get).
+ with dns_pinning.pinned_request(
+ url, allow_localhost, allow_private_ips
+ ):
+ response = requests.post(url, data=data, json=json, **kwargs)
# Follow redirects manually with SSRF validation on each hop.
# Each hop uses a fresh request without a session, so cookies
@@ -382,16 +399,21 @@ def safe_post(
current_url = redirect_url
response.close()
- if redirect_method == "GET":
- # 301/302/303: convert to GET, drop body
- data = None
- json = None
- response = requests.get(redirect_url, **kwargs)
- else:
- # 307/308: preserve current method and body
- response = requests.post(
- redirect_url, data=data, json=json, **kwargs
- )
+ # Re-pin per hop: the address validated for this redirect
+ # target is the address connected to.
+ with dns_pinning.pinned_request(
+ redirect_url, allow_localhost, allow_private_ips
+ ):
+ if redirect_method == "GET":
+ # 301/302/303: convert to GET, drop body
+ data = None
+ json = None
+ response = requests.get(redirect_url, **kwargs)
+ else:
+ # 307/308: preserve current method and body
+ response = requests.post(
+ redirect_url, data=data, json=json, **kwargs
+ )
redirects_followed += 1
if (
@@ -530,7 +552,17 @@ class SafeSession(requests.Session):
f"Redirect target failed security validation (possible SSRF): {request.url}"
)
- response = super().send(request, **kwargs)
+ # Pin the validated IP for the connection this send performs. send()
+ # runs for the initial request AND for every redirect hop
+ # (resolve_redirects re-enters here), so each hop is independently
+ # resolved, validated, and pinned — the address validated is the
+ # address connected to.
+ with dns_pinning.pinned_request(
+ request.url or "",
+ allow_localhost=self.allow_localhost,
+ allow_private_ips=self.allow_private_ips,
+ ):
+ response = super().send(request, **kwargs)
_check_response_size(response)
return response
diff --git a/src/local_deep_research/security/ssrf_validator.py b/src/local_deep_research/security/ssrf_validator.py
index 7011374b31..45adc76867 100644
--- a/src/local_deep_research/security/ssrf_validator.py
+++ b/src/local_deep_research/security/ssrf_validator.py
@@ -291,15 +291,14 @@ def validate_url(
# Resolve hostname to IP and check.
#
- # NOTE: This is a best-effort, validation-time check. The caller
- # (typically safe_requests) hands the URL to requests/urllib3
- # afterwards, which resolves the hostname AGAIN at connect time --
- # a DNS rebinding TOCTOU window. Closing it would require pinning
- # the resolved IP into the outbound connection (HTTPAdapter shim
- # with server_hostname for SNI), which is HTTPS-only and doesn't
- # follow redirects cleanly. See SECURITY.md "Notification Webhook
- # SSRF" subsection for the accepted-risk rationale (the same
- # caveat applies here).
+ # 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
+ # an external client that re-resolves on its own (e.g. an LLM SDK,
+ # Apprise) still carry the residual window; see SECURITY.md.
try:
# Get all IP addresses for hostname
# nosec B104 - DNS resolution is intentional for SSRF prevention (checking if hostname resolves to private IP)
@@ -358,10 +357,15 @@ def assert_base_url_safe(base_url: str, *, setting_key: str) -> str:
endpoints (AWS IMDS / ECS, Azure, OCI, DigitalOcean, AlibabaCloud,
Tencent).
- Caveat: this guard validates once at provider construction. The SDK
- re-resolves the hostname on every inference call, so a hostile DNS
- authority can rebind between guard and connect — same TOCTOU as
- ``validate_url``. See SECURITY.md for the accepted-risk rationale.
+ Residual risk (documented, not closed here): this guard validates once
+ at provider construction, and the LLM SDK re-resolves the hostname on
+ every inference call through its own HTTP client. Unlike the
+ ``safe_requests`` path — which pins the validated address via
+ ``security.dns_pinning`` so the connection cannot be re-steered — the
+ SDK exposes no resolver/adapter seam to pin without patching its
+ internals, so the resolve-vs-connect window remains. Egress restriction
+ at the firewall is the operator-side mitigation. See SECURITY.md
+ ("LLM Provider URL Validation").
"""
if not validate_url(base_url, allow_localhost=True, allow_private_ips=True):
raise ValueError(
diff --git a/tests/security/test_ssrf_dns_pinning.py b/tests/security/test_ssrf_dns_pinning.py
new file mode 100644
index 0000000000..e0ac435686
--- /dev/null
+++ b/tests/security/test_ssrf_dns_pinning.py
@@ -0,0 +1,573 @@
+"""Regression tests for the resolve-vs-connect pin (``security.dns_pinning``).
+
+These prove that the address the SSRF guard validated is the address the
+outbound connection actually targets, closing the window where
+``requests``/``urllib3`` would re-resolve the hostname independently at
+connect time.
+
+The gap is simulated by driving the resolver seam
+(``dns_pinning._real_getaddrinfo``): validation sees one answer while a
+naive connect-time re-resolve would see a different, attacker-chosen one.
+The pin makes the connection reuse the validated answer, so:
+
+* a host that validated as public but "rebinds" to a metadata/private IP
+ is rejected at connect time (no connection to the rebind target), and
+* a legitimate host connects to exactly the validated address and is never
+ re-resolved at connect time.
+"""
+
+import importlib
+import socket
+import threading
+from http.server import BaseHTTPRequestHandler, HTTPServer
+from unittest.mock import patch
+
+import pytest
+import requests
+
+from local_deep_research.security import dns_pinning
+from local_deep_research.security.safe_requests import (
+ safe_get,
+ safe_post,
+ SafeSession,
+)
+
+
+# --------------------------------------------------------------------------
+# Test doubles
+# --------------------------------------------------------------------------
+class _Handler(BaseHTTPRequestHandler):
+ marker = b"PINNED-OK"
+
+ def do_GET(self):
+ body = self.marker
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_POST(self):
+ self.do_GET()
+
+ def log_message(self, *args): # silence the test server
+ pass
+
+
+def _start_server(bind_ip: str, marker: bytes = b"PINNED-OK") -> HTTPServer:
+ """Start a loopback HTTP server bound to a specific 127.0.0.0/8 IP.
+
+ Binding distinct loopback IPs (127.0.0.1 vs 127.0.0.2) lets a test tell
+ apart "connected to the pinned IP" from "connected to the rebind IP":
+ only one of them has a listener.
+ """
+ handler = type("BoundHandler", (_Handler,), {"marker": marker})
+ server = HTTPServer((bind_ip, 0), handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ return server
+
+
+class _Resolver:
+ """Stand-in for ``dns_pinning._real_getaddrinfo``.
+
+ ``answers`` maps host -> list of successive answers; each ``getaddrinfo``
+ call for a host consumes the next answer, and the final answer sticks
+ for every later call (a rebind that then stays put). Each answer is a
+ list of IP-address strings. ``calls`` records the (host, port) of every
+ lookup so a test can assert that no extra connect-time resolution
+ happened.
+ """
+
+ def __init__(self, answers: dict):
+ self._answers = {
+ h.lower().rstrip("."): list(v) for h, v in answers.items()
+ }
+ self.calls: list = []
+
+ def host_calls(self, host: str) -> int:
+ key = host.lower().rstrip(".")
+ return sum(
+ 1 for h, _ in self.calls if (h or "").lower().rstrip(".") == key
+ )
+
+ def __call__(self, host, port, family=0, type=0, proto=0, flags=0):
+ self.calls.append((host, port))
+ seq = self._answers.get((host or "").lower().rstrip("."))
+ if not seq:
+ raise socket.gaierror(socket.EAI_NONAME, f"no answer for {host}")
+ ips = seq[0] if len(seq) == 1 else seq.pop(0)
+ results = []
+ for ip in ips:
+ fam = socket.AF_INET6 if ":" in ip else socket.AF_INET
+ if fam == socket.AF_INET6:
+ sockaddr = (ip, port or 0, 0, 0)
+ else:
+ sockaddr = (ip, port or 0)
+ results.append(
+ (fam, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", sockaddr)
+ )
+ return results
+
+
+# --------------------------------------------------------------------------
+# Core proofs
+# --------------------------------------------------------------------------
+def test_connection_consumes_pin_with_no_connect_time_relookup():
+ """Happy path: the connection consumes the pinned resolution and does NOT
+ perform a third, connect-time DNS lookup.
+
+ Resolver answers: call #1 is ``validate_url``, call #2 is the pin; the
+ fetch succeeds and the resolver is consulted exactly twice, so there is
+ no separate connect-time re-resolution window for the happy path. (This
+ asserts the mechanism — no redundant connect-time lookup — not that a
+ rebind is defeated; the security discrimination that a post-validation
+ rebind to a metadata/private IP is *refused* is covered by the
+ ``test_rebind_to_*`` tests below, which fail without the pin.)
+ """
+ server = _start_server("127.0.0.1", b"PINNED-OK")
+ port = server.server_address[1]
+ resolver = _Resolver(
+ {"pinned.example": [["127.0.0.1"], ["127.0.0.1"], ["127.0.0.2"]]}
+ )
+ try:
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ resp = safe_get(
+ f"http://pinned.example:{port}/",
+ allow_localhost=True,
+ timeout=5,
+ )
+ assert resp.status_code == 200
+ assert resp.content == b"PINNED-OK"
+ # Exactly two lookups: validate_url + pin. Zero at connect time —
+ # the rebind answer (127.0.0.2) was never consumed.
+ assert resolver.host_calls("pinned.example") == 2
+ finally:
+ server.shutdown()
+
+
+def test_rebind_to_metadata_ip_is_blocked_at_connect_time():
+ """Validation sees a public IP; the pin's connect-time re-validation
+ catches the rebind to a cloud-metadata IP and refuses to connect.
+ """
+ resolver = _Resolver(
+ {"rebind.example": [["93.184.216.34"], ["169.254.169.254"]]}
+ )
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ with patch(
+ "local_deep_research.security.safe_requests.requests.get"
+ ) as mock_get:
+ with pytest.raises(ValueError, match="SSRF"):
+ safe_get("http://rebind.example/", timeout=5)
+ # The connection was never attempted: the pin rejected before
+ # handing anything to requests.
+ mock_get.assert_not_called()
+ # Two lookups only: validate_url (public, passes) + pin (metadata,
+ # rejects). No connect-time lookup.
+ assert resolver.host_calls("rebind.example") == 2
+
+
+def test_rebind_to_private_ip_is_blocked_at_connect_time():
+ """Same as above but the rebind target is an RFC1918 address, with
+ default flags (allow_private_ips=False)."""
+ resolver = _Resolver({"rebind2.example": [["93.184.216.34"], ["10.1.2.3"]]})
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ with patch(
+ "local_deep_research.security.safe_requests.requests.get"
+ ) as mock_get:
+ with pytest.raises(ValueError, match="SSRF"):
+ safe_get("http://rebind2.example/", timeout=5)
+ mock_get.assert_not_called()
+
+
+def test_host_resolving_only_to_blocked_ip_is_rejected():
+ """A hostname that resolves solely to a blocked IP is rejected (at
+ validation, before the pin) and never connected to."""
+ resolver = _Resolver({"internal.example": [["169.254.169.254"]]})
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ with patch(
+ "local_deep_research.security.safe_requests.requests.get"
+ ) as mock_get:
+ with pytest.raises(ValueError, match="SSRF|security validation"):
+ safe_get("http://internal.example/", timeout=5)
+ mock_get.assert_not_called()
+
+
+def test_legitimate_public_host_still_fetches_through_pin():
+ """A permitted host resolves and fetches end-to-end through the pin,
+ connecting to exactly the validated address."""
+ server = _start_server("127.0.0.1", b"HELLO")
+ port = server.server_address[1]
+ resolver = _Resolver({"ok.example": [["127.0.0.1"]]})
+ try:
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ resp = safe_get(
+ f"http://ok.example:{port}/",
+ allow_localhost=True,
+ timeout=5,
+ )
+ assert resp.status_code == 200
+ assert resp.content == b"HELLO"
+ finally:
+ server.shutdown()
+
+
+def test_private_host_reachable_when_allow_private_ips_preserved():
+ """PRIVATE_ONLY-style scope: with allow_private_ips=True a private
+ address is intentionally reachable — the pin must not weaken that."""
+ server = _start_server("127.0.0.1", b"LAB")
+ port = server.server_address[1]
+ # 127.0.0.1 is loopback; allow_private_ips permits loopback + RFC1918.
+ resolver = _Resolver({"lab.example": [["127.0.0.1"]]})
+ try:
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ resp = safe_get(
+ f"http://lab.example:{port}/",
+ allow_private_ips=True,
+ timeout=5,
+ )
+ assert resp.status_code == 200
+ assert resp.content == b"LAB"
+ finally:
+ server.shutdown()
+
+
+def test_redirect_chain_repins_each_hop():
+ """Each redirect hop is independently resolved, validated, and pinned.
+
+ Host A (a real server on 127.0.0.1) redirects to host B. Host B's
+ resolver answers good, good, then bad — so if the hop failed to pin,
+ the connect-time re-resolve would hit the dead rebind IP. The chain
+ completes against host B's real server, and host B is resolved exactly
+ twice (validate + pin) with no connect-time lookup.
+ """
+ server_b = _start_server("127.0.0.1", b"HOP-B-OK")
+ port_b = server_b.server_address[1]
+
+ class _RedirectHandler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ self.send_response(302)
+ self.send_header("Location", f"http://host-b.example:{port_b}/")
+ self.end_headers()
+
+ def log_message(self, *args):
+ pass
+
+ server_a = HTTPServer(("127.0.0.1", 0), _RedirectHandler)
+ threading.Thread(target=server_a.serve_forever, daemon=True).start()
+ port_a = server_a.server_address[1]
+
+ resolver = _Resolver(
+ {
+ "host-a.example": [["127.0.0.1"]],
+ "host-b.example": [["127.0.0.1"], ["127.0.0.1"], ["127.0.0.2"]],
+ }
+ )
+ try:
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ resp = safe_get(
+ f"http://host-a.example:{port_a}/",
+ allow_localhost=True,
+ timeout=5,
+ )
+ assert resp.status_code == 200
+ assert resp.content == b"HOP-B-OK"
+ # Host B: validate + pin only, no connect-time re-resolution (the
+ # 127.0.0.2 rebind answer stays unconsumed).
+ assert resolver.host_calls("host-b.example") == 2
+ finally:
+ server_a.shutdown()
+ server_b.shutdown()
+
+
+# --------------------------------------------------------------------------
+# safe_post proofs
+# --------------------------------------------------------------------------
+def test_safe_post_rebind_to_metadata_ip_is_blocked_at_connect_time():
+ """``safe_post`` mirror of ``test_rebind_to_metadata_ip_is_blocked_at_connect_time``.
+
+ Validation sees a public IP; the pin's connect-time re-validation
+ catches the rebind to a cloud-metadata IP and refuses to connect —
+ before ``requests.post`` is ever called. Without the pin (or with it
+ disabled), this rebind would sail through: ``safe_post`` only validates
+ the URL once up front, so a second, independent resolution at connect
+ time would observe the rebind answer and POST to it.
+ """
+ resolver = _Resolver(
+ {"rebind-post.example": [["93.184.216.34"], ["169.254.169.254"]]}
+ )
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ with patch(
+ "local_deep_research.security.safe_requests.requests.post"
+ ) as mock_post:
+ with pytest.raises(ValueError, match="SSRF"):
+ safe_post("http://rebind-post.example/", timeout=5)
+ # The connection was never attempted: the pin rejected before
+ # handing anything to requests.
+ mock_post.assert_not_called()
+ # Two lookups only: validate_url (public, passes) + pin (metadata,
+ # rejects). No connect-time lookup.
+ assert resolver.host_calls("rebind-post.example") == 2
+
+
+def test_safe_post_rebind_to_private_ip_is_blocked_at_connect_time():
+ """Same as above but the rebind target is an RFC1918 address, with
+ default flags (allow_private_ips=False)."""
+ resolver = _Resolver(
+ {"rebind2-post.example": [["93.184.216.34"], ["10.1.2.3"]]}
+ )
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ with patch(
+ "local_deep_research.security.safe_requests.requests.post"
+ ) as mock_post:
+ with pytest.raises(ValueError, match="SSRF"):
+ safe_post("http://rebind2-post.example/", timeout=5)
+ mock_post.assert_not_called()
+
+
+class _MethodEchoHandler(BaseHTTPRequestHandler):
+ """Replies 200 with the HTTP method name as the body.
+
+ Lets a redirect test assert which method actually reached the final
+ hop (GET after a 301/302/303 downgrade vs. POST preserved for 307/308)
+ without needing to inspect request internals.
+ """
+
+ def _reply(self):
+ body = self.command.encode()
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_GET(self):
+ self._reply()
+
+ def do_POST(self):
+ length = int(self.headers.get("Content-Length", 0) or 0)
+ if length:
+ self.rfile.read(length)
+ self._reply()
+
+ def log_message(self, *args): # silence the test server
+ pass
+
+
+ "status_code,expected_method",
+ [
+ (302, "GET"), # POST -> GET downgrade
+ (307, "POST"), # method preserved
+ ],
+)
+def test_safe_post_redirect_repins_hop_and_resolves_method(
+ status_code, expected_method
+):
+ """Each ``safe_post`` redirect hop is independently pinned, and the
+ method conversion (301/302/303 -> GET, 307/308 preserve POST) matches
+ RFC 7231 / ``_resolve_redirect_method``.
+
+ Mirrors ``test_redirect_chain_repins_each_hop``: host B's resolver
+ answers good, good, then bad. If the hop's pin were skipped, urllib3's
+ own connect-time re-resolution would observe the rebind (dead) IP and
+ the fetch would fail instead of completing against the real server —
+ so host B being resolved exactly twice (validate + pin, no connect-time
+ lookup) is the discriminating assertion.
+ """
+ server_b = HTTPServer(("127.0.0.1", 0), _MethodEchoHandler)
+ threading.Thread(target=server_b.serve_forever, daemon=True).start()
+ port_b = server_b.server_address[1]
+
+ class _RedirectHandler(BaseHTTPRequestHandler):
+ def do_POST(self):
+ length = int(self.headers.get("Content-Length", 0) or 0)
+ if length:
+ self.rfile.read(length)
+ self.send_response(status_code)
+ self.send_header(
+ "Location", f"http://host-b-post.example:{port_b}/"
+ )
+ self.end_headers()
+
+ def log_message(self, *args):
+ pass
+
+ server_a = HTTPServer(("127.0.0.1", 0), _RedirectHandler)
+ threading.Thread(target=server_a.serve_forever, daemon=True).start()
+ port_a = server_a.server_address[1]
+
+ resolver = _Resolver(
+ {
+ "host-a-post.example": [["127.0.0.1"]],
+ "host-b-post.example": [
+ ["127.0.0.1"],
+ ["127.0.0.1"],
+ ["127.0.0.2"],
+ ],
+ }
+ )
+ try:
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ resp = safe_post(
+ f"http://host-a-post.example:{port_a}/",
+ data=b"payload",
+ allow_localhost=True,
+ timeout=5,
+ )
+ assert resp.status_code == 200
+ assert resp.content == expected_method.encode()
+ # Host B: validate + pin only, no connect-time re-resolution (the
+ # 127.0.0.2 rebind answer stays unconsumed).
+ assert resolver.host_calls("host-b-post.example") == 2
+ finally:
+ server_a.shutdown()
+ server_b.shutdown()
+
+
+def test_safesession_pins_and_blocks_rebind():
+ """SafeSession.send pins per hop: a host validated as public but
+ rebinding to a metadata IP is rejected before any connection."""
+ resolver = _Resolver(
+ {"sess.example": [["93.184.216.34"], ["169.254.169.254"]]}
+ )
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ with SafeSession() as session:
+ with pytest.raises(ValueError, match="SSRF|security validation"):
+ session.get("http://sess.example/", timeout=5)
+
+
+def test_safesession_fetches_through_pin():
+ """SafeSession connects to the validated address end-to-end."""
+ server = _start_server("127.0.0.1", b"SESSION-OK")
+ port = server.server_address[1]
+ resolver = _Resolver({"sess-ok.example": [["127.0.0.1"]]})
+ try:
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ with SafeSession(allow_localhost=True) as session:
+ resp = session.get(f"http://sess-ok.example:{port}/", timeout=5)
+ assert resp.status_code == 200
+ assert resp.content == b"SESSION-OK"
+ finally:
+ server.shutdown()
+
+
+# --------------------------------------------------------------------------
+# Unit-level checks on the pinning primitives
+# --------------------------------------------------------------------------
+def test_ip_literal_is_not_pinned():
+ """IP-literal URLs have no DNS to rebind; the context manager is a
+ no-op and never touches the resolver."""
+ resolver = _Resolver({})
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ with dns_pinning.pinned_request("http://93.184.216.34/"):
+ pass
+ assert resolver.calls == []
+
+
+def test_pin_registry_is_cleared_after_context():
+ """The pin is scoped strictly to the context and leaves no residue in
+ the thread-local registry."""
+ resolver = _Resolver({"scoped.example": [["93.184.216.34"]]})
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ with dns_pinning.pinned_request("http://scoped.example/"):
+ assert "scoped.example" in dns_pinning._get_pins()
+ assert "scoped.example" not in dns_pinning._get_pins()
+
+
+def test_pinned_getaddrinfo_passes_through_when_unpinned():
+ """With no active pin, the shim delegates unchanged to the real
+ resolver (transparent for all non-pinned lookups)."""
+ resolver = _Resolver({"passthrough.example": [["93.184.216.34"]]})
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ result = socket.getaddrinfo("passthrough.example", 80)
+ assert result[0][4][0] == "93.184.216.34"
+ assert resolver.host_calls("passthrough.example") == 1
+
+
+def test_pinned_getaddrinfo_filters_by_requested_socktype():
+ """A pinned entry is always resolved as SOCK_STREAM (see
+ ``_resolve_and_validate``). A caller that explicitly asks for a
+ different socket type (e.g. ``SOCK_DGRAM``) while the host happens to
+ be pinned must NOT get back the SOCK_STREAM/IPPROTO_TCP entry relabeled
+ with the requested type — it must fail closed instead, exactly like a
+ requested-family mismatch does.
+ """
+ resolver = _Resolver({"socktype.example": [["93.184.216.34"]]})
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ with dns_pinning.pinned_request("http://socktype.example/"):
+ # A SOCK_STREAM (or unspecified, 0) request is unaffected — it
+ # is exactly what urllib3's own connection lookups request.
+ stream_result = socket.getaddrinfo(
+ "socktype.example", 80, 0, socket.SOCK_STREAM
+ )
+ assert stream_result[0][1] == socket.SOCK_STREAM
+ any_result = socket.getaddrinfo("socktype.example", 80)
+ assert any_result[0][1] == socket.SOCK_STREAM
+
+ # A mismatched SOCK_DGRAM request must fail closed rather than
+ # silently returning the SOCK_STREAM/IPPROTO_TCP entry
+ # relabeled as SOCK_DGRAM.
+ with pytest.raises(socket.gaierror):
+ socket.getaddrinfo("socktype.example", 80, 0, socket.SOCK_DGRAM)
+ # Only the real (pin-establishing) resolution happened; neither the
+ # SOCK_STREAM lookups nor the rejected SOCK_DGRAM lookup fell through
+ # to a fresh resolver call.
+ assert resolver.host_calls("socktype.example") == 1
+
+
+def test_gaierror_at_pin_time_surfaces_as_connection_error():
+ """If the host stops resolving between validation and pin, the pin
+ fails closed as a transport error (retryable), not a silent bypass."""
+
+ class _FailSecondResolve:
+ def __init__(self):
+ self.n = 0
+
+ def __call__(self, host, port, *a, **k):
+ self.n += 1
+ if self.n == 1:
+ return [
+ (
+ socket.AF_INET,
+ socket.SOCK_STREAM,
+ socket.IPPROTO_TCP,
+ "",
+ ("93.184.216.34", port or 0),
+ )
+ ]
+ raise socket.gaierror(socket.EAI_NONAME, "gone")
+
+ resolver = _FailSecondResolve()
+ with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
+ with pytest.raises(requests.ConnectionError):
+ safe_get("http://transient.example/", timeout=5)
+
+
+def test_reload_does_not_make_the_shim_call_itself():
+ """Reloading the module must not turn every unpinned lookup into infinite
+ recursion.
+
+ The module captures the real resolver at import (``_real_getaddrinfo =
+ socket.getaddrinfo``) and ``install()`` then swaps ``socket.getaddrinfo``
+ for the shim. A naive ``importlib.reload`` re-runs that capture while the
+ shim is already installed, re-capturing the shim as the "real" resolver so
+ the shim's pass-through calls itself → ``RecursionError`` process-wide on
+ every unpinned lookup. The capture guard must prevent that: after a reload
+ the captured resolver is never our own shim, and a plain resolution still
+ returns.
+ """
+ importlib.reload(dns_pinning)
+ try:
+ # The captured "real" resolver must not be our shim (which is what
+ # ``socket.getaddrinfo`` now is).
+ assert not getattr(
+ dns_pinning._real_getaddrinfo, dns_pinning._SHIM_MARKER, False
+ )
+ assert dns_pinning._real_getaddrinfo is not socket.getaddrinfo
+ # An unpinned loopback lookup must resolve without recursing. It goes
+ # through the installed shim, falls through to the real resolver, and
+ # returns instead of raising RecursionError.
+ result = socket.getaddrinfo("127.0.0.1", 80)
+ assert result and result[0][4][0] == "127.0.0.1"
+ finally:
+ # Re-establish a clean, self-consistent module state for later tests.
+ importlib.reload(dns_pinning)