Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(egress): classify a collection by its vector store, not by assumption (#5777)

LearningCircuitbaaee9f4f4c6
diff --git a/changelog.d/5763.security.md b/changelog.d/5763.security.md
new file mode 100644
index 0000000000..ca41394108
--- /dev/null
+++ b/changelog.d/5763.security.md
@@ -0,0 +1,37 @@
+The egress policy no longer assumes a `library` / `collection_*` search engine
+is always contained. A collection is now classified by the vector store its
+index actually lives in: a local-file store (FAISS) stays local exactly as
+before, while a server-backed store is treated as local only while its
+configured endpoint resolves to a local host or a filesystem path. Otherwise
+the collection loses containment (`is_local=False`) but keeps its real,
+already-resolved `is_public` flag — it is NOT reclassified as public. A
+private (non-public-flagged) collection whose store is not contained is
+therefore denied under **every** scope (`private_only`, `public_only`,
+`adaptive`/`both`, `strict`), with reason `unclassified`, fail-closed, exactly
+like any other engine the policy cannot positively classify as local or
+public. Only a `collection_*` explicitly marked `is_public` stays eligible
+under public-scope runs once its store leaves the box (`library`, the
+all-collections aggregate, cannot opt in this way — see "Future work" below).
+This differs from how Paperless/Elasticsearch fail up: those engines are
+reclassified fully *public* on a public endpoint, so `private_only` alone
+blocks them while `public_only`/adaptive-public still allow them; a
+non-contained private collection is blocked everywhere instead, because
+losing containment must only ever add restriction, never grant new
+eligibility. The two-axis run-start audit (ADR-0007) independently reaches
+the same result for a private collection: it labels a non-contained
+collection `EXPOSING` regardless of `is_public`, and a `SENSITIVE` (private)
+source may not reach an `EXPOSING` sink under that rule, so the private,
+non-contained collection is blocked by both mechanisms.
+
+A non-local-file store whose endpoint cannot be resolved is treated as
+remote (not contained).
+
+**Future work:** today the only way to keep a `library`/collection engine
+usable once its vector store is server-backed and off-box is to mark the
+individual collection `is_public` (or run `unprotected`) — there is no
+opt-in for the `library` aggregate, and `policy.trusted_search_engines` is
+not wired into this containment check. A deliberate opt-in mechanism (e.g.
+extending `trusted_search_engines` to cover vector-store endpoints, or a
+per-collection "trusted remote store" flag) is a maintainer decision that
+should land before server-backed vector stores (tracked in #5331) are
+expected to be usable under anything other than `unprotected`.
diff --git a/src/local_deep_research/security/egress/README.md b/src/local_deep_research/security/egress/README.md
index a83a5fec45..336dee79f1 100644
--- a/src/local_deep_research/security/egress/README.md
+++ b/src/local_deep_research/security/egress/README.md
@@ -47,6 +47,30 @@ PUBLIC_ONLY / Adaptive-public and, when it is the primary under Adaptive,
pulls the whole run to PRIVATE_ONLY (→ local inference). To process a
collection with a cloud model, mark it **public** — the explicit opt-in.
+**Vector-store classification.** A collection is only as *local* as the vector
+store its index lives in. A local-file store (FAISS — `is_local_file = True` in
+`vector_stores/base.py`) is contained by construction. A server-backed store is
+contained only while its configured endpoint (`uri_setting`, read exactly like
+an engine's `url_setting`) resolves to a local host or a filesystem path;
+otherwise the `library` / `collection_*` engine loses containment
+(`is_local=False`) but keeps its real, already-resolved `is_public` flag — it
+is **not** reclassified as public the way Paperless/Elasticsearch are. A
+private (non-public-flagged) collection whose store is not contained ends up
+with neither `is_public` nor `is_local` true, so `evaluate_engine` fails it
+closed as `unclassified` under **every** scope (PRIVATE_ONLY, PUBLIC_ONLY,
+BOTH, STRICT) — not just PRIVATE_ONLY. Only a `collection_*` explicitly
+marked `is_public` stays eligible under public-scope runs once its store
+leaves the box; `library` (the all-collections aggregate) always resolves
+`is_public=False` (`_resolve_collection_is_public`) and so has **no** opt-in
+path back once any collection's store is non-contained, short of running
+`unprotected`. `policy.trusted_search_engines` is not wired into this
+containment check. **Future work:** a deliberate opt-in (e.g. extending
+`trusted_search_engines` to cover vector-store endpoints, or a per-collection
+"trusted remote store" flag) is a maintainer decision that should land before
+server-backed vector stores (#5331) are expected to be usable under anything
+other than `unprotected`. A non-local-file store whose endpoint cannot be
+resolved is treated as remote (not contained).
+
**Two-axis enforcement (ADR-0007).** On top of the scope check, the run-start
precheck enforces a *two-axis* rule: every source/sink is labelled
**Sensitivity × Exposure** and a *sensitive* source may not reach an *exposing*
diff --git a/src/local_deep_research/security/egress/policy.py b/src/local_deep_research/security/egress/policy.py
index c8c8443b4a..ed956c7931 100644
--- a/src/local_deep_research/security/egress/policy.py
+++ b/src/local_deep_research/security/egress/policy.py
@@ -504,6 +504,265 @@ def _resolve_collection_is_public(
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 ""
+ return raw.strip().strip("\"'").strip().lower()
+
+
+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 "/\\"
+
+
+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
+ uri = value.strip()
+ 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.
+ parsed = urlsplit(uri)
+ netloc = parsed.netloc
+ is_drive_letter_netloc = (
+ len(netloc) == 2 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.
+ return not _starts_with_double_separator(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").
+ return (
+ len(uri) > 2 and uri[0].isalpha() and uri[1] == ":" and uri[2] in "\\/"
+ )
+
+
+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
+ if _is_local_filesystem_uri(
+ _get_setting_value(settings_snapshot or {}, uri_setting, None)
+ ):
+ 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,
@@ -551,6 +810,27 @@ def classify_engine(
# ``(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)
@@ -768,7 +1048,21 @@ def _classify_engine_url(
if not isinstance(entry, str):
continue
try:
- parsed = urlsplit(entry if "://" in entry else f"http://{entry}")
+ 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:
continue
@@ -1486,6 +1780,46 @@ def _resolve_adaptive_scope(
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 a
+ # static engine that explicitly declares BOTH flags False) — NOT by a
+ # static engine that simply forgot to declare its flags: ``_engine_flags``
+ # reads missing attributes as ``None`` (not ``False``), so an undeclared
+ # engine classifies as ``(None, None)`` and falls to the retriever-lookup
+ # branch below instead. 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:
diff --git a/src/local_deep_research/security/egress/run_classification.py b/src/local_deep_research/security/egress/run_classification.py
index 958cf92994..ed923d6d49 100644
--- a/src/local_deep_research/security/egress/run_classification.py
+++ b/src/local_deep_research/security/egress/run_classification.py
@@ -10,7 +10,10 @@ configuration:
a Paperless/Elasticsearch holding private data on a public endpoint becomes
quadrant 4 (sensitive + exposing);
* a collection's sensitivity flips to ``NON_SENSITIVE`` when it is marked
- public; the aggregate ``library`` stays sensitive.
+ public; the aggregate ``library`` stays sensitive;
+ * a collection's exposure flips to ``EXPOSING`` when the vector store its
+ index lives in is not a local file and its configured endpoint does not
+ resolve local — the same fail-up, applied to the RAG sink.
``audit_run`` computes and LOGS the four-quadrant decision and returns it; the
run-start precheck AND the worker chokepoint ENFORCE on that result (rejecting a
@@ -49,6 +52,7 @@ def engine_label(engine_name: str, settings_snapshot, ctx) -> Optional[Label]:
_classify_engine_url,
_get_engine_class,
_resolve_collection_is_public,
+ vector_store_is_contained,
)
# Collections / library: the class is not a static engine, and sensitivity
@@ -58,9 +62,19 @@ def engine_label(engine_name: str, settings_snapshot, ctx) -> Optional[Label]:
sensitivity = (
Sensitivity.NON_SENSITIVE if is_public else Sensitivity.SENSITIVE
)
- # A collection is a local store: contained. (It never gains a public
- # URL the way Paperless/Elasticsearch can.)
- return Label(sensitivity, Exposure.CONTAINED)
+ # A collection is contained only while its VECTOR STORE is: with a
+ # local-file store (FAISS) the documents, embeddings and queries never
+ # leave the box, but a server-backed store on a public endpoint is a
+ # sink just like Paperless/Elasticsearch on a public ``url_setting`` —
+ # so it fails up to EXPOSING (quadrant 4 for a private collection).
+ # Shared with the scope PEP's ``classify_engine`` so the two can't
+ # diverge; a strict no-op for a local-file store.
+ exposure = (
+ Exposure.CONTAINED
+ if vector_store_is_contained(engine_name, ctx, settings_snapshot)
+ else Exposure.EXPOSING
+ )
+ return Label(sensitivity, exposure)
cls = _get_engine_class(engine_name)
if cls is None:
diff --git a/src/local_deep_research/vector_stores/base.py b/src/local_deep_research/vector_stores/base.py
index ab5c287477..58727fd084 100644
--- a/src/local_deep_research/vector_stores/base.py
+++ b/src/local_deep_research/vector_stores/base.py
@@ -93,6 +93,17 @@ class BaseVectorStore(ABC):
# — i.e. the service's file write-lock + integrity checksum + reload/merge
# model applies. A server-backed store sets this False.
is_local_file: bool = True
+ # Settings key holding this store's endpoint URI, for a store that is NOT
+ # a local file. The egress policy reads it exactly as it reads a search
+ # engine's ``url_setting`` (``security/egress/policy.py``): a
+ # server-backed store whose configured host resolves to a PUBLIC address
+ # ships the collection's embeddings and every query off the machine, so
+ # the library/collection engines fail up to exposing/public and
+ # PRIVATE_ONLY denies them. A non-local-file store that declares no key
+ # cannot be shown to be on-box and is therefore treated as remote —
+ # declaring it is how a backend proves the opposite. Unused for a
+ # local-file store (FAISS), which is contained by construction.
+ uri_setting: Optional[str] = None
# True when the store can invert id -> vector (needed for the in-place
# format migration, which re-keys vectors without re-embedding).
supports_reconstruct: bool = True
diff --git a/tests/security/test_egress_collection_semantics_followup.py b/tests/security/test_egress_collection_semantics_followup.py
index 860a3d7949..bcab575968 100644
--- a/tests/security/test_egress_collection_semantics_followup.py
+++ b/tests/security/test_egress_collection_semantics_followup.py
@@ -297,6 +297,94 @@ def test_adaptive_library_primary_resolves_to_private_only():
assert scope == EgressScope.PRIVATE_ONLY
+# ---------------------------------------------------------------------------
+# _resolve_adaptive_scope — PRIVATE, NON-CONTAINED collection primary
+# (round-6 fail-open fix: classify_engine's fail-up strips is_local while
+# preserving is_public, so a private non-contained collection buckets
+# (is_public=False, is_local=False) -- neither exclusive branch in
+# _resolve_adaptive_scope matched this before the fix, so it fell all the
+# way through to the permissive BOTH fallback, silently dropping the
+# forced-local-LLM/embeddings guarantee for the collection that most needs
+# it (and resolving MORE permissively than the equivalent PUBLIC
+# non-contained case, which already correctly hit PUBLIC_ONLY via the
+# ``is_public is True`` branch). This must now resolve to the RESTRICTIVE
+# PRIVATE_ONLY instead of BOTH.
+#
+# Interplay with ``audit_run_from_snapshot``: that function's audit trail
+# records the RESOLVED scope (whatever ``_resolve_adaptive_scope``/
+# ``context_from_snapshot`` returns), so before this fix a private
+# non-contained-collection run would have been silently AUDITED as the
+# permissive BOTH scope with require_local_llm/embeddings left at their
+# (possibly False) configured defaults -- an audit record that looks
+# compliant while the run was actually able to route the query + local
+# corpus context through a cloud LLM/embedder. After this fix the audit
+# trail correctly shows PRIVATE_ONLY with both require_local_* flags
+# forced True, matching the actual (restrictive) posture enforced.
+# ---------------------------------------------------------------------------
+
+
+def test_adaptive_private_noncontained_collection_primary_resolves_to_private_only():
+ """A PRIVATE collection primary whose vector store is NOT contained on
+ this machine buckets (is_public=False, is_local=False) via
+ classify_engine's fail-up. ADAPTIVE must resolve this to the
+ RESTRICTIVE PRIVATE_ONLY -- never the permissive BOTH -- so the
+ forced-local-inference guarantee survives loss of containment."""
+ with patch(f"{_POLICY}.classify_engine") as mock_classify:
+ mock_classify.return_value = EngineClassification(
+ is_public=False, is_local=False
+ )
+ scope = _resolve_adaptive_scope(
+ "collection_priv_noncontained",
+ {},
+ username="alice",
+ local_hostnames=(),
+ )
+ assert scope == EgressScope.PRIVATE_ONLY
+ assert scope != EgressScope.BOTH
+
+
+def test_context_adaptive_private_noncontained_collection_still_forces_local():
+ """End-to-end: ADAPTIVE + a private non-contained collection primary ->
+ PRIVATE_ONLY via context_from_snapshot, which still applies the
+ PRIVATE_ONLY -> require_local_llm/require_local_embeddings coupling.
+ This is the concrete guarantee the fail-open regression would have
+ silently dropped (the flags would otherwise stay at their configured,
+ possibly-False, defaults under the old fall-through-to-BOTH
+ behaviour)."""
+ snapshot = {"policy.egress_scope": {"value": "adaptive"}}
+ with patch(f"{_POLICY}.classify_engine") as mock_classify:
+ mock_classify.return_value = EngineClassification(
+ is_public=False, is_local=False
+ )
+ ctx = context_from_snapshot(
+ snapshot,
+ primary_engine="collection_priv_noncontained",
+ username="alice",
+ )
+ assert ctx.scope == EgressScope.PRIVATE_ONLY
+ assert ctx.require_local_llm is True
+ assert ctx.require_local_embeddings is True
+
+
+def test_adaptive_public_noncontained_collection_still_resolves_public_only():
+ """Contrast/non-regression: a PUBLIC non-contained collection buckets
+ (is_public=True, is_local=False) and must keep resolving PUBLIC_ONLY
+ via the pre-existing ``is_public is True`` branch -- the new
+ (False, False) branch added for the private case must not affect this
+ bucket."""
+ with patch(f"{_POLICY}.classify_engine") as mock_classify:
+ mock_classify.return_value = EngineClassification(
+ is_public=True, is_local=False
+ )
+ scope = _resolve_adaptive_scope(
+ "collection_pub_noncontained",
+ {},
+ username="alice",
+ local_hostnames=(),
+ )
+ assert scope == EgressScope.PUBLIC_ONLY
+
+
# ---------------------------------------------------------------------------
# context_from_snapshot — ADAPTIVE + collection primary end-to-end
# ---------------------------------------------------------------------------
diff --git a/tests/security/test_egress_policy.py b/tests/security/test_egress_policy.py
index d334160454..c82554339e 100644
--- a/tests/security/test_egress_policy.py
+++ b/tests/security/test_egress_policy.py
@@ -1448,6 +1448,62 @@ def test_t2_list_typed_url_setting_any_public_wins():
assert result is False
+def test_t2b_scheme_less_authority_url_setting_classifies_by_host():
+ """A ``url_setting`` entry written as a scheme-less ``//host:port``
+ authority (e.g. how a Milvus/vector-store endpoint can be configured)
+ must classify by its ACTUAL host, not silently fall through as
+ undetermined.
+
+ ``_classify_engine_url`` used to build the URL to parse via
+ ``entry if "://" in entry else f"http://{entry}"``. For
+ ``//attacker.example.com:19530`` that produced
+ ``http:////attacker.example.com:19530``, which ``urlsplit`` mis-parses
+ as an EMPTY netloc with the host landing in ``path`` — so ``hostname``
+ came back ``None`` and the entry was silently skipped (``continue``),
+ making the overall result ``None`` (undetermined) instead of ``False``
+ (public).
+
+ That matters beyond the vector-store path: ``classify_engine``'s
+ asymmetric fail-up (a local-nature engine like Elasticsearch/Paperless
+ whose configured host resolves public) only fires on
+ ``host_classification is False`` — ``None`` does NOT trigger it, so a
+ remote host hidden behind ``//host:port`` stayed classified as fully
+ local/private, skipping egress gating entirely. Confirm both the
+ public and local scheme-less forms now classify by hostname exactly
+ like their equivalent ``host:port`` forms.
+ """
+ from local_deep_research.security.egress.policy import (
+ _classify_engine_url,
+ )
+
+ ctx = make_ctx(scope=EgressScope.BOTH)
+
+ def fake_classify_host(host, ctx, allow_dns=True):
+ return host == "127.0.0.1"
+
+ with patch(
+ "local_deep_research.security.egress.policy._classify_host",
+ side_effect=fake_classify_host,
+ ):
+ public_scheme_less = _classify_engine_url(
+ "vector_store.uri",
+ {"vector_store.uri": "//attacker.example.com:19530"},
+ ctx,
+ )
+ public_equivalent = _classify_engine_url(
+ "vector_store.uri",
+ {"vector_store.uri": "attacker.example.com:19530"},
+ ctx,
+ )
+ local_scheme_less = _classify_engine_url(
+ "vector_store.uri", {"vector_store.uri": "//127.0.0.1:19530"}, ctx
+ )
+
+ assert public_scheme_less is False # was None before the fix
+ assert public_scheme_less == public_equivalent
+ assert local_scheme_less is True
+
+
def test_t3_classify_host_uses_dns_when_not_an_ip():
"""T3: exercise the REAL _classify_host (not patched out) with
mocked socket.getaddrinfo. Catches regressions in the DNS code
diff --git a/tests/security/test_egress_vector_store_exposure.py b/tests/security/test_egress_vector_store_exposure.py
new file mode 100644
index 0000000000..44960609b3
--- /dev/null
+++ b/tests/security/test_egress_vector_store_exposure.py
@@ -0,0 +1,622 @@
+"""A library/collection engine is only as contained as its VECTOR STORE.
+
+Both twins of the hardcoded ``library`` / ``collection_*`` branch —
+``policy.classify_engine`` (the scope PEP) and
+``run_classification.engine_label`` (the two-axis resolver) — used to return
+"contained / local" unconditionally. That holds only while the RAG index is a
+local file. A server-backed store on a public endpoint ships the collection's
+embeddings and every query to a third party, so both must fail UP, exactly as
+Paperless/Elasticsearch do via ``url_setting``.
+
+The discriminator is ``BaseVectorStore.is_local_file``, so these tests use
+synthetic store classes rather than any concrete backend: nothing here depends
+on a particular remote implementation, and the local-file case must be a strict
+no-op (see ``test_local_file_store_*``).
+"""
+
+from __future__ import annotations
+
+from contextlib import ExitStack
+from unittest.mock import patch
+
+from local_deep_research.security.egress import policy as P
+from local_deep_research.security.egress import run_classification as rc
+from local_deep_research.security.egress.classification import (
+ Exposure,
+ Label,
+ Sensitivity,
+)
+
+POLICY = "local_deep_research.security.egress.policy"
+
+URI_SETTING = "vector_store.test.uri"
+# A public IP LITERAL, so the classifier answers "public" from the address
+# itself — these tests never touch DNS.
+PUBLIC_URI = {URI_SETTING: "https://93.184.216.34:19530"}
+LOCAL_URI = {URI_SETTING: "http://127.0.0.1:19530"}
+LOCAL_PATH = {URI_SETTING: "./store.db"}
+
+
+class _LocalFileStore:
+ """Stands in for FAISS: the index is a file on this machine."""
+
+ provider_key = "faiss"
+ is_local_file = True
+
+
+class _RemoteStore:
+ """Stands in for ANY server-backed store (Milvus/Qdrant/pgvector/...)."""
+
+ provider_key = "remote"
+ is_local_file = False
+ uri_setting = URI_SETTING
+
+
+class _RemoteStoreNoUriSetting:
+ """A server-backed store that never declared where its endpoint lives."""
+
+ provider_key = "undeclared"
+ is_local_file = False
+
+
+def ctx(scope: str = "both", username=None) -> P.EgressContext:
+ return P.EgressContext(
+ scope=P.EgressScope(scope),
+ primary_engine="library",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ username=username,
+ )
+
+
+def _store(cls, providers=("remote",)):
+ """Patch the vector-store layer to report ``cls`` for ``providers``."""
+ stack = ExitStack()
+ stack.enter_context(
+ patch(f"{POLICY}._vector_store_class", lambda provider: cls)
+ )
+ stack.enter_context(
+ patch(
+ f"{POLICY}._resolve_vector_store_providers",
+ return_value=set(providers),
+ )
+ )
+ stack.enter_context(
+ patch(f"{POLICY}._resolve_collection_is_public", return_value=False)
+ )
+ return stack
+
+
+# ---------------------------------------------------------------------------
+# Local-file store: strict no-op (the FAISS user's classification must not move)
+# ---------------------------------------------------------------------------
+
+
+def test_local_file_store_is_contained():
+ with _store(_LocalFileStore, providers=("faiss",)):
+ assert P.vector_store_is_contained("library", ctx(), {}) is True
+
+
+def test_local_file_store_ignores_a_public_uri_setting():
+ """A local-file store never consults a URI — no DNS, no fail-up."""
+ with _store(_LocalFileStore, providers=("faiss",)):
+ with patch(f"{POLICY}._classify_engine_url") as classify_url:
+ assert (
+ P.vector_store_is_contained("library", ctx(), PUBLIC_URI)
+ is True
+ )
+ classify_url.assert_not_called()
+
+
+def test_local_file_store_label_unchanged():
+ with _store(_LocalFileStore, providers=("faiss",)):
+ assert rc.engine_label("library", PUBLIC_URI, ctx()) == Label(
+ Sensitivity.SENSITIVE, Exposure.CONTAINED
+ )
+ assert rc.engine_label("collection_x", PUBLIC_URI, ctx()) == Label(
+ Sensitivity.SENSITIVE, Exposure.CONTAINED
+ )
+
+
+def test_local_file_store_classification_unchanged():
+ with _store(_LocalFileStore, providers=("faiss",)):
+ assert P.classify_engine(
+ "collection_x", ctx(), settings_snapshot=PUBLIC_URI
+ ) == P.EngineClassification(is_public=False, is_local=True)
+
+
+def test_local_file_store_still_allowed_under_private_only():
+ with _store(_LocalFileStore, providers=("faiss",)):
+ assert (
+ P.evaluate_engine(
+ "collection_x",
+ ctx("private_only"),
+ settings_snapshot=PUBLIC_URI,
+ ).allowed
+ is True
+ )
+
+
+def test_default_install_is_contained_without_patching():
+ """End to end on the real provider registry: today's default is FAISS."""
+ with patch(
+ f"{POLICY}._resolve_index_vector_store_providers", return_value=set()
+ ):
+ assert P.vector_store_is_contained("library", ctx(), {}) is True
+
+
+# ---------------------------------------------------------------------------
+# Non-local-file store on a public endpoint: both twins fail up
+# ---------------------------------------------------------------------------
+
+
+def test_remote_store_on_public_uri_is_not_contained():
+ with _store(_RemoteStore):
+ assert (
+ P.vector_store_is_contained("library", ctx(), PUBLIC_URI) is False
+ )
+
+
+def test_engine_label_fails_up_to_exposing():
+ """Twin A: the two-axis resolver."""
+ with _store(_RemoteStore):
+ assert rc.engine_label("collection_x", PUBLIC_URI, ctx()) == Label(
+ Sensitivity.SENSITIVE, Exposure.EXPOSING
+ )
+ assert rc.engine_label("library", PUBLIC_URI, ctx()) == Label(
+ Sensitivity.SENSITIVE, Exposure.EXPOSING
+ )
+
+
+def test_classify_engine_fails_up_preserves_privacy():
+ """Twin B: the scope PEP. Losing containment must be a pure TIGHTENING —
+ it strips ``is_local`` but must PRESERVE the collection's real (private)
+ ``is_public`` flag rather than overwriting it with True. Overwriting it
+ would make a private collection newly ELIGIBLE under PUBLIC_ONLY just
+ because its store went remote, which is a relaxation, not a
+ tightening."""
+ with _store(_RemoteStore):
+ assert P.classify_engine(
+ "collection_x", ctx(), settings_snapshot=PUBLIC_URI
+ ) == P.EngineClassification(is_public=False, is_local=False)
+
+
+def test_private_only_denies_a_remote_vector_store():
+ with _store(_RemoteStore):
+ decision = P.evaluate_engine(
+ "collection_x", ctx("private_only"), settings_snapshot=PUBLIC_URI
+ )
+ assert decision.allowed is False
+ # Neither axis holds (not local: store left the box; not public: the
+ # collection is genuinely private) so the fail-closed "unclassified"
+ # check fires before the scope-specific PRIVATE_ONLY check does.
+ assert decision.reason == "unclassified"
+
+
+def test_private_only_denies_even_a_public_collection():
+ """``is_public`` is about the DATA, not about where the index lives."""
+ stack = _store(_RemoteStore)
+ with stack:
+ stack.enter_context(
+ patch(f"{POLICY}._resolve_collection_is_public", return_value=True)
+ )
+ assert (
+ P.evaluate_engine(
+ "collection_x",
+ ctx("private_only"),
+ settings_snapshot=PUBLIC_URI,
+ ).allowed
+ is False
+ )
+
+
+def test_unrestricted_scope_denies_a_private_remote_store():
+ """A PRIVATE collection whose store isn't contained satisfies neither
+ axis (not local: the store left the box; not public: the content is
+ private) and must be denied even under the permissive default (BOTH)
+ scope — losing containment must never grant new eligibility, in any
+ scope, to a collection that was never marked public."""
+ with _store(_RemoteStore):
+ decision = P.evaluate_engine(
+ "collection_x", ctx(), settings_snapshot=PUBLIC_URI
+ )
+ assert decision.allowed is False
+ assert decision.reason == "unclassified"
+
+
+def test_unrestricted_scope_still_allows_a_remote_store_when_public():
+ """The fail-up tightens PRIVATE_ONLY; it must not break the default scope
+ for a collection that IS actually marked public — ``is_public`` is
+ preserved (not overwritten), so a public collection stays eligible under
+ BOTH/PUBLIC_ONLY regardless of where its store lives."""
+ stack = _store(_RemoteStore)
+ with stack:
+ stack.enter_context(
+ patch(f"{POLICY}._resolve_collection_is_public", return_value=True)
+ )
+ assert P.classify_engine(
+ "collection_x", ctx(), settings_snapshot=PUBLIC_URI
+ ) == P.EngineClassification(is_public=True, is_local=False)
+ assert (
+ P.evaluate_engine(
+ "collection_x", ctx(), settings_snapshot=PUBLIC_URI
+ ).allowed
+ is True
+ )
+
+
+def test_remote_store_with_a_sensitive_peer_source_denies_the_run():
+ """Quadrant 4: a sensitive collection whose sink is off-box can't coexist
+ with another sensitive source."""
+ with _store(_RemoteStore):
+ decision = rc.audit_run(
+ PUBLIC_URI,
+ ctx(),
+ engines=["collection_x", "library"],
+ llm_provider=None,
+ )
+ assert decision.allowed is False
+ assert decision.reason == "sensitive_to_exposing_search"
+
+
+# ---------------------------------------------------------------------------
+# Non-local-file store that IS on this machine: contained (no false positive)
+# ---------------------------------------------------------------------------
+
+
+def test_remote_store_on_a_local_host_is_contained():
+ with _store(_RemoteStore):
+ assert P.vector_store_is_contained("library", ctx(), LOCAL_URI) is True
+ assert rc.engine_label("library", LOCAL_URI, ctx()) == Label(
+ Sensitivity.SENSITIVE, Exposure.CONTAINED
+ )
+
+
+def test_remote_store_on_a_local_file_path_is_contained():
+ """An embedded/lite mode pointed at a filesystem path never leaves the box."""
+ with _store(_RemoteStore):
+ assert P.vector_store_is_contained("library", ctx(), LOCAL_PATH) is True
+
+
+# ---------------------------------------------------------------------------
+# Fail direction when the store cannot be resolved
+# ---------------------------------------------------------------------------
+
+
+def test_unset_uri_fails_up():
+ with _store(_RemoteStore):
+ assert P.vector_store_is_contained("library", ctx(), {}) is False
+
+
+def test_undeclared_uri_setting_fails_up():
+ with _store(_RemoteStoreNoUriSetting, providers=("undeclared",)):
+ assert (
+ P.vector_store_is_contained("library", ctx(), PUBLIC_URI) is False
+ )
+
+
+def test_unknown_provider_class_fails_up():
+ """A configured provider whose class can't be loaded is assumed remote."""
+ with _store(None, providers=("mystery",)):
+ assert P.vector_store_is_contained("library", ctx(), {}) is False
+
+
+def test_unloadable_default_provider_stays_contained():
+ """...unless the key itself is a known local-file store: a FAISS install
+ with a broken/absent driver must not start denying local runs."""
+ with _store(None, providers=("faiss",)):
+ assert P.vector_store_is_contained("library", ctx(), {}) is True
+
+
+def test_unreachable_vector_store_layer_keeps_the_status_quo():
+ """No provider resolvable at all -> the run can't build a store either, so
+ nothing can leave the box; classification stays contained."""
+ with patch(f"{POLICY}._resolve_vector_store_providers", return_value=set()):
+ assert P.vector_store_is_contained("library", ctx(), PUBLIC_URI) is True
+
+
+def test_recorded_index_provider_tightens_the_settings_default():
+ """A collection indexed into a remote store counts even when the current
+ default setting says local-file."""
+
+ def _cls(provider):
+ return _LocalFileStore if provider == "faiss" else _RemoteStore
+
+ with patch(f"{POLICY}._vector_store_class", _cls):
+ with patch(
+ f"{POLICY}._resolve_index_vector_store_providers",
+ return_value={"remote"},
+ ):
+ assert (
+ P.vector_store_is_contained("library", ctx(), PUBLIC_URI)
+ is False
+ )
+
+
+def test_index_provider_lookup_failure_is_soft():
+ """An unavailable DB must not break classification: the settings-resolved
+ provider (FAISS today) remains the primary signal."""
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ side_effect=RuntimeError("db unavailable"),
+ ):
+ assert P._resolve_index_vector_store_providers("library", None) == set()
+ assert P.vector_store_is_contained("library", ctx(), {}) is True
+
+
+# ---------------------------------------------------------------------------
+# The filesystem-path discriminator
+# ---------------------------------------------------------------------------
+
+
+def test_local_filesystem_uri_recognition():
+ for value in ("./store.db", "/var/lib/store.db", "~/store.db"):
+ assert P._is_local_filesystem_uri(value) is True
+ assert P._is_local_filesystem_uri("C:\\data\\store.db") is True
+ assert P._is_local_filesystem_uri("file:///var/lib/store.db") is True
+
+
+def test_file_uri_with_remote_authority_is_not_a_local_file():
+ """A ``file://`` URI is local ONLY for the RFC 8089 local forms — an
+ empty authority (``file:///path``) or ``localhost``
+ (``file://localhost/path``). Any other authority is a remote-share
+ reference that some resolvers treat as a host (e.g.
+ ``file://attacker.example.com/share/store.db``); it must NOT be
+ classified as on-box, so it falls through to the DNS/remote path
+ instead of short-circuiting the containment check."""
+ assert P._is_local_filesystem_uri("file:///var/lib/x") is True
+ assert P._is_local_filesystem_uri("file://localhost/var/lib/x") is True
+ assert P._is_local_filesystem_uri("FILE://LOCALHOST/var/lib/x") is True
+ assert (
+ P._is_local_filesystem_uri("file://attacker.example.com/share/db")
+ is False
+ )
+ assert P._is_local_filesystem_uri("file://evil-host/share/db") is False
+
+
+def test_file_uri_with_remote_authority_endpoint_is_not_contained():
+ """End-to-end: a store whose ``uri_setting`` is a ``file://`` URI naming
+ a remote authority must be classified as REMOTE (not contained), not
+ silently treated as on-box just because it uses the ``file`` scheme."""
+ remote_file_uri = {URI_SETTING: "file://attacker.example.com/share/db"}
+ with _store(_RemoteStore):
+ assert (
+ P.vector_store_is_contained("library", ctx(), remote_file_uri)
+ is False
+ )
+
+ # The RFC 8089 local forms remain contained.
+ for local_uri in (
+ "file:///var/lib/store.db",
+ "file://localhost/var/lib/store.db",
+ ):
+ with _store(_RemoteStore):
+ assert (
+ P.vector_store_is_contained(
+ "library", ctx(), {URI_SETTING: local_uri}
+ )
+ is True
+ )
+
+
+def test_hostish_values_are_not_treated_as_paths():
+ """Anything that could be a host must go through the DNS classifier."""
+ for value in (
+ "store.db",
+ "example.com:19530",
+ "https://example.com",
+ "",
+ None,
+ b"/store.db",
+ ):
+ assert P._is_local_filesystem_uri(value) is False
+
+
+def test_unc_path_is_not_treated_as_a_local_file():
+ """A Windows UNC network path (``\\\\host\\share``) must NOT be mistaken for
+ a local file: it is not a recognised path prefix, so it falls through to the
+ DNS classifier and fails up rather than being silently classified on-box."""
+ assert P._is_local_filesystem_uri("\\\\server\\share\\store.db") is False
+
+
+def test_windows_forward_slash_drive_is_a_local_file():
+ """``C:/data/store.db`` (forward-slash drive path) is still a local file."""
+ assert P._is_local_filesystem_uri("C:/data/store.db") is True
+
+
+def test_file_uri_four_slash_unc_in_path_is_not_a_local_file():
+ """``file:////host/share`` (4+ slashes) parses with an EMPTY netloc —
+ ``urlsplit`` only ever gives the authority meaning to the first two
+ slashes after the scheme, so the 3rd/4th 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. This must
+ NOT be classified as on-box."""
+ assert (
+ P._is_local_filesystem_uri("file:////attacker.example.com/share/db")
+ is False
+ )
+ assert P._is_local_filesystem_uri("file:////host/share/db") is False
+
+
+def test_file_uri_windows_drive_authority_is_a_local_file():
+ """``file://C:/data/store.db`` — the Windows drive-letter form some
+ resolvers emit — parses with ``netloc == "C:"`` (a bare drive letter and
+ colon, not a real authority). This RFC 8089 local form must be
+ recognised as on-box, not misclassified as a remote host named "C"."""
+ assert P._is_local_filesystem_uri("file://C:/data/store.db") is True
+ assert P._is_local_filesystem_uri("FILE://c:/data/store.db") is True
+
+
+def test_file_uri_truth_table_full_regression():
+ """Full before/after truth table for ``_is_local_filesystem_uri``,
+ pinning the RFC 8089 local forms, the round-6 fixes (4-slash
+ UNC-in-path bypass rejected; Windows drive-letter authority accepted),
+ the round-7 mixed-slash UNC fix (``ntpath.normpath`` treats ANY pair of
+ leading "/"/"\\" separators as a UNC prefix on Windows, not just "//"),
+ and every previously-covered row unchanged."""
+ cases = [
+ # (uri, expected, label)
+ (
+ "file:////attacker.example.com/share/db",
+ False,
+ "4-slash UNC bypass",
+ ),
+ (
+ "/\\attacker.example.com/share/store.db",
+ False,
+ "mixed-slash UNC bypass (bare path)",
+ ),
+ (
+ "file:///\\attacker.example.com/share/store.db",
+ False,
+ "mixed-slash UNC bypass (file:// path)",
+ ),
+ (
+ "\\/attacker.example.com/share/store.db",
+ False,
+ "mixed-slash UNC bypass (backslash-first bare path)",
+ ),
+ ("file://C:/data/store.db", True, "windows drive-letter authority"),
+ ("file:///var/lib/store.db", True, "RFC8089 empty authority"),
+ (
+ "file://localhost/var/lib/store.db",
+ True,
+ "RFC8089 localhost authority",
+ ),
+ ("FILE://LOCALHOST/var/lib/x", True, "case-insensitive localhost"),
+ (
+ "file://attacker.example.com/share/db",
+ False,
+ "remote host authority",
+ ),
+ ("file://evil-host/share/db", False, "remote host authority 2"),
+ ("./store.db", True, "relative path"),
+ ("/var/lib/store.db", True, "absolute path"),
+ ("~/store.db", True, "home-relative"),
+ ("C:\\data\\store.db", True, "windows backslash drive path"),
+ ("C:/data/store.db", True, "windows forward-slash drive path"),
+ ("//attacker.example.com:19530", False, "scheme-less authority"),
+ ("//host/path", False, "scheme-less authority 2"),
+ ("\\\\server\\share\\store.db", False, "UNC path"),
+ ("http://example.com", False, "http url"),
+ ("https://example.com", False, "https url"),
+ ("", False, "empty string"),
+ (None, False, "None"),
+ (b"/store.db", False, "bytes"),
+ ]
+ for uri, expected, label in cases:
+ assert P._is_local_filesystem_uri(uri) is expected, (
+ f"{label}: expected {expected} for {uri!r}"
+ )
+
+
+def test_mixed_endpoint_list_with_a_public_entry_fails_up():
+ """Any public entry in a list-typed ``uri_setting`` wins (fail up): a store
+ reachable at both a local and a public endpoint is treated as remote."""
+ mixed = {URI_SETTING: ["http://127.0.0.1:19530", PUBLIC_URI[URI_SETTING]]}
+ with _store(_RemoteStore):
+ assert P.vector_store_is_contained("library", ctx(), mixed) is False
+
+
+def test_scheme_less_authority_is_not_treated_as_a_local_file():
+ """A ``//host[:port]`` URI authority (a scheme-less network endpoint, e.g.
+ how a Milvus/vector-store URI can be written) starts with a single ``/``
+ just like an absolute path, but it is NOT one: it names a remote host, not
+ a filesystem location. Misclassifying it as local would let a remote
+ endpoint skip the DNS/egress check entirely (``_vector_store_endpoint_is_local``
+ would short-circuit to True), so it must fall through to the DNS
+ classifier instead."""
+ for value in ("//attacker.example.com:19530", "//host/path"):
+ assert P._is_local_filesystem_uri(value) is False
+ # A real absolute path (single leading "/") is unaffected.
+ assert P._is_local_filesystem_uri("/var/lib/store.db") is True
+
+
+def test_scheme_less_authority_endpoint_is_not_contained():
+ """End-to-end: a store whose ``uri_setting`` is a scheme-less
+ ``//host:port`` authority (rejected as a local FILE path by the test
+ above) must still be correctly classified as REMOTE by the DNS
+ classifier it falls through to, not silently pass as undetermined.
+
+ ``_classify_engine_url`` used to reconstruct the URL to parse as
+ ``f"http://{entry}"`` whenever the entry lacked a literal ``"://"``.
+ For ``//attacker.example.com:19530`` that produced
+ ``http:////attacker.example.com:19530``, which ``urlsplit`` mis-parses
+ with an empty netloc and the host stuffed into ``path`` — so
+ ``hostname`` was ``None`` and the entry was skipped, leaving the store
+ undetermined instead of classified public. Uses a public IP LITERAL
+ (matching this file's convention) so the classifier answers from the
+ address itself and the test never touches DNS.
+ """
+ scheme_less_public = {URI_SETTING: "//93.184.216.34:19530"}
+ with _store(_RemoteStore):
+ assert (
+ P.vector_store_is_contained("library", ctx(), scheme_less_public)
+ is False
+ )
+ # "library" is always classified via _resolve_collection_is_public
+ # (patched to False by ``_store``), so the fail-up preserves that
+ # private flag rather than overwriting it with True.
+ assert P.classify_engine(
+ "library", ctx(), settings_snapshot=scheme_less_public
+ ) == P.EngineClassification(is_public=False, is_local=False)
+
+ # The local counterpart (loopback, still scheme-less) stays contained.
+ scheme_less_local = {URI_SETTING: "//127.0.0.1:19530"}
+ with _store(_RemoteStore):
+ assert (
+ P.vector_store_is_contained("library", ctx(), scheme_less_local)
+ is True
+ )
+
+
+# ---------------------------------------------------------------------------
+# Regression: fail-up must not RELAX a private collection into PUBLIC_ONLY
+# eligibility, and ADAPTIVE must not flip a private-collection-primary run
+# to PUBLIC_ONLY just because the collection's store isn't contained.
+#
+# This is dormant on today's default install (only FAISS — a local-file
+# store — is registered), but becomes live the moment a server-backed
+# vector store is registered. Pure-function coverage; no app/DB import.
+# ---------------------------------------------------------------------------
+
+
+def test_public_only_denies_a_private_remote_collection():
+ """A private collection with a non-contained store must NOT become
+ newly eligible under PUBLIC_ONLY. Before the fix, the fail-up
+ unconditionally set ``is_public=True``, which made this a false PASS."""
+ with _store(_RemoteStore):
+ decision = P.evaluate_engine(
+ "collection_x", ctx("public_only"), settings_snapshot=PUBLIC_URI
+ )
+ assert decision.allowed is False
+
+
+def test_adaptive_scope_does_not_flip_private_collection_primary_to_public():
+ """``_resolve_adaptive_scope`` must not resolve a private-collection-
+ primary run to PUBLIC_ONLY (which would admit public web engines
+ alongside the private corpus) merely because the collection's vector
+ store isn't contained.
+
+ ROUND-6 FIX: this used to assert a fall-back to the permissive BOTH
+ bucket, on the theory that ``evaluate_engine`` denying the collection
+ itself (see ``test_public_only_denies_a_private_remote_collection`` /
+ ``test_unrestricted_scope_denies_a_private_remote_store`` above) was
+ enough. It is NOT enough: BOTH also admits every OTHER public engine
+ and lifts the forced-local-LLM/embeddings coupling for the rest of the
+ run, silently widening egress for the run as a whole. A private
+ non-contained collection buckets (is_public=False, is_local=False) —
+ neither exclusive branch in ``_resolve_adaptive_scope`` matches that —
+ so it must now resolve to the RESTRICTIVE PRIVATE_ONLY instead (which
+ still denies the collection engine itself as "unclassified", exactly as
+ before, while ALSO keeping every other engine/inference path local)."""
+ with _store(_RemoteStore):
+ resolved = P._resolve_adaptive_scope(
+ "collection_x",
+ PUBLIC_URI,
+ username=None,
+ local_hostnames=(),
+ )
+ assert resolved != P.EgressScope.PUBLIC_ONLY
+ assert resolved != P.EgressScope.BOTH
+ assert resolved == P.EgressScope.PRIVATE_ONLY