~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(security): block more cloud-metadata addresses (Azure WireServer, GCP, EKS, Scaleway, Akamai, OCI, OpenStack) (#7770)
LearningCircuitc89a1427dc1e
diff --git a/.pre-commit-hooks/check-docs-attack-payloads.py b/.pre-commit-hooks/check-docs-attack-payloads.pyindex b876680dc2..8bfb233b8a 100755--- a/.pre-commit-hooks/check-docs-attack-payloads.py+++ b/.pre-commit-hooks/check-docs-attack-payloads.py@@ -42,6 +42,10 @@ _HOST_PAYLOAD = re.compile(169\.254\.\d{1,3}\.\d{1,3} # IPv4 link-local / AWS IMDS| fe80::[0-9a-f:]* # IPv6 link-local| fd00:ec2::[0-9a-f:]* # AWS IMDS over IPv6+ | fd20:ce::[0-9a-f:]* # GCP metadata over IPv6+ | fd00:42::[0-9a-f:]* # Scaleway metadata over IPv6+ | fd00:a9fe:[0-9a-f:]* # Akamai / Linode metadata over IPv6+ | fd00:c1::[0-9a-f:]* # OCI IMDS over IPv6| metadata\.google\.internal| metadata\.goog)""",diff --git a/SECURITY.md b/SECURITY.mdindex 04ade664d7..6d9acba31c 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -184,17 +184,27 @@ Both `ssrf_validator.validate_url` and `NotificationURLValidator.validate_servic| --- | --- || `169.254.169.254` | AWS IMDSv1/v2, Azure, OCI, DigitalOcean (shared) || `169.254.170.2` | AWS ECS task metadata v3 |-| `169.254.170.23` | AWS ECS task metadata v4 |+| `169.254.170.23` | AWS EKS Pod Identity credentials || `169.254.0.23` | Tencent Cloud || `100.100.100.200` | AlibabaCloud || `fd00:ec2::254` | AWS IMDS over IPv6 || `192.0.0.192` | Oracle Compute Classic / Cloud at Customer |+| `168.63.129.16` | Azure WireServer / host agent endpoint |+| `fd20:ce::254` | GCP metadata server over IPv6 (IPv6-only instances) |+| `fd00:ec2::23` | AWS EKS Pod Identity credentials over IPv6 |+| `169.254.42.42` | Scaleway instance metadata |+| `fd00:42::42` | Scaleway instance metadata over IPv6 |+| `fd00:a9fe:a9fe::1` | Akamai / Linode metadata over IPv6 |+| `fd00:c1::a9fe:a9fe` | Oracle Cloud (OCI) IMDS over IPv6 |+| `fe80::a9fe:a9fe` | OpenStack Nova / Hetzner metadata over IPv6 |`fd00:ec2::254` is AWS's native IPv6 instance-metadata endpoint. It is a ULA (`fc00::/7`), **not** an IPv4-mapped or NAT64-wrapped form of `169.254.169.254`, so it is not covered by the IPv4 entries or the NAT64 embedded-IPv4 check above and must be listed explicitly — otherwise it stays reachable under `allow_private_ips=True`, which permits the whole `fc00::/7` range. Entries are matched by canonical string form (`is_ip_blocked` parses the candidate with `ipaddress.ip_address` first), so uppercase / zero-padded / expanded variants all normalise to the listed form before the membership test.+`168.63.129.16` is Azure's WireServer (host agent) address. It is public address space, so no private-range check catches it and it must be listed explicitly. Azure also serves platform DNS from this address; the block applies only to URL destinations that LDR validates, not to the operating system's DNS resolver, so name resolution on Azure VMs is unaffected. `fd20:ce::254` is the GCP metadata server's IPv6 address (IPv6-only instances). Like `fd00:ec2::254` it is a ULA, so it is listed explicitly to stay blocked under `allow_private_ips=True`. `fd00:ec2::23` is the IPv6 form of the EKS Pod Identity Agent credentials endpoint (`169.254.170.23`) and is a ULA for the same reason. The Scaleway, Akamai / Linode and OCI IPv6 endpoints are ULAs too. `169.254.42.42` and `fe80::a9fe:a9fe` are link-local; they are listed explicitly because the LLM provider guard accepts link-local (see "LLM Provider URL Validation"), and IPv6 zone identifiers (`fe80::a9fe:a9fe%eth0`) are stripped before the membership test.+The block also catches IPv6-wrapped forms of the IPv4 metadata IPs. When an IPv6 destination falls in a NAT64 prefix (`64:ff9b::/96` RFC 6052 well-known or `64:ff9b:1::/48` RFC 8215 local-use), the validator extracts the embedded IPv4 from the low 32 bits and matches it against this set — so `[64:ff9b::a9fe:a9fe]` cannot reach `169.254.169.254` even on a host with NAT64 routes configured. The check fires before any opt-in carve-out, so the operator switch described below cannot license IMDS exposure.-Both `ssrf_validator.is_ip_blocked` and `NotificationURLValidator.validate_service_url` enforce this absolutely, including under `allow_private_ips=True`. The latter flag is an operator opt-in for self-hosted webhooks on internal networks (RFC1918, CGNAT, loopback, IPv6 ULA); it does NOT extend to metadata IPs, NAT64-wrapped metadata, or the link-local range. Both validators delegate to the same `is_ip_blocked` helper to keep the absolute-block invariant in lockstep. The two differ on link-local: `NotificationURLValidator` blocks the *entire* link-local range (IPv4 `169.254.0.0/16`, IPv6 `fe80::/10`) for every host-bearing notification destination, `http(s)://` included, even under `allow_private_ips=True` (it passes `block_link_local=True` to `is_ip_blocked`), because cloud metadata is served across link-local beyond the always-blocked literals (e.g. Scaleway at `169.254.42.42`) -- see "Notification Webhook SSRF" above. `is_ip_blocked`'s own default is unchanged: link-local remains allowed under `allow_private_ips=True` for the general fetch/LLM paths that do not pass `block_link_local=True`.+Both `ssrf_validator.is_ip_blocked` and `NotificationURLValidator.validate_service_url` enforce this absolutely, including under `allow_private_ips=True`. The latter flag is an operator opt-in for self-hosted webhooks on internal networks (RFC1918, CGNAT, loopback, IPv6 ULA); it does NOT extend to metadata IPs, NAT64-wrapped metadata, or the link-local range. Both validators delegate to the same `is_ip_blocked` helper to keep the absolute-block invariant in lockstep. The two differ on link-local: `NotificationURLValidator` blocks the *entire* link-local range (IPv4 `169.254.0.0/16`, IPv6 `fe80::/10`) for every host-bearing notification destination, `http(s)://` included, even under `allow_private_ips=True` (it passes `block_link_local=True` to `is_ip_blocked`), because cloud metadata can be served across link-local beyond the always-blocked literals -- see "Notification Webhook SSRF" above. Egress-policy host classification, `PRIVATE_ONLY` content fetching (`egress/fetch.py`), search-result full-content fetching (`full_search.py`) and its content-cache check (`search_engine_base.py`), and the request-boundary custom LLM endpoint check (`url_utils.is_safe_custom_llm_endpoint`) also pass `block_link_local=True`. The private search-engine instance-URL checks (SearXNG, Paperless, Elasticsearch) do not: link-local is allowed there under the private-engine opt-in (see `docs/CONFIGURATION.md`). `is_ip_blocked`'s own default is unchanged: link-local remains allowed under `allow_private_ips=True` for callers that do not pass the flag — notably the LLM / embedding provider guard described under "LLM Provider URL Validation" below.Future contributors must not remove entries from this set. Adding a new cloud provider's metadata IP is encouraged when a new public-cloud target appears.@@ -224,6 +234,8 @@ Operator-configured LLM endpoints (`llm.ollama.url`, `llm.lmstudio.url`, `llm.llThe guard uses `allow_localhost=True, allow_private_ips=True` because the legitimate destinations for these providers are localhost (Ollama, LM Studio, llama.cpp) and RFC1918 (Docker / private network deployments). The `ALWAYS_BLOCKED_METADATA_IPS` set still fires under those flags, so cloud-credential endpoints stay blocked regardless of the operator's settings.+The guard does **not** pass `block_link_local=True`, so link-local destinations (IPv4 `169.254.0.0/16`, IPv6 `fe80::/10`) are accepted for provider URLs. The reason is Podman's link-local mapping: rootless Podman 5.3+ (pasta) maps `host.containers.internal` to `169.254.1.2`, and under Podman the `host-gateway` value the bundled `docker-compose.yml` uses for `host.docker.internal` resolves to the same address, so a host-side Ollama / LM Studio backend is reached over link-local. Docker's own `host-gateway` and Docker Desktop's `host.docker.internal` are not link-local. Documented metadata literals in `ALWAYS_BLOCKED_METADATA_IPS`, including the link-local ones, stay blocked.+Caveats:- Settings-write access already implies arbitrary-URL exfil and RFC1918 reachability — the guard prevents only the cloud-credential-endpoint pivot, not exfil to public attacker-controlled hosts (the configured `Authorization: Bearer …` header would still go to the attacker if they swapped the URL).- DNS rebinding TOCTOU applies: the guard validates once at provider construction, but the SDK re-resolves the hostname on every inference call. Same accepted-risk rationale as elsewhere in the project — egress restriction at the firewall is the operator-side mitigation.diff --git a/changelog.d/+metadata-ip-additions.security.md b/changelog.d/+metadata-ip-additions.security.mdnew file mode 100644index 0000000000..1fcd631a40--- /dev/null+++ b/changelog.d/+metadata-ip-additions.security.md@@ -0,0 +1 @@+The SSRF validator now always blocks more cloud-metadata addresses, under every flag combination including `allow_private_ips=True`: Azure WireServer (`168.63.129.16`), GCP over IPv6 (`fd20:ce::254`), AWS EKS Pod Identity over IPv6 (`fd00:ec2::23`), Scaleway (`169.254.42.42`, `fd00:42::42`), Akamai / Linode over IPv6 (`fd00:a9fe:a9fe::1`), Oracle Cloud over IPv6 (`fd00:c1::a9fe:a9fe`) and OpenStack / Hetzner over IPv6 (`fe80::a9fe:a9fe`). Every consumer of the shared metadata block list picks this up, including stored LLM and embedding provider URLs and content fetching.diff --git a/docs/NOTIFICATIONS.md b/docs/NOTIFICATIONS.mdindex 3c8acd048a..d3f8854ec1 100644--- a/docs/NOTIFICATIONS.md+++ b/docs/NOTIFICATIONS.md@@ -303,7 +303,7 @@ The "Test" button in the notifications settings page returns the validator's rea**"Blocked cloud-metadata / link-local IP address: \<host\>"**- **Cause**: A host-bearing notification URL names a cloud-metadata or link-local endpoint. Literal addresses are checked directly; hostnames get one bounded validation-time resolution and are checked again at send time. Fixed-destination token/topic modes (Discord, Slack, ntfy cloud, Matrix t2bot and Telegram) are not resolved as user-supplied hosts.-- **Always blocked**: AWS IMDS / ECS, Azure, OCI, DigitalOcean, AlibabaCloud, Tencent — both as plain IPv4 and wrapped through any NAT64 prefix. No env var re-opens these. See [SECURITY.md](../SECURITY.md#cloud-metadata-endpoint-block-list). The rest of the link-local range is blocked for every notification URL as well; `LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS` does not reopen it.+- **Always blocked**: AWS IMDS / ECS / EKS Pod Identity, Azure IMDS and WireServer, GCP, OCI, Scaleway, Akamai / Linode, OpenStack / Hetzner, DigitalOcean, AlibabaCloud, Tencent — as plain addresses (IPv4 and IPv6) and, for the IPv4 ones, wrapped through any NAT64 prefix. No env var re-opens these. See [SECURITY.md](../SECURITY.md#cloud-metadata-endpoint-block-list). The rest of the link-local range is blocked for every notification URL as well; `LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS` does not reopen it.- **Fix**: Choose a different webhook destination. Metadata endpoints expose IAM/instance credentials and are never legitimate webhook targets.**"Blocked unsafe protocol: \<scheme\>"** / **"Unsupported protocol: \<scheme\>"**diff --git a/docs/SearXNG-Setup.md b/docs/SearXNG-Setup.mdindex cc2bbed42c..b28c74908a 100644--- a/docs/SearXNG-Setup.md+++ b/docs/SearXNG-Setup.md@@ -203,8 +203,9 @@ three ways:Regardless of which option is used:-- **Cloud metadata endpoints** (AWS IMDS / ECS, Azure, OCI, DigitalOcean,- AlibabaCloud, Tencent Cloud — see+- **Cloud metadata endpoints** (AWS IMDS / ECS / EKS Pod Identity, Azure IMDS+ and WireServer, GCP, OCI, Scaleway, Akamai / Linode, OpenStack / Hetzner,+ DigitalOcean, AlibabaCloud, Tencent Cloud — see`ssrf_validator.ALWAYS_BLOCKED_METADATA_IPS`) are always blocked to preventcredential theft in cloud environments- Only `http`/`https` URLs are accepted — other schemes are always refuseddiff --git a/src/local_deep_research/security/dns_pinning.py b/src/local_deep_research/security/dns_pinning.pyindex 2c524373e0..bc794d9b3c 100644--- a/src/local_deep_research/security/dns_pinning.py+++ b/src/local_deep_research/security/dns_pinning.py@@ -717,7 +717,7 @@ def block_private_resolution(``block_link_local`` (every notification partition): when True, thewhole link-local range stays refused even under ``allow_private_ips=True``— closing metadata reachable in link-local beyond the always-blocked- literals (e.g. Scaleway ``169.254.42.42``) without over-blocking RFC1918 /+ literals without over-blocking RFC1918 /loopback / non-link-local ULA self-hosted notifiers.This closes redirect-to-internal / rebind-to-metadata for hosts thatdiff --git a/src/local_deep_research/security/egress/fetch.py b/src/local_deep_research/security/egress/fetch.pyindex 5d1057e5fa..cf0a67fdca 100644--- a/src/local_deep_research/security/egress/fetch.py+++ b/src/local_deep_research/security/egress/fetch.py@@ -28,8 +28,8 @@ def policy_aware_validate_url(url: str, egress_context=None) -> bool:``block_link_local=True`` is DEFENSE IN DEPTH, not a fix for a knownexploit. ``ALWAYS_BLOCKED_METADATA_IPS`` covers known literal metadataaddresses; the rest of 169.254.0.0/16 (and fe80::/10) is not a- deliberate service range, but it does host provider-specific metadata- endpoints outside that list -- Scaleway's 169.254.42.42, for one. A+ deliberate service range, and provider-specific metadata endpoints+ not yet in that list may live there. APRIVATE_ONLY run is meant to reach a lab box on 192.168.x or127.0.0.1, never an auto-configuration address, so excluding therange costs nothing real and removes a class of target.diff --git a/src/local_deep_research/security/notification_validator.py b/src/local_deep_research/security/notification_validator.pyindex 827608add1..09c1bea64c 100644--- a/src/local_deep_research/security/notification_validator.py+++ b/src/local_deep_research/security/notification_validator.py@@ -1177,7 +1177,7 @@ class NotificationURLValidator:# even with the private-IP opt-in. Apprise turns some http(s) URLs# into plugins that post to the URL host (Apprise API, Workflows),# and cloud metadata lives across link-local beyond the- # always-blocked literals (Scaleway serves it at 169.254.42.42).+ # always-blocked literals.block_link_local = Trueif resolved_ips is None:try:diff --git a/src/local_deep_research/security/safe_requests.py b/src/local_deep_research/security/safe_requests.pyindex 51e074c795..7fa27d0e53 100644--- a/src/local_deep_research/security/safe_requests.py+++ b/src/local_deep_research/security/safe_requests.py@@ -491,8 +491,9 @@ def safe_get(used by Podman/rootless containers), link-local (169.254.x.x), and IPv6private ranges (fc00::/7, fe80::/10). Use for trusted self-hosted serviceslike SearXNG or Ollama in containerized environments.- Note: cloud metadata endpoints (AWS / Azure / OCI / DigitalOcean /- AlibabaCloud / Tencent / ECS) are ALWAYS blocked — see+ Note: cloud metadata endpoints (AWS / Azure / GCP / OCI /+ Scaleway / Akamai / OpenStack / Hetzner / DigitalOcean /+ AlibabaCloud / Tencent) are ALWAYS blocked — see``ssrf_validator.ALWAYS_BLOCKED_METADATA_IPS``.require_https: Refuse the fetch (and any redirect hop) whose URLis not https://. Opt-in per caller for integrity-sensitive@@ -709,8 +710,9 @@ def safe_post(used by Podman/rootless containers), link-local (169.254.x.x), and IPv6private ranges (fc00::/7, fe80::/10). Use for trusted self-hosted serviceslike SearXNG or Ollama in containerized environments.- Note: cloud metadata endpoints (AWS / Azure / OCI / DigitalOcean /- AlibabaCloud / Tencent / ECS) are ALWAYS blocked — see+ Note: cloud metadata endpoints (AWS / Azure / GCP / OCI /+ Scaleway / Akamai / OpenStack / Hetzner / DigitalOcean /+ AlibabaCloud / Tencent) are ALWAYS blocked — see``ssrf_validator.ALWAYS_BLOCKED_METADATA_IPS``.**kwargs: Additional arguments to pass to requests.post()@@ -947,8 +949,9 @@ class SafeSession(requests.Session):This includes RFC1918, CGNAT (100.64.x.x used by Podman), link-local, andIPv6 private ranges. Use for trusted self-hosted services like SearXNG orOllama in containerized environments.- Note: cloud metadata endpoints (AWS / Azure / OCI / DigitalOcean /- AlibabaCloud / Tencent / ECS) are ALWAYS blocked — see+ Note: cloud metadata endpoints (AWS / Azure / GCP / OCI /+ Scaleway / Akamai / OpenStack / Hetzner / DigitalOcean /+ AlibabaCloud / Tencent) are ALWAYS blocked — see``ssrf_validator.ALWAYS_BLOCKED_METADATA_IPS``.block_link_local: Keep the whole link-local range (IPv4``169.254.0.0/16``, IPv6 ``fe80::/10`` and their NAT64-wrappeddiff --git a/src/local_deep_research/security/ssrf_validator.py b/src/local_deep_research/security/ssrf_validator.pyindex 1c7ed617e4..e0e33f84db 100644--- a/src/local_deep_research/security/ssrf_validator.py+++ b/src/local_deep_research/security/ssrf_validator.py@@ -47,13 +47,17 @@ ALWAYS_BLOCKED_METADATA_IPS = frozenset({"169.254.169.254", # AWS IMDSv1/v2, Azure, OCI, DigitalOcean"169.254.170.2", # AWS ECS task metadata v3- "169.254.170.23", # AWS ECS task metadata v4+ "169.254.170.23", # AWS EKS Pod Identity credentials"169.254.0.23", # Tencent Cloud"100.100.100.200", # AlibabaCloud# Oracle Compute Classic and Cloud at Customer expose instance# metadata here. This address falls outside the explicit private# and link-local ranges, so policy flags must never allow it."192.0.0.192", # Oracle Compute Classic IMDS+ # Azure WireServer: the host-side endpoint Azure VMs use for+ # provisioning and extension settings. It is a public-range address,+ # so neither the private nor the link-local checks catch it.+ "168.63.129.16", # Azure WireServer# AWS native IPv6 IMDS endpoint. Documented by AWS as the IPv6# instance-metadata address ([fd00:ec2::254]). It is a ULA# (fc00::/7), NOT an IPv4-mapped / NAT64-wrapped form of@@ -62,15 +66,35 @@ ALWAYS_BLOCKED_METADATA_IPS = frozenset(# explicitly or it stays reachable under allow_private_ips=True# (which permits fc00::/7)."fd00:ec2::254", # AWS IMDS over IPv6+ "fd00:ec2::23", # AWS EKS Pod Identity credentials over IPv6+ "fd20:ce::254", # GCP metadata server over IPv6+ # Scaleway instance metadata (IPv4 and IPv6). The IPv4 address is+ # link-local, which the LLM provider guard otherwise accepts (rootless+ # Podman maps host.containers.internal into 169.254.0.0/16), so it+ # must be listed explicitly to stay blocked there.+ "169.254.42.42", # Scaleway instance metadata+ "fd00:42::42", # Scaleway instance metadata over IPv6+ # Further IPv6 metadata endpoints. The ULAs are permitted by+ # allow_private_ips=True (fc00::/7) and fe80::a9fe:a9fe by the+ # link-local allowance, so each is listed explicitly. Scope IDs+ # (fe80::a9fe:a9fe%eth0) are stripped before the membership test.+ "fd00:a9fe:a9fe::1", # Akamai / Linode metadata over IPv6+ "fd00:c1::a9fe:a9fe", # Oracle Cloud (OCI) IMDS over IPv6+ "fe80::a9fe:a9fe", # OpenStack Nova / Hetzner metadata over IPv6})-# Link-local ranges. When ``block_link_local`` is set (notification path),+# Link-local ranges. When ``block_link_local`` is set (notification+# validation and send, egress-policy host classification, PRIVATE_ONLY+# content fetching, search-result full-content fetching and the+# content-cache check, and the request-boundary custom LLM endpoint check),# these stay blocked even under ``allow_private_ips=True`` — cloud-provider-# metadata lives here beyond the always-blocked literals and no legitimate-# self-hosted notifier does. Kept as a distinct list (a subset of the private-# ranges) so the carve-out is explicit and testable. Module-level (built once-# at import) rather than rebuilt on every ``is_ip_blocked`` call.+# metadata may live here beyond the always-blocked literals. The LLM+# provider guard (``assert_base_url_safe``) and the private search-engine+# instance-URL checks do not set it. Kept as a distinct list (a subset of+# the private ranges) so the carve-out is explicit and testable.+# Module-level (built once at import) rather than rebuilt on every+# ``is_ip_blocked`` call.# nosec B104 - Hardcoded ranges are intentional for SSRF preventionLINK_LOCAL_RANGES = [ipaddress.ip_network("169.254.0.0/16"), # IPv4 link-local@@ -170,8 +194,8 @@ def is_nat64_wrapped_link_local_ip(ip: ipaddress._BaseAddress) -> bool:Mirrors ``is_nat64_wrapped_metadata_ip`` for the ``block_link_local``notification guard. The ``security.allow_nat64`` opt-in re-opens generalIPv4 reachability via NAT64, but it must not re-open link-local — where- cloud-provider metadata lives beyond the always-blocked literals (e.g.- Scaleway's ``169.254.42.42``). Consulted only when ``block_link_local`` is+ cloud-provider metadata may live beyond the always-blocked literals.+ Consulted only when ``block_link_local`` isset, so non-notification callers (which permit link-local under``allow_private_ips``) keep the opt-in's reachability unchanged."""@@ -206,25 +230,33 @@ def is_ip_blocked(allow_localhost: Whether to allow localhost/loopback addressesallow_private_ips: Whether to allow all private/internal IPs plus localhost.This includes RFC1918 (10.x, 172.16-31.x, 192.168.x), CGNAT (100.64.x.x- used by Podman/rootless containers), link-local (169.254.x.x), and IPv6- private ranges (fc00::/7, fe80::/10). Use for trusted self-hosted services- like SearXNG or Ollama in containerized environments.+ used by Podman/rootless containers), link-local (169.254.x.x,+ fe80::/10 -- unless ``block_link_local`` is set), and IPv6 ULA+ (fc00::/7). Use for trusted self-hosted services such as an+ LLM backend reached via ``host.containers.internal``.Note: cloud metadata endpoints in ``ALWAYS_BLOCKED_METADATA_IPS``- (AWS / Azure / OCI / DigitalOcean / AlibabaCloud / Tencent / ECS)- are ALWAYS blocked regardless of these flags.+ (AWS / Azure / GCP / OCI / Scaleway / Akamai / OpenStack /+ Hetzner / DigitalOcean / AlibabaCloud / Tencent) are ALWAYS+ blocked regardless of these flags.block_link_local: When True, the entire link-local range — IPv4``169.254.0.0/16`` and IPv6 ``fe80::/10`` — is treated as blocked- EVEN under ``allow_private_ips=True``. Used by the notification- send path (see ``security.dns_pinning`` /- ``notification_validator``): the lenient plugin/raw-webhook- partition allows private LAN targets, but link-local is where- cloud-provider metadata lives beyond the always-blocked metadata- literals (e.g. Scaleway's ``169.254.42.42``) and is never a- legitimate self-hosted notifier, so it stays blocked there. Has no- effect unless ``allow_private_ips=True`` — without the opt-in- link-local is already blocked. Default False preserves the- behavior every non-notification caller relies on (RFC1918 /- loopback / non-link-local ULA remain allowed under the flag).+ EVEN under ``allow_private_ips=True``. Set by the notification+ validation and send paths (see ``security.dns_pinning`` /+ ``notification_validator``), egress-policy host+ classification, PRIVATE_ONLY content fetching+ (``egress.fetch``), search-result full-content fetching+ (``full_search``) and the content-cache check+ (``search_engine_base``), and the request-boundary custom LLM+ endpoint check (``url_utils.is_safe_custom_llm_endpoint``):+ those allow private LAN targets, but cloud-provider metadata+ may live in link-local beyond the always-blocked literals, so+ it stays blocked there. Has no effect unless+ ``allow_private_ips=True`` — without the opt-in link-local is+ already blocked. Default False keeps link-local allowed under+ the opt-in for callers that do not set it — notably the LLM+ provider guard ``assert_base_url_safe`` (rootless Podman maps+ ``host.containers.internal`` to ``169.254.1.2``) and the+ private search-engine instance-URL checks.allow_nat64: Override for the ``security.allow_nat64`` carve-out.``None`` (default) reads the env setting — the behavior everyexisting caller relies on. An explicit ``bool`` answers a@@ -278,7 +310,8 @@ def is_ip_blocked(ip = ip.ipv4_mapped# ALWAYS block cloud-metadata endpoints - critical SSRF target- # for credential theft (AWS IMDS/ECS, Azure, OCI, DigitalOcean,+ # for credential theft (AWS IMDS/ECS/EKS, Azure IMDS/WireServer,+ # GCP, OCI, Scaleway, Akamai, OpenStack/Hetzner, DigitalOcean,# AlibabaCloud, Tencent Cloud). These are never legitimate# destinations regardless of allow_localhost / allow_private_ips.if str(ip) in ALWAYS_BLOCKED_METADATA_IPS:@@ -295,7 +328,7 @@ def is_ip_blocked(# For the notification send path (``block_link_local``), a NAT64-wrapped# link-local address must also stay blocked even under the allow_nat64# opt-in — otherwise the carve-out below `continue`s past the link-local- # check for the IPv6-wrapped form of e.g. Scaleway's 169.254.42.42.+ # check for the IPv6-wrapped form of a link-local address.# (When NAT64 is off the whole prefix is already blocked in the loop, so# this only changes the opt-in case; gated on block_link_local so# non-notification callers are unaffected.)@@ -418,12 +451,14 @@ def validate_url(search engines (e.g., searxng). Default False.allow_private_ips: Whether to allow all private/internal IPs plus localhost.This includes RFC1918 (10.x, 172.16-31.x, 192.168.x), CGNAT (100.64.x.x- used by Podman/rootless containers), link-local (169.254.x.x), and IPv6- private ranges (fc00::/7, fe80::/10). Use for trusted self-hosted services- like SearXNG or Ollama in containerized environments.+ used by Podman/rootless containers), link-local (169.254.x.x,+ fe80::/10 -- unless ``block_link_local`` is set), and IPv6 ULA+ (fc00::/7). Use for trusted self-hosted services such as an+ LLM backend reached via ``host.containers.internal``.Note: cloud metadata endpoints in ``ALWAYS_BLOCKED_METADATA_IPS``- (AWS / Azure / OCI / DigitalOcean / AlibabaCloud / Tencent / ECS)- are ALWAYS blocked regardless of these flags.+ (AWS / Azure / GCP / OCI / Scaleway / Akamai / OpenStack /+ Hetzner / DigitalOcean / AlibabaCloud / Tencent) are ALWAYS+ blocked regardless of these flags.Returns:True if URL is safe, False otherwise@@ -595,11 +630,22 @@ def assert_base_url_safe(base_url: str, *, setting_key: str) -> str:Uses ``allow_localhost=True, allow_private_ips=True`` because thelegitimate destinations for LLM SDKs are localhost (Ollama, LM Studio,- llama.cpp) and RFC1918 (Docker / private network deployments). The+ llama.cpp) and RFC1918 (Docker / private network deployments).+ Link-local (``169.254.0.0/16``, ``fe80::/10``) is deliberately NOT+ excluded here, unlike the notification and content-fetch guards.+ The link-local mapping is Podman's: rootless Podman 5.3+ (pasta) maps+ ``host.containers.internal`` to ``169.254.1.2``, and under Podman the+ ``host-gateway`` value the bundled docker-compose.yml uses for+ ``host.docker.internal`` resolves to that same address. (Docker's own+ ``host-gateway`` and Docker Desktop's ``host.docker.internal`` are not+ link-local.) Excluding link-local would break host-side Ollama /+ LM Studio backends under Podman. The``ALWAYS_BLOCKED_METADATA_IPS`` set still fires under those flags andprevents the auth-gated SSRF that would otherwise reach cloud-credential- endpoints (AWS IMDS / ECS, Azure, OCI, DigitalOcean, AlibabaCloud,- Tencent).+ endpoints (AWS IMDS / ECS / EKS Pod Identity, Azure IMDS and WireServer,+ GCP, OCI, Scaleway, Akamai / Linode, OpenStack, DigitalOcean,+ AlibabaCloud, Tencent). See SECURITY.md ("LLM Provider URL+ Validation").Residual risk (documented, not closed here): this guard validates onceat provider construction, and the LLM SDK re-resolves the hostname ondiff --git a/src/local_deep_research/web_search_engines/engines/full_search.py b/src/local_deep_research/web_search_engines/engines/full_search.pyindex 1ed30cb5f3..edd1343270 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@@ -455,9 +455,9 @@ class FullSearchResults:if url is None:continue# block_link_local=True is the carve-out inside the private-IP- # grant: the rest of the link-local range hosts provider metadata- # beyond ALWAYS_BLOCKED_METADATA_IPS (Scaleway's endpoint, for- # one) and no legitimate result page lives there. No effect+ # grant: the rest of the link-local range may host provider+ # metadata beyond ALWAYS_BLOCKED_METADATA_IPS and no legitimate+ # result page lives there. No effect# without the grant, where link-local is already blocked.if not validate_url(url,diff --git a/tests/llm/test_provider_base_url_ssrf.py b/tests/llm/test_provider_base_url_ssrf.pyindex 5531dfbc41..bc0aad19e2 100644--- a/tests/llm/test_provider_base_url_ssrf.py+++ b/tests/llm/test_provider_base_url_ssrf.py@@ -48,7 +48,7 @@ def _supply_base_provider_key(monkeypatch):["169.254.169.254", # AWS IMDS / Azure / OCI / DigitalOcean"169.254.170.2", # AWS ECS task metadata v3- "169.254.170.23", # AWS ECS task metadata v4+ "169.254.170.23", # AWS EKS Pod Identity credentials"169.254.0.23", # Tencent Cloud"100.100.100.200", # AlibabaCloud],diff --git a/tests/notifications/test_notification_destination_guard.py b/tests/notifications/test_notification_destination_guard.pyindex c67ee57531..6b86a18f3e 100644--- a/tests/notifications/test_notification_destination_guard.py+++ b/tests/notifications/test_notification_destination_guard.py@@ -35,7 +35,7 @@ def test_authority_plugin_needs_operator_private_opt_in(url):def test_authority_plugin_link_local_remains_blocked_with_opt_in():allowed, reason = NotificationURLValidator.validate_service_url(- "json://169.254.42.42/hook", allow_private_ips=True+ "json://169.254.10.5/hook", allow_private_ips=True)assert allowed is Falseassert "link-local" in reason.lower()@@ -169,7 +169,7 @@ def test_admin_test_url_explains_private_plugin_opt_in():def test_admin_test_url_does_not_suggest_opt_in_for_link_local():service = NotificationService(allow_private_ips=True, outbound_allowed=True)- result = service.test_service("json://169.254.42.42/hook")+ result = service.test_service("json://169.254.10.5/hook")assert result["success"] is Falseassert "LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS" not in result["error"]@@ -583,7 +583,7 @@ def test_matrix_forms_accepted_by_apprise_are_classified(url, kind, host):@pytest.mark.parametrize("url",- ["http://169.254.42.42/notify/abc", "https://[fe80::1]/x"],+ ["http://169.254.10.5/notify/abc", "https://[fe80::1]/x"],)def test_http_link_local_is_blocked_even_with_opt_in(url):# Apprise turns http://<host>/notify/<token> into its Apprise APIdiff --git a/tests/notifications/test_notification_webhook_dns_pin.py b/tests/notifications/test_notification_webhook_dns_pin.pyindex 61dd8a2786..0124f9c49d 100644--- a/tests/notifications/test_notification_webhook_dns_pin.py+++ b/tests/notifications/test_notification_webhook_dns_pin.py@@ -1325,20 +1325,20 @@ def test_ipv6_imds_rebind_refused_through_send():# RFC1918 self-hosted notifiers keep working.# ==========================================================================def test_link_local_refused_by_notification_block_window():- """An UNPINNED lookup that resolves into the link-local range (Scaleway's- metadata ``169.254.42.42`` is the canonical example — NOT one of the- always-blocked literals) is refused by the notification block-private+ """An UNPINNED lookup that resolves into the link-local range (``169.254.10.5``,+ a generic link-local address — NOT one of the always-blocked+ literals) is refused by the notification block-privatewindow when ``block_link_local=True``, even though allow_private_ips=Truepermits RFC1918. Teeth: drop ``block_link_local`` and this lookupresolves normally (link-local is otherwise allowed under the private-IPopt-in)."""- resolver = _Resolver({"scaleway.example": [["169.254.42.42"]]})+ resolver = _Resolver({"link-local.example": [["169.254.10.5"]]})with patch.object(dns_pinning, "_real_getaddrinfo", resolver):with dns_pinning.block_private_resolution(allow_private_ips=True, block_link_local=True):with pytest.raises(socket.gaierror):- socket.getaddrinfo("scaleway.example", 80)+ socket.getaddrinfo("link-local.example", 80)def test_ipv6_link_local_refused_by_notification_block_window():@@ -1381,12 +1381,12 @@ def test_rfc1918_still_allowed_under_block_link_local():assert socket.getaddrinfo("ula.example", 80)[0][4][0] == "fd00::1"-def test_link_local_scaleway_pin_rejects_rebind():+def test_link_local_pin_rejects_rebind():"""A pinnable raw-webhook host that rebinds INTO link-local at pin time isrefused (fail closed) under ``block_link_local=True`` — the connect-timere-validation catches metadata that lives in link-local beyond thealways-blocked literals."""- resolver = _Resolver({"hook.example": [["169.254.42.42"]]})+ resolver = _Resolver({"hook.example": [["169.254.10.5"]]})with patch.object(dns_pinning, "_real_getaddrinfo", resolver):with pytest.raises(ValueError, match="SSRF"):with dns_pinning.pin_hosts(@@ -1397,9 +1397,9 @@ def test_link_local_scaleway_pin_rejects_rebind():pass-def test_scaleway_link_local_refused_end_to_end_through_send():+def test_link_local_refused_end_to_end_through_send():"""End-to-end: ``send()`` refuses a json:// webhook whose IP-literal host- is a link-local metadata address (Scaleway ``169.254.42.42``). The+ is a link-local address (``169.254.10.5``). Thevalidator's plugin-scheme IMDS guard rejects it pre-send, so ``send``raises ServiceError and no connection is made to the link-local IP."""resolver = _Resolver({})@@ -1409,9 +1409,9 @@ def test_scaleway_link_local_refused_end_to_end_through_send():_service().send(title="t",body="b",- service_urls="json://169.254.42.42/notify",+ service_urls="json://169.254.10.5/notify",)- assert not any(addr[0] == "169.254.42.42" for addr in targets), targets+ assert not any(addr[0] == "169.254.10.5" for addr in targets), targetsdef test_rfc1918_json_webhook_still_delivers_end_to_end():@@ -1443,7 +1443,7 @@ def test_rfc1918_json_webhook_still_delivers_end_to_end():# Every test above that exercises link-local either drives the primitives# directly (``dns_pinning.block_private_resolution`` /# ``dns_pinning.pin_hosts``) or uses an IP-LITERAL URL-# (``test_scaleway_link_local_refused_end_to_end_through_send``), which the+# (``test_link_local_refused_end_to_end_through_send``), which the# validator's plugin-scheme IMDS guard rejects PRE-SEND — ``_dispatch`` /# ``pinned_notification_send`` is never reached. So none of them would# notice if ``block_link_local=True`` were dropped at either call site while@@ -1452,7 +1452,7 @@ def test_rfc1918_json_webhook_still_delivers_end_to_end():# These tests use a HOSTNAME that validates PUBLIC (the validator's own# resolution, call #1 of the scripted resolver) but rebinds to a link-local# address that is NOT one of the always-blocked metadata literals (call-# #2, at the guarded send call site itself) — Scaleway's ``169.254.42.42``+# #2, at the guarded send call site itself) — ``169.254.10.5``# / a bare IPv6 ``fe80::`` address, both ordinary link-local space that# ``allow_private_ips=True`` would otherwise ADMIT. So a refusal here can# only come from the ``block_link_local=True`` threaded through the@@ -1466,10 +1466,10 @@ def test_link_local_rebind_refused_by_dispatch_lenient_partition():``block_link_local=True`` (``notifications/service.py`` ~line 535).``ll-rebind.example`` validates PUBLIC at ``send()``'s pre-send- validation (resolver call #1) but rebinds to Scaleway's link-local- metadata address ``169.254.42.42`` at ``_dispatch``'s ``pin_hosts``+ validation (resolver call #1) but rebinds to the link-local+ address ``169.254.10.5`` at ``_dispatch``'s ``pin_hosts``resolution (call #2, "pin time" — json:// is a pinnable scheme).- ``169.254.42.42`` is ordinary link-local space, which the+ ``169.254.10.5`` is ordinary link-local space, which the``allow_private_ips=True`` opt-in (set on the service here) wouldotherwise admit; it is refused ONLY because ``_dispatch`` also passes``block_link_local=True`` into that same ``pinned_notification_send``@@ -1481,7 +1481,7 @@ def test_link_local_rebind_refused_by_dispatch_lenient_partition():at _dispatch's authority-partition ``pinned_notification_send`` call(leaving ``is_ip_blocked`` / the validator untouched) and this testfails — the rebind pins successfully and the connect spy sees- 169.254.42.42.+ 169.254.10.5.The confirmed rebind raises ``SecurityBlockError`` (non-retryable, a``ServiceError`` subclass), not SendError. Asserting the subclass (not@@ -1489,7 +1489,7 @@ def test_link_local_rebind_refused_by_dispatch_lenient_partition():exercised by ``_dispatch``, not any pre-dispatch reject."""resolver = _Resolver(- {"ll-rebind.example": [["93.184.216.34"], ["169.254.42.42"]]}+ {"ll-rebind.example": [["93.184.216.34"], ["169.254.10.5"]]})with patch.object(dns_pinning, "_real_getaddrinfo", resolver):with _connect_spy() as targets:@@ -1499,7 +1499,7 @@ def test_link_local_rebind_refused_by_dispatch_lenient_partition():body="b",service_urls="json://ll-rebind.example/notify",)- assert not any(addr[0] == "169.254.42.42" for addr in targets), (+ assert not any(addr[0] == "169.254.10.5" for addr in targets), (f"connected to link-local IP: {targets}")@@ -1545,8 +1545,8 @@ def test_test_service_link_local_rebind_refused_by_guard_factory():under the block-private WINDOW (``block_private_resolution``), whichconsults the SAME ``block_link_local`` flag ``test_service`` threadsinto its guard factory. The host validates public at ``test_service``'s- pre-send validation (resolver call #1) and rebinds to Scaleway's- link-local ``169.254.42.42`` at send time (call #2), and the window+ pre-send validation (resolver call #1) and rebinds to the+ link-local ``169.254.10.5`` at send time (call #2), and the windowrefuses it.Teeth: with ``allow_private_ips=False`` (the service used here) the@@ -1556,7 +1556,7 @@ def test_test_service_link_local_rebind_refused_by_guard_factory():``test_notification_destination_guard.py`` locks the flag itself."""resolver = _Resolver(- {"ll-rebind-ts.example": [["93.184.216.34"], ["169.254.42.42"]]}+ {"ll-rebind-ts.example": [["93.184.216.34"], ["169.254.10.5"]]})with patch.object(dns_pinning, "_real_getaddrinfo", resolver):with _connect_spy() as targets:@@ -1564,7 +1564,7 @@ def test_test_service_link_local_rebind_refused_by_guard_factory():"ntfy://ll-rebind-ts.example/mytopic")assert result["success"] is False- assert not any(addr[0] == "169.254.42.42" for addr in targets), (+ assert not any(addr[0] == "169.254.10.5" for addr in targets), (f"connected to link-local IP: {targets}")# Cosmetic corroboration that the block-private WINDOW (not some otherdiff --git a/tests/notifications/test_service.py b/tests/notifications/test_service.pyindex 587729fd57..41bd44c711 100644--- a/tests/notifications/test_service.py+++ b/tests/notifications/test_service.py@@ -711,10 +711,10 @@ class TestTestServiceInvalidFragmentRefusal:the parser — closed here at the consumer, not by weakening the parser."""- # A hostile link-local (Scaleway-style metadata) target hidden behind+ # A hostile link-local (metadata-style) target hidden behind# a perfectly valid Discord webhook decoy, joined by a backslash.BACKSLASH_DECOY_URL = (- "json://169.254.42.42/x"+ "json://169.254.10.5/x""\\https://discord.com/api/webhooks/123456789/abcdefghijklmnop")@@ -731,7 +731,7 @@ class TestTestServiceInvalidFragmentRefusal:With ONLY that revert, ``add(list(url_entries))`` hands Apprisethe decoy, so the send goes to ``discord.com`` rather than to thelink-local target. Reaching the raw- ``json://169.254.42.42/x\https://...`` string — the original+ ``json://169.254.10.5/x\https://...`` string — the originaldefect, where the link-local host is what actually gets notified— takes the SECOND revert as well: ``add(list(url_entries))``back to ``add(url)``. That is the pairing the class docstring@@ -756,7 +756,7 @@ class TestTestServiceInvalidFragmentRefusal:mock_apprise_instance.add.assert_not_called()mock_apprise_instance.notify.assert_not_called()# And nothing derived from the input is echoed back to the user.- assert "169.254.42.42" not in result["error"]+ assert "169.254.10.5" not in result["error"]assert "discord.com" not in result["error"]@patch("local_deep_research.notifications.service.apprise.Apprise")diff --git a/tests/research_library/downloaders/test_playwright_html.py b/tests/research_library/downloaders/test_playwright_html.pyindex ccec1ac1d2..319eddf736 100644--- a/tests/research_library/downloaders/test_playwright_html.py+++ b/tests/research_library/downloaders/test_playwright_html.py@@ -552,7 +552,7 @@ class TestAutoDownloaderBlockLinkLocalReachesJsRoute:the threaded flag can refuse it."""ENTRY_URL = "http://10.0.0.5/wiki"- LINK_LOCAL_URL = "http://169.254.42.42/latest/meta-data"+ LINK_LOCAL_URL = "http://169.254.10.5/latest/meta-data"@pytest.mark.parametrize("guard", ["playwright", "crawl4ai"])def test_js_route_refuses_redirect_into_link_local_under_open_grant(diff --git a/tests/security/test_egress_fetch_link_local.py b/tests/security/test_egress_fetch_link_local.pyindex b23470a3d0..641366fe21 100644--- a/tests/security/test_egress_fetch_link_local.py+++ b/tests/security/test_egress_fetch_link_local.py@@ -7,8 +7,7 @@ operator already listed), so it is a hardening gap rather than an open door.What it does close: ``ALWAYS_BLOCKED_METADATA_IPS`` holds known literalmetadata addresses, and the remainder of 169.254.0.0/16 still carries-provider-specific metadata endpoints -- Scaleway's 169.254.42.42 among-them. Before this, the two egress gates disagreed: ``policy.py``+provider-specific metadata endpoints that are not listed there. Before this, the two egress gates disagreed: ``policy.py``excluded link-local, ``fetch.py`` did not.The controls below matter as much as the blocks: PRIVATE_ONLY exists so a@@ -57,7 +56,7 @@ def _ctx(scope=EgressScope.PRIVATE_ONLY):@pytest.mark.parametrize("ip,why",[- ("169.254.42.42", "Scaleway metadata, outside the listed literals"),+ ("169.254.10.5", "link-local outside the listed metadata literals"),("169.254.169.254", "the canonical metadata literal"),("169.254.1.1", "generic IPv4 link-local"),],@@ -83,7 +82,7 @@ def test_private_hosts_still_reachable_under_private_only(ip, why):def test_link_local_still_rejected_with_no_context():"""CONTROL: strict default path is unaffected and still rejects."""- with resolves_to("169.254.42.42"):+ with resolves_to("169.254.10.5"):assert not policy_aware_validate_url(f"http://{HOST}/x", None)@@ -96,7 +95,7 @@ def test_gate_agrees_with_policy_classify_host():from local_deep_research.security.egress.policy import evaluate_urlctx = _ctx()- with resolves_to("169.254.42.42"):+ with resolves_to("169.254.10.5"):fetch_allows = policy_aware_validate_url(f"http://{HOST}/x", ctx)try:policy_allows = evaluate_url(f"http://{HOST}/x", ctx).alloweddiff --git a/tests/security/test_egress_fullsearch.py b/tests/security/test_egress_fullsearch.pyindex 499df685a4..f23092f77b 100644--- a/tests/security/test_egress_fullsearch.py+++ b/tests/security/test_egress_fullsearch.py@@ -372,7 +372,7 @@ def test_grant_off_blocks_private_result_before_any_fetch(transport):def test_link_local_result_stays_blocked_with_grant_and_no_policy(transport):"""CONTROL: the link-local carve-out survives the grant on the pathwhere the grant does reach the pipeline (no run context)."""- link_local = "http://169.254.42.42/latest/meta-data"+ link_local = "http://169.254.10.5/latest/meta-data"transport["responses"] = {link_local: _html_ok(_ARTICLE_HTML)}engine = _granted_engine([{"title": "r", "link": link_local}], None)diff --git a/tests/security/test_llm_endpoint_link_local_hardening.py b/tests/security/test_llm_endpoint_link_local_hardening.pyindex 8cec6fcf9b..55dbe90aed 100644--- a/tests/security/test_llm_endpoint_link_local_hardening.py+++ b/tests/security/test_llm_endpoint_link_local_hardening.py@@ -32,7 +32,7 @@ from local_deep_research.utilities.url_utils import (# Representative IPv4 and IPv6 link-local inputs.LINK_LOCAL_ENDPOINTS = [- "http://169.254.42.42/v1",+ "http://169.254.10.5/v1","http://169.254.1.1:8080/v1","http://[fe80::1]:8080/v1",]@@ -75,7 +75,7 @@ def test_public_endpoint_still_accepted():assert is_safe_custom_llm_endpoint("https://api.openai.com/v1") is True[email protected]("host", ["169.254.42.42", "169.254.1.1", "fe80::1"])[email protected]("host", ["169.254.10.5", "169.254.1.1", "fe80::1"])def test_link_local_does_not_classify_as_local_in_egress_policy(host):"""Layer 2 refuses a submitted link-local host under PRIVATE_ONLY."""assert _classify_host(host, _private_only_ctx()) is False, (diff --git a/tests/security/test_metadata_ip_set_tripwire.py b/tests/security/test_metadata_ip_set_tripwire.pyindex cabc3b4fbd..fe6b967bb5 100644--- a/tests/security/test_metadata_ip_set_tripwire.py+++ b/tests/security/test_metadata_ip_set_tripwire.py@@ -11,10 +11,15 @@ The IPv6 member deserves its own pin: ``fd00:ec2::254`` is a ULA,not an IPv4-mapped or NAT64-wrapped form of the IPv4 entries, so noderived check covers it — it must stay listed explicitly or it isreachable under ``allow_private_ips=True`` (which permits fc00::/7).+The same holds for GCP's ``fd20:ce::254``. Azure's ``168.63.129.16`` is+public address space, so no private-range check covers it either."""from __future__ import annotations+import ipaddress+import itertools+import pytestfrom local_deep_research.security.ssrf_validator import (@@ -28,11 +33,19 @@ DOCUMENTED_METADATA_IPS = frozenset({"169.254.169.254", # AWS IMDSv1/v2, Azure, OCI, DigitalOcean"169.254.170.2", # AWS ECS task metadata v3- "169.254.170.23", # AWS ECS task metadata v4+ "169.254.170.23", # AWS EKS Pod Identity credentials"169.254.0.23", # Tencent Cloud"100.100.100.200", # AlibabaCloud"192.0.0.192", # Oracle Compute Classic IMDS+ "168.63.129.16", # Azure WireServer"fd00:ec2::254", # AWS IMDS over IPv6+ "fd00:ec2::23", # AWS EKS Pod Identity credentials over IPv6+ "fd20:ce::254", # GCP metadata server over IPv6+ "169.254.42.42", # Scaleway instance metadata+ "fd00:42::42", # Scaleway instance metadata over IPv6+ "fd00:a9fe:a9fe::1", # Akamai / Linode metadata over IPv6+ "fd00:c1::a9fe:a9fe", # Oracle Cloud (OCI) IMDS over IPv6+ "fe80::a9fe:a9fe", # OpenStack Nova / Hetzner metadata over IPv6})@@ -70,3 +83,185 @@ class TestMetadataIpSetTripwire:for member in ALWAYS_BLOCKED_METADATA_IPS:ipaddress.ip_address(member)+++#: Every combination of the is_ip_blocked policy flags. allow_nat64 is+#: passed explicitly so the result never depends on the process env.+_FLAG_COMBOS = [+ dict(+ allow_localhost=lh,+ allow_private_ips=priv,+ allow_nat64=nat64,+ block_link_local=ll,+ )+ for lh, priv, nat64, ll in itertools.product([False, True], repeat=4)+]+_FLAG_IDS = [+ "lh{allow_localhost:d}-priv{allow_private_ips:d}-nat64{allow_nat64:d}"+ "-ll{block_link_local:d}".format(**c)+ for c in _FLAG_COMBOS+]+++def _nat64_96(v4: str) -> str:+ """RFC 6052 /96 well-known-prefix form (64:ff9b::/96) of ``v4``."""+ return str(+ ipaddress.IPv6Address(+ bytes.fromhex("0064ff9b0000000000000000")+ + ipaddress.IPv4Address(v4).packed+ )+ )+++def _nat64_48(v4: str) -> str:+ """RFC 6052 §2.2 /48 local-use form (64:ff9b:1::/48) of ``v4``: the+ IPv4 sits at bytes 6, 7, 9, 10 around the reserved octet 8."""+ packed = ipaddress.IPv4Address(v4).packed+ raw = bytearray(16)+ raw[0:6] = bytes.fromhex("0064ff9b0001")+ raw[6:8] = packed[0:2]+ raw[9:11] = packed[2:4]+ return str(ipaddress.IPv6Address(bytes(raw)))+++class TestAzureWireServerAndGcpIpv6Metadata:+ """168.63.129.16 (Azure WireServer) and fd20:ce::254 (GCP metadata+ over IPv6) are blocked under every flag combination."""++ @pytest.mark.parametrize("flags", _FLAG_COMBOS, ids=_FLAG_IDS)+ @pytest.mark.parametrize(+ "ip", ["168.63.129.16", "fd20:ce::254"], ids=["azure", "gcp-v6"]+ )+ def test_blocked_under_every_flag_combination(self, ip, flags):+ assert is_ip_blocked(ip, **flags) is True++ @pytest.mark.parametrize(+ "ip",+ [+ "FD20:CE::254",+ "fd20:00ce:0000:0000:0000:0000:0000:0254",+ "fd20:ce::254%eth0",+ ],+ )+ def test_gcp_v6_textual_variants_blocked_under_allow_private(self, ip):+ assert (+ is_ip_blocked(+ ip,+ allow_localhost=True,+ allow_private_ips=True,+ allow_nat64=True,+ )+ is True+ )++ @pytest.mark.parametrize("flags", _FLAG_COMBOS, ids=_FLAG_IDS)+ @pytest.mark.parametrize(+ "wrapped",+ [+ "::ffff:168.63.129.16",+ _nat64_96("168.63.129.16"),+ _nat64_48("168.63.129.16"),+ ],+ ids=["v4-mapped", "nat64-96", "nat64-48"],+ )+ def test_wrapped_azure_wireserver_blocked(self, wrapped, flags):+ """IPv4-mapped and NAT64-wrapped forms resolve to the same+ destination, including under the allow_nat64 opt-in."""+ assert is_ip_blocked(wrapped, **flags) is True++ @pytest.mark.parametrize("ip", ["168.63.129.15", "168.63.129.17"])+ def test_neighbouring_public_addresses_stay_allowed(self, ip):+ """Positive control: only the exact literal is blocked."""+ assert is_ip_blocked(ip) is False+ assert is_ip_blocked(ip, allow_private_ips=True) is False++ def test_neighbouring_ula_stays_allowed_under_allow_private(self):+ """Positive control: fd20:ce::253 is ordinary ULA space, allowed+ under the private-IP opt-in like any other fc00::/7 address."""+ assert is_ip_blocked("fd20:ce::253", allow_private_ips=True) is False++ def test_neighbouring_wrapped_address_stays_allowed(self):+ """Positive control for the wrapped forms: the neighbour's mapped+ and NAT64 forms are not blocked when their direct form is not."""+ assert (+ is_ip_blocked("::ffff:168.63.129.17", allow_private_ips=True)+ is False+ )+ assert (+ is_ip_blocked(_nat64_96("168.63.129.17"), allow_nat64=True) is False+ )+++#: Provider metadata endpoints that the permissive LLM-provider posture+#: would otherwise admit: Scaleway's IPv4 address is ordinary link-local+#: (accepted for provider URLs because rootless Podman maps+#: host.containers.internal into 169.254.0.0/16), the IPv6 ULAs fall in+#: fc00::/7 and fe80::a9fe:a9fe is IPv6 link-local.+_LINK_LOCAL_AND_ULA_METADATA = [+ "169.254.42.42",+ "fd00:42::42",+ "fd00:a9fe:a9fe::1",+ "fd00:c1::a9fe:a9fe",+ "fe80::a9fe:a9fe",+]+++class TestLinkLocalAndUlaProviderMetadata:+ """Each entry is blocked under every flag combination, including the+ allow_private_ips=True / block_link_local=False posture of the LLM+ provider guard, where only the explicit listing blocks it."""++ @pytest.mark.parametrize("flags", _FLAG_COMBOS, ids=_FLAG_IDS)+ @pytest.mark.parametrize(+ "ip", _LINK_LOCAL_AND_ULA_METADATA, ids=lambda v: v.replace(":", "-")+ )+ def test_blocked_under_every_flag_combination(self, ip, flags):+ assert is_ip_blocked(ip, **flags) is True++ @pytest.mark.parametrize(+ "ip",+ [+ "fe80::a9fe:a9fe%eth0",+ "fe80::a9fe:a9fe%2",+ "FE80:0000:0000:0000:0000:0000:A9FE:A9FE",+ "FD00:42::42",+ "fd00:0042:0000:0000:0000:0000:0000:0042%eth0",+ "fd00:a9fe:a9fe:0:0:0:0:1",+ "FD00:C1::A9FE:A9FE",+ ],+ )+ def test_textual_and_scoped_variants_blocked_under_allow_private(self, ip):+ assert (+ is_ip_blocked(+ ip,+ allow_localhost=True,+ allow_private_ips=True,+ allow_nat64=True,+ )+ is True+ )++ @pytest.mark.parametrize("flags", _FLAG_COMBOS, ids=_FLAG_IDS)+ @pytest.mark.parametrize(+ "wrapped",+ [+ "::ffff:169.254.42.42",+ _nat64_96("169.254.42.42"),+ _nat64_48("169.254.42.42"),+ ],+ ids=["v4-mapped", "nat64-96", "nat64-48"],+ )+ def test_wrapped_scaleway_blocked(self, wrapped, flags):+ assert is_ip_blocked(wrapped, **flags) is True++ @pytest.mark.parametrize(+ "ip", ["169.254.42.41", "169.254.1.2", "fd00:42::43", "fe80::1"]+ )+ def test_neighbouring_link_local_and_ula_stay_allowed(self, ip):+ """Positive control: only the exact literals are blocked. The+ neighbours stay allowed under the provider posture, so a host-side+ backend at 169.254.1.2 (rootless Podman) keeps working."""+ assert (+ is_ip_blocked(ip, allow_localhost=True, allow_private_ips=True)+ is False+ )diff --git a/tests/security/test_notification_validator.py b/tests/security/test_notification_validator.pyindex 2e4479aca5..64816de4ee 100644--- a/tests/security/test_notification_validator.py+++ b/tests/security/test_notification_validator.py@@ -490,7 +490,7 @@ class TestCloudMetadataBlockedForPluginSchemes:METADATA_IPS = ("169.254.169.254", # AWS IMDSv1/v2, Azure, OCI, DigitalOcean"169.254.170.2", # AWS ECS task metadata v3- "169.254.170.23", # AWS ECS task metadata v4+ "169.254.170.23", # AWS EKS Pod Identity credentials"169.254.0.23", # Tencent Cloud"100.100.100.200", # AlibabaCloud)@@ -786,8 +786,7 @@ class TestLinkLocalBlockedForPluginSchemes:The lenient plugin/raw-webhook partition runs with``allow_private_ips=True`` so self-hosted LAN notifiers work. Butcloud-provider metadata lives across the WHOLE link-local range- (169.254.0.0/16, fe80::/10), not just the always-blocked literals- (e.g. Scaleway's 169.254.42.42). ``validate_service_url`` must reject+ (169.254.0.0/16, fe80::/10), not just the always-blocked literals. ``validate_service_url`` must rejectany link-local plugin-scheme target while still allowing RFC1918 /loopback / non-link-local ULA."""@@ -795,7 +794,7 @@ class TestLinkLocalBlockedForPluginSchemes:# Link-local metadata / auto-config addresses that are NOT in# ALWAYS_BLOCKED_METADATA_IPS — these were reachable before the fix.LINK_LOCAL_IPS = (- "169.254.42.42", # Scaleway metadata (verified reachable pre-fix)+ "169.254.10.5","169.254.1.1","169.254.255.254",)diff --git a/tests/security/test_provider_metadata_guards.py b/tests/security/test_provider_metadata_guards.pynew file mode 100644index 0000000000..450bb10fbc--- /dev/null+++ b/tests/security/test_provider_metadata_guards.py@@ -0,0 +1,282 @@+"""Provider construction and content fetching agree on metadata exclusions."""++import ipaddress+import socket+from unittest.mock import Mock++import pytest++from local_deep_research.security import ssrf_validator as ssrf+from local_deep_research.security.egress.fetch import policy_aware_validate_url+from local_deep_research.security.egress.policy import (+ EgressContext,+ EgressScope,+ _classify_host,+ evaluate_url,+)+++def _answers(addresses):+ return [+ (+ socket.AF_INET6+ if ipaddress.ip_address(ip).version == 6+ else socket.AF_INET,+ socket.SOCK_STREAM,+ socket.IPPROTO_TCP,+ "",+ (ip, 80),+ )+ for ip in addresses+ ]+++def _ctx(scope=EgressScope.PRIVATE_ONLY, local_hostnames=()):+ return EgressContext(+ scope=scope,+ primary_engine="test",+ require_local_llm=False,+ require_local_embeddings=False,+ local_hostnames=local_hostnames,+ )+++ "address",+ [+ "168.63.129.16",+ "fd20:ce::254",+ "169.254.42.42",+ "fd00:42::42",+ "fd00:a9fe:a9fe::1",+ "fd00:c1::a9fe:a9fe",+ "fe80::a9fe:a9fe",+ "fe80::a9fe:a9fe%25eth0",+ "192.0.0.192",+ "::ffff:192.0.0.192",+ "fd00:ec2::23",+ "FD00:0EC2:0000:0000:0000:0000:0000:0023",+ ],+)+def test_provider_guard_rejects_metadata_literals(monkeypatch, address):+ # Any resolver call answers with a public address, so the literal must+ # be refused by the metadata check itself: neither a DNS answer nor a+ # local resolver failure (e.g. a missing ``eth0`` zone) can produce the+ # refusal asserted below.+ resolver = Mock(return_value=_answers(["93.184.216.34"]))+ monkeypatch.setattr(socket, "getaddrinfo", resolver)+ host = f"[{address}]" if ":" in address else address+ with pytest.raises(ValueError, match="refusing to send") as excinfo:+ ssrf.assert_base_url_safe(+ f"http://{host}/v1", setting_key="llm.openai_endpoint.url"+ )+ assert "could not resolve" not in str(excinfo.value)+ resolver.assert_not_called()+++ "addresses",+ [+ ["168.63.129.16"],+ ["192.0.0.192"],+ ["fd00:ec2::23"],+ ["fd20:ce::254"],+ ["169.254.42.42"],+ ["fe80::a9fe:a9fe"],+ ["10.0.0.5", "169.254.42.42"],+ ["93.184.216.34", "168.63.129.16"],+ ["93.184.216.34", "192.0.0.192"],+ ["93.184.216.34", "fd00:ec2::23"],+ ],+)+def test_provider_and_fetch_guards_reject_dns_metadata(monkeypatch, addresses):+ monkeypatch.setattr(+ socket, "getaddrinfo", lambda *a, **kw: _answers(addresses)+ )+ url = "http://metadata-fixture.invalid/v1"+ with pytest.raises(ValueError, match="failed SSRF validation"):+ ssrf.assert_base_url_safe(url, setting_key="llm.openai_endpoint.url")+ # The PRIVATE_ONLY fetch gate refuses the same answers. (It does not+ # read local_hostnames; the allowlisted end-to-end path is covered by+ # test_allowlisted_metadata_dns_never_reaches_fetch_transport.)+ assert policy_aware_validate_url(url, _ctx()) is False+++ "address", ["127.0.0.1", "10.0.0.5", "192.168.1.10", "::1", "fd12::1"]+)+def test_self_hosted_backends_remain_usable(monkeypatch, address):+ monkeypatch.setattr(+ socket, "getaddrinfo", lambda *a, **kw: _answers([address])+ )+ url = "http://self-hosted-fixture.invalid/v1"+ assert (+ ssrf.assert_base_url_safe(url, setting_key="llm.openai_endpoint.url")+ == url+ )+ assert policy_aware_validate_url(url, _ctx()) is True+++def test_public_provider_remains_usable(monkeypatch):+ monkeypatch.setattr(+ socket, "getaddrinfo", lambda *a, **kw: _answers(["93.184.216.34"])+ )+ url = "https://provider-fixture.invalid/v1"+ assert (+ ssrf.assert_base_url_safe(url, setting_key="llm.openai_endpoint.url")+ == url+ )++[email protected]("scope", list(EgressScope))+def test_legacy_metadata_literal_cannot_be_allowlisted(scope):+ context = _ctx(scope, local_hostnames=("192.0.0.192",))+ assert evaluate_url("http://192.0.0.192/", context).allowed is False+ assert policy_aware_validate_url("http://192.0.0.192/", context) is False++[email protected]("allow_private", [False, True])[email protected]("allow_localhost", [False, True])[email protected]("allow_nat64", [False, True])+def test_legacy_metadata_blocks_all_allow_flags(+ allow_private, allow_localhost, allow_nat64+):+ for address in (+ "192.0.0.192",+ "::ffff:192.0.0.192",+ "64:ff9b::c000:c0",+ "64:ff9b:1:c000:0:c000::",+ ):+ assert (+ ssrf.is_ip_blocked(+ address,+ allow_private_ips=allow_private,+ allow_localhost=allow_localhost,+ allow_nat64=allow_nat64,+ )+ is True+ )++[email protected]("allow_private", [False, True])[email protected]("allow_localhost", [False, True])[email protected]("allow_nat64", [False, True])+def test_eks_ipv6_metadata_blocks_all_allow_flags(+ allow_private, allow_localhost, allow_nat64+):+ for address in (+ "fd00:ec2::23",+ "FD00:EC2::23",+ "fd00:0ec2:0000:0000:0000:0000:0000:0023",+ ):+ assert ssrf.is_ip_blocked(+ address,+ allow_private_ips=allow_private,+ allow_localhost=allow_localhost,+ allow_nat64=allow_nat64,+ )++[email protected]("scope", list(EgressScope))+ "address",+ [+ "fd00:ec2::23",+ "FD00:EC2::23",+ "fd00:0ec2:0000:0000:0000:0000:0000:0023",+ ],+)+def test_eks_ipv6_metadata_cannot_be_local_or_allowlisted(scope, address):+ assert _classify_host(address, _ctx(scope), allow_dns=False) is False+ context = _ctx(scope, local_hostnames=(address,))+ url = f"http://[{address}]/v1/credentials"+ assert evaluate_url(url, context).allowed is False+ assert policy_aware_validate_url(url, context) is False+++ "address",+ [+ "169.254.1.2", # rootless Podman 5.3+ host.containers.internal+ "169.254.10.5",+ "fe80::1",+ ],+)+def test_provider_guard_keeps_link_local_backends_usable(monkeypatch, address):+ # The provider guard deliberately does not set block_link_local: rootless+ # Podman maps host.containers.internal (and host-gateway) to 169.254.1.2,+ # so link-local is a real self-hosted LLM destination. Only the+ # always-blocked metadata literals are refused here.+ monkeypatch.setattr(+ socket, "getaddrinfo", lambda *a, **kw: _answers([address])+ )+ host = f"[{address}]" if ":" in address else address+ url = f"http://{host}/v1"+ assert ssrf.assert_base_url_safe(url, setting_key="llm.ollama.url") == url+ url = "http://host.containers.internal:11434"+ assert ssrf.assert_base_url_safe(url, setting_key="llm.ollama.url") == url+++ "addresses",+ [["169.254.10.5"], ["fe80::1"], ["93.184.216.34", "169.254.1.1"]],+)+def test_private_fetch_guard_still_rejects_link_local_dns(+ monkeypatch, addresses+):+ monkeypatch.setattr(+ socket, "getaddrinfo", lambda *a, **kw: _answers(addresses)+ )+ url = "http://link-local-fixture.invalid/v1"+ assert policy_aware_validate_url(url, _ctx()) is False+++def test_provider_guard_blocks_nat64_metadata_even_with_operator_opt_in(+ monkeypatch,+):+ monkeypatch.setenv("LDR_SECURITY_ALLOW_NAT64", "true")+ for address in ("64:ff9b::a83f:8110", "64:ff9b::a9fe:a9fe"):+ with pytest.raises(ValueError, match="failed SSRF validation"):+ ssrf.assert_base_url_safe(+ f"http://[{address}]/v1",+ setting_key="llm.openai_endpoint.url",+ )+++def test_nat64_private_backend_remains_usable_when_operator_enabled(+ monkeypatch,+):+ address = "64:ff9b::a00:5"+ monkeypatch.setenv("LDR_SECURITY_ALLOW_NAT64", "true")+ monkeypatch.setattr(+ socket, "getaddrinfo", lambda *a, **kw: _answers([address])+ )+ url = f"http://[{address}]/v1"+ assert (+ ssrf.assert_base_url_safe(url, setting_key="llm.openai_endpoint.url")+ == url+ )+++def test_private_service_allowlist_is_not_blanket_denied():+ context = _ctx(local_hostnames=("10.0.0.5",))+ assert evaluate_url("http://10.0.0.5/", context).allowed is True+++def test_generic_private_validation_retains_explicit_link_local_opt_in(+ monkeypatch,+):+ # Narrow the provider constructor, not the generic validator's existing+ # explicit allow-private contract for callers outside that boundary.+ monkeypatch.setattr(+ socket, "getaddrinfo", lambda *a, **kw: _answers(["169.254.1.1"])+ )+ assert (+ ssrf.validate_url("http://169.254.1.1/", allow_private_ips=True) is True+ )+ assert (+ ssrf.validate_url(+ "http://169.254.1.1/", allow_private_ips=True, block_link_local=True+ )+ is False+ )diff --git a/tests/security/test_provider_metadata_integration.py b/tests/security/test_provider_metadata_integration.pynew file mode 100644index 0000000000..1821a92f93--- /dev/null+++ b/tests/security/test_provider_metadata_integration.py@@ -0,0 +1,328 @@+"""Exercise stored provider URLs and response-bearing fetches without egress.++The settings API, encrypted settings store, provider factory, SDK, fetch tool,+ContentFetcher, and HTML downloader are real. Only DNS and the final HTTP+transports are replaced; socket connections fail the test, including attempts+whose exceptions application code catches.+"""++import ipaddress+import socket+from types import SimpleNamespace++import httpx+import pytest+import requests+from openai import DefaultHttpxClient++from local_deep_research.content_fetcher import ContentFetcher+from local_deep_research.database.session_context import get_user_db_session+from local_deep_research.llm.providers import openai_base+from local_deep_research.llm.providers.implementations.custom_openai_endpoint import (+ CustomOpenAIEndpointProvider,+)+from local_deep_research.security import dns_pinning+from local_deep_research.security.egress.policy import (+ EgressContext,+ EgressScope,+)+from local_deep_research.settings import SettingsManager+++ENDPOINT_SETTING = "llm.openai_endpoint.url"+FIXTURE_TEXT = "Local research service content is available."+# Always-blocked metadata literals: refused by every guard, the stored+# provider endpoint included.+METADATA_ADDRESSES = [+ "169.254.169.254",+ "192.0.0.192",+ "168.63.129.16",+ "fd00:ec2::23",+ "fd20:ce::254",+ "169.254.42.42",+ "fe80::a9fe:a9fe",+]+# Other link-local addresses: refused by the content-fetch guards, but+# deliberately still accepted as a provider endpoint (rootless Podman maps+# host.containers.internal to 169.254.1.2).+LINK_LOCAL_ADDRESSES = [+ "169.254.10.5",+ "169.254.169.253",+ "fe80::1",+]++[email protected](autouse=True)+def synthetic_network(monkeypatch):+ answers = {+ "localhost": ["127.0.0.1"],+ "backend-fixture.invalid": ["10.0.0.5"],+ }+ connections = []++ def resolve(host, port=None, *args, **kwargs):+ addresses = answers.get(host, [host])+ records = []+ for address in addresses:+ try:+ ip = ipaddress.ip_address(address)+ except ValueError as exc:+ raise socket.gaierror("No synthetic DNS answer") from exc+ family = socket.AF_INET6 if ip.version == 6 else socket.AF_INET+ records.append(+ (family, socket.SOCK_STREAM, 6, "", (str(ip), port or 80))+ )+ return records++ def refuse_connect(sock, address):+ connections.append(address)+ raise AssertionError(+ "A metadata regression test attempted a socket connection"+ )++ monkeypatch.setattr(socket, "getaddrinfo", resolve)+ # The downloader pins DNS through the resolver captured at module import.+ monkeypatch.setattr(dns_pinning, "_real_getaddrinfo", resolve)+ monkeypatch.setattr(socket.socket, "connect", refuse_connect)+ monkeypatch.setattr(socket.socket, "connect_ex", refuse_connect)+ yield answers+ assert connections == [], "All HTTP traffic must stay in fixture transports"+++def _url(host):+ authority = f"[{host}]" if ":" in host else host+ return f"http://{authority}/v1"+++def sdk_transport(monkeypatch):+ requests_seen = []+ constructors = []+ real_constructor = openai_base.ChatOpenAI+ # OpenAI 2 uses httpx; the locked OpenAI 3 client uses httpx2.+ if issubclass(DefaultHttpxClient, httpx.Client):+ transport_module = httpx+ else:+ import httpx2++ transport_module = httpx2++ def respond(request):+ requests_seen.append(request)+ return transport_module.Response(+ 200,+ json={+ "id": "chatcmpl-metadata-guard-fixture",+ "object": "chat.completion",+ "created": 0,+ "model": "fixture-model",+ "choices": [+ {+ "index": 0,+ "message": {+ "role": "assistant",+ "content": FIXTURE_TEXT,+ },+ "finish_reason": "stop",+ }+ ],+ },+ )++ # Preserve the real provider-owned clients and their redirect policy;+ # replace only the final network transport, not constructor arguments.+ monkeypatch.setattr(+ transport_module.HTTPTransport,+ "handle_request",+ lambda transport, request: respond(request),+ )+ models = []++ def construct(**kwargs):+ constructors.append(kwargs["base_url"])+ model = real_constructor(**kwargs)+ models.append(model)+ return model++ monkeypatch.setattr(openai_base, "ChatOpenAI", construct)+ try:+ yield SimpleNamespace(requests=requests_seen, constructors=constructors)+ finally:+ from local_deep_research.utilities.llm_utils import _close_base_llm++ for model in models:+ _close_base_llm(model)+++def _save_and_read_snapshot(client, endpoint):+ response = client.put(+ f"/settings/api/{ENDPOINT_SETTING}", json={"value": endpoint}+ )+ assert response.status_code == 200, response.text+ username = client.get("/auth/check").json()["username"]+ with get_user_db_session(username) as session:+ snapshot = SettingsManager(session).get_settings_snapshot()+ assert snapshot[ENDPOINT_SETTING] == endpoint+ snapshot["llm.openai_endpoint.api_key"] = "metadata-guard-fixture-key"+ snapshot["llm.streaming"] = False+ return snapshot++[email protected]_session_check[email protected]("address", METADATA_ADDRESSES)+def test_stored_endpoint_blocks_before_sdk_but_localhost_still_works(+ authenticated_client, sdk_transport, address+):+ snapshot = _save_and_read_snapshot(authenticated_client, _url(address))+ with pytest.raises(ValueError, match="failed SSRF validation"):+ CustomOpenAIEndpointProvider.create_llm(+ "fixture-model", settings_snapshot=snapshot+ )+ assert sdk_transport.constructors == []+ assert sdk_transport.requests == []++ # Exercise the same saved-setting path with a usable self-hosted backend.+ snapshot = _save_and_read_snapshot(authenticated_client, _url("localhost"))+ llm = CustomOpenAIEndpointProvider.create_llm(+ "fixture-model", settings_snapshot=snapshot+ )+ assert llm.invoke("Check the local service").content == FIXTURE_TEXT+ assert sdk_transport.constructors == [_url("localhost")]+ assert len(sdk_transport.requests) == 1+ assert str(sdk_transport.requests[0].url) == (+ "http://localhost/v1/chat/completions"+ )++[email protected]_session_check[email protected]("address", ["169.254.1.2"] + LINK_LOCAL_ADDRESSES)+def test_stored_link_local_endpoint_still_constructs(+ authenticated_client, sdk_transport, address+):+ # Not a metadata literal, so the provider guard must not refuse it: a+ # rootless Podman host backend lives at 169.254.1.2.+ snapshot = _save_and_read_snapshot(authenticated_client, _url(address))+ CustomOpenAIEndpointProvider.create_llm(+ "fixture-model", settings_snapshot=snapshot+ )+ assert len(sdk_transport.constructors) == 1+ assert address in sdk_transport.constructors[0]+ assert sdk_transport.requests == []+++def html_transport(monkeypatch):+ requests_seen = []+ paragraphs = "".join(+ f"<p>{FIXTURE_TEXT} This fixture describes a local document service "+ "that researchers use to read articles on their private network. "+ "The complete article should be returned through the fetch tool.</p>"+ for _ in range(8)+ )+ html = (+ "<html><head><title>Local research fixture</title></head>"+ f"<body><article>{paragraphs}</article></body></html>"+ )++ def send(adapter, request, **kwargs):+ requests_seen.append(request)+ response = requests.Response()+ response.status_code = 200+ response.url = request.url+ response.request = request+ response.headers["Content-Type"] = "text/html; charset=utf-8"+ response._content = html.encode()+ response.headers["Content-Length"] = str(len(response._content))+ return response++ monkeypatch.setattr(requests.adapters.HTTPAdapter, "send", send)+ return requests_seen+++def _fetch(entry_point, url, local_hostnames=()):+ context = EgressContext(+ scope=EgressScope.PRIVATE_ONLY,+ primary_engine="test",+ require_local_llm=False,+ require_local_embeddings=False,+ local_hostnames=local_hostnames,+ )+ if entry_point == "content_fetcher":+ with ContentFetcher(egress_context=context) as fetcher:+ result = fetcher.fetch(url)+ return result["status"] == "success", result.get(+ "content", result.get("error")+ )++ from local_deep_research.advanced_search_system.tools.fetch import (+ build_fetch_tool,+ )+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (+ SearchResultsCollector,+ )++ collector = SearchResultsCollector()+ tool = build_fetch_tool(+ "full",+ collector,+ egress_context=context,+ settings_snapshot={"web.enable_javascript_rendering": False},+ max_fetches=0,+ )+ output = tool.invoke({"url": url})+ return collector.find_by_url(url) is not None, output++[email protected]("entry_point", ["content_fetcher", "agent_tool"])[email protected]("address", METADATA_ADDRESSES + LINK_LOCAL_ADDRESSES)+def test_metadata_never_reaches_fetch_transport(+ entry_point, address, html_transport+):+ success, output = _fetch(entry_point, _url(address))+ assert not success+ assert "blocked" in output.lower()+ assert FIXTURE_TEXT not in output+ assert html_transport == []++[email protected]("entry_point", ["content_fetcher", "agent_tool"])+ "addresses",+ [+ ["169.254.10.5"],+ ["fe80::1"],+ ["192.0.0.192"],+ ["10.0.0.5", "192.0.0.192"],+ ],+)+def test_allowlisted_metadata_dns_never_reaches_fetch_transport(+ entry_point, addresses, synthetic_network, html_transport+):+ host = "metadata-fixture.invalid"+ synthetic_network[host] = addresses+ success, output = _fetch(entry_point, _url(host), local_hostnames=(host,))+ assert not success+ assert "blocked" in output.lower()+ assert FIXTURE_TEXT not in output+ assert html_transport == []++[email protected]("entry_point", ["content_fetcher", "agent_tool"])+ "host",+ [+ "localhost",+ "10.0.0.5",+ "192.168.1.10",+ "fd12::1",+ "backend-fixture.invalid",+ ],+)+def test_private_content_reaches_fetch_output(+ entry_point, host, html_transport+):+ success, output = _fetch(entry_point, _url(host))+ assert success, output+ assert FIXTURE_TEXT in output+ assert html_transport+ assert all(request.url == _url(host) for request in html_transport)diff --git a/tests/security/test_real_world_urls_regression_prevention.py b/tests/security/test_real_world_urls_regression_prevention.pyindex 303fd1dfb8..feb6915a4b 100644--- a/tests/security/test_real_world_urls_regression_prevention.py+++ b/tests/security/test_real_world_urls_regression_prevention.py@@ -136,7 +136,7 @@ REAL_WORLD_URLS_THAT_MUST_FAIL = [# ---- Cloud metadata — always blocked under every flag ----("http://169.254.169.254/latest/meta-data/", "aws_imds"),("http://169.254.170.2/v2/credentials/", "aws_ecs_v3"),- ("http://169.254.170.23/v4/credentials/", "aws_ecs_v4"),+ ("http://169.254.170.23/v1/credentials", "aws_eks_pod_identity"),("http://169.254.0.23/", "tencent"),("http://100.100.100.200/latest/meta-data/", "alibaba"),# ---- Loopback / private (default flags) ----diff --git a/tests/security/test_scoped_metadata_guards.py b/tests/security/test_scoped_metadata_guards.pynew file mode 100644index 0000000000..bafefbf0a8--- /dev/null+++ b/tests/security/test_scoped_metadata_guards.py@@ -0,0 +1,183 @@+"""IPv6 zone identifiers must not change the metadata deny decision."""++import json+import os+from pathlib import Path+import socket+import subprocess+import sys+import textwrap+from unittest.mock import Mock++import pytest++from local_deep_research.security import ssrf_validator as ssrf+from local_deep_research.security.egress.policy import (+ EgressContext,+ EgressScope,+ evaluate_url,+)+++SCOPED_METADATA_IPS = (+ "fd20:ce::254%1",+ "fd20:ce::254%eth0",+ "fd00:ec2::254%1",+ "fd00:ec2::254%eth0",+ "fd00:ec2::254%25eth0",+ "FD00:0EC2:0000:0000:0000:0000:0000:0254%1",+ "fd00:ec2::23%1",+ "fd00:ec2::23%eth0",+ "fd00:ec2::23%25eth0",+ "FD00:0EC2:0000:0000:0000:0000:0000:0023%1",+)+++def _context(scope, local_hostnames=()):+ return EgressContext(+ scope=scope,+ primary_engine="library",+ require_local_llm=False,+ require_local_embeddings=False,+ local_hostnames=local_hostnames,+ )++[email protected]("address", SCOPED_METADATA_IPS)[email protected]("allow_private", [False, True])[email protected]("allow_localhost", [False, True])[email protected]("allow_nat64", [False, True])[email protected]("block_link_local", [False, True])+def test_scoped_metadata_blocks_every_allow_flag_combination(+ address, allow_private, allow_localhost, allow_nat64, block_link_local+):+ assert ssrf.is_ip_blocked(+ address,+ allow_private_ips=allow_private,+ allow_localhost=allow_localhost,+ allow_nat64=allow_nat64,+ block_link_local=block_link_local,+ )++[email protected]("address", SCOPED_METADATA_IPS)[email protected]("scope", list(EgressScope))[email protected]("explicit_local", [False, True])+def test_scoped_metadata_is_denied_before_scope_or_local_hostname_allowances(+ address, scope, explicit_local+):+ context = _context(scope, (address,) if explicit_local else ())+ decision = evaluate_url(f"http://[{address}]/v1", context)+ assert decision.allowed is False+ assert decision.reason == "blocked_metadata_ip"++[email protected]("address", SCOPED_METADATA_IPS)+def test_scoped_metadata_provider_rejection_does_not_depend_on_dns(+ monkeypatch, address+):+ canonical_address = address.partition("%")[0]+ resolver = Mock(+ return_value=[+ (+ socket.AF_INET6,+ socket.SOCK_STREAM,+ socket.IPPROTO_TCP,+ "",+ (canonical_address, 80, 0, 0),+ )+ ]+ )+ monkeypatch.setattr(socket, "getaddrinfo", resolver)+ with pytest.raises(ValueError, match="failed SSRF validation"):+ ssrf.assert_base_url_safe(+ f"http://[{address}]/v1", setting_key="llm.openai_endpoint.url"+ )+ resolver.assert_not_called()+++ "scope", [EgressScope.PRIVATE_ONLY, EgressScope.STRICT]+)+ "address", ["fd12::1%1", "fd12::1%eth0", "::1%1", "::1%lo"]+)+def test_ordinary_scoped_private_and_loopback_destinations_remain_allowed(+ scope, address+):+ assert not ssrf.is_ip_blocked(+ address,+ allow_localhost=True,+ allow_private_ips=True,+ block_link_local=True,+ )+ assert evaluate_url(f"http://[{address}]/v1", _context(scope)).allowed+++ "scope", [EgressScope.PRIVATE_ONLY, EgressScope.STRICT]+)+def test_installed_socket_hook_rejects_scoped_metadata_before_transport(scope):+ # Audit hooks cannot be removed. Use an isolated child so the final+ # connection-refusal witness does not affect unrelated source tests.+ probe = textwrap.dedent(+ """+ import json, socket, sys+ from pathlib import Path+ from local_deep_research.security import install_audit_hook+ from local_deep_research.security import ssrf_validator+ from local_deep_research.security.egress.audit_hook import active_egress_context+ from local_deep_research.security.egress.policy import EgressContext, EgressScope, PolicyDeniedError++ assert Path(ssrf_validator.__file__).resolve() == Path(sys.argv[2]).resolve()+ install_audit_hook()+ witness = []++ class TransportRefused(RuntimeError):+ pass++ def no_wire(event, args):+ if event == "socket.connect":+ witness.append(args[1][0])+ raise TransportRefused("Stop every admitted connect before network I/O")++ sys.addaudithook(no_wire)+ metadata = ["fd00:ec2::254", "fd00:ec2::254%1", "fd00:ec2::23", "fd00:ec2::23%1"]+ controls = ["fd12::1", "fd12::1%1", "::1", "::1%1"]+ context = EgressContext(scope=EgressScope(sys.argv[1]), primary_engine="library",+ require_local_llm=False, require_local_embeddings=False)+ results = []+ with active_egress_context(context):+ for address in metadata + controls:+ sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)+ try:+ sock.connect((address, 80, 0, 0))+ raise AssertionError("The final witness must stop every connect")+ except PolicyDeniedError as exc:+ results.append({"address": address, "denied": True, "reason": exc.decision.reason})+ except TransportRefused:+ results.append({"address": address, "denied": False, "reason": None})+ finally:+ sock.close()+ print(json.dumps({"results": results, "witness": witness}))+ """+ )+ environment = os.environ.copy()+ source_root = Path(ssrf.__file__).resolve().parents[2]+ environment["PYTHONPATH"] = str(source_root)+ environment["PYTHONDONTWRITEBYTECODE"] = "1"+ result = subprocess.run(+ [sys.executable, "-B", "-c", probe, scope.value, ssrf.__file__],+ env=environment,+ text=True,+ capture_output=True,+ check=True,+ timeout=30,+ )+ observed = json.loads(result.stdout)+ assert all(+ item["denied"] and item["reason"] == "blocked_metadata_ip"+ for item in observed["results"][:4]+ )+ assert all(not item["denied"] for item in observed["results"][4:])+ assert observed["witness"] == ["fd12::1", "fd12::1%1", "::1", "::1%1"]diff --git a/tests/security/test_searxng_private_url_warning.py b/tests/security/test_searxng_private_url_warning.pyindex b049bfe0a8..efeb8d90d9 100644--- a/tests/security/test_searxng_private_url_warning.py+++ b/tests/security/test_searxng_private_url_warning.py@@ -229,7 +229,7 @@ class TestGateMirroring:_clear_approvals(monkeypatch)assert (check_searxng_private_url_blocked(- "searxng", "http://169.254.42.42:8080", False+ "searxng", "http://169.254.10.5:8080", False)is not None)diff --git a/tests/security/test_ssrf_dns_pinning.py b/tests/security/test_ssrf_dns_pinning.pyindex 59ab577f21..d964bcaad5 100644--- a/tests/security/test_ssrf_dns_pinning.py+++ b/tests/security/test_ssrf_dns_pinning.py@@ -582,7 +582,7 @@ def test_pinned_request_forwards_block_link_local():whose answer sits in 169.254.0.0/16 is refused under``allow_private_ips`` when the caller keeps link-local blocked, and ispinned as before when it does not."""- resolver = _Resolver({"ll.example": [["169.254.42.42"]]})+ resolver = _Resolver({"ll.example": [["169.254.10.5"]]})with patch.object(dns_pinning, "_real_getaddrinfo", resolver):with pytest.raises(ValueError, match="SSRF|security validation"):with dns_pinning.pinned_request(@@ -593,7 +593,7 @@ def test_pinned_request_forwards_block_link_local():passassert "ll.example" not in dns_pinning._get_pins()- resolver = _Resolver({"ll.example": [["169.254.42.42"]]})+ resolver = _Resolver({"ll.example": [["169.254.10.5"]]})with patch.object(dns_pinning, "_real_getaddrinfo", resolver):with dns_pinning.pinned_request("http://ll.example/", allow_private_ips=Truediff --git a/tests/security/test_ssrf_redirect_bypass.py b/tests/security/test_ssrf_redirect_bypass.pyindex c81fc82324..cde77217e2 100644--- a/tests/security/test_ssrf_redirect_bypass.py+++ b/tests/security/test_ssrf_redirect_bypass.py@@ -1403,7 +1403,7 @@ class TestSafeSessionBlockLinkLocal:(``request``) and on every redirect hop (``send``). Real validator; theallow/deny pairs prove the flag is what decides."""- LINK_LOCAL_URL = "http://169.254.42.42/latest/meta-data"+ LINK_LOCAL_URL = "http://169.254.10.5/latest/meta-data"@staticmethoddef _prepared(url):diff --git a/tests/security/test_ssrf_validator.py b/tests/security/test_ssrf_validator.pyindex 7c1775cf57..30ce198841 100644--- a/tests/security/test_ssrf_validator.py+++ b/tests/security/test_ssrf_validator.py@@ -1714,8 +1714,8 @@ class TestNat64EnvOptOut:def test_env_does_not_unblock_link_local_for_notification_path(self):"""NAT64 opt-in must not reopen link-local metadata for the- notification send path. ``64:ff9b::a9fe:2a2a`` is the NAT64 wrap of- Scaleway's ``169.254.42.42`` (link-local metadata); with+ notification send path. ``64:ff9b::a9fe:a05`` is the NAT64 wrap of+ the link-local ``169.254.10.5`` (not a listed metadata literal); with``block_link_local=True`` it stays blocked even under the carve-out,matching how the direct v4 form is blocked."""from local_deep_research.security.ssrf_validator import is_ip_blocked@@ -1723,7 +1723,7 @@ class TestNat64EnvOptOut:# NAT64 well-known prefix wrap of the link-local metadata address.assert (is_ip_blocked(- "64:ff9b::a9fe:2a2a",+ "64:ff9b::a9fe:a05",allow_private_ips=True,block_link_local=True,allow_nat64=True,@@ -1733,7 +1733,7 @@ class TestNat64EnvOptOut:# RFC 8215 local-use NAT64 prefix wrap of the same address.assert (is_ip_blocked(- "64:ff9b:1:a9fe:2a:2a00::",+ "64:ff9b:1:a9fe:a:500::",allow_private_ips=True,block_link_local=True,allow_nat64=True,@@ -1743,7 +1743,7 @@ class TestNat64EnvOptOut:# Control: the direct v4 link-local form is blocked on this path.assert (is_ip_blocked(- "169.254.42.42",+ "169.254.10.5",allow_private_ips=True,block_link_local=True,allow_nat64=True,@@ -1760,7 +1760,7 @@ class TestNat64EnvOptOut:assert (is_ip_blocked(- "64:ff9b::a9fe:2a2a",+ "64:ff9b::a9fe:a05",allow_private_ips=True,allow_nat64=True,)@@ -1980,10 +1980,10 @@ class TestNat64Rfc6052Embedding:)is True)- # Scaleway link-local 169.254.42.42 at RFC positions, under block_link_local.+ # Link-local 169.254.10.5 at RFC positions, under block_link_local.assert (is_ip_blocked(- "64:ff9b:1:a9fe:2a:2a00:808:808",+ "64:ff9b:1:a9fe:a:500:808:808",allow_private_ips=True,block_link_local=True,allow_nat64=True,diff --git a/tests/security/test_ssrf_validator_extended.py b/tests/security/test_ssrf_validator_extended.pyindex 0b5a1b07d6..5f77ee67ab 100644--- a/tests/security/test_ssrf_validator_extended.py+++ b/tests/security/test_ssrf_validator_extended.py@@ -30,7 +30,7 @@ class TestAlwaysBlockedMetadataIPsConstant:"""AWS IMDS / Azure / OCI / DigitalOcean shared endpoint."""assert "169.254.169.254" in ALWAYS_BLOCKED_METADATA_IPS- def test_contains_aws_ecs_v3_and_v4(self):+ def test_contains_aws_ecs_v3_and_eks_pod_identity(self):assert "169.254.170.2" in ALWAYS_BLOCKED_METADATA_IPSassert "169.254.170.23" in ALWAYS_BLOCKED_METADATA_IPSdiff --git a/tests/security/test_ssrf_validator_high_value.py b/tests/security/test_ssrf_validator_high_value.pyindex 5ad4ac462f..43e21f3d8b 100644--- a/tests/security/test_ssrf_validator_high_value.py+++ b/tests/security/test_ssrf_validator_high_value.py@@ -88,11 +88,10 @@ class TestIsIpBlockedSpecialRanges:def test_link_local_blocked_with_block_link_local_flag(self):"""block_link_local=True (notification path) keeps the wholelink-local range blocked even under allow_private_ips=True —- metadata lives there beyond the always-blocked literals (e.g.- Scaleway 169.254.42.42)."""+ metadata lives there beyond the always-blocked literals."""assert (is_ip_blocked(- "169.254.42.42",+ "169.254.10.5",allow_private_ips=True,block_link_local=True,)@@ -340,6 +339,14 @@ class TestConstants:"169.254.0.23","100.100.100.200","192.0.0.192",+ "168.63.129.16","fd00:ec2::254",+ "fd00:ec2::23",+ "fd20:ce::254",+ "169.254.42.42",+ "fd00:42::42",+ "fd00:a9fe:a9fe::1",+ "fd00:c1::a9fe:a9fe",+ "fe80::a9fe:a9fe",})diff --git a/tests/utilities/test_utilities_layer_contracts.py b/tests/utilities/test_utilities_layer_contracts.pyindex 11e011ac44..305a787f1e 100644--- a/tests/utilities/test_utilities_layer_contracts.py+++ b/tests/utilities/test_utilities_layer_contracts.py@@ -519,9 +519,9 @@ class TestUrlUtilsUnvalidatedInput:@pytest.mark.parametrize("link_local_endpoint",[- # Scaleway instance metadata -- link-local, not one of the- # always-blocked metadata literals.- "http://169.254.42.42/conf",+ # Generic link-local, not one of the always-blocked+ # metadata literals.+ "http://169.254.10.5/conf",# AWS VPC resolver / EC2 legacy helper range -- same /16, not# one of the always-blocked metadata literals."http://169.254.169.253/",diff --git a/tests/web/services/test_notification_coverage.py b/tests/web/services/test_notification_coverage.pyindex f5c14f7aaf..ff5e4b958f 100644--- a/tests/web/services/test_notification_coverage.py+++ b/tests/web/services/test_notification_coverage.py@@ -844,7 +844,9 @@ class TestNotificationService:"http://169.254.169.254/latest/meta-data/", False, id="aws-imds"),pytest.param("http://169.254.170.2/", False, id="aws-ecs-v3"),- pytest.param("http://169.254.170.23/", False, id="aws-ecs-v4"),+ pytest.param(+ "http://169.254.170.23/", False, id="aws-eks-pod-identity"+ ),pytest.param("http://169.254.0.23/", False, id="tencent-metadata"),pytest.param("http://100.100.100.200/", False, id="alibaba-metadata"@@ -891,9 +893,7 @@ class TestNotificationService:# Link-local stays blocked for every notification URL, even# with the private-IP opt-in, so the hint must not offer it.pytest.param("http://[fe80::1]/", False, id="link-local-fe80"),- pytest.param(- "http://169.254.42.42/", False, id="link-local-scaleway"- ),+ pytest.param("http://169.254.10.5/", False, id="link-local-ipv4"),# Plugin-scheme metadata (different validator prefix)pytest.param("signal://169.254.169.254:8080/path",@@ -1028,7 +1028,7 @@ class TestNotificationService:("http://[::ffff:169.254.169.254]/", False),# Link-local: the opt-in never reopens it.("http://[fe80::1]/", False),- ("http://169.254.42.42/", False),+ ("http://169.254.10.5/", False),# Plugin-scheme metadata — never reaches the hint branch via# test_service (prefix guard short-circuits earlier) but pin# the decision directly in case a future caller uses it.diff --git a/tests/web_search_engines/engines/test_full_search.py b/tests/web_search_engines/engines/test_full_search.pyindex 74a253d387..3253060415 100644--- a/tests/web_search_engines/engines/test_full_search.py+++ b/tests/web_search_engines/engines/test_full_search.py@@ -1328,8 +1328,8 @@ class TestAllowPrivateIps:def test_run_with_flag_still_blocks_link_local_url(self):"""NEGATIVE: even with the grant, the rest of 169.254.0.0/16 (provider- metadata outside ``ALWAYS_BLOCKED_METADATA_IPS``, e.g. Scaleway's- 169.254.42.42) is rejected by the real ``validate_url`` via+ metadata outside ``ALWAYS_BLOCKED_METADATA_IPS``, e.g.+ 169.254.10.5) is rejected by the real ``validate_url`` via``block_link_local=True``; the downloader is never invoked."""from local_deep_research.web_search_engines.engines.full_search import (FullSearchResults,@@ -1337,7 +1337,7 @@ class TestAllowPrivateIps:mock_web_search = Mock()mock_web_search.invoke.return_value = [- {"link": "http://169.254.42.42/latest/meta-data", "title": "M"},+ {"link": "http://169.254.10.5/latest/meta-data", "title": "M"},]with (@@ -1377,7 +1377,7 @@ class TestAllowPrivateIps:items = engine._get_full_content([{- "link": "http://169.254.42.42/latest/meta-data",+ "link": "http://169.254.10.5/latest/meta-data","title": "M",}]diff --git a/tests/web_search_engines/engines/test_search_engine_searxng.py b/tests/web_search_engines/engines/test_search_engine_searxng.pyindex 0246e0f617..bb192ba317 100644--- a/tests/web_search_engines/engines/test_search_engine_searxng.py+++ b/tests/web_search_engines/engines/test_search_engine_searxng.py@@ -3695,13 +3695,13 @@ class TestFullSearchPrivateIpGate:def test_gated_instance_still_blocks_link_local_url(self, monkeypatch):"""Even with both approvals, the rest of 169.254.0.0/16 (provider- metadata outside the always-blocked literals, e.g. Scaleway's 169.254.42.42)+ metadata outside the always-blocked literals, e.g. 169.254.10.5)stays blocked via ``block_link_local=True``."""engine = self._make_engine(monkeypatch, instance_gate=True, result_fetch=True)results, mock_batch = self._run_full_search(- self._wrap(engine), "http://169.254.42.42/latest/meta-data"+ self._wrap(engine), "http://169.254.10.5/latest/meta-data")mock_batch.assert_not_called()assert results[0]["full_content"] is None