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): fail closed on fake-IP DNS egress classification (#7106)

LearningCircuitb0b08182817e
diff --git a/changelog.d/6535.security.md b/changelog.d/6535.security.md
index f61087729a..b505472902 100644
--- a/changelog.d/6535.security.md
+++ b/changelog.d/6535.security.md
@@ -4,10 +4,10 @@ that context is unavailable, the factory returns the snippets-only engine
instead of fetching full content without the run's scope.
`LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH` (#6196) therefore takes effect only
under the `unprotected` scope; under every other scope, the default `adaptive`
-included, private result URLs are refused before the counted scope check
+included, non-public result URLs are refused before the counted scope check
(by the SSRF check, or, for addresses the SSRF check admits but the egress
-policy classifies private such as `198.18.0.0/15` from fake-IP DNS, the
-documentation ranges and `240.0.0.0/4`, by the policy's own non-counting
+policy does not classify public, such as ambiguous `198.18.0.0/15` from
+fake-IP DNS, the documentation ranges and `240.0.0.0/4`, by the non-counting
classifier), so they do not count toward the run's denied-fetch quota
(`MAX_DENIED_FETCHES_PER_RUN`) and cannot exhaust it and block public
fetches. The classifier check also runs under `strict`, `private_only` and
@@ -19,11 +19,11 @@ when available under Both or Unprotected, its requests retain SSRF checks.
Under `unprotected` without the flag only the SSRF check applies, so those
ranges are fetched there.
Known limitation: with fake-IP DNS (Clash, sing-box, Surge in TUN mode),
-public names resolve into `198.18.0.0/15`, which the egress policy classifies
-as private. Full-content fetching is then unavailable under every scope except
-`unprotected`, and under `strict` / `private_only` the other fetch paths and
-the socket guard admit those public hosts as private; see "Known limitations"
-in `docs/egress-modes.md` and #7093.
+public names resolve into `198.18.0.0/15`, which the egress policy now treats
+as ambiguous. Full-content fetching and other protected policy-checked
+fetches remain unavailable for those hosts, but `strict` / `private_only`
+also refuse them at the socket guard; see "Known limitations" in
+`docs/egress-modes.md` and #7093.
Upgrade note: released v1.x versions never fetched private result URLs, so
nothing changes for them. Operators who ran a development build with the flag
and relied on it for intranet full content must run those researches under
diff --git a/changelog.d/7093.security.md b/changelog.d/7093.security.md
new file mode 100644
index 0000000000..3be0993539
--- /dev/null
+++ b/changelog.d/7093.security.md
@@ -0,0 +1 @@
+Treat `198.18.0.0/15` fake-IP DNS answers as ambiguous so protected egress scopes cannot mistake proxy-routed public hosts for private destinations, including when fake and public DNS answers are mixed. With `LDR_SECURITY_ALLOW_NAT64=true`, NAT64-wrapped addresses are classified by the IPv4 address they embed, so a DNS64-wrapped fake IP stays ambiguous, a wrapped private address no longer counts as public, and a public address under the `64:ff9b:1::/48` local-use prefix no longer counts as private. Elasticsearch `hosts` are classified node by node, including host dictionaries and comma-separated or JSON strings. A fake-IP or unparseable node anywhere in the list, a host URL that the Elasticsearch client reads as a different host than Python's `urlsplit`, a non-ASCII host name in a URL or a host dictionary (the resolver and the client encode it differently; write it in its `xn--` form to have it classified), or a `%` in such a host (including an IPv6 zone ID such as `fe80::1%eth0`), leaves the engine unclassified, so protected scopes refuse it; otherwise any public node makes it public. The run-start two-axis check labels Elasticsearch and Paperless from the same classification, so an endpoint the scope check rates public, or cannot classify, is labelled exposing. A real local service at a fixed `198.18.0.0/15` address now needs that address, and the hostname it is configured by, listed in `llm.allowed_local_hostnames` (see "Known limitations" in `docs/egress-modes.md`).
diff --git a/docs/SearXNG-Setup.md b/docs/SearXNG-Setup.md
index 335347a1a9..cc2bbed42c 100644
--- a/docs/SearXNG-Setup.md
+++ b/docs/SearXNG-Setup.md
@@ -251,12 +251,12 @@ wrapper itself (see below):
redirect and pinned connect address.
Under every scope except `unprotected` the wrapper refuses every result URL
-whose address the egress policy classifies as private, including ranges the
-SSRF check itself lets through (for example `198.18.0.0/15`, which fake-IP
-DNS resolvers hand out, the documentation ranges, `240.0.0.0/4` and
-`2001:db8::/32`). It asks the policy's own classifier before the counted
-scope check, so this also holds under `strict`, `private_only` and `both`,
-whose scope check would otherwise admit such private hosts. Refused private
+whose address the egress policy cannot classify as public. This includes the
+ambiguous `198.18.0.0/15` range handed out by fake-IP DNS resolvers, and
+private ranges the SSRF check itself lets through (the documentation ranges,
+`240.0.0.0/4` and `2001:db8::/32`). It asks the policy's own classifier
+before the counted scope check, so this also holds under `strict`,
+`private_only` and `both`. Refused non-public
result URLs do not count toward the run's denied-fetch quota, so they cannot
use it up and block later public fetches. The snippets of those results are
still returned, only their full content is missing. These checks apply to the
@@ -268,11 +268,12 @@ applies, so the ranges it lets through are fetched there.
> **Known limitation: fake-IP DNS.** Proxy tools in fake-IP mode (Clash,
> sing-box, Surge in TUN mode) answer public names with `198.18.0.0/15`
-> addresses, which the egress policy classifies as private. Full-content
+> addresses, which the egress policy cannot classify as public or private.
+> Full-content
> fetching is then unavailable under the default `adaptive` scope (which
> resolves to `public_only` with SearXNG) and every other scope except
-> `unprotected`, and `strict` treats those public hosts as private on its
-> other fetch paths. See
+> `unprotected`. Other policy-checked fetch paths and the `strict` /
+> `private_only` socket guard refuse these addresses too. See
> [Known limitations](egress-modes.md#known-limitations) in the egress modes
> guide.
diff --git a/docs/egress-modes.md b/docs/egress-modes.md
index aee3cc8fab..e745efc0b0 100644
--- a/docs/egress-modes.md
+++ b/docs/egress-modes.md
@@ -71,7 +71,8 @@ link-local and the other ranges they list) unless the operator also set
`LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH` for an approved engine such as a
self-hosted SearXNG; this is the only mode in which that flag takes effect.
Addresses the SSRF checks do not block are fetched here even when the egress
-policy counts them as private, such as `198.18.0.0/15`, the documentation
+policy cannot classify them as public (`198.18.0.0/15`) or counts them as
+private, such as the documentation
ranges (`192.0.2.0/24`, `198.51.100.0/24`, `203.0.113.0/24`, `2001:db8::/32`)
and `240.0.0.0/4`. Every other mode refuses them as full-content result URLs.
A loud, non-dismissible banner
@@ -147,7 +148,7 @@ such as a self-hosted SearXNG does not change that: the full-content wrapper
applies it only under Unprotected, so under Strict, Public only, Private only,
Both and the default Adaptive that engine's private result URLs stay blocked
(see [SearXNG setup](SearXNG-Setup.md#full-content-fetching-of-private-result-urls)).
-That covers every address the egress policy counts as private, including
+That covers every address the egress policy cannot classify as public, including
ranges the SSRF checks let through, such as `198.18.0.0/15`, the
documentation ranges and `240.0.0.0/4`: full-content search refuses those
result URLs itself under every mode except Unprotected. The run policy also
@@ -271,28 +272,39 @@ dropdown state without a page reload. The backend precheck remains the enforceme
Proxy tools in "fake-IP" mode answer DNS lookups for public names with
addresses from `198.18.0.0/15` and route the connection through the proxy.
-LDR's egress policy classifies that range as private (it follows Python's
-`ipaddress.is_private`), so on such a machine every public website looks like
-a private host:
+An address in that range might also be a real benchmarking host, so LDR
+cannot infer the actual destination from the address alone. The egress policy
+classifies it, and its IPv4-mapped or NAT64-wrapped (DNS64) form, as unknown
+rather than private or public:
- **Public only, and Adaptive when it resolves to Public only** (the default
with SearXNG or another public primary engine): full-content fetching of
search results is unavailable, because every result URL is refused as
- private; the snippets are still returned. Other fetches the egress policy
- checks (the content fetcher tool, library downloads) are refused the same
- way.
-- **Strict and Private only**: those public hosts are treated as private.
- Full-content search still refuses them (it refuses every private result
- URL under these modes), but the other fetch paths and the socket guard
- admit them, so these modes do not keep such a run off the public internet.
-- **Both**: Both admits private and public hosts alike, so the other fetch
- paths are unaffected; full-content search refuses these hosts as private
- result URLs, so it is unavailable here too.
+ unclassified; the snippets are still returned. Other policy-checked fetches
+ (the content fetcher tool, library downloads) are refused too.
+- **Strict and Private only**: policy-checked fetch paths and the socket guard
+ refuse these addresses instead of admitting public hosts as private.
+ Full-content search also refuses them.
+- **Both**: policy-checked fetch paths refuse unclassified hosts; full-content
+ search refuses the result URLs too.
+
+**Unprotected** still permits these addresses if the separate SSRF checks
+allow them. A local engine configured at an ambiguous address is withheld
+under protected scopes; Adaptive keeps its local-inference requirement instead
+of widening to a cloud-capable scope.
+
+A real local service at a fixed address in this range can be declared local
+in `llm.allowed_local_hostnames`. List the address itself (for example
+`198.18.3.4`), and also the hostname if the service is configured by name.
+Under Strict and Private only the socket guard checks the address a
+connection goes to, so a declared hostname alone is still refused there. Do
+not declare an address that a fake-IP resolver handed out: the proxy can later
+assign it to another name, including a public one.
To avoid this, exclude LDR's traffic from fake-IP resolution (for example a
real-IP / `fake-ip-filter` rule for the hosts LDR needs, or run LDR outside the
-TUN interface). Classifying `198.18.0.0/15` by the address a fake-IP resolver
-maps it to is a known gap in the egress classifier, tracked in
+TUN interface). Automatically distinguishing real local benchmark hosts from
+proxy-mapped public hosts remains unresolved in
[#7093](https://github.com/LearningCircuit/local-deep-research/issues/7093).
## Audit log
diff --git a/src/local_deep_research/security/egress/README.md b/src/local_deep_research/security/egress/README.md
index 22a21607a2..63efc3d146 100644
--- a/src/local_deep_research/security/egress/README.md
+++ b/src/local_deep_research/security/egress/README.md
@@ -336,7 +336,7 @@ Each cell is the decision produced by the real `evaluate_*` logic / PEP for that
| **Raw socket** (audit hook → `evaluate_url`) | private→ARMED (public BLOCKED, best effort); public→INACTIVE | INACTIVE (passthrough) | INACTIVE (passthrough) | **ARMED** — public-address socket.connect BLOCKED on threads carrying the run's context (best effort, see below) | ARMED — public-address socket.connect BLOCKED on threads carrying the run's context (best effort, see below) |
| **Cloud-metadata IP** (169.254.169.254 / NAT64) | BLOCKED | BLOCKED | BLOCKED | BLOCKED | BLOCKED |
-The URL-fetch rows show the `evaluate_url` decision where that check runs. Under `strict`, search-result and document fetches normally reach neither public nor private hosts. Private hosts are normally refused because LDR's fetch-time SSRF checks relax private addresses only under `private_only`. `LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH` for an approved public engine such as a self-hosted SearXNG does not change that under `strict` or any other protected scope: the full-content wrapper applies that grant only under `unprotected` (see the Full-content fetch row above; link-local and cloud metadata stay blocked even there). The SSRF checks do not cover every policy-private range (198.18.0.0/15, the documentation ranges and 240.0.0.0/4 pass them); the full-content wrapper refuses those result URLs itself under every scope but `unprotected`, but on the other fetch paths and at the socket guard `strict` admits them as private hosts. Under fake-IP DNS (Clash, sing-box), which answers public names inside 198.18.0.0/15, that means `strict` admits public hosts there, and `public_only` refuses every such host, full-content search included (see "Known limitations" in `docs/egress-modes.md`). Public hosts are normally stopped by the policy check or, on fetch paths without one, by the socket guard (best effort).
+The URL-fetch rows show the `evaluate_url` decision where that check runs. Under `strict`, search-result and document fetches normally reach neither public nor private hosts. Private hosts are normally refused because LDR's fetch-time SSRF checks relax private addresses only under `private_only`. `LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH` for an approved public engine such as a self-hosted SearXNG does not change that under `strict` or any other protected scope: the full-content wrapper applies that grant only under `unprotected` (see the Full-content fetch row above; link-local and cloud metadata stay blocked even there). The SSRF checks do not cover every non-public policy range (198.18.0.0/15, the documentation ranges and 240.0.0.0/4 pass them); the full-content wrapper refuses those result URLs under every scope but `unprotected`. The policy now treats 198.18.0.0/15 as unknown because it might be a real benchmark host or a public hostname mapped by fake-IP DNS (Clash, sing-box): protected policy-checked fetch paths refuse it, as does the `strict` / `private_only` socket guard. Other policy-private ranges retain their existing classification (see "Known limitations" in `docs/egress-modes.md`). Public hosts are normally stopped by the policy check or, on fetch paths without one, by the socket guard (best effort).
### Key invariants (the crystal-clear takeaways)
diff --git a/src/local_deep_research/security/egress/policy.py b/src/local_deep_research/security/egress/policy.py
index cb473d8584..224afabc60 100644
--- a/src/local_deep_research/security/egress/policy.py
+++ b/src/local_deep_research/security/egress/policy.py
@@ -17,6 +17,7 @@ Vocabulary borrowed from XACML / zero-trust:
from __future__ import annotations
import hashlib
+import ipaddress
import json
import socket
import threading
@@ -301,11 +302,52 @@ def _resolve_with_timeout(hostname: str) -> Optional[list]:
_UNCACHED = object()
+_FAKE_IP_BENCHMARK_NET = ipaddress.ip_network("198.18.0.0/15")
+
+
+def _destination_address(address: str) -> str:
+ """Return the IPv4 that a wrapped IPv6 literal reaches, else ``address``.
+
+ An IPv4-mapped or NAT64 (RFC 6052) literal connects to its embedded IPv4,
+ so classification follows that payload, not the wrapper prefix, which
+ ``ipaddress`` rates without looking at the payload (``64:ff9b::/96`` as
+ public and, in current Python releases, ``64:ff9b:1::/48`` as private).
+ NAT64 payloads are read with the SSRF validator's ``nat64_embedded_ipv4``,
+ so both layers decode the same bytes.
+ """
+ from ..ssrf_validator import nat64_embedded_ipv4
+
+ try:
+ parsed = ipaddress.ip_address(address.strip("[]"))
+ except (ValueError, TypeError, AttributeError):
+ return address
+ if not isinstance(parsed, ipaddress.IPv6Address):
+ return address
+ embedded = parsed.ipv4_mapped or nat64_embedded_ipv4(parsed)
+ return address if embedded is None else str(embedded)
+
+
+def _is_ambiguous_fake_ip(address: str) -> bool:
+ """Recognize addresses that can be real benchmark hosts or proxy fake IPs.
+
+ The resolved address alone cannot tell which destination a TUN proxy will
+ reach. Treating it as private would let a public hostname through a
+ PRIVATE_ONLY/STRICT gate. IPv4-mapped and NAT64-wrapped (DNS64) forms
+ have the same ambiguity.
+ """
+ try:
+ parsed = ipaddress.ip_address(_destination_address(address).strip("[]"))
+ except (ValueError, TypeError, AttributeError):
+ return False
+ return (
+ isinstance(parsed, ipaddress.IPv4Address)
+ and parsed in _FAKE_IP_BENCHMARK_NET
+ )
def _cache_classification(
- ctx: EgressContext, hostname: str, value: bool
-) -> bool:
+ ctx: EgressContext, hostname: str, value: Optional[bool]
+) -> Optional[bool]:
"""First-writer-wins cache set; returns the value now in the cache.
Concurrent subagent threads may classify the same hostname outside the
@@ -390,7 +432,11 @@ def _classify_host(
block_link_local=True,
):
return _cache_classification(ctx, hostname, False)
- if is_private_ip(hostname):
+ # An IPv4-mapped or NAT64 literal that passed is_ip_blocked is
+ # classified by its embedded IPv4, like a direct connection to it.
+ if _is_ambiguous_fake_ip(hostname):
+ return _cache_classification(ctx, hostname, None)
+ if is_private_ip(_destination_address(hostname)):
return _cache_classification(ctx, hostname, True)
except Exception as exc:
logger.debug(
@@ -412,11 +458,14 @@ def _classify_host(
# Fail-safe: unresolvable / timeout → treat as public.
return _cache_classification(ctx, hostname, False)
- # A hostname is local only when every resolved address is local. A single
- # public or metadata answer can be selected by the HTTP client, so it must
- # prevent a local classification.
+ # A hostname is local only when every resolved address is local. Inspect
+ # every ordinary answer: a fake IP keeps the destination ambiguous even
+ # alongside a public address, regardless of the resolver's answer order.
+ # Metadata answers still prevent a local classification immediately.
if not addr_info:
return _cache_classification(ctx, hostname, False)
+ ambiguous_address = False
+ public_address = False
for entry in addr_info:
try:
ip_str = entry[4][0]
@@ -436,11 +485,16 @@ def _classify_host(
return _cache_classification(ctx, hostname, False)
if _is_nat64_wrapped_metadata(ip_str):
return _cache_classification(ctx, hostname, False)
- if not is_private_ip(ip_str):
- return _cache_classification(ctx, hostname, False)
+ if _is_ambiguous_fake_ip(ip_str):
+ ambiguous_address = True
+ continue
+ if not is_private_ip(_destination_address(ip_str)):
+ public_address = True
except Exception: # pragma: no cover - defensive
return _cache_classification(ctx, hostname, False)
- return _cache_classification(ctx, hostname, True)
+ return _cache_classification(
+ ctx, hostname, None if ambiguous_address else not public_address
+ )
def _get_engine_class(engine_name: str):
@@ -937,9 +991,10 @@ def _vector_store_endpoint_is_local(
#
# COUPLED WITH ``_classify_engine_url``: this loop and that function must
# keep the SAME container test (``isinstance(..., list)``, not
- # ``(list, tuple)``) and the same "skip non-``str`` entries" rule. If one
- # side alone grows tuple support, a tuple-shaped setting reaches hostname
- # classification with a rejected network-share path still in it — the
+ # ``(list, tuple)``) and the default "skip non-``str`` entries" rule.
+ # Elasticsearch's dictionary-host opt-in must remain disabled here.
+ # If one side alone grows tuple support, a tuple-shaped setting reaches
+ # hostname classification with a rejected network-share path still in it — the
# exact bypass this per-entry loop exists to close. Change both or
# neither.
for entry in uri if isinstance(uri, list) else (uri,):
@@ -1012,7 +1067,8 @@ def classify_engine(
The URL override is asymmetric and can only make the classification
MORE restrictive: a local-nature engine whose ``url_setting`` resolves
to a public host is reclassified public (queries would leave the box),
- while a public-nature engine on a local URL stays public.
+ while an ambiguous configured endpoint is ineligible under protected
+ scopes. A public-nature engine on a local URL stays public.
- Static engines: read declared ``is_public``/``is_local`` flags directly.
- ``library`` / ``collection_<uuid>``: per-collection ``is_public``
@@ -1067,18 +1123,34 @@ def classify_engine(
# local-data engine (Elasticsearch, Paperless) whose configured URL
# resolves to a PUBLIC host is reclassified as public — querying it
# sends the user's queries off the box, so PRIVATE_ONLY must deny it
- # at selection time (matching pre-static-flags behavior). The reverse
+ # at selection time (matching pre-static-flags behavior). An ambiguous
+ # configured URL is ineligible under protected scopes. The reverse
# direction is deliberately NOT applied: a public-nature engine
# (SearXNG) hosted on localhost stays public, because its data source
# is the internet regardless of where the proxy runs.
if url_setting and is_local is True and is_public is not True:
host_classification = _classify_engine_url(
- url_setting, settings_snapshot, ctx, allow_dns=allow_dns
+ url_setting,
+ settings_snapshot,
+ ctx,
+ allow_dns=allow_dns,
+ allow_host_dicts=engine_name == "elasticsearch",
)
if host_classification is False:
# False from _classify_engine_url == "connect target is a
# PUBLIC host" -> fail up to public.
return EngineClassification(is_public=True, is_local=False)
+ if (
+ host_classification is None
+ and allow_dns
+ and _get_setting_value(settings_snapshot, url_setting, None)
+ ):
+ # A configured endpoint in the fake-IP benchmark range could be
+ # a local benchmark service or a public site behind a TUN proxy.
+ # Neither eligibility is safe to infer. Deny this engine in
+ # protected scopes while Adaptive retains its restrictive
+ # PRIVATE_ONLY fallback for a non-contained private primary.
+ return EngineClassification(is_public=False, is_local=False)
return EngineClassification(is_public=is_public, is_local=is_local)
@@ -1254,17 +1326,49 @@ def evaluate_engine(
return Decision(False, "internal_error")
+def _urllib3_reads_same_host(url: str, hostname: str) -> bool:
+ """Whether urllib3's ``parse_url`` finds ``hostname`` in ``url`` too.
+
+ The Elasticsearch client parses host URLs with it, while this module uses
+ ``urlsplit``, and the two can disagree. For ``http://a:9200\\@b:9200``
+ ``urlsplit`` reads ``b`` but urllib3 reads ``a``. urllib3 also
+ IDNA-encodes a non-ASCII name, which the resolver can encode differently.
+ Brackets and letter case are the only differences ignored.
+ """
+ from urllib3.util import parse_url
+
+ try:
+ host = parse_url(url).host
+ except Exception:
+ return False
+ return (
+ isinstance(host, str) and host.strip("[]").lower() == hostname.lower()
+ )
+
+
def _classify_engine_url(
url_setting: str,
settings_snapshot: dict,
ctx: EgressContext,
allow_dns: bool = True,
+ *,
+ allow_host_dicts: bool = False,
) -> Optional[bool]:
"""Classify an engine's configured URL via DNS resolution.
- For list-typed settings (Elasticsearch ``hosts``), returns False (public)
- if ANY entry classifies as public — safer fail-up.
- Returns True if local, False if public, None if undetermined.
+ For list-typed settings (Elasticsearch ``hosts``), an unknown entry
+ prevents either classification because the client may select it. With
+ no unknown entries, a public entry wins over local entries. Returns True
+ if wholly local, False if public, None if undetermined.
+
+ Elasticsearch also accepts dictionaries with a ``host`` field. Only its
+ engine opts in (``allow_host_dicts``). The opt-in also splits a string
+ value into the nodes the engine connects to, and treats as unknown a URL
+ whose host the client's parser reads differently, and a URL or dictionary
+ host that is not ASCII (the resolver and the client encode such a name
+ differently) or contains ``%`` (HTTP client normalization is
+ version-dependent). Other consumers keep single URL-string parsing
+ and percent-decoding.
"""
value = _get_setting_value(settings_snapshot, url_setting, None)
if not value:
@@ -1272,50 +1376,111 @@ def _classify_engine_url(
# COUPLED WITH the per-entry network-share rejection in
# ``_vector_store_endpoint_is_local``: both must keep the SAME container
- # test (``isinstance(..., list)``, not ``(list, tuple)``) and the same
+ # test (``isinstance(..., list)``, not ``(list, tuple)``) and the default
# "skip non-``str`` entries" rule. Widening only one side lets a
# tuple-shaped setting reach this classifier with an entry the other side
- # never examined. Change both or neither.
- entries = value if isinstance(value, list) else [value]
+ # never examined. Dictionary hosts and the string splitting below are an
+ # Elasticsearch-only opt-in; vector-store URI classification must not
+ # enable it.
+ if allow_host_dicts and isinstance(value, str):
+ # The engine splits a string value with ``_ensure_list`` (a JSON
+ # list, else comma-separated nodes; a non-JSON env override or form
+ # value stays a string) and connects to every node. Parsing the
+ # whole string as one URL would judge only its first host.
+ from ...web_search_engines.engines.search_engine_elasticsearch import (
+ ElasticsearchSearchEngine,
+ )
+
+ entries = ElasticsearchSearchEngine._ensure_list(value)
+ else:
+ entries = value if isinstance(value, list) else [value]
any_public = False
any_local = False
+ any_unknown = False
for entry in entries:
- if not isinstance(entry, str):
- continue
- try:
- if "://" in entry:
- to_parse = entry
- elif entry.startswith("//"):
- # Scheme-less "//host[:port]" authority form (e.g. a Milvus
- # endpoint written without a scheme). Prepending "http://"
- # here would yield "http:////host:port", which urlsplit
- # mis-parses as an empty netloc with the host landing in
- # ``path`` — silently dropping the hostname from
- # classification. Prepend only the scheme so the leading
- # "//" the entry already supplies becomes the URL's
- # authority marker.
- to_parse = f"http:{entry}"
- else:
- to_parse = f"http://{entry}"
- parsed = urlsplit(to_parse)
- hostname = parsed.hostname
- except Exception:
+ if allow_host_dicts and isinstance(entry, dict):
+ # The SDK uses the bare host, not a URL: retain IPv6 colons and
+ # never reinterpret a path, userinfo, or query as an authority.
+ hostname = entry.get("host")
+ if not isinstance(hostname, str) or not hostname:
+ any_unknown = True
+ continue
+ hostname = hostname.lower().rstrip(".")
+ if not hostname or any(
+ char.isspace() or ord(char) < 32 or char in "/?#@[]"
+ for char in hostname
+ ):
+ any_unknown = True
+ continue
+ elif isinstance(entry, str):
+ try:
+ if "://" in entry:
+ to_parse = entry
+ elif entry.startswith("//"):
+ # Scheme-less "//host[:port]" authority form (e.g. a Milvus
+ # endpoint written without a scheme). Prepending "http://"
+ # here would yield "http:////host:port", which urlsplit
+ # mis-parses as an empty netloc with the host landing in
+ # ``path`` — silently dropping the hostname from
+ # classification. Prepend only the scheme so the leading
+ # "//" the entry already supplies becomes the URL's
+ # authority marker.
+ to_parse = f"http:{entry}"
+ else:
+ to_parse = f"http://{entry}"
+ parsed = urlsplit(to_parse)
+ hostname = parsed.hostname
+ except Exception:
+ if allow_host_dicts:
+ any_unknown = True
+ continue
+ if not hostname:
+ if allow_host_dicts:
+ any_unknown = True
+ continue
+ if allow_host_dicts and not _urllib3_reads_same_host(
+ to_parse, hostname
+ ):
+ # The Elasticsearch client connects to the host urllib3
+ # reads, so a different one here was never classified.
+ any_unknown = True
+ continue
+ if not allow_host_dicts:
+ # Other consumers decode, as evaluate_url does: requests
+ # percent-decodes the host before connecting, so
+ # "192%2e168%2e1%2e1" is 192.168.1.1. Elasticsearch's HTTP
+ # client has varied across versions, so percent-bearing
+ # hosts are withheld below.
+ hostname = unquote(hostname)
+ else:
+ if allow_host_dicts:
+ any_unknown = True
continue
- if not hostname:
+ if allow_host_dicts and (not hostname.isascii() or "%" in hostname):
+ # Both branches meet here, so a dictionary host and a URL host are
+ # judged alike, as written. urllib3 2.8 decodes unreserved host
+ # escapes that 2.7 passed to DNS unchanged. Keep percent-bearing
+ # hosts unknown under either behavior, including scoped IPv6
+ # literals such as ``fe80::1%eth0``. The resolver also encodes a
+ # non-ASCII name with IDNA 2003 (``faß`` is looked up as
+ # ``fass``) but the client's urllib3 uses IDNA 2008
+ # (``xn--fa-hia``). Either way the name classified here need not
+ # be the one the client connects to. An ``xn--`` spelling is
+ # plain ASCII and is classified as written.
+ any_unknown = True
continue
- # Decode percent-encoding before classifying, identically to
- # evaluate_url: the HTTP client decodes the host before connecting,
- # so "192%2e168%2e1%2e1" must be classified as 192.168.1.1, not as
- # an unresolvable literal.
- hostname = unquote(hostname)
result = _classify_host(hostname, ctx, allow_dns=allow_dns)
if result is True:
any_local = True
elif result is False:
any_public = True
+ else:
+ any_unknown = True
+ if any_unknown:
+ return None # an ambiguous endpoint can still be selected
if any_public:
- return False # "any public" wins under list-typed settings
+ return False # public wins over local under list-typed settings
if any_local:
return True
return None
@@ -1751,9 +1916,11 @@ def host_not_classified_public(url: str, ctx: EgressContext) -> bool:
as ``scope_mismatch_public_only`` under ``public_only``, not a second,
differently defined list. (The SSRF validator's ``PRIVATE_IP_RANGES``
is narrower: it admits 198.18.0.0/15, the TEST-NETs, 192.0.0.0/24,
- 240.0.0.0/4, 2001:db8::/32 and, with NAT64 allowed, 64:ff9b:1::/48,
- all of which classify private here; so does any hostname a fake-IP DNS
- resolver answers inside 198.18.0.0/15.)
+ 240.0.0.0/4 and 2001:db8::/32, and with NAT64 allowed any NAT64 address
+ whose embedded IPv4 it admits. The 198.18.0.0/15 addresses (including
+ fake-IP DNS answers) are unclassified here; the other listed ranges
+ classify private. IPv4-mapped and NAT64 addresses classify as their
+ embedded IPv4.)
Returns False for anything ``evaluate_url`` refuses for another reason
first (malformed URL, non-http(s) scheme, no host); a cloud-metadata
diff --git a/src/local_deep_research/security/egress/run_classification.py b/src/local_deep_research/security/egress/run_classification.py
index ed923d6d49..46dbc68fd2 100644
--- a/src/local_deep_research/security/egress/run_classification.py
+++ b/src/local_deep_research/security/egress/run_classification.py
@@ -51,6 +51,7 @@ def engine_label(engine_name: str, settings_snapshot, ctx) -> Optional[Label]:
from .policy import (
_classify_engine_url,
_get_engine_class,
+ _get_setting_value,
_resolve_collection_is_public,
vector_store_is_contained,
)
@@ -85,10 +86,24 @@ def engine_label(engine_name: str, settings_snapshot, ctx) -> Optional[Label]:
# Exposure fail-up: a contained store whose configured URL resolves to a
# public host leaks the query off the box -> EXPOSING. Only ever tightens,
- # mirroring the policy's asymmetric URL override.
+ # mirroring the policy's asymmetric URL override. COUPLED WITH
+ # ``classify_engine``: it reads the endpoint with the same Elasticsearch
+ # node handling (a ``hosts`` string split into nodes, host dictionaries)
+ # and acts on the same two verdicts, a public endpoint (the engine turns
+ # public) and a configured one it cannot classify, such as a fake-IP
+ # address (the engine is withheld). Neither is provably on the box.
url_setting = getattr(cls, "url_setting", None)
if url_setting and exposure is Exposure.CONTAINED:
- if _classify_engine_url(url_setting, settings_snapshot, ctx) is False:
+ host_classification = _classify_engine_url(
+ url_setting,
+ settings_snapshot,
+ ctx,
+ allow_host_dicts=engine_name == "elasticsearch",
+ )
+ if host_classification is False or (
+ host_classification is None
+ and _get_setting_value(settings_snapshot, url_setting, None)
+ ):
exposure = Exposure.EXPOSING
# Per-destination trust (ADR-0007 stage D): the user has explicitly vouched
diff --git a/src/local_deep_research/web_search_engines/engines/full_search.py b/src/local_deep_research/web_search_engines/engines/full_search.py
index e0eef77336..aa68667cf3 100644
--- a/src/local_deep_research/web_search_engines/engines/full_search.py
+++ b/src/local_deep_research/web_search_engines/engines/full_search.py
@@ -258,11 +258,11 @@ class FullSearchResults:
return False
scope_name = getattr(scope, "value", scope)
logger.bind(policy_audit=True).warning(
- "full_search URL denied by egress policy (private result host, "
- "not counted toward the denied-fetch quota)",
+ "full_search URL denied by egress policy (non-public result "
+ "host, not counted toward the denied-fetch quota)",
url=redact_url_for_log(url),
scope=scope_name,
- reason=f"private_result_host_{scope_name}",
+ reason=f"nonpublic_result_host_{scope_name}",
)
return True
diff --git a/tests/security/test_egress_elasticsearch_host_shapes.py b/tests/security/test_egress_elasticsearch_host_shapes.py
new file mode 100644
index 0000000000..eb801eb340
--- /dev/null
+++ b/tests/security/test_egress_elasticsearch_host_shapes.py
@@ -0,0 +1,651 @@
+"""Elasticsearch host dictionaries and host strings are classified for egress."""
+
+import json
+from types import SimpleNamespace
+from unittest.mock import patch
+from urllib.parse import urlsplit
+
+import pytest
+import requests
+from elastic_transport.client_utils import url_to_node_config
+from elasticsearch._sync.client.utils import client_node_configs
+from urllib3 import HTTPConnectionPool
+
+from local_deep_research.security.egress.classification import Exposure
+from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+ _classify_engine_url,
+ _vector_store_endpoint_is_local,
+ classify_engine,
+ evaluate_engine,
+)
+from local_deep_research.security.egress.run_classification import engine_label
+from local_deep_research.web_search_engines.engines.search_engine_elasticsearch import (
+ ElasticsearchSearchEngine,
+)
+
+
+SETTING = "search.engine.web.elasticsearch.default_params.hosts"
+PROTECTED_SCOPES = [
+ EgressScope.PUBLIC_ONLY,
+ EgressScope.PRIVATE_ONLY,
+ EgressScope.STRICT,
+ EgressScope.BOTH,
+]
+
+
+def classify_hosts(hosts, scope, *, local_hostnames=()):
+ # This parses the real SDK configuration without opening a connection.
+ assert len(client_node_configs(hosts, None)) == len(hosts)
+ context = EgressContext(
+ scope=scope,
+ primary_engine="elasticsearch",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ local_hostnames=local_hostnames,
+ )
+ snapshot = {SETTING: hosts}
+ return (
+ classify_engine("elasticsearch", context, settings_snapshot=snapshot),
+ evaluate_engine("elasticsearch", context, settings_snapshot=snapshot),
+ )
+
+
+ "scope",
+ [
+ EgressScope.PUBLIC_ONLY,
+ EgressScope.PRIVATE_ONLY,
+ EgressScope.STRICT,
+ EgressScope.BOTH,
+ ],
+)
[email protected]("other_host", ["10.0.0.42", "93.184.216.34"])
+ "fake_host", ["198.18.3.4", "::ffff:198.18.3.4", "mixed.fakeip.test"]
+)
[email protected]("dictionary_first", [False, True])
+def test_fake_ip_dictionary_endpoint_makes_whole_host_list_ineligible(
+ scope, other_host, fake_host, dictionary_first
+):
+ hosts = [
+ f"http://{other_host}:9200",
+ {"host": fake_host, "port": 9200, "scheme": "http"},
+ ]
+ if dictionary_first:
+ hosts.reverse()
+
+ def resolve(host):
+ address = "198.18.3.4" if host == "mixed.fakeip.test" else host
+ return [(None, None, None, None, (address, 0))]
+
+ with patch(
+ "local_deep_research.security.egress.policy._resolve_with_timeout",
+ side_effect=resolve,
+ ):
+ classification, decision = classify_hosts(hosts, scope)
+
+ assert classification.is_public is False
+ assert classification.is_local is False
+ assert not decision.allowed
+
+
[email protected]("host", ["10.0.0.43", "::1"])
[email protected]("include_url", [False, True])
+def test_private_dictionary_endpoints_remain_eligible(host, include_url):
+ hosts = [{"host": host, "port": 9200, "scheme": "http"}]
+ if include_url:
+ hosts.insert(0, "http://10.0.0.42:9200")
+ classification, decision = classify_hosts(hosts, EgressScope.PRIVATE_ONLY)
+ assert classification.is_local is True
+ assert classification.is_public is False
+ assert decision.allowed
+
+
[email protected]("include_url", [False, True])
+def test_public_dictionary_endpoint_reclassifies_engine_as_public(include_url):
+ hosts = [{"host": "93.184.216.34", "port": 443, "scheme": "https"}]
+ if include_url:
+ hosts.insert(0, "http://10.0.0.42:9200")
+ with patch(
+ "local_deep_research.security.egress.policy._resolve_with_timeout",
+ return_value=[(None, None, None, None, ("93.184.216.34", 0))],
+ ):
+ classification, decision = classify_hosts(
+ hosts, EgressScope.PUBLIC_ONLY
+ )
+ assert classification.is_local is False
+ assert classification.is_public is True
+ assert decision.allowed
+
+
+def test_declared_local_dictionary_hostname_keeps_operator_override():
+ hosts = [{"host": "known.local.test", "port": 9200, "scheme": "http"}]
+ with patch(
+ "local_deep_research.security.egress.policy._resolve_with_timeout"
+ ) as resolve:
+ classification, decision = classify_hosts(
+ hosts,
+ EgressScope.PRIVATE_ONLY,
+ local_hostnames=("known.local.test",),
+ )
+ assert classification.is_local is True
+ assert decision.allowed
+ resolve.assert_not_called()
+
+
+ "host",
+ [
+ None,
+ "",
+ 123,
+ "localhost/path",
+ "localhost?query",
+ "localhost@remote",
+ "localhost%2fremote",
+ "localhost%00remote",
+ "[::1]",
+ ],
+)
+def test_unparseable_dictionary_does_not_hide_behind_a_private_url(host):
+ context = EgressContext(
+ scope=EgressScope.PRIVATE_ONLY,
+ primary_engine="elasticsearch",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+ snapshot = {SETTING: ["http://10.0.0.42:9200", {"host": host}]}
+ assert not evaluate_engine(
+ "elasticsearch", context, settings_snapshot=snapshot
+ ).allowed
+
+
[email protected]("host", ["KNOWN.LOCAL.TEST", "known.local.test."])
+def test_dictionary_hostname_normalization_keeps_local_override(host):
+ with patch(
+ "local_deep_research.security.egress.policy._resolve_with_timeout"
+ ) as resolve:
+ classification, decision = classify_hosts(
+ [{"host": host, "port": 9200, "scheme": "http"}],
+ EgressScope.PRIVATE_ONLY,
+ local_hostnames=("known.local.test",),
+ )
+ assert classification.is_local is True
+ assert decision.allowed
+ resolve.assert_not_called()
+
+
[email protected]("as_list", [False, True])
+def test_elasticsearch_dictionary_support_does_not_widen_vector_store_uris(
+ as_list,
+):
+ uri = {"host": "127.0.0.1", "scheme": "http", "port": 19530}
+ snapshot = {"vector_store.test.uri": [uri] if as_list else uri}
+ context = EgressContext(
+ scope=EgressScope.PRIVATE_ONLY,
+ primary_engine="library",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+ with patch(
+ "local_deep_research.security.egress.policy._vector_store_class",
+ return_value=SimpleNamespace(uri_setting="vector_store.test.uri"),
+ ):
+ assert not _vector_store_endpoint_is_local("test", snapshot, context)
+
+
+def resolve_names_privately(host):
+ # An IP literal answers itself; every name resolves to a private address,
+ # so only the host-string parsing can make an entry unknown.
+ address = host if host[:1].isdigit() else "10.0.0.9"
+ return [(None, None, None, None, (address, 0))]
+
+
+def hosts_string(nodes, form):
+ if form == "json":
+ return json.dumps(nodes)
+ return (", " if form == "comma_space" else ",").join(nodes)
+
+
+def classify_hosts_string(value, scope):
+ """Classify a string ``hosts`` value, which the engine splits itself."""
+ nodes = ElasticsearchSearchEngine._ensure_list(value)
+ # The engine hands every node to the SDK, which parses all of them.
+ assert len(client_node_configs(nodes, None)) == len(nodes)
+ context = EgressContext(
+ scope=scope,
+ primary_engine="elasticsearch",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+ snapshot = {SETTING: value}
+ with patch(
+ "local_deep_research.security.egress.policy._resolve_with_timeout",
+ side_effect=resolve_names_privately,
+ ):
+ return (
+ classify_engine(
+ "elasticsearch", context, settings_snapshot=snapshot
+ ),
+ evaluate_engine(
+ "elasticsearch", context, settings_snapshot=snapshot
+ ),
+ )
+
+
+HOSTS_STRING_FORMS = ["comma", "comma_space", "json"]
+
+
[email protected]("scope", PROTECTED_SCOPES, ids=lambda s: s.value)
[email protected]("other_host", ["10.0.0.42", "93.184.216.34"])
[email protected]("fake_first", [False, True])
[email protected]("form", HOSTS_STRING_FORMS)
+def test_fake_ip_node_in_a_hosts_string_makes_the_engine_ineligible(
+ scope, other_host, fake_first, form
+):
+ """A comma-separated or JSON string is split into nodes by the engine, so
+ a fake-IP node outside the first position is still a connect target."""
+ nodes = [f"http://{other_host}:9200", "http://198.18.3.4:9200"]
+ if fake_first:
+ nodes.reverse()
+
+ classification, decision = classify_hosts_string(
+ hosts_string(nodes, form), scope
+ )
+
+ assert classification.is_public is False
+ assert classification.is_local is False
+ assert not decision.allowed
+
+
[email protected]("public_first", [False, True])
[email protected]("form", HOSTS_STRING_FORMS)
+def test_public_node_in_a_hosts_string_reclassifies_the_engine_public(
+ public_first, form
+):
+ nodes = ["http://10.0.0.42:9200", "http://93.184.216.34:9200"]
+ if public_first:
+ nodes.reverse()
+
+ classification, decision = classify_hosts_string(
+ hosts_string(nodes, form), EgressScope.PRIVATE_ONLY
+ )
+
+ assert classification.is_public is True
+ assert classification.is_local is False
+ assert decision.reason == "scope_mismatch_private_only"
+
+
[email protected]("form", HOSTS_STRING_FORMS)
+def test_private_hosts_string_remains_eligible(form):
+ nodes = ["http://10.0.0.42:9200", "http://[::1]:9200"]
+
+ classification, decision = classify_hosts_string(
+ hosts_string(nodes, form), EgressScope.PRIVATE_ONLY
+ )
+
+ assert classification.is_local is True
+ assert classification.is_public is False
+ assert decision.allowed
+
+
+# Host URLs that urlsplit and urllib3 (the SDK's parser) read differently.
+SPLIT_HOST_URLS = [
+ # urlsplit takes the host after "@"; urllib3 ends the authority at "\".
+ ("https://198.18.3.4:9200\\@10.0.0.42:9200", "198.18.3.4"),
+ ("http://93.184.216.34:9200\\@10.0.0.42:9200", "93.184.216.34"),
+ # urllib3 applies IDNA 2008; the resolver would look up "strasse".
+ ("http://straße.example:9200", "xn--strae-oqa.example"),
+]
+
+
[email protected]("scope", PROTECTED_SCOPES, ids=lambda s: s.value)
[email protected]("as_list", [False, True])
+ ("url", "sdk_host"),
+ SPLIT_HOST_URLS,
+ ids=["backslash_fake_ip", "backslash_public", "idna"],
+)
+def test_host_the_sdk_reads_differently_is_unknown(
+ scope, as_list, url, sdk_host
+):
+ """The client connects to the host urllib3 reads, so a URL whose urlsplit
+ host differs was never classified and keeps the engine ineligible."""
+ assert url_to_node_config(url).host == sdk_host
+ assert urlsplit(url).hostname != sdk_host
+
+ if as_list:
+ context = EgressContext(
+ scope=scope,
+ primary_engine="elasticsearch",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+ snapshot = {SETTING: [url]}
+ with patch(
+ "local_deep_research.security.egress.policy._resolve_with_timeout",
+ side_effect=resolve_names_privately,
+ ):
+ classification = classify_engine(
+ "elasticsearch", context, settings_snapshot=snapshot
+ )
+ decision = evaluate_engine(
+ "elasticsearch", context, settings_snapshot=snapshot
+ )
+ else:
+ classification, decision = classify_hosts_string(url, scope)
+
+ assert classification.is_public is False
+ assert classification.is_local is False
+ assert not decision.allowed
+
+
+ "url",
+ [
+ "http://[::1]:9200",
+ "HTTP://LOCALHOST:9200",
+ "http://[email protected]:9200",
+ ],
+)
+def test_host_urls_both_parsers_read_alike_remain_classified(url):
+ assert url_to_node_config(url).host == urlsplit(url).hostname
+
+ classification, decision = classify_hosts_string(
+ url, EgressScope.PRIVATE_ONLY
+ )
+
+ assert classification.is_local is True
+ assert decision.allowed
+
+
+def classify_private_names(hosts, scope):
+ """Classify a ``hosts`` list whose names all resolve to a private address.
+
+ Only the parsing of an entry can then make it unknown. Also returns the
+ names the resolver was asked for.
+ """
+ assert len(client_node_configs(hosts, None)) == len(hosts)
+ context = EgressContext(
+ scope=scope,
+ primary_engine="elasticsearch",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+ snapshot = {SETTING: hosts}
+ with patch(
+ "local_deep_research.security.egress.policy._resolve_with_timeout",
+ side_effect=resolve_names_privately,
+ ) as resolve:
+ return (
+ classify_engine(
+ "elasticsearch", context, settings_snapshot=snapshot
+ ),
+ evaluate_engine(
+ "elasticsearch", context, settings_snapshot=snapshot
+ ),
+ [call.args[0] for call in resolve.call_args_list],
+ )
+
+
+def dictionary_host(host):
+ return {"host": host, "port": 9200, "scheme": "http"}
+
+
+def sdk_connects_to(host):
+ """The name the SDK's urllib3 pool connects to for a host dictionary."""
+ (node,) = client_node_configs([dictionary_host(host)], None)
+ return HTTPConnectionPool(node.host, port=node.port).host
+
+
+# The resolver encodes a non-ASCII name with IDNA 2003 and the SDK's urllib3
+# with IDNA 2008: "faß" is looked up as "fass" but connected to as
+# "xn--fa-hia". The tuples are (host, name the SDK connects to, name the
+# resolver looks up).
+NON_ASCII_DICTIONARY_HOSTS = [
+ pytest.param(
+ "faß.corp.example",
+ "xn--fa-hia.corp.example",
+ "fass.corp.example",
+ id="sharp_s",
+ ),
+ pytest.param(
+ "straße.example",
+ "xn--strae-oqa.example",
+ "strasse.example",
+ id="strasse",
+ ),
+ # The two encodings agree here, yet the same host in a URL is unknown.
+ pytest.param(
+ "münchen.example",
+ "xn--mnchen-3ya.example",
+ "xn--mnchen-3ya.example",
+ id="encodings_agree",
+ ),
+]
+
+
[email protected]("scope", PROTECTED_SCOPES, ids=lambda s: s.value)
[email protected]("include_url", [False, True])
+ ("host", "sdk_host", "resolver_host"), NON_ASCII_DICTIONARY_HOSTS
+)
+def test_non_ascii_dictionary_host_is_unknown(
+ scope, include_url, host, sdk_host, resolver_host
+):
+ """The resolver would look up ``resolver_host`` while the client connects
+ to ``sdk_host``, so a name that resolves private under one encoding says
+ nothing about the other. A dictionary host stays unknown, as it does in
+ a URL."""
+ assert sdk_connects_to(host) == sdk_host
+ assert host.encode("idna").decode("ascii") == resolver_host
+
+ hosts = [dictionary_host(host)]
+ if include_url:
+ hosts.insert(0, "http://10.0.0.42:9200")
+ classification, decision, looked_up = classify_private_names(hosts, scope)
+
+ assert classification.is_public is False
+ assert classification.is_local is False
+ assert not decision.allowed
+ assert host not in looked_up
+
+
+# (is_public, is_local) of the engine when its only node is the host.
+LOCAL, PUBLIC, UNKNOWN = (False, True), (True, False), (False, False)
+
+HOST_IN_URL_AND_DICTIONARY = [
+ pytest.param("10.0.0.42", LOCAL, id="private_ip"),
+ pytest.param("93.184.216.34", PUBLIC, id="public_ip"),
+ pytest.param("kibana.corp.example", LOCAL, id="name"),
+ pytest.param("Kibana.Corp.Example", LOCAL, id="mixed_case"),
+ # Punycode is ASCII: classified as the client connects to it.
+ pytest.param("xn--fa-hia.corp.example", LOCAL, id="punycode"),
+ # The Kelvin sign lower-cases to an ASCII "k" for the resolver and the SDK
+ # alike.
+ pytest.param("Kibana.corp.example", LOCAL, id="kelvin_sign"),
+ pytest.param("faß.corp.example", UNKNOWN, id="sharp_s"),
+ pytest.param("straße.example", UNKNOWN, id="strasse"),
+ pytest.param("münchen.example", UNKNOWN, id="encodings_agree"),
+ # Percent-bearing hosts stay unknown in both shapes, regardless of the
+ # installed HTTP client's normalization (covered below).
+ pytest.param("10%2e0%2e0%2e42", UNKNOWN, id="percent_encoded_ip"),
+ pytest.param("fa%C3%9F.corp.example", UNKNOWN, id="percent_encoded_utf8"),
+]
+
+
[email protected](("host", "expected"), HOST_IN_URL_AND_DICTIONARY)
+def test_dictionary_host_is_classified_like_the_same_host_in_a_url(
+ host, expected
+):
+ for entry in (dictionary_host(host), f"http://{host}:9200"):
+ classification, _, _ = classify_private_names(
+ [entry], EgressScope.PRIVATE_ONLY
+ )
+ assert (
+ classification.is_public,
+ classification.is_local,
+ ) == expected, entry
+
+
+def test_punycode_dictionary_host_is_classified_as_the_client_connects():
+ """Writing the host in its ``xn--`` form is the way to keep an
+ internationalized name classified."""
+ host = "xn--fa-hia.corp.example"
+ assert sdk_connects_to(host) == host
+
+ classification, decision, looked_up = classify_private_names(
+ [dictionary_host(host)], EgressScope.PRIVATE_ONLY
+ )
+
+ assert classification.is_local is True
+ assert decision.allowed
+ assert set(looked_up) == {host}
+
+
+# urllib3 2.8 decodes unreserved percent escapes that 2.7 passed through,
+# and rejects these scoped IPv6 entries before DNS. The policy deliberately
+# withholds all percent-bearing hosts under either client behavior, including
+# IPv6 zone IDs. Keep that invariant independent of the SDK's normalization.
+PERCENT_BEARING_HOSTS = [
+ pytest.param(
+ dictionary_host("10%2e0%2e0%2e42"),
+ id="dictionary_ip",
+ ),
+ pytest.param("http://10%2E0%2E0%2E42:9200", id="url_ip"),
+ pytest.param(dictionary_host("%6cocalhost"), id="dictionary_name"),
+ pytest.param(
+ dictionary_host("fd00::1%eth0"),
+ id="dictionary_scoped_ipv6",
+ ),
+ pytest.param("http://[fd00::1%eth0]:9200", id="url_scoped_ipv6"),
+ pytest.param(
+ "http://[fd00::1%25eth0]:9200",
+ id="url_scoped_ipv6_rfc6874",
+ ),
+]
+
+
[email protected]("scope", PROTECTED_SCOPES, ids=lambda s: s.value)
[email protected]("include_url", [False, True])
[email protected]("entry", PERCENT_BEARING_HOSTS)
+def test_percent_bearing_host_is_unknown_without_dns(scope, include_url, entry):
+ """Every protected scope refuses the entry before policy DNS lookup,
+ even beside a valid private URL and regardless of SDK normalization."""
+ hosts = [entry]
+ if include_url:
+ hosts.insert(0, "http://10.0.0.42:9200")
+ classification, decision, looked_up = classify_private_names(hosts, scope)
+
+ assert classification.is_public is False
+ assert classification.is_local is False
+ assert not decision.allowed
+ assert looked_up == []
+
+
+def test_other_consumers_still_decode_a_percent_escaped_host():
+ """``requests`` decodes the host, so only the Elasticsearch opt-in
+ (``allow_host_dicts``) stops doing it."""
+ url = "http://10%2e0%2e0%2e42:8000"
+ prepared = requests.Request("GET", url).prepare()
+ assert prepared.url == "http://10.0.0.42:8000/"
+ context = EgressContext(
+ scope=EgressScope.PRIVATE_ONLY,
+ primary_engine="paperless",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+ snapshot = {"engine.url": url}
+
+ assert _classify_engine_url("engine.url", snapshot, context) is True
+ assert (
+ _classify_engine_url(
+ "engine.url", snapshot, context, allow_host_dicts=True
+ )
+ is None
+ )
+
+
+CONTAINED, EXPOSING = Exposure.CONTAINED, Exposure.EXPOSING
+PRIVATE_URL = "http://10.0.0.42:9200"
+PUBLIC_URL = "http://93.184.216.34:9200"
+FAKE_IP_URL = "http://198.18.3.4:9200"
+
+LABEL_SHAPES = [
+ pytest.param(None, CONTAINED, id="unset"),
+ pytest.param(PRIVATE_URL, CONTAINED, id="private_string"),
+ pytest.param(
+ [PRIVATE_URL, dictionary_host("10.0.0.43")],
+ CONTAINED,
+ id="private_url_and_dictionary",
+ ),
+ pytest.param(PUBLIC_URL, EXPOSING, id="public_string"),
+ pytest.param(
+ f"{PRIVATE_URL},{PUBLIC_URL}", EXPOSING, id="public_second_comma"
+ ),
+ pytest.param(
+ json.dumps([PRIVATE_URL, PUBLIC_URL]),
+ EXPOSING,
+ id="public_second_json",
+ ),
+ pytest.param(
+ [PRIVATE_URL, dictionary_host("93.184.216.34")],
+ EXPOSING,
+ id="public_dictionary",
+ ),
+ pytest.param(FAKE_IP_URL, EXPOSING, id="fake_ip_string"),
+ pytest.param(
+ f"{PRIVATE_URL},{FAKE_IP_URL}", EXPOSING, id="fake_ip_second_comma"
+ ),
+ pytest.param(
+ [PRIVATE_URL, dictionary_host("198.18.3.4")],
+ EXPOSING,
+ id="fake_ip_dictionary",
+ ),
+ pytest.param(
+ [dictionary_host("faß.corp.example")],
+ EXPOSING,
+ id="non_ascii_dictionary",
+ ),
+ pytest.param(
+ [PRIVATE_URL, dictionary_host("localhost/path")],
+ EXPOSING,
+ id="unparseable_dictionary",
+ ),
+]
+
+
[email protected](("hosts", "exposure"), LABEL_SHAPES)
+def test_two_axis_label_agrees_with_the_scope_policy(hosts, exposure):
+ """``engine_label`` reads the node list the way ``classify_engine`` does:
+ the engine stays CONTAINED only where the policy keeps it local, and it
+ fails up to EXPOSING where the policy withholds it or rates it public."""
+ snapshot = {}
+ if hosts is not None:
+ snapshot = {SETTING: hosts}
+ nodes = (
+ ElasticsearchSearchEngine._ensure_list(hosts)
+ if isinstance(hosts, str)
+ else hosts
+ )
+ assert len(client_node_configs(nodes, None)) == len(nodes)
+ context = EgressContext(
+ scope=EgressScope.BOTH,
+ primary_engine="elasticsearch",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+
+ with patch(
+ "local_deep_research.security.egress.policy._resolve_with_timeout",
+ side_effect=resolve_names_privately,
+ ):
+ label = engine_label("elasticsearch", snapshot, context)
+ classification = classify_engine(
+ "elasticsearch", context, settings_snapshot=snapshot
+ )
+
+ assert label.exposure is exposure
+ assert (classification.is_local is True) == (exposure is CONTAINED)
diff --git a/tests/security/test_egress_fake_ip_classification.py b/tests/security/test_egress_fake_ip_classification.py
new file mode 100644
index 0000000000..44571d19d9
--- /dev/null
+++ b/tests/security/test_egress_fake_ip_classification.py
@@ -0,0 +1,361 @@
+"""Fake-IP DNS must not make public destinations look private to egress."""
+
+from __future__ import annotations
+
+import socket
+from unittest.mock import patch
+
+import pytest
+
+from local_deep_research.security.egress.audit_hook import (
+ _audit_hook,
+ clear_active_context,
+ set_active_context,
+)
+from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+ PolicyDeniedError,
+ _classify_host,
+ classify_engine,
+ context_from_snapshot,
+ evaluate_engine,
+ evaluate_url,
+ host_not_classified_public,
+)
+from local_deep_research.security.egress.validators import (
+ validate_allowed_local_hostnames,
+)
+from local_deep_research.security.ssrf_validator import validate_url
+
+
+def _ctx(scope: EgressScope, **kwargs) -> EgressContext:
+ return EgressContext(
+ scope=scope,
+ primary_engine="paperless",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ **kwargs,
+ )
+
+
+def _fake_ip_answers(*addresses: str) -> list[tuple]:
+ return [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", (address, 0))
+ for address in addresses
+ ]
+
+
+ "host", ["198.18.0.7", "198.19.255.254", "::ffff:198.18.0.7"]
+)
+def test_fake_ip_literal_is_unknown_not_private(host):
+ ctx = _ctx(EgressScope.PRIVATE_ONLY)
+ assert _classify_host(host, ctx) is None
+ assert host in ctx._dns_cache
+
+
+def test_fake_ip_dns_and_mixed_private_answer_remain_unknown():
+ ctx = _ctx(EgressScope.PRIVATE_ONLY)
+ with patch(
+ "local_deep_research.security.egress.policy._resolve_with_timeout",
+ return_value=_fake_ip_answers("10.0.0.42", "198.18.3.4"),
+ ):
+ assert _classify_host("news.fakeip.test", ctx) is None
+ assert ctx._dns_cache["news.fakeip.test"] is None
+
+
[email protected]("public_first", [False, True])
+ "scope",
+ [
+ EgressScope.STRICT,
+ EgressScope.PRIVATE_ONLY,
+ EgressScope.PUBLIC_ONLY,
+ EgressScope.BOTH,
+ ],
+)
+def test_fake_ip_mixed_public_dns_stays_unknown_and_refused(
+ scope, public_first
+):
+ ctx = _ctx(scope)
+ addresses = ["198.18.3.4", "8.8.8.8"]
+ if public_first:
+ addresses.reverse()
+ with patch(
+ "local_deep_research.security.egress.policy._resolve_with_timeout",
+ return_value=_fake_ip_answers(*addresses),
+ ):
+ assert _classify_host("mixed.fakeip.test", ctx) is None
+ assert not evaluate_url("https://mixed.fakeip.test/story", ctx).allowed
+ assert ctx._dns_cache["mixed.fakeip.test"] is None
+
+
+ "scope",
+ [
+ EgressScope.STRICT,
+ EgressScope.PRIVATE_ONLY,
+ EgressScope.PUBLIC_ONLY,
+ EgressScope.BOTH,
+ ],
+)
+def test_fake_ip_dns_url_refused_in_every_protected_scope(scope):
+ ctx = _ctx(scope)
+ with patch(
+ "local_deep_research.security.egress.policy._resolve_with_timeout",
+ return_value=_fake_ip_answers("198.18.3.4"),
+ ):
+ assert not evaluate_url("https://news.fakeip.test/story", ctx).allowed
+
+
+ "scope", [EgressScope.STRICT, EgressScope.PRIVATE_ONLY]
+)
+def test_fake_ip_socket_refused_under_local_only_scopes(scope):
+ ctx = _ctx(scope)
+ set_active_context(ctx)
+ try:
+ with pytest.raises(PolicyDeniedError):
+ _audit_hook("socket.connect", (_IPv4Socket(), ("198.18.3.4", 443)))
+ finally:
+ clear_active_context()
+
+
+def test_fake_ip_endpoint_does_not_make_private_engine_eligible():
+ setting = "search.engine.web.paperless.default_params.api_url"
+ snapshot = {
+ "policy.egress_scope": "adaptive",
+ setting: "https://paper.fakeip.test/api",
+ }
+ with patch(
+ "local_deep_research.security.egress.policy._resolve_with_timeout",
+ return_value=_fake_ip_answers("198.18.3.4"),
+ ):
+ ctx = context_from_snapshot(snapshot, "paperless")
+ classification = classify_engine(
+ "paperless", ctx, settings_snapshot=snapshot
+ )
+ decision = evaluate_engine("paperless", ctx, settings_snapshot=snapshot)
+
+ assert ctx.scope == EgressScope.PRIVATE_ONLY
+ assert ctx.require_local_llm and ctx.require_local_embeddings
+ assert classification.is_public is False
+ assert classification.is_local is False
+ assert not decision.allowed
+
+
[email protected]("other_host", ["10.0.0.42", "8.8.8.8"])
+def test_fake_ip_endpoint_in_engine_host_list_is_not_ignored(other_host):
+ snapshot = {
+ "search.engine.web.elasticsearch.default_params.hosts": [
+ f"http://{other_host}:9200",
+ "http://198.18.3.4:9200",
+ ]
+ }
+ ctx = _ctx(EgressScope.PRIVATE_ONLY)
+
+ classification = classify_engine(
+ "elasticsearch", ctx, settings_snapshot=snapshot
+ )
+ decision = evaluate_engine("elasticsearch", ctx, settings_snapshot=snapshot)
+
+ assert classification.is_local is False
+ assert classification.is_public is False
+ assert not decision.allowed
+
+
+class _IPv4Socket:
+ family = socket.AF_INET
+
+
+def _connect_through_socket_guard(ctx: EgressContext, address: str) -> None:
+ set_active_context(ctx)
+ try:
+ _audit_hook("socket.connect", (_IPv4Socket(), (address, 8000)))
+ finally:
+ clear_active_context()
+
+
[email protected]("scope", ["strict", "private_only"])
+def test_declared_address_admits_a_real_local_service_at_the_socket_guard(
+ scope,
+):
+ """The documented remedy for a real local service at a fixed address in
+ 198.18.0.0/15: declare that address, and the hostname it is configured
+ by. The socket guard sees only the address a connection goes to."""
+ snapshot = {
+ "policy.egress_scope": scope,
+ "llm.allowed_local_hostnames": ["paper.lab.test", "198.18.3.4"],
+ "search.engine.web.paperless.default_params.api_url": (
+ "http://paper.lab.test:8000/api"
+ ),
+ }
+ with patch(
+ "local_deep_research.security.egress.policy._resolve_with_timeout",
+ return_value=_fake_ip_answers("198.18.3.4"),
+ ):
+ ctx = context_from_snapshot(snapshot, "paperless")
+ assert ctx.scope.value == scope
+ assert evaluate_engine(
+ "paperless", ctx, settings_snapshot=snapshot
+ ).allowed
+ assert evaluate_url("http://paper.lab.test:8000/api", ctx).allowed
+ assert evaluate_url("http://198.18.3.4:8000/api", ctx).allowed
+ _connect_through_socket_guard(ctx, "198.18.3.4")
+
+
[email protected]("scope", ["strict", "private_only"])
+def test_declared_hostname_alone_is_refused_at_the_socket_guard(scope):
+ """A declared name stays local at URL checks, but under Strict and
+ Private only the socket guard checks the address it resolves to. That
+ address must be declared too (docs/egress-modes.md)."""
+ ctx = context_from_snapshot(
+ {
+ "policy.egress_scope": scope,
+ "llm.allowed_local_hostnames": ["paper.fakeip.test"],
+ },
+ "paperless",
+ )
+ with patch(
+ "local_deep_research.security.egress.policy._resolve_with_timeout",
+ return_value=_fake_ip_answers("198.18.3.4"),
+ ):
+ assert evaluate_url("https://paper.fakeip.test/api", ctx).allowed
+ with pytest.raises(PolicyDeniedError):
+ _connect_through_socket_guard(ctx, "198.18.3.4")
+
+
+def test_allowed_local_hostnames_accepts_an_address_in_the_fake_ip_range():
+ def answer_itself(host):
+ return _fake_ip_answers(host)
+
+ key = "llm.allowed_local_hostnames"
+ with (
+ patch(
+ "local_deep_research.security.egress.validators._resolve_with_timeout",
+ side_effect=answer_itself,
+ ),
+ patch(
+ "local_deep_research.security.egress.policy._resolve_with_timeout",
+ side_effect=answer_itself,
+ ),
+ ):
+ assert (
+ validate_allowed_local_hostnames({key: ["198.18.3.4"]}, {}) is None
+ )
+ rejected = validate_allowed_local_hostnames({key: ["8.8.8.8"]}, {})
+ assert rejected is not None
+ assert "8.8.8.8" in rejected["error"]
+
+
+def test_unprotected_still_allows_fake_ip_range():
+ ctx = _ctx(EgressScope.UNPROTECTED)
+ assert evaluate_url("http://198.18.0.7/", ctx).allowed
+
+
+# NAT64 literals per RFC 6052: the well-known /96 prefix carries the IPv4 in
+# the low 32 bits; the RFC 8215 local-use /48 prefix splits it around the
+# reserved byte 8 (bytes 6, 7, 9 and 10).
+_NAT64_FAKE_IPS = ["64:ff9b::198.18.0.7", "64:ff9b:1:c612:0:700::"]
+_NAT64_RFC1918 = ["64:ff9b::10.0.0.5", "64:ff9b:1:a00:0:500::"]
+_NAT64_LOCAL_USE_PUBLIC = "64:ff9b:1:808:8:800::" # 8.8.8.8
+_PROTECTED_SCOPES = [
+ EgressScope.STRICT,
+ EgressScope.PRIVATE_ONLY,
+ EgressScope.PUBLIC_ONLY,
+ EgressScope.BOTH,
+]
+
+
+class _IPv6Socket:
+ family = socket.AF_INET6
+
+
+def nat64_allowed(monkeypatch):
+ """The DNS64+NAT64 deployment ``LDR_SECURITY_ALLOW_NAT64`` exists for."""
+ monkeypatch.setenv("LDR_SECURITY_ALLOW_NAT64", "true")
+
+
[email protected]("scope", _PROTECTED_SCOPES, ids=lambda s: s.value)
[email protected]("host", _NAT64_FAKE_IPS)
+def test_nat64_wrapped_fake_ip_is_unknown_and_refused(
+ nat64_allowed, host, scope
+):
+ """With NAT64 allowed the SSRF check admits a wrapped fake IP, so the
+ policy must keep it as ambiguous as the bare address."""
+ url = f"http://[{host}]/story"
+ assert validate_url(url, allow_private_ips=False)
+ ctx = _ctx(scope)
+
+ assert _classify_host(host, ctx) is None
+ assert host_not_classified_public(url, ctx)
+ assert not evaluate_url(url, ctx).allowed
+
+
[email protected]("host", _NAT64_RFC1918)
+def test_nat64_wrapped_rfc1918_classifies_private(nat64_allowed, host):
+ url = f"http://[{host}]/"
+
+ assert _classify_host(host, _ctx(EgressScope.PRIVATE_ONLY)) is True
+ assert evaluate_url(url, _ctx(EgressScope.PRIVATE_ONLY)).allowed
+ decision = evaluate_url(url, _ctx(EgressScope.PUBLIC_ONLY))
+ assert decision.reason == "scope_mismatch_public_only"
+
+
+ "scope",
+ [EgressScope.STRICT, EgressScope.PRIVATE_ONLY],
+ ids=lambda s: s.value,
+)
+ ("host", "expected"),
+ [(_NAT64_FAKE_IPS[1], None), (_NAT64_LOCAL_USE_PUBLIC, False)],
+ ids=["fake_ip", "public"],
+)
+def test_nat64_local_use_prefix_does_not_make_payload_local(
+ nat64_allowed, host, expected, scope
+):
+ """Current Python releases count 64:ff9b:1::/48 as private whatever it
+ carries. The embedded IPv4 decides, at the policy check and at the
+ socket guard."""
+ ctx = _ctx(scope)
+
+ assert _classify_host(host, ctx) is expected
+ assert not evaluate_url(f"http://[{host}]/", ctx).allowed
+ set_active_context(ctx)
+ try:
+ with pytest.raises(PolicyDeniedError):
+ _audit_hook("socket.connect", (_IPv6Socket(), (host, 443, 0, 0)))
+ finally:
+ clear_active_context()
+
+
+ ("answer", "expected"),
+ [
+ ("64:ff9b::198.18.3.4", None),
+ ("64:ff9b::10.0.0.42", True),
+ (_NAT64_LOCAL_USE_PUBLIC, False),
+ ],
+ ids=["fake_ip", "rfc1918", "public"],
+)
+def test_dns64_answers_classify_by_embedded_ipv4(
+ nat64_allowed, answer, expected
+):
+ ctx = _ctx(EgressScope.PRIVATE_ONLY)
+ with patch(
+ "local_deep_research.security.egress.policy._resolve_with_timeout",
+ return_value=[
+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", (answer, 0, 0, 0))
+ ],
+ ):
+ assert _classify_host("dns64.example.test", ctx) is expected
+
+
[email protected]("scope", _PROTECTED_SCOPES, ids=lambda s: s.value)
+def test_nat64_literals_stay_refused_when_nat64_is_disabled(monkeypatch, scope):
+ monkeypatch.setenv("LDR_SECURITY_ALLOW_NAT64", "false")
+ for host in [*_NAT64_FAKE_IPS, *_NAT64_RFC1918, _NAT64_LOCAL_USE_PUBLIC]:
+ assert not evaluate_url(f"http://[{host}]/", _ctx(scope)).allowed
diff --git a/tests/security/test_egress_fullsearch.py b/tests/security/test_egress_fullsearch.py
index eda8f67921..499df685a4 100644
--- a/tests/security/test_egress_fullsearch.py
+++ b/tests/security/test_egress_fullsearch.py
@@ -660,7 +660,7 @@ def test_grant_withheld_is_logged_once_per_wrapper(monkeypatch):
# ===========================================================================
-# Private hosts the SSRF validator admits but the policy classifies private
+# Hosts the SSRF validator admits but the policy does not classify public
# are refused uncounted too, under every scope but ``unprotected``: the
# wrapper asks the policy's own classifier (``host_not_classified_public``),
# not a second, narrower list
@@ -668,11 +668,10 @@ def test_grant_withheld_is_logged_once_per_wrapper(monkeypatch):
# Each host passes ``validate_url`` with the grant withheld (the SSRF
# validator's PRIVATE_IP_RANGES does not list it) yet ``_classify_host``
-# (``ipaddress.is_private``) classifies it private, so under ``public_only``
-# ``evaluate_url`` refuses it as ``scope_mismatch_public_only`` and counts
-# it, and under ``strict`` / ``private_only`` / ``both`` ``evaluate_url``
-# ADMITS it.
-_SSRF_ADMITTED_POLICY_PRIVATE_HOSTS = [
+# does not classify it public. The fake-IP range is ambiguous; the other
+# ranges are private. The wrapper refuses them before ``evaluate_url`` so
+# no scope's denied-fetch quota is spent.
+_SSRF_ADMITTED_NONPUBLIC_HOSTS = [
"198.18.0.7", # benchmarking range; fake-ip DNS (Clash, sing-box)
"192.0.2.10", # TEST-NET-1
"198.51.100.7", # TEST-NET-2
@@ -711,9 +710,9 @@ def _run_quota_batch(monkeypatch, method, links, scope=EgressScope.PUBLIC_ONLY):
return ctx, fetched, {r["link"]: r["full_content"] for r in out}
[email protected]("host", _SSRF_ADMITTED_POLICY_PRIVATE_HOSTS)
[email protected]("host", _SSRF_ADMITTED_NONPUBLIC_HOSTS)
@pytest.mark.parametrize("method", ["run", "_get_full_content"])
-def test_ssrf_admitted_private_results_do_not_spend_denial_quota(
+def test_ssrf_admitted_nonpublic_results_do_not_spend_denial_quota(
monkeypatch, host, method
):
ctx, fetched, by_link = _run_quota_batch(
@@ -726,30 +725,48 @@ def test_ssrf_admitted_private_results_do_not_spend_denial_quota(
assert all(v is None for k, v in by_link.items() if k != _PUBLIC_URL)
+ "nat64_host",
+ [
+ "[64:ff9b::198.18.0.7]", # fake IP, RFC 6052 well-known /96
+ "[64:ff9b:1:c612:0:700::]", # 198.18.0.7, RFC 8215 local-use /48
+ "[64:ff9b::192.0.2.10]", # TEST-NET-1, /96
+ ],
+)
@pytest.mark.parametrize("method", ["run", "_get_full_content"])
-def test_nat64_local_use_results_do_not_spend_denial_quota(monkeypatch, method):
- """With ``LDR_SECURITY_ALLOW_NAT64`` set, a 64:ff9b:1::/48 (RFC 8215)
- wrap of a public IPv4 passes the SSRF validator but classifies private."""
- import ipaddress
-
- # Python's ``ipaddress`` lists 64:ff9b:1::/48 as private only in newer
- # releases (3.12.4+, 3.13+); where it does not, the policy classifies
- # the address public and there is nothing private to refuse.
- if not ipaddress.ip_address("64:ff9b:1::1").is_private:
- pytest.skip(
- "this Python's ipaddress does not treat 64:ff9b:1::/48 as private"
- )
+def test_nat64_wrapped_nonpublic_results_do_not_spend_denial_quota(
+ monkeypatch, nat64_host, method
+):
+ """With ``LDR_SECURITY_ALLOW_NAT64`` set, the SSRF validator admits a
+ NAT64 wrap of an address it admits. The policy classifies the embedded
+ IPv4, so the wrapped form is refused uncounted like the bare one."""
monkeypatch.setenv("LDR_SECURITY_ALLOW_NAT64", "true")
- # 93.184.216.34 embedded at the RFC 6052 /48 byte positions.
- nat64 = "http://[64:ff9b:1:5db8:d8:2200::]/"
- assert fs.validate_url(
- nat64, allow_private_ips=False, block_link_local=True
- )
+ link = f"http://{nat64_host}/"
+ assert fs.validate_url(link, allow_private_ips=False, block_link_local=True)
- ctx, fetched, _ = _run_quota_batch(monkeypatch, method, [nat64])
+ ctx, fetched, by_link = _run_quota_batch(monkeypatch, method, [link])
assert ctx._fetch_denial_count["count"] == 0
assert fetched["urls"] == [_PUBLIC_URL]
+ assert all(v is None for k, v in by_link.items() if k != _PUBLIC_URL)
+
+
[email protected]("method", ["run", "_get_full_content"])
+def test_nat64_local_use_wrap_of_public_ipv4_is_a_public_result(
+ monkeypatch, method
+):
+ """Current Python releases count 64:ff9b:1::/48 (RFC 8215) as private
+ whatever it carries; the policy follows the embedded IPv4, so a public
+ payload is fetched under ``public_only`` like the bare address."""
+ monkeypatch.setenv("LDR_SECURITY_ALLOW_NAT64", "true")
+ # 93.184.216.34 embedded at the RFC 6052 /48 byte positions.
+ link = "http://[64:ff9b:1:5db8:d8:2200::]/"
+
+ ctx, fetched, by_link = _run_quota_batch(monkeypatch, method, [link])
+
+ assert ctx._fetch_denial_count["count"] == 0
+ assert sorted(fetched["urls"]) == sorted(by_link)
+ assert set(by_link.values()) == {"content"}
def _patch_fake_ip_dns(monkeypatch):
@@ -772,8 +789,8 @@ def _patch_fake_ip_dns(monkeypatch):
@pytest.mark.parametrize("method", ["run", "_get_full_content"])
def test_fake_ip_dns_results_do_not_spend_denial_quota(monkeypatch, method):
"""Hostnames that resolve into 198.18.0.0/15 (a fake-ip resolver, or a
- hostile A record) pass the SSRF validator's DNS check and classify
- private through the policy's own DNS path: refused, uncounted."""
+ hostile A record) pass the SSRF validator's DNS check but remain
+ unclassified through the policy's own DNS path: refused, uncounted."""
_patch_fake_ip_dns(monkeypatch)
ctx, fetched, _ = _run_quota_batch(
@@ -786,7 +803,28 @@ def test_fake_ip_dns_results_do_not_spend_denial_quota(monkeypatch, method):
assert fetched["urls"] == [_PUBLIC_URL]
-_SCOPES_ADMITTING_POLICY_PRIVATE_HOSTS = [
+def test_fake_ip_refusal_audit_reason_names_a_nonpublic_host(monkeypatch):
+ """The uncounted refusal covers ambiguous (fake-IP) hosts as well as
+ private ones, so its audit reason says "nonpublic", not "private"."""
+ _patch_fake_ip_dns(monkeypatch)
+ records = []
+ logger.enable("local_deep_research")
+ sink_id = logger.add(lambda m: records.append(m.record), level="WARNING")
+ try:
+ _run_quota_batch(monkeypatch, "run", ["http://h0.fakeip.test/"])
+ finally:
+ logger.remove(sink_id)
+ logger.disable("local_deep_research")
+
+ reasons = {
+ r["extra"].get("reason")
+ for r in records
+ if r["extra"].get("policy_audit") and "url" in r["extra"]
+ }
+ assert reasons == {"nonpublic_result_host_public_only"}
+
+
+_SCOPES_WITH_PRIVATE_HOST_FETCHES = [
EgressScope.STRICT,
EgressScope.PRIVATE_ONLY,
EgressScope.BOTH,
@@ -820,19 +858,17 @@ def _fetch_one(monkeypatch, method, link, ctx, grant=True):
@pytest.mark.parametrize("grant", [True, False], ids=["grant", "no_grant"])
@pytest.mark.parametrize(
- "scope", _SCOPES_ADMITTING_POLICY_PRIVATE_HOSTS, ids=lambda s: s.value
+ "scope", _SCOPES_WITH_PRIVATE_HOST_FETCHES, ids=lambda s: s.value
)
[email protected]("host", _SSRF_ADMITTED_POLICY_PRIVATE_HOSTS)
[email protected]("host", _SSRF_ADMITTED_NONPUBLIC_HOSTS)
@pytest.mark.parametrize("method", ["run", "_get_full_content"])
-def test_ssrf_admitted_private_results_stay_blocked_under_protected_scopes(
+def test_ssrf_admitted_nonpublic_results_stay_blocked_under_protected_scopes(
monkeypatch, host, scope, grant, method
):
- """``evaluate_url`` ADMITS these policy-private hosts under ``strict``
- / ``private_only`` / ``both``, and the SSRF check admits them too, so
- without the wrapper's own refusal they would be fetched although
- private result URLs stay blocked under every scope but ``unprotected``.
- Refused before ``evaluate_url``, uncounted, with or without the
- (withheld) grant."""
+ """The SSRF check admits these addresses; evaluate_url admits the
+ private ranges under strict/private_only/both but now refuses ambiguous
+ fake-IP addresses. The wrapper refuses all non-public result URLs before
+ evaluate_url, uncounted, with or without the withheld grant."""
ctx = _make_ctx(scope)
link = f"http://{host}/page"
assert fs.validate_url(link, allow_private_ips=False, block_link_local=True)
@@ -846,9 +882,8 @@ def test_ssrf_admitted_private_results_stay_blocked_under_protected_scopes(
@pytest.mark.parametrize("method", ["run", "_get_full_content"])
def test_fake_ip_public_hosts_are_not_fetched_under_strict(monkeypatch, method):
"""Under fake-IP DNS a public name resolves into 198.18.0.0/15 and the
- policy classifies it private, so ``evaluate_url`` would ADMIT it under
- ``strict``. The wrapper refuses it (uncounted) instead of fetching the
- public page."""
+ policy cannot tell whether it is public or local. The wrapper refuses it
+ (uncounted) instead of fetching the public page."""
_patch_fake_ip_dns(monkeypatch)
ctx = _make_ctx(EgressScope.STRICT)
diff --git a/tests/security/test_egress_run_classification.py b/tests/security/test_egress_run_classification.py
index 2184bd00e1..cc7677dbdb 100644
--- a/tests/security/test_egress_run_classification.py
+++ b/tests/security/test_egress_run_classification.py
@@ -82,6 +82,22 @@ def test_local_store_fails_up_to_exposing_on_public_url():
assert rc.engine_label("paperless", {}, ctx()) == Label(S, EXP)
+def test_local_store_at_a_fake_ip_address_fails_up_to_exposing():
+ # 198.18.0.0/15 may be a proxy's stand-in for a public host, so the policy
+ # cannot call the endpoint local: ``classify_engine`` withholds the store
+ # and the label must not claim it stays on the box.
+ snapshot = {_LocalStore.url_setting: "http://198.18.3.4:8000"}
+ with patch(f"{POLICY}._get_engine_class", return_value=_LocalStore):
+ assert rc.engine_label("paperless", snapshot, ctx()) == Label(S, EXP)
+
+
+def test_local_store_without_a_configured_url_stays_contained():
+ # Nothing is configured, so there is no endpoint to rate and the policy
+ # keeps the store's static classification.
+ with patch(f"{POLICY}._get_engine_class", return_value=_LocalStore):
+ assert rc.engine_label("paperless", {}, ctx()) == Label(S, CON)
+
+
# ---------------------------------------------------------------------------
# engine_label — collections / library (sensitivity from is_public)
# ---------------------------------------------------------------------------
diff --git a/tests/security/test_egress_transport_scope_v2.py b/tests/security/test_egress_transport_scope_v2.py
index b0203ab3a7..a7e3884557 100644
--- a/tests/security/test_egress_transport_scope_v2.py
+++ b/tests/security/test_egress_transport_scope_v2.py
@@ -283,6 +283,31 @@ def test_content_fetcher_attaches_run_context_to_downloader_session():
downloader.close()
+ "scope", [EgressScope.PRIVATE_ONLY, EgressScope.BOTH], ids=lambda s: s.value
+)
+def test_browser_child_built_through_parent_carries_run_context(scope):
+ """The lazily built browser child has its own SafeSession for robots.txt
+ and its guards. Built through the parent, that session must carry the
+ run's context, so the child's own requests stay under the run scope."""
+ ctx = _context(scope)
+ downloader = ContentFetcher(egress_context=ctx)._get_downloader(
+ URLType.HTML
+ )
+ try:
+ child = downloader._get_playwright_downloader()
+ assert child.session is not downloader.session
+ assert child.session.egress_context is ctx
+ with (
+ patch.object(requests.Session, "send") as transport,
+ pytest.raises(PolicyDeniedError),
+ ):
+ child.session.get("http://198.18.0.7/robots.txt")
+ transport.assert_not_called()
+ finally:
+ downloader.close()
+
+
@pytest.mark.parametrize(
("scope", "expected"),
[