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.

141 KB
Raw Blame
"""Egress policy module: central PDP for search engines, LLM endpoints,
embeddings, and URL fetches.

This is an in-process correctness guardrail, NOT a hard security boundary.
It defends against honest misconfiguration, prompt-injection-induced
URL fetches, accidental egress, and the LangGraph silent-expansion bug.
It does NOT defend against compromised dependencies, code-execution
in the LDR process, or a determined adversary who can modify the policy
module itself. Operators needing a hard boundary should layer OS-level
controls (network namespaces, firewall rules, restricted Docker).

Vocabulary borrowed from XACML / zero-trust:
  PDP — Policy Decision Point (the evaluate_* functions in this module)
  PEP — Policy Enforcement Point (the call sites that consult the PDP)
"""

from __future__ import annotations

import hashlib
import ipaddress
import json
import re
import socket
import threading
from collections import OrderedDict
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout
from dataclasses import dataclass, field
from enum import Enum
from typing import Literal, Optional
from urllib.parse import unquote, urlsplit

from loguru import logger

from ..log_sanitizer import sanitize_for_log
from ..network_utils import is_private_ip
from ...utilities.type_utils import unwrap_setting


# Bounded DNS lookup timeout; getaddrinfo has no native timeout kwarg, so
# we run it inside a single-shot ThreadPoolExecutor and abandon the
# Future after the timeout elapses. This avoids the previous
# socket.setdefaulttimeout() approach, which mutated a process-global
# setting and could corrupt unrelated network code under concurrency.
_DNS_TIMEOUT_SEC = 2.0


# Hard limit: after this many denied fetches in a single run, fail closed
# even on otherwise-legal fetches. Prevents an exhaust attack via a malicious
# indexed document looping the agent through hundreds of denied URLs.
MAX_DENIED_FETCHES_PER_RUN = 50

# Only SECURITY-relevant denials count toward the per-run quota. Benign parse
# failures (a mailto:/ftp:/tel: link or a malformed href scraped from a page)
# are common in legitimate documents and must NOT exhaust the budget — doing
# so would make a long PUBLIC_ONLY run start refusing legitimate public URLs
# mid-run. These reasons are still audit-logged; they just don't tick the quota.
# ``dangerous_scheme`` (javascript:/data:/file:/… hrefs) belongs here too: these
# are non-fetchable, non-network schemes scraped from ordinary HTML (onclick
# handlers, inline data: URIs), so — like ``unsupported_scheme`` — they can't
# cause egress and shouldn't let a doc full of data: URIs exhaust the budget.
_NON_QUOTA_DENIAL_REASONS = frozenset(
    {"url_malformed", "unsupported_scheme", "no_hostname", "dangerous_scheme"}
)


class EgressScope(str, Enum):
    """User-declared egress boundary for a research run.

    - STRICT: only the user's primary engine; no expansion at all.
    - PUBLIC_ONLY: any public (external web/academic) engine.
    - PRIVATE_ONLY: any private (local collection / library) engine.
    - BOTH: INTERNAL ONLY — the resolved scope for an unclassifiable ADAPTIVE
      primary (allow any classified engine, no local-inference coupling). It is
      NO LONGER a user-selectable scope: `both` was the "muddy middle" (ADR-0007
      Problem 3), retired in favour of `adaptive` + per-collection `is_public`.
      A residual user `both` (stored / env / queued) is coerced to `adaptive`
      by ``context_from_snapshot`` and migration 0019.
    - ADAPTIVE: scope FOLLOWS the primary engine — a concrete private
      primary behaves as PRIVATE_ONLY, a concrete public primary as
      PUBLIC_ONLY, and an unclassifiable primary as BOTH.
      The default: most users never touch scope and "it just matches my
      main engine." Resolved to a concrete scope at context construction;
      the stored EgressContext carries the RESOLVED scope, not ADAPTIVE.
    - UNPROTECTED: escape hatch — egress protection is DISABLED for the run.
      Any engine / URL / provider is permitted; the hard SSRF and
      cloud-metadata blocks in ``evaluate_url`` still apply. Not recommended.
    """

    STRICT = "strict"
    PUBLIC_ONLY = "public_only"
    PRIVATE_ONLY = "private_only"
    BOTH = "both"
    ADAPTIVE = "adaptive"
    UNPROTECTED = "unprotected"


USER_SELECTABLE_PROTECTED_SCOPES = frozenset(
    {
        EgressScope.ADAPTIVE,
        EgressScope.PUBLIC_ONLY,
        EgressScope.PRIVATE_ONLY,
        EgressScope.STRICT,
    }
)


def unprotected_egress_allowed() -> bool:
    """Return whether the operator enabled the unprotected escape hatch."""
    from ...settings.env_registry import get_env_setting

    return bool(get_env_setting("policy.allow_unprotected_egress", False))


# Code-side single source of truth for the default egress scope, used by
# every reader that needs a fallback for a MISSING policy.egress_scope key
# (partial snapshots from the programmatic API, un-bootstrapped settings
# DBs). Import THIS instead of hardcoding a string literal: scattered
# literals are how the registry default ("adaptive") and the code
# fallbacks ("both") drifted apart in the first place. Must match the
# registered default in defaults/default_settings.json — pinned by
# tests/security/test_egress_policy.py::
# test_default_scope_constant_matches_registry.
DEFAULT_EGRESS_SCOPE: str = EgressScope.ADAPTIVE.value


@dataclass(frozen=True)
class EgressContext:
    """Frozen per-run policy snapshot.

    Constructed once via ``context_from_snapshot()`` at run-start.
    The dataclass is frozen, but mutable internals (``_dns_cache``,
    ``_fetch_denial_count``) use ``field(init=False, default_factory=...)``
    so they can accumulate state during a run. Counters live inside a
    dict because direct ``int`` field reassignment fails on ``frozen=True``.
    """

    scope: EgressScope
    primary_engine: str
    require_local_llm: bool
    require_local_embeddings: bool
    local_hostnames: tuple[str, ...] = ()
    username: Optional[str] = None
    # Mutable internal state (kept off the public surface).
    _dns_cache: dict = field(init=False, default_factory=dict, repr=False)
    _fetch_denial_count: dict = field(
        init=False, default_factory=lambda: {"count": 0}, repr=False
    )
    # Guards _dns_cache + _fetch_denial_count mutations. Scope is the
    # cache writes only — DNS I/O must NOT happen while holding the lock,
    # or concurrent subagent threads serialize on each other's lookups.
    _lock: threading.RLock = field(
        init=False, default_factory=threading.RLock, repr=False
    )


@dataclass(frozen=True)
class Decision:
    """Result of a PDP evaluation. ``reason`` is a short machine code
    (e.g. ``"unclassified"``, ``"scope_mismatch"``) — never the user's
    rejected query or URL content.
    """

    allowed: bool
    reason: str


@dataclass(frozen=True, slots=True)
class EngineClassification:
    """Public/local classification for one search engine."""

    is_public: bool | None
    is_local: bool | None


class PolicyDeniedError(RuntimeError):
    """Raised by PEPs when a policy decision is hard-stop denial.

    Raising (rather than returning a graceful empty result) ensures
    consistent denial latency, which mitigates the LangGraph timing-leak
    pattern where an LLM could infer policy state from how fast a denied
    tool call returns.
    """

    def __init__(self, decision: Decision, target: str = ""):
        self.decision = decision
        self.target = target
        super().__init__(f"policy_denied: {decision.reason}")


def parse_user_egress_scope(
    raw: object,
    *,
    disabled_unprotected: Literal["reject", "adaptive"] = "reject",
) -> EgressScope:
    """Parse a user-facing scope and enforce the operator escape-hatch gate.

    BOTH is deliberately absent from the protected allowlist: it remains an
    internal adaptive-resolution result, not a value users may select. Runtime
    readers can request the protective adaptive fallback for stale queued
    unprotected values; request and settings writers use the default hard
    rejection.
    """
    if disabled_unprotected not in {"reject", "adaptive"}:
        raise ValueError("disabled_unprotected must be 'reject' or 'adaptive'")
    if not isinstance(raw, str):
        raise PolicyDeniedError(
            Decision(False, "unknown_egress_scope"), target=str(raw)
        )
    normalized = raw.strip().lower()
    try:
        scope = EgressScope(normalized)
    except ValueError as exc:
        raise PolicyDeniedError(
            Decision(False, "unknown_egress_scope"), target=str(raw)
        ) from exc
    if scope in USER_SELECTABLE_PROTECTED_SCOPES:
        return scope
    if scope == EgressScope.UNPROTECTED:
        if unprotected_egress_allowed():
            return scope
        if disabled_unprotected == "adaptive":
            return EgressScope.ADAPTIVE
        raise PolicyDeniedError(
            Decision(False, "unprotected_egress_disabled"), target=str(raw)
        )
    raise PolicyDeniedError(
        Decision(False, "unknown_egress_scope"), target=str(raw)
    )


def effective_scope_for_display(raw: object) -> str:
    """Return a canonical, presentation-safe user scope value.

    Invalid values, retired both, and operator-disabled unprotected selections
    render as the protective default. This helper is presentation only;
    enforcement remains in context_from_snapshot and its PEPs.
    """
    try:
        return parse_user_egress_scope(
            raw, disabled_unprotected="adaptive"
        ).value
    except PolicyDeniedError:
        return DEFAULT_EGRESS_SCOPE


def _is_nat64_wrapped_metadata(hostname: str) -> bool:
    """True iff ``hostname`` parses as an IPv6 NAT64 address wrapping a
    cloud-metadata IPv4 (AWS / Azure / GCE / etc).

    The wrapping passes ``is_private_ip`` (because IPv6 link-local
    ranges match) but the embedded IPv4 actually reaches the metadata
    endpoint. We classify these as PUBLIC so STRICT and PRIVATE_ONLY
    refuse to fetch them.
    """
    try:
        import ipaddress

        from ..ssrf_validator import is_nat64_wrapped_metadata_ip

        candidate = hostname
        if candidate.startswith("[") and candidate.endswith("]"):
            candidate = candidate[1:-1]
        ip = ipaddress.ip_address(candidate)
        return is_nat64_wrapped_metadata_ip(ip)
    except (ValueError, TypeError):
        return False
    except Exception:  # pragma: no cover - defensive
        return False


# A DNS label as host classification accepts it: ASCII letters, digits,
# hyphens and underscores, 1-63 characters, not starting or ending with a
# hyphen. Underscores are outside LDH but appear in container and compose
# service names (the bundled docker-compose.yml names its Ollama container
# ``ollama_service``); no resolver or HTTP client reads one as anything but
# a literal character.
_DNS_LABEL_RE = re.compile(r"[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?")

# A final label ``inet_aton`` reads as a number (decimal, octal or 0x-hex).
# A name ending in one is an IPv4 address in a shorthand notation, not a DNS
# name; real top-level domains are never numeric.
_NUMERIC_LABEL_RE = re.compile(r"[0-9]+|0x[0-9a-f]*")


def _canonical_host(hostname: object) -> Optional[str]:
    """The canonical spelling of ``hostname`` for host classification, or
    None when it has none.

    The single host canonicaliser for every classification caller
    (``_classify_host`` and through it the require-local LLM / embeddings
    checks and the engine URL classification, the
    ``llm.allowed_local_hostnames`` override, and the settings validator for
    that list). Callers pass the host as parsed or configured, NOT
    percent-decoded: it is decoded here exactly once, as the HTTP clients
    do before connecting, and lower-cased (``str.lower``, as ``urlsplit``
    does for a URL host). A single trailing root dot is then dropped, except
    from a bracketed IPv6 literal.

    Before any decoding, a host that contains both ``:`` and ``%`` as
    written (an IPv6 literal with a zone ID, bracketed or not) returns
    None. ``%`` is both the zone delimiter and the escape character, so
    such a host has two readings: an HTTP client takes what follows the
    ``%`` as the zone, while one decode can splice an encoded zone into the
    address (``fd00:ec2::254%31`` would decode to the different address
    ``fd00:ec2::2541``, and ``fd12::1%3a1`` to ``fd12::1:1``).

    The result is accepted only if it is ASCII and either

    * an IP literal ``ipaddress.ip_address`` parses as written: an IPv4
      address only in dotted-quad decimal, an IPv6 address bracketed or
      not but without a trailing dot, returned in its standard (compressed)
      form; or
    * a plain DNS name: dot-separated labels of ASCII letters, digits,
      hyphens and underscores (``_DNS_LABEL_RE``), at most 253 characters,
      whose last label is not numeric, so that ``inet_aton`` cannot read it
      as an IPv4 address.

    Everything else returns None: an IPv6 zone ID in any spelling (above), a
    ``%`` left after the one decode (a second level of percent-encoding), any
    non-ASCII character (IDN, fullwidth or ideographic spellings that need
    IDNA folding; checked on the decoded text before case folding, so a
    character ``str.lower`` turns into ASCII, the KELVIN SIGN, is refused
    too), whitespace or control characters, empty labels, and the
    integer / hex / octal / short IPv4 notations. Classification treats such
    a host as unclassified instead of guessing which destination a resolver
    or client would make of it. Pure string logic: no DNS, never raises.
    """
    if not isinstance(hostname, str) or not hostname:
        return None
    # An IPv6-style host carrying a zone delimiter, checked as written: no
    # decoding may turn an encoded zone into part of the address. Brackets
    # contain neither character, so this holds bracketed or not.
    if ":" in hostname and "%" in hostname:
        return None
    decoded = unquote(hostname)
    # ASCII-only is checked BEFORE case folding: str.lower maps the KELVIN
    # SIGN (U+212A) to an ASCII "k", so a host spelt with it would pass as
    # a plain DNS name.
    if not decoded.isascii() or "%" in decoded:
        return None
    host = decoded.lower()
    if host.startswith("[") and host.endswith("]"):
        try:
            address = ipaddress.ip_address(host[1:-1])
        except ValueError:
            return None
        return str(address) if address.version == 6 else None
    trailing_dot = host.endswith(".")
    if trailing_dot:
        host = host[:-1]
    if not host:
        return None
    try:
        address = ipaddress.ip_address(host)
    except ValueError:
        address = None
    if address is not None:
        if address.version == 6:
            # A root dot means nothing after an IPv6 literal; the resolver
            # would look the text up as a name.
            return None if trailing_dot else str(address)
        # str() equality refuses a zero-padded IPv4 octet on any Python
        # version.
        return host if str(address) == host else None
    if len(host) > 253:
        return None
    labels = host.split(".")
    if not all(_DNS_LABEL_RE.fullmatch(label) for label in labels):
        return None
    if _NUMERIC_LABEL_RE.fullmatch(labels[-1]):
        return None
    try:
        socket.inet_aton(host)
    except (OSError, ValueError, TypeError, UnicodeError):
        return host
    # The platform resolver reads it as an IPv4 address after all.
    return None


def _is_metadata_ip(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
    """True iff ``ip`` is a cloud-metadata address
    (``ALWAYS_BLOCKED_METADATA_IPS``), ignoring an IPv6 zone ID, or an IPv6
    address that carries one where an IPv4-embedding mechanism puts the
    IPv4 address it reaches: the RFC 6052 positions for every NAT64 prefix
    length, well-known or network-specific (the /96 position is also where
    IPv4-mapped, IPv4-compatible and IPv4-translated addresses carry it),
    6to4 and both Teredo addresses. Pure: no DNS, never raises.
    """
    from ..ssrf_validator import (
        _NAT64_V4_BYTE_INDICES,
        ALWAYS_BLOCKED_METADATA_IPS,
    )

    if isinstance(ip, ipaddress.IPv6Address) and ip.scope_id:
        ip = ipaddress.IPv6Address(ip.packed)
    if str(ip) in ALWAYS_BLOCKED_METADATA_IPS:
        return True
    if not isinstance(ip, ipaddress.IPv6Address):
        return False
    packed = ip.packed
    embedded = [
        ipaddress.IPv4Address(bytes(packed[i] for i in positions))
        for positions in _NAT64_V4_BYTE_INDICES.values()
    ]
    if ip.sixtofour is not None:
        embedded.append(ip.sixtofour)
    if ip.teredo is not None:
        embedded.extend(ip.teredo)
    return any(str(v4) in ALWAYS_BLOCKED_METADATA_IPS for v4 in embedded)


def _is_metadata_host(host: str) -> bool:
    """True iff the CANONICAL host ``host`` (``_canonical_host`` output)
    names a cloud-metadata endpoint: a listed metadata hostname
    (``ALWAYS_BLOCKED_METADATA_HOSTNAMES``) or an address ``_is_metadata_ip``
    recognises. No normalisation happens here; pass a canonical host."""
    from ..ssrf_validator import ALWAYS_BLOCKED_METADATA_HOSTNAMES

    if host in ALWAYS_BLOCKED_METADATA_HOSTNAMES:
        return True
    try:
        address = ipaddress.ip_address(host)
    except ValueError:
        return False
    return _is_metadata_ip(address)


def _classifiable_host(hostname: object) -> Optional[str]:
    """``_canonical_host(hostname)``, or None when the host has no canonical
    spelling or names a cloud-metadata endpoint. A None here means
    "unclassified": never local, and never eligible as a public endpoint
    either. Takes the host as parsed or configured, not percent-decoded."""
    host = _canonical_host(hostname)
    if host is None or _is_metadata_host(host):
        return None
    return host


def _declared_local_hosts(ctx: EgressContext) -> frozenset[str]:
    """The ``llm.allowed_local_hostnames`` entries classification honours,
    in canonical form. An entry without a canonical spelling, or one that
    names a cloud-metadata endpoint, is ignored (``_classifiable_host``)."""
    return frozenset(
        host
        for host in map(_classifiable_host, ctx.local_hostnames)
        if host is not None
    )


def _is_metadata_destination(hostname: str) -> bool:
    """True iff ``evaluate_url`` should refuse ``hostname`` as a
    cloud-metadata destination: the fetch-time check, deliberately broader
    than classification.

    ``hostname`` is the host as ``urlsplit`` returns it (not decoded). It is
    expanded by ``_policy_host_forms`` into every spelling the resolver may
    connect to (percent-decoded once, not decoded, and decoded until stable;
    trailing dots removed; IDNA-folded forms of a non-ASCII host; the dotted
    quad of an octal / hex / integer / short IPv4 notation), and refused
    when any form is a listed metadata hostname (``is_metadata_hostname``,
    checked on every form, which also fails closed on a non-ASCII name no
    IDNA encoder can encode) or an address ``_is_metadata_ip`` recognises,
    zone-scoped IPv6 included. String checks only, no DNS: a
    name that merely resolves to a metadata address is left to the SSRF
    validator at the connection point.

    Classification does not use this. It accepts only canonical hosts
    (``_canonical_host``), so a spelling recognised only here is
    unclassified there anyway, and it checks the canonical form with
    ``_is_metadata_host``.
    """
    from ..ssrf_validator import is_metadata_hostname

    if not isinstance(hostname, str) or not hostname:
        return False
    for candidate in _policy_host_forms(hostname):
        if is_metadata_hostname(candidate):
            return True
        try:
            address = ipaddress.ip_address(candidate)
        except ValueError:
            continue
        if _is_metadata_ip(address):
            return True
    return False


def _resolve_with_timeout(hostname: str) -> Optional[list]:
    """Resolve ``hostname`` via getaddrinfo with a bounded timeout.

    Returns the addrinfo list on success or None on timeout / lookup
    failure. getaddrinfo has no native timeout, so we drive it from a
    single-shot worker thread and abandon the Future on timeout — far
    safer than socket.setdefaulttimeout(), which mutates a
    process-global setting and races with unrelated network code.
    """

    def _do_lookup():
        return socket.getaddrinfo(hostname, None, type=socket.SOCK_STREAM)

    # NB: do NOT use ``with ThreadPoolExecutor(...)`` here. The context
    # manager's __exit__ calls shutdown(wait=True), which blocks until the
    # worker thread finishes — so a hung getaddrinfo would defeat the whole
    # point of the timeout (the call would return only after the OS DNS
    # timeout, not after _DNS_TIMEOUT_SEC). Instead we abandon the worker on
    # timeout via shutdown(wait=False): the caller returns promptly and the
    # orphaned thread dies on its own when getaddrinfo eventually returns.
    executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="ldr-dns")
    future = executor.submit(_do_lookup)
    try:
        return future.result(timeout=_DNS_TIMEOUT_SEC)
    except (FutureTimeout, socket.gaierror, socket.timeout, OSError):
        return None
    except Exception:  # pragma: no cover - defensive
        return None
    finally:
        # wait=False so a timed-out lookup does not re-block here; a
        # completed lookup leaves an idle thread that shuts down at once.
        executor.shutdown(wait=False)


_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: 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
    lock (the DNS lookup is intentionally unsynchronized). If a round-robin
    DNS name resolves to a private IP for one thread and a public IP for
    another, last-writer-wins would let a later call flip an earlier call's
    result — cache *incoherence* that could relax PRIVATE_ONLY/STRICT on a
    subsequent fetch. Pinning the first writer's value makes the per-run
    classification stable and deterministic regardless of completion order.
    """
    with ctx._lock:
        existing = ctx._dns_cache.get(hostname, _UNCACHED)
        if existing is not _UNCACHED:
            return existing
        ctx._dns_cache[hostname] = value
        return value


def _classify_host(
    hostname: str, ctx: EgressContext, allow_dns: bool = True
) -> Optional[bool]:
    """Classify a host as local (True) / public (False) / unknown (None).

    ``hostname`` is the host as parsed from the URL or configured value,
    NOT percent-decoded: ``_canonical_host`` decodes it exactly once. Only a
    plain DNS name or a canonical IP literal is classified. Any other
    spelling (residual ``%``, IPv6 zone ID, non-ASCII, control characters,
    integer / hex / octal / short IPv4) and any cloud-metadata name or
    address, in canonical spelling or wrapped in an IPv6 form, returns
    False: "not local", which every require-local caller relies on. It does
    NOT mean "public, therefore eligible": a caller that reads False that way
    (the engine URL fail-up in ``_classify_engine_url``) checks
    ``_classifiable_host`` first and treats None from it as unclassified.

    A canonical host is local when it is listed in
    ``llm.allowed_local_hostnames`` (compared in canonical form, so case and
    a trailing dot do not matter; an entry without a canonical spelling is
    ignored), else it is classified by ``_classify_destination``: by its
    literal address, or by every address DNS returns for it. Falls back to
    public on DNS timeout (fail-safe).
    """
    if not hostname:
        return None
    host = _classifiable_host(hostname)
    if host is None:
        return False
    if host in _declared_local_hosts(ctx):
        return True
    return _classify_destination(host, ctx, allow_dns=allow_dns)


def _classify_destination(
    hostname: str, ctx: EgressContext, allow_dns: bool = True
) -> Optional[bool]:
    """Classify ``hostname`` by its literal address or its DNS answers:
    local (True) / public (False) / unknown (None).

    No normalisation and no ``local_hostnames`` override: ``_classify_host``
    calls this with a canonical host after both, and ``evaluate_url`` calls
    it for a host without a canonical spelling, which it classifies as it
    always has (see ``_classify_url_host``).

    Uses the run-scoped DNS cache to avoid repeated ``getaddrinfo`` lookups.

    Lock discipline: cache reads and writes are guarded by ``ctx._lock``;
    the DNS lookup itself runs OUTSIDE the lock so concurrent subagent
    threads don't serialize on each other's DNS calls. Cache writes are
    first-writer-wins (``_cache_classification``) so a hostname's
    classification is stable for the run even under concurrent disagreeing
    lookups.
    """
    # Cache hit — read under the lock so concurrent writers don't tear
    # the dict.
    with ctx._lock:
        if hostname in ctx._dns_cache:
            return ctx._dns_cache[hostname]

    # NAT64-wrapped metadata IPs (e.g. 64:ff9b::169.254.169.254) classify
    # as link-local by is_private_ip but actually wrap AWS/GCE instance
    # metadata. Force them to PUBLIC so STRICT/PRIVATE_ONLY don't allow
    # them. Check happens BEFORE is_private_ip so the wrapping wins.
    if _is_nat64_wrapped_metadata(hostname):
        return _cache_classification(ctx, hostname, False)

    # String-literal check first (no DNS needed for IPs and known literals).
    # If the helper itself raises (malformed hostname, broken stdlib edge case),
    # fall through to DNS resolution rather than fail the whole evaluation —
    # the DNS path has its own bounded timeout and error handling.
    from ..ssrf_validator import is_ip_blocked

    try:
        # A literal cloud-metadata IP (169.254.169.254, fd00:ec2::254, …) passes
        # is_private_ip (link-local) but must NOT be treated as local — otherwise
        # STRICT/PRIVATE_ONLY would accept an IMDS SSRF target as a "local"
        # inference/search host. Mirror the DNS-branch metadata block below.
        # is_ip_blocked returns False for non-IP hostnames (ValueError → False),
        # so legitimate hostnames still fall through to is_private_ip / DNS.
        # block_link_local extends the same classification from the literal
        # metadata-address list to the whole IPv4 and IPv6 link-local ranges,
        # which must not be admitted under STRICT/PRIVATE_ONLY.
        #
        # Regression evidence and local-backend controls:
        # tests/security/test_llm_endpoint_link_local_hardening.py
        # - test_link_local_does_not_classify_as_local_in_egress_policy
        # - test_self_hosted_still_classifies_as_local
        #
        # Localhost and RFC1918 are untouched -- self-hosted backends live
        # there and must keep working.
        if is_ip_blocked(
            hostname,
            allow_localhost=True,
            allow_private_ips=True,
            block_link_local=True,
        ):
            return _cache_classification(ctx, hostname, False)
        # 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(
            "is_private_ip raised on hostname, falling back to DNS",
            error=str(exc),
        )

    # DNS-resolved classification — runs OUTSIDE the lock.
    if not allow_dns:
        # The caller (the advisory warning-banner render path) opted OUT of
        # the synchronous getaddrinfo so a settings-page render never blocks
        # up to _DNS_TIMEOUT_SEC on a lookup. Return "unknown" so adaptive
        # scope resolution falls back to the engine's static classification.
        # Deliberately NOT cached — a later enforcement-path call (allow_dns
        # default True) must still resolve this host for real.
        return None
    addr_info = _resolve_with_timeout(hostname)
    if addr_info is None:
        # Fail-safe: unresolvable / timeout → treat as public.
        return _cache_classification(ctx, hostname, False)

    # 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]
            # A hostname that resolves to a cloud-metadata IP must NOT be
            # treated as local: link-local metadata IPs (169.254.169.254, …)
            # pass is_private_ip, which would classify the host local and let
            # STRICT/PRIVATE_ONLY fetch it. Classify as public so those scopes
            # refuse it — mirrors the literal-IP metadata block in evaluate_url
            # and the NAT64 handling just below. (Under PUBLIC_ONLY/BOTH the
            # SSRF validator at the actual fetch is the metadata backstop.)
            if is_ip_blocked(
                ip_str,
                allow_localhost=True,
                allow_private_ips=True,
                block_link_local=True,
            ):
                return _cache_classification(ctx, hostname, False)
            if _is_nat64_wrapped_metadata(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, None if ambiguous_address else not public_address
    )


def _get_engine_class(engine_name: str):
    """Lazy load the engine class from the registry to avoid circular imports."""
    # Import is lazy to break the dependency cycle:
    # security/* → engines/* → security/*
    from ...web_search_engines.engine_registry import ENGINE_REGISTRY
    from ..module_whitelist import get_safe_module_class

    entry = ENGINE_REGISTRY.get(engine_name)
    if entry is None:
        return None
    try:
        return get_safe_module_class(entry.module_path, entry.class_name)
    except Exception:
        return None


def _engine_flags(engine_cls):
    """Read the (is_public, is_local, url_setting) triple from an engine class.

    Uses ``is True`` / ``is False`` semantics: a missing attribute is treated
    as "not declared", which is distinct from an attribute explicitly set
    to ``False``.
    """
    is_public = getattr(engine_cls, "is_public", None)
    is_local = getattr(engine_cls, "is_local", None)
    url_setting = getattr(engine_cls, "url_setting", None)
    return is_public, is_local, url_setting


def _resolve_collection_is_public(
    engine_name: str, username: Optional[str]
) -> bool:
    """Look up a collection engine's per-collection ``is_public`` flag.

    ``engine_name`` is ``"collection_<uuid>"`` or ``"library"``. The
    aggregate ``library`` is always private (it spans all local docs).
    Fails closed to private (False) on any lookup error or missing row —
    a collection we can't classify must NOT be treated as public.
    """
    if engine_name == "library" or not engine_name.startswith("collection_"):
        return False
    collection_id = engine_name[len("collection_") :]
    try:
        from ...database.models.library import Collection
        from ...database.session_context import get_user_db_session

        with get_user_db_session(username) as session:
            row = (
                session.query(Collection)
                .filter(Collection.id == collection_id)
                .first()
            )
            return bool(getattr(row, "is_public", False)) if row else False
    except Exception:  # noqa: silent-exception - fail closed to private
        logger.debug(
            "could not resolve collection is_public; treating as private",
            engine=engine_name,
        )
        return False


# ---------------------------------------------------------------------------
# Vector-store (RAG sink) classification
# ---------------------------------------------------------------------------

# Provider keys known to keep every byte on this machine. This is a FALLBACK
# ONLY — the authoritative signal is the provider class's ``is_local_file``
# flag (``vector_stores/base.py``); this set is consulted just when the class
# cannot be introspected (e.g. a partial install of an optional backend).
# Like the snapshot-less LLM allow-list below, keeping it tight is the point:
# a provider key that is not enumerated here and whose class cannot be loaded
# is treated as REMOTE, not local.
_LOCAL_FILE_VECTOR_STORE_PROVIDERS = frozenset({"faiss"})

# Prefixes a *network host* can never start with, so a vector-store URI that
# begins with one is unambiguously a local filesystem path (e.g. a Milvus-Lite
# style "./store.db"). Deliberately conservative: anything not matched here — a
# bare "store.db", a "host:port" — is NOT assumed to be a path and goes through
# the DNS classifier, which fails up to public when it cannot resolve.
#
# NOTE: a bare "/" is intentionally NOT in this tuple. A URI authority (the
# "//host[:port]" form used by e.g. a Milvus endpoint written without a
# scheme) also starts with "/", so treating a single leading "/" as
# sufficient would misclassify a network host as a local path. A genuine
# absolute path is handled separately by ``_is_local_filesystem_uri`` — a
# single leading "/" whose second character is NOT another "/".
_LOCAL_PATH_URI_PREFIXES = ("./", "../", "~/", "~\\", ".\\", "..\\")


def _vector_store_class(provider: str):
    """Load a vector-store provider's class, or ``None`` if unavailable.

    Import is lazy and failure-tolerant: an optional backend whose driver is
    not installed (or an unknown provider key) must not break classification —
    the caller treats an un-introspectable non-default provider as remote.
    """
    if not provider:
        return None
    try:
        from ...vector_stores.config import get_vector_store_class

        return get_vector_store_class(provider)
    except Exception:
        logger.debug(
            "vector-store provider class unavailable; "
            "classifying from the provider key alone",
            provider=sanitize_for_log(provider),
        )
        return None


def _normalize_provider_key(raw) -> str:
    """Normalize a provider key the way the vector-store factory does."""
    if not isinstance(raw, str):
        return ""
    # Lazy import: ``llm.providers.base`` imports ``security.egress``, so a
    # module-level import here would be circular.
    from ...llm.providers.base import normalize_provider

    return normalize_provider(raw) or ""


def _resolve_index_vector_store_providers(
    engine_name: str, username: Optional[str]
) -> set:
    """Providers recorded on the CURRENT ``RAGIndex`` rows for this engine.

    A collection is queried through the store its index was built in, which
    can differ from the currently configured default, so the recorded provider
    is an additional (tightening) signal on top of the settings-resolved one.
    ``library`` spans every collection, so every current row counts.

    Fails SOFT (empty set) when the column does not exist (older schema), the
    DB is unavailable, or anything else goes wrong: the settings-resolved
    provider remains the primary signal, and the endpoint URI that decides
    exposure comes from settings regardless.
    """
    try:
        from ...database.models.library import RAGIndex
        from ...database.session_context import get_user_db_session

        column = getattr(RAGIndex, "vector_store_provider", None)
        if column is None:
            return set()  # schema without a provider column: FAISS-only
        with get_user_db_session(username) as session:
            query = session.query(column).filter(RAGIndex.is_current.is_(True))
            if engine_name != "library":
                query = query.filter(RAGIndex.collection_name == engine_name)
            return {
                key
                for key in (_normalize_provider_key(row[0]) for row in query)
                if key
            }
    except Exception:  # noqa: silent-exception - additive signal only
        logger.debug(
            "could not resolve RAG index vector-store providers",
            engine=sanitize_for_log(engine_name),
        )
        return set()


def _resolve_vector_store_providers(
    engine_name: str, ctx: EgressContext, settings_snapshot: Optional[dict]
) -> set:
    """Every vector-store provider a library/collection run could query.

    The union of the settings-resolved default and the providers recorded on
    the engine's current index rows. An EMPTY set means the vector-store layer
    itself could not be reached — in which case the run cannot construct a
    store either, so nothing can leave the box and the caller keeps the
    (contained) status quo.
    """
    providers = set()
    try:
        from ...vector_stores.config import resolve_provider

        key = _normalize_provider_key(resolve_provider(settings_snapshot))
        if key:
            providers.add(key)
    except Exception:  # noqa: silent-exception - see docstring
        logger.debug("vector-store provider resolution unavailable")
    providers |= _resolve_index_vector_store_providers(
        engine_name, getattr(ctx, "username", None)
    )
    return providers


def _starts_with_double_separator(s: str) -> bool:
    """True when ``s`` opens with two path-separator characters.

    Covers all four combinations of "/" and "\\" — "//", "/\\", "\\/", and
    "\\\\" — since ``ntpath.normpath`` treats any of them as the start of a
    UNC network-share prefix on Windows (e.g. ``ntpath.normpath("/\\host/x")
    == "\\\\host\\x"``). A forward-slash-only check lets the mixed-slash
    forms smuggle a remote share past the "unambiguously local" classifier.
    """
    return len(s) >= 2 and s[0] in "/\\" and s[1] in "/\\"


# ``urllib.parse.urlsplit`` does NOT parse the string it is handed verbatim.
# Following the WHATWG URL parser it first lstrips every C0 control character
# and space, then DELETES every tab, CR and LF from ANYWHERE in the URL
# (CPython's ``_WHATWG_C0_CONTROL_OR_SPACE`` and
# ``_UNSAFE_URL_BYTES_TO_REMOVE``). ``str.strip()`` does neither: it leaves
# "\x00" and the other non-whitespace C0 controls in place, and never touches
# a tab in the MIDDLE of a string.
_URL_PARSER_LEADING_STRIP = "".join(chr(code) for code in range(0x20)) + " "
_URL_PARSER_REMOVED_CHARS = ("\t", "\r", "\n")


def _normalize_uri_like_url_parser(value: str) -> str:
    """``value`` reduced to the string ``urlsplit`` would actually parse.

    Exists for the RAW string tests in ``_is_local_filesystem_uri``
    (``startswith``, ``_starts_with_double_separator``, a drive-letter index),
    whose verdict is consumed side by side with ``_classify_engine_url``,
    which reads the host out of ``urlsplit``. Judging the raw string opens a
    parser differential in which one value is simultaneously "a local
    filesystem path" to ``str.startswith`` and "an authority" to every real
    URL parser:

    * ``"x:/\\t/attacker.example.com:19530"`` looks drive-absolute to a
      literal ``"//"`` test (``uri[2:]`` is ``"/\\t/..."``), while
      ``urlsplit`` deletes the tab and reports netloc
      ``attacker.example.com:19530``.
    * ``"/\\t/attacker.example.com/share/db"`` looks like an ordinary
      single-slash absolute path to ``_starts_with_double_separator``, while
      ``urlsplit`` deletes the tab and reports the same authority.
    * A leading ``"\\x00"`` (or any other non-whitespace C0 control) survives
      ``str.strip()`` and defeats every raw prefix test, while ``urlsplit``
      lstrips it away.

    Normalising once, here, is what keeps those predicates and ``urlsplit``
    from drifting apart again.

    A raw-string test is not the only caller that needs this. The final
    ``strip()`` is BIDIRECTIONAL, and its LEADING half removes 19
    Unicode-whitespace codepoints that ``urlsplit``'s WHATWG lstrip
    (``\\x00``-``\\x20`` only) leaves in place: U+0085, U+00A0, U+1680,
    U+2000-U+200A, U+2028, U+2029, U+202F, U+205F and U+3000. A leading one
    of those makes ``urlsplit`` report an EMPTY scheme, so a function that
    asks the parser for the scheme does NOT already get this preprocessing
    for free. The call is therefore load-bearing in
    ``_file_uri_names_a_remote_share``: without it,
    "\\xa0file://localhost//attacker.example.com/share/db" has scheme "" and
    is not a ``file://`` URI to that function, the network-share rejection
    never fires, and the entry falls through to hostname classification —
    where a sibling entry such as "127.0.0.1" answers LOCAL and the whole
    setting classifies contained. Never drop this call on the ground that
    ``urlsplit`` repeats it; for the leading-whitespace half it does not.

    Only the TRAILING half of that ``strip()`` is a pure caller-compatibility
    trim: ``urlsplit`` keeps trailing whitespace where this does not, but
    trailing whitespace can never turn a local path into an authority, so the
    extra trim cannot make a remote endpoint look local.
    """
    normalized = value.lstrip(_URL_PARSER_LEADING_STRIP)
    for char in _URL_PARSER_REMOVED_CHARS:
        normalized = normalized.replace(char, "")
    return normalized.strip()


def _is_local_filesystem_uri(value) -> bool:
    """True when a vector-store URI is unambiguously a local file path."""
    if not isinstance(value, str):
        return False
    # Judge the string ``urlsplit`` would parse, never the raw one — see
    # ``_normalize_uri_like_url_parser``. Every prefix, separator and
    # drive-letter test below is a RAW string test, so without this the
    # "local drive path" / "single-slash absolute path" verdicts diverge from
    # the host ``_classify_engine_url`` goes on to classify. This call is what
    # stops "x:/\t/attacker.example.com:19530" and
    # "/\t/attacker.example.com/share/db" short-circuiting LOCAL.
    uri = _normalize_uri_like_url_parser(value)
    if not uri:
        return False
    if uri.lower().startswith("file://"):
        # RFC 8089 local forms: "file:///path" (empty authority),
        # "file://localhost/path", or the Windows drive-letter form some
        # resolvers write as "file://C:/data/store.db" — urlsplit reads the
        # drive letter + colon as the netloc there (there is no real
        # authority, just a colon that looks like one). Any OTHER authority
        # is a remote-share reference some resolvers treat as a host (e.g.
        # "file://attacker.example.com/share/store.db") and must NOT be
        # classified as on-box — fall through to the remote/DNS path.
        #
        # ``urlsplit`` is NOT exception-safe: a malformed authority (e.g. an
        # unbalanced IPv6-literal bracket, "file://[attacker.example.com/x"
        # or "file://[::1/x") raises ``ValueError: Invalid IPv6 URL`` instead
        # of returning a parse. Unlike its sibling in ``_classify_engine_url``
        # (which already wraps this identical call), this call was bare, so
        # the exception used to propagate all the way up through
        # ``_vector_store_endpoint_is_local`` -> ``vector_store_is_contained``
        # -> ``classify_engine`` into ``_resolve_adaptive_scope``'s catch-all,
        # which resolves the PERMISSIVE ``EgressScope.BOTH`` — exactly the
        # cloud-capable scope this module's fail-up rules exist to avoid.
        # Fail toward not-local instead, matching every other unknown here.
        try:
            parsed = urlsplit(uri)
        except Exception:
            return False
        netloc = parsed.netloc
        # Windows drive letters are ASCII A-Z only. ``str.isalpha()`` is
        # Unicode-wide (Cyrillic "с", fullwidth "C", accented "é" all
        # match), so a Unicode lookalike authority (e.g.
        # "file://с:/share/db") must NOT pass as an on-box drive path —
        # the same hazard class as the single-letter-scheme lookalikes at
        # the bottom of this function.
        is_drive_letter_netloc = (
            len(netloc) == 2
            and netloc[0].isascii()
            and netloc[0].isalpha()
            and netloc[1] == ":"
        )
        if not (
            netloc == ""
            or netloc.lower() == "localhost"
            or is_drive_letter_netloc
        ):
            return False
        # A 4-plus-slash form ("file:////attacker.example.com/share/db")
        # parses with an EMPTY netloc too — urlsplit only ever gives the
        # first two slashes after the scheme authority meaning, so a third
        # and fourth slash just start the PATH — but that path then begins
        # with "//host/share", a UNC-style remote-share reference smuggled
        # past the empty-netloc check above. Reject that form: a local file
        # path never legitimately starts with two slashes. A mixed-slash
        # variant ("file:///\\host/share/db" -> path "/\\host/share/db")
        # smuggles the same UNC authority past a forward-slash-only check:
        # ``ntpath.normpath`` treats ANY pair of leading separators — "//",
        # "/\\", "\\/", or "\\\\" — as a UNC prefix on Windows, so reject all
        # four combinations, not just the literal "//" one. The path may be
        # percent-encoded (RFC 8089), so DECODE it before the separator
        # check: "file:///%2fattacker.example.com/share/db" and the "%5c"
        # twin read as single-separator paths while encoded, but unquote
        # to exactly the "//host" / "/\\host" UNC prefixes the check exists
        # to catch (``ntpath.normpath`` resolves both to a remote share).
        # Decoding cannot smuggle an authority in: netloc was already
        # validated above, and plain local paths ("/var/lib/x",
        # "/C:/data") keep their single leading separator through unquote.
        #
        # DEFENCE IN DEPTH: this decode-and-check is a deliberate duplicate
        # of ``_file_uri_names_a_remote_share``, which
        # ``_vector_store_endpoint_is_local`` — the ONLY production caller of
        # this function — already ran one frame earlier over every entry of
        # the setting. At every production entry point the earlier check has
        # therefore already returned "not contained", so reverting the
        # ``unquote`` here changes no end-to-end outcome; it stays because
        # this function is a general-purpose predicate that a future caller
        # may reach directly, and it is pinned by its own unit test
        # (``test_file_uri_percent_encoded_unc_in_path_is_not_a_local_file``).
        return not _starts_with_double_separator(unquote(parsed.path))
    if uri.startswith(_LOCAL_PATH_URI_PREFIXES):
        return True
    # A single leading "/" is a local absolute path ("/var/lib/x.db") ONLY
    # when it is not the start of a "//host[:port]" URI authority (e.g. a
    # Milvus endpoint written as "//attacker.example.com:19530"), including
    # the mixed-slash smuggling form "/\\host/share" that ``ntpath.normpath``
    # also resolves to a UNC network share on Windows. Reject any such
    # authority-ish form here so it falls through to the DNS classifier
    # instead of being silently treated as on-box.
    if uri.startswith("/") and not _starts_with_double_separator(uri):
        return True
    # Windows drive-absolute path ("C:\\data\\store.db"). What follows the
    # drive letter must not be a literal "//" — "<letter>://" is a
    # "scheme://host" URL authority marker, not a path, so e.g.
    # "x://attacker.example.com:19530" must NOT be misread as a local drive
    # path and skip the DNS classifier. Note ``str.isalpha()`` is
    # Unicode-wide (Cyrillic/fullwidth letters match too, e.g. "с://host" or
    # "C://host"), so the drive letter must be ASCII here for the same
    # reason the ``file://`` netloc test above requires it: "с:/x", "C:/x"
    # and "é:/x" are not Windows drive-absolute paths, and short-circuiting
    # them to on-box would skip the DNS classifier on a value no resolver
    # reads as a local drive. The literal-"//" authority check below is a
    # separate, independent guard covering the "<letter>://host" form.
    #
    # ONLY the literal "//" form is rejected, not every doubled separator:
    # a drive letter always wins over a UNC prefix on Windows
    # (``ntpath.normpath("C:\\\\data") == "C:\\data"``, never a network
    # share), and — ON THE NORMALISED STRING this function tests —
    # ``urlsplit`` gives an authority only to a literal "//", so
    # "C:\\\\data\\store.db", "C:/\\data" and "C:\\/data" cannot name a
    # remote host under either reading and are genuine local paths. That
    # equivalence holds ONLY because ``_normalize_uri_like_url_parser`` has
    # already deleted the tab/CR/LF and leading C0 controls that ``urlsplit``
    # itself deletes: on the RAW string "x:/\t/attacker.example.com:19530"
    # this literal-"//" test answers "no authority, local drive path" while
    # ``urlsplit`` answers "netloc=attacker.example.com:19530". Never move
    # this test back onto an un-normalised string. The
    # forward-slash form "C://data" is irreducibly ambiguous — it parses as
    # scheme "c" with hostname "data" — so it stays rejected and falls
    # through to the DNS classifier; see changelog.d/5763.security.md.
    return (
        len(uri) > 2
        and uri[0].isascii()
        and uri[0].isalpha()
        and uri[1] == ":"
        and uri[2] in "\\/"
        and not uri[2:].startswith("//")
    )


def _file_uri_names_a_remote_share(value) -> bool:
    """True when ``value`` is a ``file://`` URI that does not stay on the box.

    The DECODED path of a ``file://`` URI can name a UNC network share
    (``//host/share``, or any of the mixed "/"/"\\" separator pairs
    ``ntpath.normpath`` also resolves to one) regardless of what the URI's
    nominal authority says — "file://localhost//attacker.example.com/share"
    reads as localhost but resolves off-box. Such a URI must stay
    non-contained even after ``_is_local_filesystem_uri`` has declined it,
    so hostname classification cannot rescue it via the local-looking
    authority.

    The "is this a ``file://`` URI?" question is answered by the PARSED
    scheme, not by a raw ``startswith`` on the string: ``urlsplit`` deletes
    tab/CR/LF from anywhere in a URL and lstrips C0 controls, so
    "fi\\tle://localhost//attacker.example.com/share/db" is not a ``file://``
    URI to ``startswith`` but IS one to every real URL parser — and
    ``_classify_engine_url``, the frame that decides the host, is a real URL
    parser, which for that value reports the local-looking authority
    ``localhost`` and would classify the endpoint contained. Asking
    ``urlsplit`` for the scheme is what keeps this function from being
    stepped around by such a value.

    ``value`` is normalised by ``_normalize_uri_like_url_parser`` BEFORE it
    reaches ``urlsplit``, and that call is load-bearing here, not a duplicate
    of the parser's own preprocessing. ``urlsplit`` lstrips only
    ``\\x00``-``\\x20``, while the normaliser's final ``strip()`` is
    bidirectional and additionally removes the 19 leading Unicode-whitespace
    codepoints ``str.strip()`` knows and the parser does not (U+0085, U+00A0,
    U+1680, U+2000-U+200A, U+2028, U+2029, U+202F, U+205F, U+3000). Handed
    the RAW value, "\\xa0file://localhost//attacker.example.com/share/db"
    parses with an EMPTY scheme, this function answers False, the
    network-share rejection never fires, and — inside a list-shaped endpoint
    setting whose sibling entry is "127.0.0.1" — the whole setting classifies
    CONTAINED. Normalise first; see
    ``test_leading_unicode_whitespace_cannot_hide_a_network_share``.

    Fails toward "remote" for a malformed authority: ``urlsplit`` raises
    (``ValueError``: "Invalid IPv6 URL") on an unbalanced IPv6 bracket rather
    than parsing, and an endpoint we cannot parse is one we cannot prove
    local. The catch is broad, matching its sibling in
    ``_is_local_filesystem_uri``, so a future parser error class cannot turn
    a fail-closed answer into an exception that escapes into
    ``_resolve_adaptive_scope``'s permissive catch-all.

    Non-strings answer False here — they are not ``file://`` URIs, and every
    other non-string shape already fails closed downstream by never proving
    itself local.
    """
    if not isinstance(value, str):
        return False
    uri = _normalize_uri_like_url_parser(value)
    try:
        parsed = urlsplit(uri)
        if parsed.scheme.lower() != "file":
            return False
        return _starts_with_double_separator(unquote(parsed.path))
    except Exception:
        return True


def _vector_store_endpoint_is_local(
    provider: str,
    settings_snapshot: Optional[dict],
    ctx: EgressContext,
    allow_dns: bool = True,
) -> bool:
    """Whether a non-local-file store's configured endpoint stays on the box.

    Mirrors the engine ``url_setting`` fail-up: the provider class names the
    settings key holding its endpoint (``uri_setting``), that value is
    classified by DNS, and ONLY a positively-local answer counts as contained.
    A provider that declares no key, an unset/unparseable URI, or a host that
    resolves publicly all yield False — for a store that is not a local file,
    an endpoint we cannot prove local must be assumed to be off-machine.
    """
    cls = _vector_store_class(provider)
    uri_setting = getattr(cls, "uri_setting", None) if cls else None
    if not uri_setting:
        return False
    uri = _get_setting_value(settings_snapshot or {}, uri_setting, None)
    # Reject a network-share file path PER ENTRY. A setting value is not
    # necessarily a string: ``unwrap_setting`` peels the ``{"value": ...}``
    # snapshot wrapper and returns whatever it wrapped, uncoerced, and
    # ``_classify_engine_url`` below explicitly supports the LIST shape
    # (Elasticsearch-style endpoint lists). A string-only guard here would
    # leave a one-element list to fall through to hostname classification,
    # where a nominally local authority ("localhost", "127.0.0.1") answers
    # True and overrules the path rejection. Normalising to entries first
    # keeps a single rejection site that covers every shape the setting can
    # hold, and fails the WHOLE setting closed when ANY entry is a rejected
    # path — matching the "any public entry wins" fail-up
    # ``_classify_engine_url`` already applies to list-typed endpoints.
    #
    # COUPLED WITH ``_classify_engine_url``: this loop and that function must
    # keep the SAME container test (``isinstance(..., list)``, not
    # ``(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,):
        if _file_uri_names_a_remote_share(entry):
            return False
    if _is_local_filesystem_uri(uri):
        return True
    return (
        _classify_engine_url(
            uri_setting, settings_snapshot or {}, ctx, allow_dns=allow_dns
        )
        is True
    )


def vector_store_is_contained(
    engine_name: str,
    ctx: EgressContext,
    settings_snapshot: Optional[dict],
    allow_dns: bool = True,
) -> bool:
    """Whether the RAG vector store(s) behind ``engine_name`` stay on the box.

    A library/collection engine is only as contained as the vector store its
    embeddings are written to and searched in. A local-file store (FAISS) is
    contained by construction — ``is_local_file`` is the discriminator, so
    this is a strict no-op for it and no DNS lookup happens. A server-backed
    store is contained only while its configured endpoint resolves local;
    otherwise the collection's embeddings (and every query) leave the machine
    and the engine must fail UP, exactly as Paperless/Elasticsearch do via
    ``url_setting``.

    Single home for the rule so the scope PEP (:func:`classify_engine`) and
    the two-axis resolver (``run_classification.engine_label``) can never
    diverge.
    """
    for provider in _resolve_vector_store_providers(
        engine_name, ctx, settings_snapshot
    ):
        cls = _vector_store_class(provider)
        if cls is not None:
            if getattr(cls, "is_local_file", False) is True:
                continue
        elif provider in _LOCAL_FILE_VECTOR_STORE_PROVIDERS:
            continue
        if not _vector_store_endpoint_is_local(
            provider, settings_snapshot, ctx, allow_dns=allow_dns
        ):
            return False
    return True


def classify_engine(
    engine_name: str,
    ctx: EgressContext,
    *,
    settings_snapshot: dict,
    metadata: Optional[dict] = None,
    allow_dns: bool = True,
) -> EngineClassification:
    """Classify an engine from its flags, collection metadata, and URL policy.

    The class-level ``is_public`` / ``is_local`` flags express the engine's
    *nature* — whether it queries the public internet or searches local data —
    regardless of where the engine's server happens to be hosted.  This is used
    by ``evaluate_engine`` and ``_resolve_adaptive_scope`` so that e.g. a
    locally-hosted SearXNG (which proxies to Google/Bing) is still treated as
    a public 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 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``
      flag (from ``metadata`` when the caller has the engine config, else a
      direct DB lookup), defaulting private.
    - Anything else (unknown): ``EngineClassification(None, None)``.
    """
    engine_cls = _get_engine_class(engine_name)
    if engine_cls is None:
        if engine_name == "library" or engine_name.startswith("collection_"):
            if metadata is not None and metadata.get("is_public") is not None:
                is_public = bool(metadata.get("is_public"))
            else:
                is_public = _resolve_collection_is_public(
                    engine_name, ctx.username
                )
            # A collection is ALWAYS a local knowledge base — it lives on this
            # machine — so it stays searchable under PRIVATE_ONLY regardless of
            # its public flag. ``is_public`` is ADDITIVE, not exclusive: marking
            # a collection public (non-sensitive content — papers you fetched,
            # public publications) ALSO makes it eligible under PUBLIC_ONLY and
            # OK to process with cloud inference. A private collection is
            # local-only and excluded from public-scope runs. Hence
            # ``(is_public, is_local=True)`` rather than the old mutually-
            # exclusive ``(is_public, not is_public)`` which wrongly hid a
            # public collection from private runs.
            #
            # ... UNLESS the vector store behind it is not on this machine.
            # A collection is only local while its index is: a server-backed
            # store on a public endpoint ships the collection's embeddings and
            # every query to a third party, so it fails UP — but unlike the
            # Elasticsearch/Paperless case (a nature-private engine that
            # becomes nature-public once its endpoint leaves the box), a
            # collection's ``is_public`` is an independent, already-resolved
            # signal about the *content*, not a byproduct of containment.
            # Losing containment must only ever ADD restriction, never grant
            # new eligibility: it strips ``is_local`` (PRIVATE_ONLY denies it,
            # data no longer stays on the box) while PRESERVING the real
            # ``is_public`` flag (a private-flagged collection does NOT
            # become newly eligible under PUBLIC_ONLY just because its store
            # is remote — that would be a relaxation, not a tightening).
            # Strict no-op for a local-file store (FAISS):
            # ``vector_store_is_contained`` returns True without touching DNS.
            if not vector_store_is_contained(
                engine_name, ctx, settings_snapshot, allow_dns=allow_dns
            ):
                return EngineClassification(is_public=is_public, is_local=False)
            return EngineClassification(is_public=is_public, is_local=True)
        return EngineClassification(is_public=None, is_local=None)
    is_public, is_local, url_setting = _engine_flags(engine_cls)
    # Fail-up URL override (asymmetric, only ever MORE restrictive): a
    # 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). 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,
            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.
            # An endpoint whose host is a cloud-metadata name or address, or
            # has no canonical spelling (see _canonical_host), lands here
            # too, so it is refused in every protected scope.
            return EngineClassification(is_public=False, is_local=False)
    return EngineClassification(is_public=is_public, is_local=is_local)


# Denial reasons that justify dropping an engine from an LLM candidate
# list. Only ACTIVE policy denials qualify — see filter_engines_by_egress.
_PREFILTER_STRIP_REASONS = frozenset(
    {
        "scope_mismatch_public_only",
        "scope_mismatch_private_only",
        "strict_not_primary",
        # Registered engine without classification flags: the factory's
        # evaluate_engine call fails it closed too, so stripping matches
        # enforcement exactly.
        "unclassified",
    }
)


def filter_engines_by_egress(
    engine_names: list[str],
    ctx: EgressContext,
    settings_snapshot: dict,
) -> list[str]:
    """ADVISORY pre-filter for a candidate engine list: remove engines the
    egress scope actively denies so the LLM doesn't waste selection slots
    on them. Uses the engine's static class flags (``is_public`` /
    ``is_local``) — a locally-hosted SearXNG is still treated as public
    because it queries the internet.

    This is a UX optimization in FRONT of the factory PEP, not an
    enforcement point — so it must never be STRICTER than the factory.
    Names unknown to the static registry (``engine_unknown``) are KEPT
    (except under STRICT, where the not-the-primary gate fires before the
    registry lookup — exactly as it does in the factory):
    they may be retriever-backed or dynamically injected engines that the
    factory evaluates via its own retriever path; dropping them here would
    silently hide legitimate engines from LLM selection. The factory
    still denies anything truly disallowed at instantiation.

    Callers: the LangGraph tool builder, or any code that builds a
    selection set before presenting it to an LLM.
    """
    allowed: list[str] = []
    for name in engine_names:
        decision = evaluate_engine(
            name, ctx, settings_snapshot=settings_snapshot
        )
        if decision.allowed or decision.reason not in _PREFILTER_STRIP_REASONS:
            allowed.append(name)
    return allowed


def filter_candidates_by_egress(
    engine_names: list[str],
    settings_snapshot: Optional[dict],
) -> list[str]:
    """Best-effort scope pre-filter for an LLM candidate list.

    Wraps ``filter_engines_by_egress`` with the snapshot plumbing
    LLM-selection callers share: read ``policy.egress_scope`` /
    ``search.tool`` from the snapshot (flat or ``{"value": ...}`` shaped),
    build the context, filter. Returns the input list unchanged when the
    snapshot is missing, the scope is BOTH (nothing to strip), or anything
    fails — the factory PEP still enforces at child instantiation, so this
    helper must never break engine selection.
    """
    if not settings_snapshot:
        return engine_names
    try:
        scope_raw = str(
            _get_setting_value(
                settings_snapshot, "policy.egress_scope", DEFAULT_EGRESS_SCOPE
            )
            or DEFAULT_EGRESS_SCOPE
        ).lower()
        # BOTH (or an unrecognized value) strips nothing at selection time;
        # adaptive is included because it can RESOLVE to a restrictive scope.
        if scope_raw not in (
            "private_only",
            "public_only",
            "strict",
            "adaptive",
        ):
            return engine_names
        primary = resolve_run_primary_engine(settings_snapshot)
        ctx = context_from_snapshot(
            settings_snapshot,
            primary,
            username=settings_snapshot.get("_username"),
        )
        return filter_engines_by_egress(engine_names, ctx, settings_snapshot)
    except Exception:  # noqa: silent-exception - advisory pre-filter only
        logger.bind(policy_audit=True).debug(
            "egress candidate pre-filter failed; "
            "factory PEP still enforces at child instantiation"
        )
        return engine_names


def evaluate_engine(
    engine_name: str,
    ctx: EgressContext,
    *,
    settings_snapshot: dict,
    metadata: Optional[dict] = None,
) -> Decision:
    """Decide whether an engine may be instantiated under the current policy.

    Allows iff (a) the engine's classification is compatible with the scope's
    bucket AND (b) if scope == STRICT, the engine name equals the primary.
    Unclassified engines always fail closed.

    ``metadata`` (optional) carries the engine's config entry (e.g. the
    per-collection ``is_public`` from search_config) so callers that already
    have it avoid a redundant DB lookup; when absent it's resolved directly.
    """
    if settings_snapshot is None:
        return Decision(False, "no_snapshot")
    try:
        # UNPROTECTED: egress protection disabled for this run (escape hatch)
        # — any engine is permitted. SSRF/metadata blocks still apply at
        # evaluate_url; this only lifts the egress-scope engine gate.
        if ctx.scope == EgressScope.UNPROTECTED:
            return Decision(True, "egress_unprotected")

        # STRICT: only the primary engine is permitted.
        if (
            ctx.scope == EgressScope.STRICT
            and engine_name != ctx.primary_engine
        ):
            return Decision(False, "strict_not_primary")

        # A truly unknown engine (not in the static registry and not a
        # collection) fails closed as engine_unknown. ``library`` /
        # ``collection_*`` are classified by classify_engine below.
        is_collection = engine_name == "library" or engine_name.startswith(
            "collection_"
        )
        if _get_engine_class(engine_name) is None and not is_collection:
            return Decision(False, "engine_unknown")

        classification = classify_engine(
            engine_name,
            ctx,
            settings_snapshot=settings_snapshot,
            metadata=metadata,
        )

        # Fail-closed for unclassified engines.
        if (
            classification.is_public is not True
            and classification.is_local is not True
        ):
            return Decision(False, "unclassified")

        # Scope/bucket compatibility.
        if (
            ctx.scope == EgressScope.PUBLIC_ONLY
            and classification.is_public is not True
        ):
            return Decision(False, "scope_mismatch_public_only")
        if (
            ctx.scope == EgressScope.PRIVATE_ONLY
            and classification.is_local is not True
        ):
            return Decision(False, "scope_mismatch_private_only")

        return Decision(True, "allowed")
    except Exception:  # pragma: no cover - defensive
        logger.bind(policy_audit=True).exception(
            "evaluate_engine internal error", engine=engine_name
        )
        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``), 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 contains ``%`` (HTTP client normalization is
    version-dependent). Other consumers keep single URL-string parsing
    and percent-decoding.

    Every host is canonicalised by ``_classifiable_host`` (one
    percent-decode, one trailing root dot, case). A host that is not a
    plain DNS name or a canonical IP literal, or that names a cloud-metadata
    endpoint, is unknown, so an engine configured with one is refused under
    every protected scope rather than classified local or failed up to
    public.
    """
    value = _get_setting_value(settings_snapshot, url_setting, None)
    if not value:
        return None

    # 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 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. 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 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
                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
        else:
            if allow_host_dicts:
                any_unknown = True
            continue
        if allow_host_dicts and "%" 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, so for Elasticsearch
            # even a host that decodes to a canonical one is ambiguous: keep
            # every percent-bearing host unknown, under either behaviour.
            any_unknown = True
            continue
        # The host is passed as parsed, NOT decoded: _classifiable_host
        # percent-decodes it exactly once (other consumers' HTTP clients
        # decode it before connecting, so "192%2e168%2e1%2e1" is
        # 192.168.1.1), ignores one trailing root dot and folds case. A host
        # that is not then a plain DNS name or a canonical IP literal
        # (residual "%", IPv6 zone ID, non-ASCII, control characters,
        # integer / hex / octal / short IPv4), or that names a cloud-metadata
        # endpoint, is unclassified. _classify_host would report it as not
        # local (False), which this function reads as "public" and would use
        # to fail a local engine UP, making it eligible under PUBLIC_ONLY:
        # leave it unknown instead, so classify_engine withholds the engine
        # in every protected scope. Vector-store callers only accept True,
        # so this changes nothing for them. A non-ASCII name is unknown here
        # for a second reason as well: the resolver encodes it with IDNA
        # 2003 ("faß" is looked up as "fass") but the Elasticsearch client's
        # urllib3 with IDNA 2008 ("xn--fa-hia"). An "xn--" spelling is plain
        # ASCII and is classified as written.
        if _classifiable_host(hostname) is None:
            any_unknown = True
            continue
        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  # public wins over local under list-typed settings
    if any_local:
        return True
    return None


_CLOUD_LLM_PROVIDERS = frozenset(
    {
        "openai",
        "anthropic",
        "google",
        "openrouter",
        "requesty",
        "orcarouter",
        "atlascloud",
        "qwen",
        "deepseek",
        "xai",
        "ionos",
    }
)

# Providers that default to a localhost endpoint and ship without any
# remote routing. The LLM gate at ``config/llm_config.py`` uses this set
# as a SNAPSHOT-LESS ALLOW-LIST: when ``get_llm`` is invoked with no
# settings snapshot (background helpers, scaffolding paths, tests), only
# these providers may proceed; everything else — including ambiguous
# providers like ``openai_endpoint`` and any future cloud provider not
# yet enumerated in ``_CLOUD_LLM_PROVIDERS`` — fails closed at the gate.
# Keeping the set tight is the point: anything new defaults to refused.
_LOCAL_DEFAULT_LLM_PROVIDERS = frozenset(
    {
        "ollama",
        "lmstudio",
        "llamacpp",
    }
)

# Embeddings analogue of ``_LOCAL_DEFAULT_LLM_PROVIDERS``. Used by the
# embeddings gate as a SNAPSHOT-LESS ALLOW-LIST: when ``get_embeddings``
# runs without a settings snapshot (the ``embeddings.require_local`` toggle
# is then unreadable), only these localhost-default providers may proceed.
# ``openai`` (and any future cloud embeddings provider) fails closed —
# matching the LLM gate so a snapshot-less background caller can't ship the
# local corpus to a cloud embedder. ``sentence_transformers`` runs fully
# in-process; ``ollama`` defaults to a localhost endpoint.
_LOCAL_DEFAULT_EMBEDDING_PROVIDERS = frozenset(
    {
        "sentence_transformers",
        "ollama",
    }
)


def _is_user_registered_llm(
    provider: str, username: Optional[str] = None
) -> bool:
    """True when ``provider`` is a user-registered in-process LLM.

    The programmatic API (``quick_summary(llms={"mock": ...})``) and plugins
    register LLM objects in the LLM registry. Built-in providers are ALSO
    auto-registered there by ``discover_providers()``, so registry membership
    alone cannot discriminate — a name that is registered but NOT one of the
    auto-discovered built-ins is user-supplied in-process code. Such objects
    carry no configurable endpoint the PDP could classify (denying them with
    ``provider_url_unset`` just breaks the documented offline workflow), the
    operator injected them deliberately at code level, and under
    PRIVATE_ONLY/STRICT the PEP-578 audit hook still blocks any stray
    outbound socket they might open.

    A user registration that *shadows* a built-in name (e.g. "openai") is NOT
    treated as user code: the discovered-name check keeps it on the strict
    path, and the ``_CLOUD_LLM_PROVIDERS`` gate fires first anyway.

    Fails closed (False) on any error.
    """
    try:
        from ...llm.llm_registry import is_llm_registered
        from ...llm.providers import discover_providers
        from ...llm.providers.base import normalize_provider

        if not provider or not is_llm_registered(provider, username=username):
            return False
        discovered = {normalize_provider(key) for key in discover_providers()}
        return normalize_provider(provider) not in discovered
    except Exception:  # pragma: no cover - defensive
        logger.bind(policy_audit=True).exception(
            "user-registered LLM check failed", provider=provider
        )
        return False


def evaluate_llm_endpoint(
    provider: str,
    ctx: EgressContext,
    *,
    settings_snapshot: dict,
    username: Optional[str] = None,
) -> Decision:
    """Decide whether an LLM provider may be instantiated.

    Only meaningful when ``ctx.require_local_llm`` is True; otherwise allow.

    ``username`` scopes the user-registered-LLM exemption to the caller's own
    namespace so a per-user in-process LLM is recognized. It defaults to the
    context's username when the caller does not pass one explicitly.
    """
    if username is None:
        username = getattr(ctx, "username", None)
    if settings_snapshot is None:
        return Decision(False, "no_snapshot")
    try:
        if not ctx.require_local_llm:
            return Decision(True, "no_local_requirement")

        # Hard-cloud providers always fail under require_local_llm.
        if provider in _CLOUD_LLM_PROVIDERS:
            return Decision(False, "provider_cloud_only")

        # User-registered in-process LLMs (programmatic API / plugins) have
        # no endpoint to classify; allow them — the audit hook still
        # backstops stray sockets under PRIVATE_ONLY/STRICT.
        if _is_user_registered_llm(provider, username=username):
            return Decision(True, "user_registered_llm")

        # Providers with a configurable URL: classify the URL.
        url_key = f"llm.{provider}.url"
        url_value = _get_setting_value(settings_snapshot, url_key, None)
        if not url_value:
            # Local-default providers (ollama, lmstudio, llamacpp) without
            # an override fall back to their localhost defaults. Use the
            # shared constant so this can't drift from the snapshot-less
            # allow-list.
            if provider in _LOCAL_DEFAULT_LLM_PROVIDERS:
                return Decision(True, "provider_local_default")
            return Decision(False, "provider_url_unset")

        try:
            parsed = urlsplit(url_value)
            # Passed as parsed, NOT decoded: _classify_host percent-decodes
            # the host exactly once (the HTTP client decodes it before
            # connect, so "http://127%2e0%2e0%2e1:11434" reads as the local
            # 127.0.0.1) and refuses to call any host local that is not a
            # plain DNS name or a canonical IP literal after that decode.
            hostname = parsed.hostname
        except Exception:
            return Decision(False, "url_malformed")

        classification = _classify_host(hostname, ctx) if hostname else None
        if classification is True:
            return Decision(True, "provider_local")
        return Decision(False, "provider_remote")
    except Exception:  # pragma: no cover - defensive
        logger.bind(policy_audit=True).exception(
            "evaluate_llm_endpoint internal error", provider=provider
        )
        return Decision(False, "internal_error")


def evaluate_embeddings(
    provider: str,
    ctx: EgressContext,
    *,
    settings_snapshot: dict,
) -> Decision:
    """Decide whether an embeddings provider may be instantiated.

    Only meaningful when ``ctx.require_local_embeddings`` is True.
    OpenAI is treated as unambiguously cloud unless ``embeddings.openai.base_url``
    is configured to a local host.
    """
    if settings_snapshot is None:
        return Decision(False, "no_snapshot")
    try:
        if not ctx.require_local_embeddings:
            return Decision(True, "no_local_requirement")

        if provider == "sentence_transformers":
            return Decision(True, "provider_local")

        if provider == "ollama":
            url = _get_setting_value(
                settings_snapshot, "embeddings.ollama.url", None
            ) or _get_setting_value(settings_snapshot, "llm.ollama.url", None)
            if not url:
                return Decision(True, "provider_local_default")
            parsed = urlsplit(url)
            # As parsed: _classify_host decodes the host once itself.
            host = parsed.hostname
            classification = _classify_host(host, ctx) if host else None
            return (
                Decision(True, "provider_local")
                if classification is True
                else Decision(False, "provider_remote")
            )

        if provider == "openai":
            base_url = _get_setting_value(
                settings_snapshot, "embeddings.openai.base_url", None
            )
            if base_url:
                parsed = urlsplit(base_url)
                # As parsed: _classify_host decodes the host once itself.
                host = parsed.hostname
                classification = _classify_host(host, ctx) if host else None
                if classification is True:
                    return Decision(True, "provider_local_endpoint")
            return Decision(False, "provider_cloud")

        return Decision(False, "provider_unknown")
    except Exception:  # pragma: no cover - defensive
        logger.bind(policy_audit=True).exception(
            "evaluate_embeddings internal error", provider=provider
        )
        return Decision(False, "internal_error")


_DANGEROUS_SCHEMES = frozenset(
    {"javascript", "data", "file", "vbscript", "about"}
)

# Cloud-metadata endpoints reachable by HOSTNAME rather than literal IP (GCP
# metadata.google.internal / metadata.goog, IBM Cloud classic
# api.service.softlayer.com) are blocked in evaluate_url via
# _is_metadata_destination (ssrf_validator.is_metadata_hostname), and in host
# classification via _is_metadata_host. ssrf_validator's
# ALWAYS_BLOCKED_METADATA_HOSTNAMES set is the single source of truth shared
# with validate_url and the notification validator. is_ip_blocked only catches
# IP literals, so the name check is needed to honor the "metadata is NEVER
# permitted, regardless of scope" invariant in evaluate_url.


def _normalize_alt_ipv4(host: str) -> Optional[str]:
    """Return the canonical dotted-quad for an IPv4 host written in an
    alternate encoding the libc resolver accepts but ``ipaddress.ip_address``
    rejects — octal (``0251.0376.0251.0376``), hex (``0xa9fea9fe``), integer
    (``2852039166``) and short forms (``169.254.43518``). Returns ``None`` for
    anything ``inet_aton`` won't parse (real hostnames, IPv6, junk).

    ``socket.getaddrinfo`` resolves these numeric forms to the same address the
    HTTP client will ``connect()`` to, so the metadata-IP block in
    ``evaluate_url`` must classify them by their *real* target — otherwise
    ``http://0251.0376.0251.0376/`` slips past ``is_ip_blocked`` (which only
    parses canonical notation) and reads as an allowed public host.
    """
    try:
        return socket.inet_ntoa(socket.inet_aton(host))
    except (OSError, UnicodeError, TypeError, ValueError):
        # ValueError: an embedded NUL character. Never raises, so a caller
        # (evaluate_url's metadata check) cannot fail on any input.
        return None


def _quota_ctx(ctx: EgressContext) -> EgressContext:
    """Return the EgressContext whose counter backs the per-RUN denied-fetch
    quota.

    Each call site (ContentFetcher, full_search, download_service, the audit
    hook) builds its OWN EgressContext from the snapshot, so a per-context
    counter would reset the budget every time a new engine/fetcher is built —
    letting a malicious document evade ``MAX_DENIED_FETCHES_PER_RUN`` by
    spreading denied fetches across contexts. The run's ARMED active context is
    set once at run start and re-armed identically on pool workers, so it is
    shared across the whole run; anchoring the counter there makes the quota
    truly per-run. Falls back to the passed ctx when no run context is armed
    (snapshot-less / programmatic callers, settings-page calls), keeping those
    isolated calls self-contained.
    """
    try:
        from .audit_hook import get_active_context

        active = get_active_context()
    except Exception:  # pragma: no cover - defensive
        active = None
    return active if active is not None else ctx


def _url_host_refusal(hostname: str) -> Optional[str]:
    """The reason ``evaluate_url`` refuses a URL host before classifying it
    (``"blocked_metadata_ip"`` or ``"url_malformed"``), or None. Shared with
    ``host_not_classified_public`` so the two cannot disagree. ``hostname``
    is the host as ``urlsplit`` returns it (not decoded).

    HTTP client libraries (requests/urllib3) percent-DECODE the host in the
    netloc before the socket connect, but urlsplit().hostname preserves the
    encoding, and trailing dots are insignificant to the resolver. The
    checks below therefore look at every spelling the resolver may connect
    to (``_policy_host_forms``: decoded once, undecoded, decoded until
    stable, trailing dots stripped, the IDNA-folded forms of a non-ASCII
    host, the dotted quad of an octal / hex / integer / short IPv4
    notation). This broad expansion only ever adds refusals; whether a host
    is local or public is left to ``_classify_url_host``.
    """
    host_forms = _policy_host_forms(hostname)

    # Cloud-metadata endpoints (AWS/GCE/Azure IMDS at 169.254.169.254 etc.)
    # are NEVER permitted, regardless of scope. They classify as
    # link-local/private, so STRICT and PRIVATE_ONLY would otherwise ALLOW
    # them — a credential-theft path for prompt-injected fetches and, more
    # importantly, for the audit-hook net which calls evaluate_url directly
    # on raw socket.connect targets (bypassing the SSRF validator that the
    # explicit fetch PEPs run first).
    #
    # is_ip_blocked(allow_localhost=True, allow_private_ips=True) is True
    # for the always-blocked metadata set (IPv4-mapped forms unwrapped, zone
    # IDs ignored) and NAT64 wraps of it, and also for every other address
    # in the SSRF validator's blocked ranges that is neither loopback nor
    # one of the private ranges it allows: 0.0.0.0/8, the IPv6 unspecified
    # address, 6to4, Teredo, the IPv4-compatible and IPv4-translated forms,
    # the IPv6 discard prefix, and the NAT64 prefixes (when the operator
    # allows NAT64, only a wrap whose embedded IPv4 is itself blocked). All
    # of those are refused under the same blocked_metadata_ip reason. It
    # only parses IP notation ipaddress accepts, so each form is checked.
    try:
        from ..ssrf_validator import is_ip_blocked

        for form in host_forms:
            if is_ip_blocked(
                form, allow_localhost=True, allow_private_ips=True
            ):
                return "blocked_metadata_ip"
    except Exception:  # noqa: silent-exception - defensive, see below
        # Non-IP host or helper error: fall through to the metadata check
        # below and then to normal classification (the DNS path has its
        # own handling).
        pass

    # Metadata endpoints reachable by hostname (GCP, IBM Cloud classic) in
    # any of those spellings, and metadata addresses wherever an IPv6
    # address may embed them (every RFC 6052 NAT64 position,
    # network-specific prefixes included, 6to4, Teredo), which is_ip_blocked
    # does not look for. IBM's name resolves to RFC1918 (10.0.80.88), which
    # STRICT / PRIVATE_ONLY would otherwise admit as a local host. Refused
    # in every scope (the SSRF validator also blocks the name on the actual
    # fetch, but evaluate_url's own guarantee must not depend on it).
    # Deliberately OUTSIDE the try/except above, so a helper exception
    # cannot swallow this refusal: _is_metadata_destination never raises
    # (is_metadata_hostname fails closed), and evaluate_url's outer handler
    # denies with internal_error if anything here does.
    if _is_metadata_destination(hostname):
        return "blocked_metadata_ip"

    # A host that is, or decodes to, text with whitespace, a control
    # character or a backslash names no destination an HTTP client can
    # reach (getaddrinfo refuses an embedded NUL outright): malformed in
    # every scope rather than classified.
    from ..ssrf_validator import RFC_FORBIDDEN_URL_CHARS_RE

    if any(RFC_FORBIDDEN_URL_CHARS_RE.search(form) for form in host_forms):
        return "url_malformed"
    return None


def evaluate_url(
    url: str, ctx: EgressContext, *, record_denial: bool = True
) -> Decision:
    """Decide whether an arbitrary URL may be fetched (e.g., by ``fetch_content``).

    Enforces the run's denied-fetch quota to prevent exhaustion attacks
    via malicious indexed documents that loop the agent through hundreds
    of denied fetches.

    ``record_denial=False`` returns the same decision without recording a
    denial: it is neither counted toward that quota nor written to the
    audit log (an internal error is still logged). Only for a caller that
    fetches nothing on the decision, such as one that ranks URLs; a fetch
    must be decided with the default, so that its denials are counted.
    """
    deny = _record_denial if record_denial else _unrecorded_denial
    try:
        # Quota check: hard fail after MAX_DENIED_FETCHES_PER_RUN. Anchor the
        # counter to the run's active context (``_quota_ctx``) so the budget is
        # per-RUN, not per-EgressContext. Read under that ctx's lock so
        # concurrent subagents see a consistent count. The check itself never
        # records, so probes and fetches share the same fail-closed cliff.
        qctx = _quota_ctx(ctx)
        with qctx._lock:
            if qctx._fetch_denial_count["count"] >= MAX_DENIED_FETCHES_PER_RUN:
                return Decision(False, "denial_quota_exceeded")

        if not isinstance(url, str) or not url:
            return deny(ctx, url, "url_malformed")

        try:
            parsed = urlsplit(url)
        except Exception:
            return deny(ctx, url, "url_malformed")

        if parsed.scheme.lower() in _DANGEROUS_SCHEMES:
            return deny(ctx, url, "dangerous_scheme")
        if parsed.scheme.lower() not in ("http", "https"):
            return deny(ctx, url, "unsupported_scheme")
        if not parsed.hostname:
            return deny(ctx, url, "no_hostname")

        # Cloud-metadata endpoints, other always-blocked addresses and
        # malformed hosts are refused in every scope, before any scope or
        # local_hostnames logic (see _url_host_refusal).
        refusal = _url_host_refusal(parsed.hostname)
        if refusal is not None:
            return deny(ctx, url, refusal)

        # UNPROTECTED: egress protection disabled — any host is allowed. This
        # gate is deliberately AFTER the SSRF / cloud-metadata block above
        # (which always applies), so the escape hatch only lifts the
        # egress-scope host restriction, never the hard SSRF invariant.
        if ctx.scope == EgressScope.UNPROTECTED:
            return Decision(True, "egress_unprotected")

        # Shared with ``host_not_classified_public`` so both classify the
        # same host the same way.
        classification = _classify_url_host(parsed.hostname, ctx)

        if ctx.scope == EgressScope.STRICT:
            # Under STRICT, URLs whose host is private are allowed; public
            # hosts (DOI redirects, citations) are not. This is a deliberate
            # trade-off: prompt-injection spoofing of provenance tags is a
            # bigger risk than false-positives on DOI redirects.
            if classification is True:
                return Decision(True, "allowed_private_host_under_strict")
            return deny(ctx, url, "strict_public_host")

        if ctx.scope == EgressScope.PUBLIC_ONLY:
            if classification is False:
                return Decision(True, "allowed_public_host")
            return deny(ctx, url, "scope_mismatch_public_only")

        if ctx.scope == EgressScope.PRIVATE_ONLY:
            if classification is True:
                return Decision(True, "allowed_private_host")
            return deny(ctx, url, "scope_mismatch_private_only")

        # BOTH: any classified host is fine.
        if classification is None:
            return deny(ctx, url, "host_unclassified")
        return Decision(True, "allowed_both_scope")
    except Exception:  # pragma: no cover - defensive
        logger.bind(policy_audit=True).exception("evaluate_url internal error")
        return Decision(False, "internal_error")


def _unrecorded_denial(
    ctx: EgressContext, url: object, reason: str
) -> Decision:
    """A denial for ``evaluate_url(record_denial=False)``.

    Neither counted toward the denied-fetch quota nor logged.
    """
    return Decision(False, reason)


def host_not_classified_public(url: str, ctx: EgressContext) -> bool:
    """True when ``url`` is an http(s) URL whose host the policy does NOT
    classify public (private, or unclassifiable), decided WITHOUT recording
    a denial (nothing counts toward ``MAX_DENIED_FETCHES_PER_RUN``).

    Independent of ``ctx.scope``: the caller decides which scopes refuse
    such hosts. Lets a caller that refuses private destinations as a matter
    of course (the full-content search wrapper, whose result URLs come from
    an index it does not control, under every scope but ``unprotected``)
    drop them before ``evaluate_url`` without each one spending the run's
    quota. It uses the SAME refusal checks (``_url_host_refusal``) and the
    SAME classification (``_classify_url_host``, and the run-scoped DNS
    cache) as ``evaluate_url``, so the set it returns True for is exactly
    the set ``evaluate_url`` refuses 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 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 or host, non-http(s) scheme, no host, and a
    cloud-metadata or other always-blocked host, ``_url_host_refusal``), so
    that refusal is left to ``evaluate_url``, which counts a metadata
    denial. An internal error returns True (fails toward refusal, which
    records no denial either).
    """
    if not isinstance(url, str) or not url:
        return False
    try:
        parsed = urlsplit(url)
        hostname = parsed.hostname
    except Exception:  # noqa: silent-exception - malformed, see docstring
        return False
    if parsed.scheme.lower() not in ("http", "https") or not hostname:
        return False
    try:
        if _url_host_refusal(hostname) is not None:
            return False
        return _classify_url_host(hostname, ctx) is not False
    except Exception:  # noqa: silent-exception - fail toward refusal
        return True


def _policy_host(hostname: str) -> str:
    """``evaluate_url``'s broad reading of a URL host: percent-decoded once
    (HTTP clients decode it before connecting) and without trailing dots
    (insignificant to the resolver). The first of ``_policy_host_forms``,
    and the host ``_classify_url_host`` classifies when it has no canonical
    spelling. Classification of a canonical host uses ``_canonical_host``
    instead."""
    return unquote(hostname).rstrip(".")


def _classify_url_host(hostname: str, ctx: EgressContext) -> Optional[bool]:
    """How ``evaluate_url`` and ``host_not_classified_public`` classify the
    host of a URL being fetched: local (True) / public (False) / unknown
    (None). ``hostname`` is the host as ``urlsplit`` returns it.

    A host with a canonical spelling (``_canonical_host``) is classified by
    ``_classify_host``, exactly as the require-local and engine checks
    classify it; a cloud-metadata host comes back False (not local), and
    ``evaluate_url`` has refused it before asking.

    A host without one (IDN or fullwidth spelling, IPv6 zone ID, integer /
    hex / octal / short IPv4, a residual ``%``) is still classified as the
    fetch check always has, by ``_classify_destination`` on its
    ``_policy_host`` reading: the fetch check keeps its broader handling.
    Only the ``llm.allowed_local_hostnames`` override is not applied to it:
    an entry
    without a canonical spelling is ignored everywhere, and a URL host that
    matches one exactly is unknown (None) here rather than local, so that
    the ignored entry cannot make the host classify public either. And when
    the host as written, NOT decoded, is itself an IP literal (an HTTP
    client reads ``%`` in an IPv6 literal as the zone delimiter, so
    ``fd12::1%10`` is that address on interface 10, while the decoded
    reading is not an address at all), the two readings must agree or the
    host is unknown. Each of these can only turn a classification into
    None, which no scope admits, so this path is never looser than before.
    """
    if _canonical_host(hostname) is not None:
        return _classify_host(hostname, ctx)
    host = _policy_host(hostname)
    if not host or host in ctx.local_hostnames:
        return None
    result = _classify_destination(host, ctx)
    undecoded = hostname.rstrip(".")
    if undecoded != host:
        try:
            ipaddress.ip_address(undecoded)
        except ValueError:
            return result
        if _classify_destination(undecoded, ctx) is not result:
            return None
    return result


def _policy_host_forms(hostname: str) -> tuple[str, ...]:
    """The spellings of ``hostname`` ``evaluate_url`` checks for a metadata
    destination (directly and through ``_is_metadata_destination``). Broad
    on purpose: every extra form can only add a denial. Host classification
    does not use it; it accepts only canonical hosts (``_canonical_host``).
    ``hostname`` is the host as ``urlsplit`` returns it (not decoded).

    The first element is ``_policy_host(hostname)`` (percent-decoded once,
    trailing dots removed), without IPv6 brackets. When the host contains
    ``%``, it is followed by the same host NOT decoded (an HTTP client reads
    ``%`` in an IPv6 literal as the zone delimiter: ``fd00:ec2::254%10`` is
    that address on interface 10) and by the host decoded until no escape
    is left. A non-ASCII host is followed by the ASCII forms the resolver
    or an HTTP client may turn it into (``ssrf_validator._idna_folded_names``:
    IDNA 2003 folding of fullwidth digits and letters and ideographic full
    stops, and the IDNA 2008 / UTS #46 encodings), and every form that is an
    IPv4 address in an alternate notation ``inet_aton`` (and so the
    resolver) accepts — octal, hex, integer or a short form — is followed by
    its dotted quad (``_normalize_alt_ipv4``). Never raises.
    """
    from ..ssrf_validator import _idna_folded_names

    host = _policy_host(hostname)
    if host.startswith("[") and host.endswith("]"):
        host = host[1:-1]
    forms = [host]
    undecoded = hostname.rstrip(".")
    if undecoded.startswith("[") and undecoded.endswith("]"):
        undecoded = undecoded[1:-1]
    if undecoded and undecoded not in forms:
        forms.append(undecoded)
    # And decoded until stable (bounded): no HTTP client decodes twice, but
    # a host that only decodes to a metadata address after a second pass is
    # never a legitimate destination either, so refusing it costs nothing.
    repeated = host
    for _ in range(4):
        decoded = unquote(repeated)
        if decoded == repeated:
            break
        repeated = decoded
    repeated = repeated.rstrip(".")
    if repeated.startswith("[") and repeated.endswith("]"):
        repeated = repeated[1:-1]
    if repeated and repeated not in forms:
        forms.append(repeated)
    if not host.isascii():
        # None (not encodable) adds nothing; is_metadata_hostname fails
        # closed on such a name.
        for folded in _idna_folded_names(host) or ():
            folded = folded.lower().rstrip(".")
            if folded and folded not in forms:
                forms.append(folded)
    for form in list(forms):
        alt = _normalize_alt_ipv4(form)
        if alt is not None and alt not in forms:
            forms.append(alt)
    return tuple(forms)


def url_host_is_declared_local(url: object, ctx: EgressContext) -> bool:
    """Whether the URL host has the run's operator-declared local status.

    The declared name must retain its classification when DNS pinning checks
    the connect-time address; an address-only URL would lose that override.
    Uses the same rule as ``_classify_host``: the host's canonical spelling
    (``_canonical_host``) is one of the canonical, non-metadata entries
    (``_declared_local_hosts``). A host without a canonical spelling is
    never declared local.
    """
    if not ctx.local_hostnames or not isinstance(url, str) or not url:
        return False
    try:
        host = _canonical_host(urlsplit(url).hostname)
    except Exception:
        return False
    return host is not None and host in _declared_local_hosts(ctx)


def _record_denial(ctx: EgressContext, url: object, reason: str) -> Decision:
    """Increment the denial counter inside the frozen context's mutable dict
    and emit a redacted audit log line. Lock guards the read-modify-write
    against concurrent subagent threads.

    The offending URL is inlined into the WARNING message body rather than
    bound as a kwarg, matching the rest of the app's log convention (see
    ``[FILE_INTEGRITY]`` audit lines, successful-fetch ``[N] Title: ... URL: ...``
    observations). The ``database_sink`` persists ``record["message"]``
    verbatim into ``app_logs.message`` — and that is what the JSONL exporter
    emits — so this is the only layer at which a triager can read the URL.

    Note: after ``langgraph_agent_strategy._observation_event`` was taught
    to return ``None`` for ``fetch_content`` denial/error strings, the chat
    panel no longer emits a ``📄 From the page: Cannot fetch …`` MILESTONE
    for denials. The persisted WARNING is therefore the **only** record of
    the denial in the research log — if the URL is missing from this
    message body, there is nothing else to cross-reference. The URL still
    passes through ``redact_url_for_log`` so tokens, query strings, and
    paths never reach the audit log.
    """
    from ..ssrf_validator import redact_url_for_log

    counts_toward_quota = reason not in _NON_QUOTA_DENIAL_REASONS
    # Increment the per-RUN counter (the run's active context, shared across
    # every call-site context) rather than this one context's — see _quota_ctx.
    qctx = _quota_ctx(ctx)
    with qctx._lock:
        if counts_toward_quota:
            qctx._fetch_denial_count["count"] += 1
        count = qctx._fetch_denial_count["count"]
    # ``url_malformed`` and the ``urlsplit``-except path can hand us a
    # non-string (None, bytes, int) — urllib3.parse_url raises TypeError on
    # int/bytes and returns a Url with scheme=None for None, neither of which
    # we want on the audit line. Coerce to a stable, type-tagged placeholder
    # so the WARNING still carries a useful field even when the URL itself
    # was unparseable. The denial decision is unaffected — we already
    # decided to refuse.
    if not isinstance(url, str):
        audit_url = f"<unparseable:{type(url).__name__}>"
    else:
        audit_url = redact_url_for_log(url)
    # The URL / reason / scope / count / counted must ride on the message
    # body, NOT as logger.warning kwargs. database_sink persists
    # record["message"] into ``app_logs.message`` verbatim and only copies a
    # small fixed set of structured fields into the DB row. It *does* read
    # selected routing metadata from ``record["extra"]`` (for example
    # ``research_id`` / ``username``), but arbitrary extras or warning kwargs
    # are not serialized into ``app_logs.message`` (or the JSONL exporter that
    # reads it). The pinned
    # ``test_record_denial_warning_message_carries_redacted_url`` and
    # ``test_record_denial_warning_message_reaches_persisted_log`` tests
    # assert this invariant.
    logger.bind(policy_audit=True).warning(
        f"policy denied URL fetch url={audit_url} reason={reason} "
        f"scope={ctx.scope.value} count={count} counted={counts_toward_quota}"
    )
    return Decision(False, reason)


def evaluate_retriever(
    retriever_name: str,
    ctx: EgressContext,
    *,
    metadata: Optional[dict] = None,
) -> Decision:
    """Decide whether a registered retriever may be invoked.

    Reads classification (``{"is_local": bool}``) set at registration
    time. Unclassified retrievers fail closed. ``metadata`` may be
    supplied by the caller (e.g. the search-engine factory, which has
    already looked up the retriever in its own registry reference) to
    avoid a second registry lookup and to honor a test-patched registry;
    when ``None`` the global registry is consulted.
    """
    try:
        # UNPROTECTED: egress protection disabled — any retriever is permitted.
        if ctx.scope == EgressScope.UNPROTECTED:
            return Decision(True, "egress_unprotected")

        if metadata is None:
            from ...web_search_engines.retriever_registry import (
                retriever_registry,
            )

            try:
                metadata = retriever_registry.get_metadata(
                    retriever_name, username=ctx.username
                )
            except AttributeError:
                # Older registry without metadata API; treat as unclassified.
                return Decision(False, "retriever_unclassified")

        if not metadata:
            return Decision(False, "retriever_unknown")

        is_local = metadata.get("is_local")
        if is_local is None:
            return Decision(False, "retriever_unclassified")

        if ctx.scope == EgressScope.STRICT:
            # STRICT permits only the user's primary engine. A retriever
            # IS allowed under STRICT when it is itself the primary (the
            # common "research only against my private KB" setup);
            # otherwise it's an expansion STRICT forbids.
            if retriever_name == ctx.primary_engine:
                return Decision(True, "allowed_primary_retriever")
            return Decision(False, "strict_not_primary")
        if ctx.scope == EgressScope.PUBLIC_ONLY and is_local:
            return Decision(False, "scope_mismatch_public_only")
        if ctx.scope == EgressScope.PRIVATE_ONLY and not is_local:
            return Decision(False, "scope_mismatch_private_only")
        return Decision(True, "allowed")
    except Exception:  # pragma: no cover - defensive
        logger.bind(policy_audit=True).exception(
            "evaluate_retriever internal error", retriever=retriever_name
        )
        return Decision(False, "internal_error")


def _retriever_is_local(
    retriever_name: str, username: Optional[str]
) -> Optional[bool]:
    """Return the ``is_local`` classification (True/False) of a registered
    retriever, or ``None`` when it is unknown/unclassified.

    Mirrors the registry lookup in ``evaluate_retriever`` so adaptive-scope
    resolution and enforcement agree on a retriever primary's classification.
    """
    try:
        from ...web_search_engines.retriever_registry import (
            retriever_registry,
        )

        metadata = retriever_registry.get_metadata(
            retriever_name, username=username
        )
    except Exception:  # noqa: silent-exception - unknown → caller falls back
        return None
    if not metadata:
        return None
    is_local = metadata.get("is_local")
    return is_local if isinstance(is_local, bool) else None


# Bounded, thread-safe, PER-USER dedup for the ADAPTIVE fail-open WARNING
# emitted below. Multiple run setup paths build contexts for the same
# (user, primary) pair, so an unclassifiable primary would otherwise emit
# repeated warnings. We remember, PER USER, which (sanitized) primary
# engines have already warned, so a genuinely new
# (user, primary) combination still logs once while repeats are silent.
#
# The dedup MUST be keyed on the actual user identity (a stable hash of the
# username, ``None`` bucket for an unauthenticated / un-threaded run) -- NOT
# merely on "was a username present". Keying on presence alone means a
# genuine fail-open for user B on a primary name already logged for user A is
# silently swallowed: the audit signal for B never fires. Keying on identity
# keeps each user's fail-opens independently detectable.
#
# ``primary_engine`` is user-controlled (``search.tool``), so the dedup state
# is bounded in BOTH dimensions -- mirroring the capped ``warned: set`` dedup
# in ``web/services/socketio_asgi.py::_install_origin_rejection_logging``:
#   * each user's bucket caps the distinct primaries it remembers
#     (``_ADAPTIVE_FAILOPEN_WARN_CAP_PER_USER``); once full it stops
#     warning/recording, exactly as the old single global set did -- but now
#     that ceiling is reached PER USER, so it only ever silences the ONE user
#     who flooded it, and
#   * the set of tracked users is a bounded LRU
#     (``_ADAPTIVE_FAILOPEN_MAX_USERS``); the least-recently-seen user's whole
#     bucket is evicted beyond the cap (which can only ever re-enable a
#     warning, never suppress one).
# A single authenticated user flooding distinct junk primaries therefore only
# ever exhausts THEIR OWN bucket -- it can never suppress the fail-open audit
# warnings of any other user (the bug a single global set had: 512 junk
# primaries from one user permanently silenced everyone). Total memory is
# capped at MAX_USERS * WARN_CAP_PER_USER short strings.
_ADAPTIVE_FAILOPEN_WARNED: "OrderedDict[Optional[str], OrderedDict[str, None]]" = OrderedDict()
_ADAPTIVE_FAILOPEN_LOCK = threading.Lock()
# Max distinct (sanitized) primaries remembered per user; once a user's bucket
# is full we stop warning/recording for that user (memory-safe, and preserves
# the original anti-log-amplification behavior) -- but PER USER, so it never
# touches another user's audit budget.
_ADAPTIVE_FAILOPEN_WARN_CAP_PER_USER = 128
# Max distinct users tracked at once; the least-recently-seen user's whole
# bucket is LRU-evicted beyond this, keeping total memory bounded.
_ADAPTIVE_FAILOPEN_MAX_USERS = 256


def _adaptive_failopen_user_key(username: Optional[str]) -> Optional[str]:
    """Stable, bounded-length bucket key for the per-user fail-open dedup.

    ``None`` (unauthenticated / un-threaded run) is its own bucket. A present
    username is hashed rather than stored raw: it bounds the key length
    regardless of the username, and avoids retaining plaintext identities in
    this long-lived process-global audit structure (the warning itself only
    ever emits ``username_present``, never the name).
    """
    if username is None:
        return None
    return hashlib.sha256(username.encode("utf-8")).hexdigest()[:16]


def _should_warn_adaptive_failopen(
    sanitized_primary: str, username: Optional[str]
) -> bool:
    """True the first time this ``(user, sanitized_primary)`` pair is seen.

    Dedup is PER USER: the bucket key is a stable hash of ``username``
    (``None`` for an unauthenticated run), so a genuine fail-open for one user
    is never swallowed by an already-logged fail-open for a DIFFERENT user on
    the same primary name. Returns False for a repeat of an already-recorded
    pair, and for any NEW primary once *this* user's bucket is full (bounded,
    and only that user is affected). The set of tracked users is a bounded LRU
    -- see the ``_ADAPTIVE_FAILOPEN_WARNED`` docstring above for the
    memory-safety and cross-user-isolation rationale.
    """
    user_key = _adaptive_failopen_user_key(username)
    with _ADAPTIVE_FAILOPEN_LOCK:
        bucket = _ADAPTIVE_FAILOPEN_WARNED.get(user_key)
        if bucket is None:
            # First fail-open for this user. Enforce the users-tracked cap by
            # LRU-evicting the least-recently-seen user before inserting.
            if len(_ADAPTIVE_FAILOPEN_WARNED) >= _ADAPTIVE_FAILOPEN_MAX_USERS:
                _ADAPTIVE_FAILOPEN_WARNED.popitem(last=False)
            bucket = OrderedDict()
            _ADAPTIVE_FAILOPEN_WARNED[user_key] = bucket
        else:
            # Seen this user before -> mark most-recently-used so an active
            # user is never the one evicted by the users cap.
            _ADAPTIVE_FAILOPEN_WARNED.move_to_end(user_key)

        if sanitized_primary in bucket:
            return False
        # This user's per-user budget is full: stop warning AND recording, so
        # one user's junk-primary flood can neither grow memory nor amplify
        # logs. Bounded and scoped to this ONE user's bucket -- every other
        # user keeps their full audit budget.
        if len(bucket) >= _ADAPTIVE_FAILOPEN_WARN_CAP_PER_USER:
            return False
        bucket[sanitized_primary] = None
        return True


def _resolve_adaptive_scope(
    primary_engine: str,
    settings_snapshot: dict,
    *,
    username: Optional[str],
    local_hostnames: tuple,
    allow_dns: bool = True,
) -> EgressScope:
    """Map ADAPTIVE to a concrete scope by classifying the primary engine.

    Uses the engine's **static class flags** (plus ``classify_engine``'s
    fail-up URL override) so that e.g. a locally-hosted SearXNG is still
    treated as a public engine, and a remote-hosted Elasticsearch resolves
    public rather than pulling the run into PRIVATE_ONLY.

    private primary => PRIVATE_ONLY, public primary => PUBLIC_ONLY,
    unknown / classification-error => BOTH (adaptive's documented
    permissive fallback, equivalent to pre-policy behavior, so a
    classification hiccup never hard-fails the run).

    A registered LangChain retriever (private KB) is not in ENGINE_REGISTRY,
    so ``classify_engine`` returns no classification for it; we then consult the
    retriever registry so a local retriever primary resolves to PRIVATE_ONLY
    (forcing local inference) rather than leaking the corpus to cloud models.
    """
    if not primary_engine:
        return EgressScope.BOTH
    try:
        probe_ctx = EgressContext(
            scope=EgressScope.BOTH,
            primary_engine=primary_engine,
            require_local_llm=False,
            require_local_embeddings=False,
            local_hostnames=local_hostnames,
            username=username,
        )
        classification = classify_engine(
            primary_engine,
            probe_ctx,
            settings_snapshot=settings_snapshot,
            allow_dns=allow_dns,
        )
    except Exception:  # noqa: silent-exception - adaptive falls back to BOTH
        logger.bind(policy_audit=True).debug(
            "adaptive scope classification failed; falling back to BOTH",
            primary=primary_engine,
        )
        return EgressScope.BOTH

    if classification.is_local is True and classification.is_public is not True:
        return EgressScope.PRIVATE_ONLY
    if classification.is_public is True and classification.is_local is not True:
        return EgressScope.PUBLIC_ONLY

    # SECURITY (fail-open regression): a PRIVATE non-contained collection —
    # its vector store lives off this machine — classifies as
    # (is_public=False, is_local=False). ``classify_engine``'s fail-up logic
    # (see its docstring) strips ``is_local`` when containment is lost while
    # PRESERVING the real ``is_public`` flag, so this is the mirror image of
    # a PUBLIC non-contained collection: that one correctly matches the
    # ``is_public is True`` branch above and resolves PUBLIC_ONLY, but a
    # PRIVATE one matches NEITHER exclusive branch and, without this rule,
    # fell through all the way to the permissive ``BOTH`` fallback below —
    # silently dropping the forced-local-LLM/embeddings guarantee
    # (``context_from_snapshot``'s PRIVATE_ONLY coupling) for exactly the
    # collection that most needs it, and resolving MORE permissively than
    # the public case despite being the more sensitive one. Resolve to the
    # RESTRICTIVE PRIVATE_ONLY instead — this preserves the pre-PR
    # forced-local posture. The collection engine itself still gets denied
    # by ``evaluate_engine`` as "unclassified" (neither flag is True)
    # regardless of the scope resolved here; PRIVATE_ONLY's role is to keep
    # every OTHER engine/inference path in the run local too, rather than
    # letting the run silently widen to cloud-capable BOTH. This branch is
    # reached via the private-non-contained-collection fail-up above, or by a
    # static engine whose class overrides NEITHER flag: ``BaseSearchEngine``
    # declares ``is_public = False`` and ``is_local = False`` as CLASS
    # DEFAULTS (``search_engine_base.py``), so such a subclass inherits
    # ``(False, False)`` from the base class — it need not explicitly write
    # either assignment itself — and lands HERE, not in the ``(None, None)``
    # branch below. ``_engine_flags`` only returns ``None`` for a flag that is
    # genuinely absent from the class's MRO, which no attribute on
    # ``BaseSearchEngine`` ever is; all 29 current registry engines override
    # exactly one flag to ``True`` and so don't reach this branch today, but
    # the next engine author who forgets to override either flag will, not
    # the retriever-lookup fallback. Dedup/log via the same per-(user, primary) mechanism
    # as the fail-open warning below — this fires on the identical hot path
    # (once per research-run start AND once per fetch-gate check).
    if classification.is_public is False and classification.is_local is False:
        safe_primary = sanitize_for_log(primary_engine)
        if _should_warn_adaptive_failopen(f"nonlocal:{safe_primary}", username):
            logger.bind(policy_audit=True).warning(
                f"ADAPTIVE egress: primary engine '{safe_primary}' classified "
                f"as neither public nor local-contained (a PRIVATE collection "
                f"whose vector store is not on this machine, or a "
                f"mis-declared static engine); resolving to the RESTRICTIVE "
                f"PRIVATE_ONLY scope (forcing local LLM/embeddings) rather "
                f"than the permissive BOTH."
            )
        return EgressScope.PRIVATE_ONLY

    # Unknown to classify_engine — it may be a registered retriever (private
    # KB). Classify via the retriever registry before falling back to BOTH.
    if classification.is_public is None and classification.is_local is None:
        retriever_local = _retriever_is_local(primary_engine, username)
        if retriever_local is True:
            return EgressScope.PRIVATE_ONLY
        if retriever_local is False:
            return EgressScope.PUBLIC_ONLY

        # SECURITY (detectable fail-open): the primary could not be classified
        # in ANY namespace visible here — it is not a static engine, not a
        # collection, and not a retriever resolvable for ``username``. ADAPTIVE
        # therefore resolves to the PERMISSIVE ``BOTH`` (cloud-capable) scope.
        #
        # The benign cause is a genuinely-unregistered / typo'd / removed
        # meta-engine primary. The DANGEROUS cause is a per-user PRIVATE
        # retriever that is invisible here because ``username=`` was not
        # threaded into this resolution (or the snapshot lacked ``_username``):
        # the retriever would classify as local (=> PRIVATE_ONLY, forcing local
        # inference) if its owner's namespace were consulted, but under the
        # wrong/absent username it disappears and the run silently fails open
        # to cloud-capable BOTH.
        #
        # We do NOT fail closed here: reaching this branch means classify_engine
        # returned (None, None), i.e. a *legitimately-public* primary can never
        # land here (a public engine classifies is_public=True => PUBLIC_ONLY
        # above). But we still cannot cleanly separate "benign unregistered
        # primary" from "invisible per-user retriever" without peeking across
        # other users' registry namespaces (breaking the isolation this PR
        # establishes, and misfiring PRIVATE_ONLY onto a legitimate
        # unregistered public primary that merely shares a name). Since the
        # distinction isn't clean, per the security-hardening guidance we keep
        # the non-breaking permissive behavior and make it DETECTABLE instead:
        # a missed ``username=`` threading now shows up as this WARNING rather
        # than silently permissive egress.
        # primary_engine is user-controlled (search.tool): scrub it before
        # interpolating into the log line so embedded newlines/control chars
        # can't forge additional log entries (log injection). Dedup on the
        # SANITIZED value too, per _should_warn_adaptive_failopen above, so
        # this fires at most once per unique (user, primary) pair in the
        # process rather than once per call. The dedup keys on the ACTUAL
        # username (hashed), not merely "was one present", so a genuine
        # fail-open for one user is never swallowed by another user's.
        safe_primary = sanitize_for_log(primary_engine)
        if _should_warn_adaptive_failopen(safe_primary, username):
            logger.bind(policy_audit=True).warning(
                f"ADAPTIVE egress fail-open: primary engine "
                f"'{safe_primary}' could not be classified in any visible "
                f"namespace (static engine, collection, or retriever visible to "
                f"this user); resolving PERMISSIVELY to BOTH (cloud-capable). If "
                f"'{safe_primary}' is a per-user PRIVATE retriever this is a "
                f"fail-open — verify username= is threaded into egress "
                f"resolution (username_present={username is not None})."
            )
        return EgressScope.BOTH

    return EgressScope.BOTH


def context_from_snapshot(
    settings_snapshot: dict,
    primary_engine: str,
    *,
    username: Optional[str] = None,
    allow_dns: bool = True,
) -> EgressContext:
    """Construct the frozen ``EgressContext`` for a research run.

    Reads policy settings out of the snapshot exactly once at run-start.
    A missing ``policy.egress_scope`` yields ``DEFAULT_EGRESS_SCOPE``
    (``adaptive`` — the protective default that follows the primary engine),
    NOT a permissive fallback. A residual ``both`` value is coerced to
    ``adaptive`` below.

    ``allow_dns=False`` makes ADAPTIVE resolution skip the synchronous
    getaddrinfo when classifying a URL-configurable primary engine — used by
    the advisory warning-banner render path so a settings-page load never
    blocks on DNS. Enforcement callers leave it True so classification is
    accurate. (Has no effect for non-ADAPTIVE scopes, which never resolve
    a URL.)
    """
    if settings_snapshot is None:
        raise ValueError("settings_snapshot is required")
    if not isinstance(settings_snapshot, dict):
        # Fail closed with the same ValueError contract callers already
        # handle (llm_config / research_service convert it to a hard policy
        # stop). A non-dict snapshot would otherwise crash deeper in
        # _get_setting_value with a bare AttributeError, which a broad
        # caller-side except could swallow into a permissive default.
        raise ValueError(
            f"settings_snapshot must be a dict, got "
            f"{type(settings_snapshot).__name__}"
        )

    scope_raw = _get_setting_value(
        settings_snapshot, "policy.egress_scope", DEFAULT_EGRESS_SCOPE
    )
    from ...settings.manager import check_env_setting

    env_scope = check_env_setting("policy.egress_scope")
    if env_scope is not None:
        scope_raw = env_scope
    # `both` is retired (ADR-0007): the blanket-permissive middle scope is
    # coerced to the protective `adaptive` default so a residual value — an
    # un-migrated DB, a queued snapshot, or an env-var override that bypasses
    # settings validation — can never silently keep the old no-protection
    # behaviour. Migration 0019 rewrites stored values; this is the read-time
    # backstop. (EgressScope.BOTH still exists as the INTERNAL resolution result
    # for an unclassifiable ADAPTIVE primary — it is never a user-facing scope.)
    if str(scope_raw).strip().lower() == EgressScope.BOTH.value:
        scope_raw = EgressScope.ADAPTIVE.value
    try:
        scope = parse_user_egress_scope(
            scope_raw, disabled_unprotected="adaptive"
        )
    except PolicyDeniedError:
        # An unrecognised scope means the saved setting was corrupted
        # or tampered with — silently falling back to BOTH (the most
        # permissive scope) would mask policy violations rather than
        # surface them. Refuse the run instead so the operator notices.
        logger.bind(policy_audit=True).warning(
            "refusing to construct EgressContext from unknown scope",
            value=scope_raw,
        )
        raise

    if (
        str(scope_raw).strip().lower() == EgressScope.UNPROTECTED.value
        and scope == EgressScope.ADAPTIVE
    ):
        logger.bind(policy_audit=True).warning(
            "unprotected egress is disabled; coercing scope to adaptive"
        )

    env_require_local_llm = check_env_setting("llm.require_local_endpoint")
    env_require_local_embeddings = check_env_setting("embeddings.require_local")
    require_local_llm = _coerce_bool(
        env_require_local_llm
        if env_require_local_llm is not None
        else _get_setting_value(
            settings_snapshot, "llm.require_local_endpoint", False
        )
    )
    require_local_embeddings = _coerce_bool(
        env_require_local_embeddings
        if env_require_local_embeddings is not None
        else _get_setting_value(
            settings_snapshot, "embeddings.require_local", False
        )
    )

    raw_hostnames = _get_setting_value(
        settings_snapshot, "llm.allowed_local_hostnames", ()
    )
    if isinstance(raw_hostnames, (list, tuple)):
        local_hostnames = tuple(h for h in raw_hostnames if isinstance(h, str))
    else:
        local_hostnames = ()

    # ADAPTIVE resolves to a concrete scope by classifying the primary
    # engine: a concrete private primary => PRIVATE_ONLY, a concrete public
    # primary => PUBLIC_ONLY, an unclassifiable primary => BOTH.
    # The resolved scope is what the EgressContext stores and what
    # every downstream PEP enforces. Classification reuses classify_engine
    # via a throwaway BOTH-scoped context (its DNS cache is discarded).
    if scope == EgressScope.ADAPTIVE:
        scope = _resolve_adaptive_scope(
            primary_engine,
            settings_snapshot,
            username=username,
            local_hostnames=local_hostnames,
            allow_dns=allow_dns,
        )

    # PRIVATE_ONLY means "my data stays on this box." That guarantee only
    # holds if BOTH inference paths are local — a cloud LLM receives the
    # query + retrieved local chunks, and a cloud embedder receives the
    # whole corpus at ingest. So under PRIVATE_ONLY the require_local_*
    # flags are IMPLIED: scope overrides them, so a user who left them at
    # their default (False) can't silently exfiltrate via inference. This
    # also fires when ADAPTIVE resolved to PRIVATE_ONLY above.
    #
    # STRICT is deliberately NOT coupled here: it restricts the search
    # engine set to the primary only and is orthogonal to where inference
    # runs (a user may legitimately want single-engine search + a cloud
    # LLM). Callers that gate on ctx.require_local_* therefore get
    # scope-correct behaviour without a separate flag read.
    if scope == EgressScope.PRIVATE_ONLY:
        require_local_llm = True
        require_local_embeddings = True
    elif scope == EgressScope.UNPROTECTED:
        # The escape hatch lifts user-level locality requirements, but cannot
        # weaken immutable operator environment locks.
        if env_require_local_llm is None:
            require_local_llm = False
        if env_require_local_embeddings is None:
            require_local_embeddings = False

    return EgressContext(
        scope=scope,
        primary_engine=primary_engine,
        require_local_llm=require_local_llm,
        require_local_embeddings=require_local_embeddings,
        local_hostnames=local_hostnames,
        username=username,
    )


def _get_setting_value(snapshot: dict, key: str, default):
    """Read a setting from the snapshot.

    Accepts both flat ({key: value}) and nested ({key: {"value": value}})
    schemas — both shapes appear in LDR's settings infrastructure.
    """
    raw = snapshot.get(key, default)
    return unwrap_setting(raw)


def coerce_str_list(raw) -> tuple[bool, list[str]]:
    """Decode a JSON-list-ish setting value into a list of strings.

    Returns ``(ok, values)``. Accepts a real list/tuple or a JSON-string list
    and filters to string entries. ``ok`` is False only when a non-empty JSON
    string failed to parse — callers that must *reject* malformed input branch
    on it; fail-safe callers ignore it and use the (empty) list. Single home for
    the decode shared by the trust resolver, the trust banner, and the
    settings-save validators.
    """
    if isinstance(raw, str):
        if not raw.strip():
            return True, []
        try:
            raw = json.loads(raw)
        except Exception:
            return False, []
    if isinstance(raw, (list, tuple)):
        return True, [x for x in raw if isinstance(x, str)]
    return True, []


def resolve_run_primary_engine(
    settings_snapshot: Optional[dict], default: Optional[str] = None
) -> str:
    """Resolve a research run's primary search engine id from a snapshot.

    Single source of truth for "which engine drives this run's egress
    scope". Under the default ADAPTIVE scope the concrete scope is derived by
    classifying THIS primary, so run-scoped callers that build an
    ``EgressContext`` should derive the primary here. Otherwise two layers can
    resolve ADAPTIVE to different scopes and one silently under-enforces — the
    LangGraph tool-list filter once derived the primary from the engine CLASS
    name (a collection -> ``"libraryrag"`` -> unclassified -> BOTH) while the
    factory PEP derived it from ``search.tool`` (the real collection key ->
    PRIVATE_ONLY), so a public engine reached the agent and was then
    hard-denied mid-run (``scope_mismatch_private_only``).

    Reads ``search.tool`` (flat or ``{"value": ...}`` shaped). A blank-after-
    strip (``"  "``) or non-string (``5``, list/dict) value is treated as
    MISSING — it must not slip through the truthiness check and classify to the
    permissive BOTH scope.

    A run with NO configured primary is a wiring error, not a normal state.
    Silently substituting a default would set the egress scope from an engine
    the user never chose — and since the system default is public (``searxng``),
    that fails OPEN. So a missing/empty ``search.tool`` raises ``ValueError``
    unless the caller passes an explicit ``default``:

    * run-level callers (research_service, the strategy tool-list filter,
      ``filter_candidates_by_egress``) pass none and fail closed — the worker
      refuses the run; advisory filters degrade to unfiltered with the factory
      PEP still enforcing.
    * the search-engine factory and per-engine checks pass
      ``default=engine_name`` outside STRICT because they evaluate that one
      specific engine. Under STRICT they require the saved primary so an
      engine cannot authorize itself by becoming the fallback.

    Raises:
        ValueError: The snapshot is neither a dictionary nor None, or
            ``search.tool`` is missing/blank/non-string and no truthy
            ``default`` is given.
    """
    if settings_snapshot is not None and not isinstance(
        settings_snapshot, dict
    ):
        raise ValueError(
            "settings_snapshot must be a dict, got "
            f"{type(settings_snapshot).__name__}"
        )
    primary = (
        _get_setting_value(settings_snapshot, "search.tool", None)
        if settings_snapshot
        else None
    )
    # Blank-after-strip or non-string is not a usable engine id → missing.
    primary = primary.strip() if isinstance(primary, str) else None
    if primary:
        return primary
    if default:
        return default
    raise ValueError(
        "no primary search engine configured: settings 'search.tool' is "
        "missing, blank, or not a string, so the run's egress scope cannot "
        "be resolved"
    )


def build_run_egress_context(
    settings_snapshot: Optional[dict],
    search_engine: Optional[str],
    *,
    username: Optional[str] = None,
) -> EgressContext:
    """Resolve the research worker's per-run ``EgressContext``.

    Composes the policy setup ``run_research_process`` runs at startup:
    current operator env policy is reapplied on the snapshot, the primary
    engine is derived, and the ``EgressContext`` is constructed. This is the
    single production seam invoked by the worker; a stale queued snapshot
    carrying an operator-disabled ``unprotected`` scope is coerced to a
    protected scope here (via the read-time backstop in
    ``context_from_snapshot``), not at queue extraction time.

    Under ``STRICT`` the primary is the *saved* snapshot primary only — a
    blank/missing saved primary raises ``ValueError`` (fail closed) rather
    than letting the request choose its own primary. Under every other
    scope the requested engine wins when present, matching
    ``_precheck_engine_policy``.
    """
    from ...settings.manager import (
        apply_environment_overrides_to_snapshot,
    )

    effective = apply_environment_overrides_to_snapshot(settings_snapshot or {})
    scope_raw = _get_setting_value(
        effective, "policy.egress_scope", DEFAULT_EGRESS_SCOPE
    )
    if str(scope_raw).strip().lower() == EgressScope.STRICT.value:
        primary = resolve_run_primary_engine(effective)
    else:
        saved_primary = resolve_run_primary_engine(
            effective, default=search_engine or None
        )
        primary = search_engine or saved_primary
    return context_from_snapshot(effective, primary, username=username)


def _coerce_bool(value) -> bool:
    """Coerce a setting value to bool, defensively.

    Strings ``"true"`` / ``"True"`` are True; anything else string-shaped
    is False. Real booleans pass through. The strict coercion prevents
    type confusion (e.g., the string ``"false"`` being truthy).
    """
    if isinstance(value, bool):
        return value
    if isinstance(value, str):
        return value.strip().lower() in ("true", "1", "yes", "on")
    return bool(value)


def coerce_policy_bool(value) -> bool:
    """Public alias for the coercion the policy applies to its own flags.

    UI code that has to report *whether the policy is in force* (for example
    the reason a provider is greyed out) must decide truthiness the same way
    ``context_from_snapshot`` does. HTML-checkbox parsers such as
    ``settings.manager.parse_boolean`` treat every non-falsy string as True,
    so ``LDR_LLM_REQUIRE_LOCAL_ENDPOINT=enabled`` would be reported as a
    server lock while the policy itself computes ``require_local_llm=False``.
    """
    return _coerce_bool(value)