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.

feat(security): two-axis egress classification core (ADR-0007) (#4882)

LearningCircuitb922c413dfb2
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index a5800982e9..e89e2d0a78 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -325,6 +325,13 @@ repos:
files: ^src/local_deep_research/defaults/.*\.json$
pass_filenames: false
description: "Ensure golden master settings are updated when defaults change"
+ - id: check-adr-numbers
+ name: Check ADR numbering
+ entry: .pre-commit-hooks/check-adr-numbers.py
+ language: script
+ files: ^docs/decisions/.*\.md$
+ pass_filenames: false
+ description: "Ensure docs/decisions ADR numbers are unique (no two files share a NNNN prefix)"
- id: check-readme-links
name: Check README links and examples
entry: .pre-commit-hooks/check-readme-links.py
diff --git a/.pre-commit-hooks/check-adr-numbers.py b/.pre-commit-hooks/check-adr-numbers.py
new file mode 100755
index 0000000000..d4a3738815
--- /dev/null
+++ b/.pre-commit-hooks/check-adr-numbers.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python3
+"""Guard ADR numbering under docs/decisions/.
+
+Fails when two ADRs share a ``NNNN`` prefix — the exact accident of two
+``0006-*`` records landing from separate PRs cut off main at different times.
+Runs in CI via pre-commit, so a duplicate number can't merge silently.
+
+The scan is deliberately loose about *what* counts as an ADR file: it matches
+any file whose name starts with four digits and a separator (``-`` or ``_``),
+in any subdirectory and with any extension. A number collision must be caught
+even if a file is named slightly off-convention (uppercase slug, ``.rst``) or
+tucked into an archive subfolder — a strict ``NNNN-slug.md`` match would let
+those slip past and give false confidence.
+"""
+
+import re
+import sys
+from pathlib import Path
+
+ADR_FILE_RE = re.compile(r"^(\d{4})[-_]")
+
+
+def main() -> int:
+ decisions_dir = Path(__file__).parent.parent / "docs" / "decisions"
+ if not decisions_dir.is_dir():
+ return 0
+
+ seen: dict[str, str] = {}
+ errors: list[str] = []
+ for path in sorted(decisions_dir.rglob("*")):
+ if not path.is_file():
+ continue
+ match = ADR_FILE_RE.match(path.name)
+ if not match:
+ continue
+ number = match.group(1)
+ rel = str(path.relative_to(decisions_dir))
+ if number in seen:
+ errors.append(
+ f"Duplicate ADR number {number}: {rel} collides with "
+ f"{seen[number]}. Renumber one of them."
+ )
+ else:
+ seen[number] = rel
+
+ if errors:
+ print("ADR numbering check failed:\n")
+ for err in errors:
+ print(f" - {err}")
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/SECURITY.md b/SECURITY.md
index 7c24a1ba5e..35ab523fc4 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -214,7 +214,7 @@ Operators needing a hard boundary **must** layer OS-level controls: network name
#### Caveats
- **DNS rebinding TOCTOU**: `_classify_host` resolves once at evaluation time; the actual HTTP request resolves again at connect time. Closing this race would require pinning the resolved IP into the outbound connection, which is HTTPS-only and doesn't follow redirects cleanly. See the "Notification Webhook SSRF" subsection for the accepted-risk rationale (the same caveat applies here).
-- **Settings tampering**: an adversary with write access to a user's per-user settings DB can flip `policy.egress_scope` to `both` and disable all enforcement. Per-user SQLCipher databases mean one user can't trivially tamper with another's policy, but an attacker who can read/write a user's DB can change anything about that user's runtime. Policy-key changes emit `policy_audit=True` log lines so admins can audit changes after the fact.
+- **Settings tampering**: an adversary with write access to a user's per-user settings DB can flip `policy.egress_scope` to the `unprotected` escape hatch and disable enforcement (the retired `both` value no longer does this — it is coerced to the protective `adaptive` scope). Per-user SQLCipher databases mean one user can't trivially tamper with another's policy, but an attacker who can read/write a user's DB can change anything about that user's runtime. Policy-key changes emit `policy_audit=True` log lines so admins can audit changes after the fact.
- **Audit log routing**: `policy_audit=True` log lines are filtered from the WebSocket sink (`frontend_progress_sink`), so they never reach a CORS-permissive browser observer. They are written to the loguru file/console sinks and persisted to the encrypted research-log DB if a research is active.
- **LLM/embeddings endpoint locality is best-effort**: the "stays local" guarantee is *strong* for named cloud providers (OpenAI, Anthropic, Google, OpenRouter, etc.) and localhost-default providers (Ollama/LM Studio/llama.cpp) — those are classified by name and reliably blocked/allowed. It is *weaker* for configurable-URL providers (`openai_endpoint`): the endpoint is classified by resolving its host, so an OpenAI-compatible endpoint pointed at a private-looking IP (split-horizon DNS, a tunnel, a proxy) is **trusted as local**. A user who wants to process private-collection data with a cloud LLM is expected to mark the collection **public** (the explicit opt-in); the policy prevents *accidental/silent* egress, not a determined user who deliberately points "local" inference at a cloud endpoint. This is consistent with the guardrail-not-boundary model above.
diff --git a/changelog.d/+egress-trusted-destinations.feature.md b/changelog.d/+egress-trusted-destinations.feature.md
new file mode 100644
index 0000000000..2251c76157
--- /dev/null
+++ b/changelog.d/+egress-trusted-destinations.feature.md
@@ -0,0 +1 @@
+Add per-destination trust to the egress model (ADR-0007): `policy.trusted_inference_providers` and `policy.trusted_search_engines` let you mark specific off-machine LLM/embeddings providers or search engines as trusted, so the two-axis classification treats them as *contained* (e.g. a zero-retention enterprise Anthropic endpoint, or a self-hosted Elasticsearch/Paperless on a public hostname). A banner surfaces active trust entries.
diff --git a/changelog.d/+egress-two-axis-classification.security.md b/changelog.d/+egress-two-axis-classification.security.md
new file mode 100644
index 0000000000..e741dcebb1
--- /dev/null
+++ b/changelog.d/+egress-two-axis-classification.security.md
@@ -0,0 +1 @@
+The egress guardrail now enforces a two-axis (data-sensitivity × destination-exposure) admissibility rule at the start of a research run (ADR-0007): the run is refused when a sensitive source (a private collection/library/store) would reach an exposing sink (a public search engine or a cloud LLM/embeddings provider), in addition to the existing scope checks. Override by setting Egress Scope to **Unprotected**, marking the collection public, or trusting the destination.
diff --git a/changelog.d/+egress-unprotected-escape-hatch.feature.md b/changelog.d/+egress-unprotected-escape-hatch.feature.md
new file mode 100644
index 0000000000..d2746ea7a2
--- /dev/null
+++ b/changelog.d/+egress-unprotected-escape-hatch.feature.md
@@ -0,0 +1 @@
+Add an **Unprotected** egress scope — an explicit opt-out that disables the egress-scope restrictions for a run (the hard SSRF and cloud-metadata blocks still apply), surfaced with a light-red panel and a non-dismissible "protection disabled" banner. The rarely-used **Both** scope is retired: it is removed from the selector, and existing saved `both` values are migrated to **Adaptive** (a residual value is also coerced to Adaptive at read time). If you relied on `both` to run a private collection with a cloud model, mark that collection **public** or choose **Unprotected**.
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index d6818e63dc..24061e740a 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -193,7 +193,9 @@ They are not available in the Web UI because they are needed to start the applic
| `notifications.rate_limit_per_day` | `LDR_NOTIFICATIONS_RATE_LIMIT_PER_DAY` | `50` | Maximum number of notifications per day per user. Daily cap prevents notification fatigue. Default of 50 balances staying informed with avoiding excessive alerts. | APP |
| `notifications.rate_limit_per_hour` | `LDR_NOTIFICATIONS_RATE_LIMIT_PER_HOUR` | `10` | Maximum number of notifications per hour per user. Prevents notification spam during burst activity. Default of 10 allows important notifications through while limiting noise. | APP |
| `notifications.service_url` | `LDR_NOTIFICATIONS_SERVICE_URL` | `` | Notification service URL(s). Supports multiple comma-separated URLs to send notifications to multiple destinations (e.g., discord://YOUR_WEBHOOK_ID/YOUR_TOKEN, mailto://YOUR_USER:[email protected][email protected]). See <a href="https://github.com/LearningCircuit/local-deep-research/blob/main/docs/NOTIFICATIONS.md" target="_blank">documentation</a> for supported services. | APP |
-| `policy.egress_scope` | `LDR_POLICY_EGRESS_SCOPE` | `adaptive` | EXPERIMENTAL — this egress boundary is new defense-in-depth, not an absolute guarantee yet; don't rely on it as your only protection for highly sensitive data. Restrict which search engines a research run may use. ADAPTIVE (default) = follow your primary engine: a private primary keeps everything local, a public primary allows public engines. STRICT = only the primary engine you picked; PUBLIC_ONLY = any public web/academic engine; PRIVATE_ONLY = any local engine (library, paperless, etc.); BOTH = any classified engine. | SEARCH |
+| `policy.egress_scope` | `LDR_POLICY_EGRESS_SCOPE` | `adaptive` | EXPERIMENTAL — this egress boundary is new defense-in-depth, not an absolute guarantee yet; don't rely on it as your only protection for highly sensitive data. Restrict which search engines a research run may use. ADAPTIVE (default) = follow your primary engine: a private primary keeps everything local, a public primary allows public engines. STRICT = only the primary engine you picked; PUBLIC_ONLY = any public web/academic engine; PRIVATE_ONLY = any local engine (library, paperless, etc.); UNPROTECTED = escape hatch that disables egress protection entirely (not recommended; hard SSRF/cloud-metadata blocking still applies). | SEARCH |
+| `policy.trusted_inference_providers` | `LDR_POLICY_TRUSTED_INFERENCE_PROVIDERS` | ``[]`` | EXPERIMENTAL. LLM/embeddings providers you explicitly trust to receive sensitive content — listing one treats it as a 'contained' inference sink even though it is off-machine (e.g. a zero-retention enterprise Anthropic endpoint). Relaxes the two-axis egress classification; use only for providers you have vetted. | LLM |
+| `policy.trusted_search_engines` | `LDR_POLICY_TRUSTED_SEARCH_ENGINES` | ``[]`` | EXPERIMENTAL. Search engines whose endpoint you explicitly trust — listing one (e.g. a self-hosted Elasticsearch/Paperless on a public hostname) treats it as 'contained' rather than an exposing sink. Relaxes the two-axis egress classification; use only for endpoints you control. | SEARCH |
| `rag.indexing_batch_size` | `LDR_RAG_INDEXING_BATCH_SIZE` | `15` | Number of documents to process in parallel during RAG indexing. Higher values are faster but use more memory. | APP |
| `rate_limiting.decay_per_day` | `LDR_RATE_LIMITING_DECAY_PER_DAY` | `0.95` | How much to trust old rate limit data as it ages (0.5-0.99). At 0.95, data retains 95% reliability per day. Lower values discard old data faster, forcing the system to re-learn optimal wait times. | APP |
| `rate_limiting.enabled` | `LDR_RATE_LIMITING_ENABLED` | `true` | Enable adaptive rate limiting that learns optimal wait times for each search engine to avoid hitting API rate limits. When disabled, requests are sent with minimal delay (0.1s), which may trigger rate limit errors from some APIs. | APP |
diff --git a/docs/decisions/0007-egress-two-axis-data-classification.md b/docs/decisions/0007-egress-two-axis-data-classification.md
new file mode 100644
index 0000000000..e33e35c0b6
--- /dev/null
+++ b/docs/decisions/0007-egress-two-axis-data-classification.md
@@ -0,0 +1,302 @@
+# ADR-0007: Restructure egress around a two-axis data-classification model
+
+**Date:** 2026-06-28
+**Status:** Accepted (incremental rollout)
+
+## The model at a glance
+
+Every model a run touches (search engine, collection / store, LLM, embeddings)
+is labelled on two **orthogonal** axes — **Sensitivity** (of the data it
+*sources*) and **Exposure** (of the *sink* it is). The matrix reads: *a
+component with this Sensitivity (row) and this Exposure (column) is treated as
+follows.*
+
+| | **Contained** sink | **Exposing** sink |
+|---|---|---|
+| **Non-sensitive** source | Combines with **anything** — *public collection, local Ollama* | Only alongside **non-sensitive** sources — *public web engine, cloud LLM* |
+| **Sensitive** source | Only with other **contained** sources; never an exposing sink — *private collection + local LLM* | **By itself only**, with contained (local) inference — *remote monitored store of private data* |
+
+**The rule in one line:** a run may never let a *sensitive* source reach an
+*exposing* sink — unless it is explicitly switched to **Permissive** mode (which
+warns but never blocks). The rest of this document explains why this is the
+right model, how each component is classified, and how we roll it out.
+
+## Out of scope: the query text itself
+
+This model classifies **sources** and **sinks** — not the **question the user
+types**. A run's query is sent verbatim to whichever search sinks the run uses,
+so a sensitive question typed against an exposing engine leaves the machine
+*regardless* of how the sources are labelled. The guardrail cannot inspect or
+sanitise query intent; that stays the **user's responsibility**. The UI must say
+so plainly — *we can't protect the content of your questions, so choose sources
+appropriate to how sensitive your question is.*
+
+## Context
+
+The egress guardrail (`src/local_deep_research/security/egress/`, see its
+`README.md`) currently expresses policy on a **single axis**: a per-run
+`policy.egress_scope` enum (`adaptive` / `both` / `public_only` /
+`private_only` / `strict`), refined by a per-collection `is_public` flag and
+two `require_local` inference toggles.
+
+This works for the common cases, but it collapses two genuinely independent
+properties into one word, and that conflation is now blocking us.
+
+### Problem 1 — sensitivity and exposure are different things, fused into one word
+
+"public ↔ private" is treated as a single spectrum. Two distinct questions hide
+inside it:
+
+- **Is the *data* sensitive?** — a property of a **source** (a collection, a
+ document store).
+- **Does the *destination* expose data outward?** — a property of a **sink** (a
+ web search engine you send a query to; a cloud LLM you send chunks to).
+
+A collection marked `is_public` is the clearest symptom. The word implies the
+data is *published*, but a collection is **always a local store** — searching it
+never pushes its contents to a search engine. What `is_public` actually
+authorizes is *cloud inference* on that data. "Public" overstates the exposure
+axis to describe the sensitivity axis.
+
+### Problem 2 — dual-risk sources can't be expressed
+
+Elasticsearch and Paperless break the single axis outright. An Elasticsearch
+instance can be:
+
+- a **sensitive data store** (your private corpus) → must not be combined with
+ exposing sinks, **and/or**
+- a **monitored / external service** (a sink that itself exposes the queries you
+ send it).
+
+These are opposite risks, and a single `is_local` / `is_public` flag can only
+pick one. Today the only safety for them is the asymmetric URL fail-up. We
+genuinely "cannot guarantee anything" for these engines under the current model,
+so for now they should not be auto-combined with other sources.
+
+### Problem 3 — `both` is a silent blanket
+
+`both` overrides every per-source classification at once, with no visual or
+conceptual signal that protection has been dropped. It is the muddy middle
+between "classify each source" and "turn the policy off."
+
+### This is a known model
+
+The two-axis framing is the standard **Data Loss Prevention (DLP) /
+information-flow-control** model: classify data by **sensitivity**, classify
+destinations by **trust / exposure**, forbid sensitive→exposing flows. The
+enforcement-mode vocabulary is **SELinux's** (`enforcing` / `permissive` /
+`disabled`). The egress package already borrows XACML / zero-trust PDP–PEP
+vocabulary, so this is a continuation, not a foreign import.
+
+## Decision
+
+Re-base the egress model on **two orthogonal labels**:
+
+| Axis | Applies to | Values | Question |
+|---|---|---|---|
+| **Sensitivity** | sources | `sensitive` / `non-sensitive` | Must this data never leave the machine? |
+| **Exposure** | sinks | `exposing` / `contained` | Does sending data here put it off-machine? |
+
+Some components play **both roles** — a search engine is a *sink* for your query
+and a *source* of results; Elasticsearch is a *source* of data and a *sink* for
+your query. Each gets a label on every axis it participates in. This is exactly
+what the single-axis model cannot represent and is the crux of the change.
+
+**Core invariant:** *sensitive* data must not flow to an *exposing* sink —
+unless the run is explicitly switched to the escape-hatch mode.
+
+### Every model carries both labels — classification is per-component
+
+The classification is computed **per component**, and "component" means *every*
+model the run touches: each search engine, each collection / store, the LLM, and
+the embeddings model. A single function —
+`classify(component, settings) -> (Sensitivity, Exposure)` — becomes the one
+home for logic scattered today across `_engine_bucket`, the
+`_CLOUD_LLM_PROVIDERS` set, the per-collection `is_public` lookup, and the URL
+fail-up.
+
+| Component (example) | Sensitivity | Exposure |
+|---|---|---|
+| Public collection / public web results | non-sensitive | contained |
+| Private collection (default) | **sensitive** | contained |
+| Public web / academic engine (Google, arXiv) | non-sensitive | **exposing** (query egress) |
+| Cloud LLM / embeddings (Anthropic, OpenAI) | non-sensitive | **exposing** |
+| Local LLM / embeddings (Ollama, sentence-transformers) | non-sensitive | contained |
+| Paperless / Elasticsearch — local, private | **sensitive** | contained |
+| Elasticsearch — remote / monitored, private | **sensitive** | **exposing** |
+
+### The four quadrants — the combination rule
+
+A run touches a *set* of components. Whether the set is permitted follows
+directly from the two labels:
+
+| # | A component that is… | may be combined with | Example |
+|---|---|---|---|
+| 1 | non-sensitive, contained | **anything** | public collection; local Ollama |
+| 2 | **sensitive**, contained | other **contained** sources only (sensitive or not) — **no exposing sink** | private collection + local LLM |
+| 3 | non-sensitive, **exposing** | **non-sensitive** sources only | cloud LLM; public web engine |
+| 4 | **sensitive + exposing** | the **only sensitive source** (non-sensitive contained companions are fine), with **contained (local) inference** | remote monitored store holding private data |
+
+Underlying invariant: **a run may not let a sensitive source reach an exposing
+sink.** Because an agentic run can turn one engine's results into another
+engine's query (the LangGraph silent-expansion class already in our threat
+model), this is enforced over the whole run's component set, not per call.
+Equivalent phrasing: a run must be **either** all-non-sensitive **or** free of
+exposing sinks — with a lone quadrant-4 component allowed to run as the **only
+sensitive source** (non-sensitive contained companions are still fine), since
+returning its own data to itself is not a *new* leak and its inference is forced
+contained.
+
+The escape hatch (**Permissive / "Unprotected"**) means "suspend this invariant
+for this run, keep warning."
+
+### Enforcement modes (SELinux naming)
+
+- **Enforcing** — current behaviour: the invariant is enforced; violating
+ engines/sinks are blocked.
+- **Permissive ("Unprotected")** — the escape hatch: the policy is still
+ *evaluated* so the warning banners fire, but nothing is blocked. Replaces
+ `both`, with an honest, loud, light-red UI. (User-facing label is an open
+ question — "Unprotected" / "Unrestricted" / "Permissive".)
+
+### Mapping the current model onto the two axes (migration, not rewrite)
+
+- collection `is_public=False` → Sensitivity **sensitive**; `is_public=True` →
+ **non-sensitive** (relabel away from "public" — it never *publishes*).
+- public web / academic engines → Exposure **exposing**.
+- cloud LLM / cloud embeddings → Exposure **exposing** sinks;
+ `require_local_*` = "forbid exposing inference sinks."
+- local collections / local LLM (Ollama) → Exposure **contained**.
+- scopes re-expressed: `private_only` ≈ "no exposing sinks"; `public_only` ≈
+ "exposing sinks allowed, sensitive sources excluded"; `strict` ≈ single
+ source; `adaptive` ≈ infer the run's posture from the primary.
+- `both` → removed, superseded by per-source classification + Permissive mode.
+- Elasticsearch / Paperless → declared **sensitive + contained** by default
+ (usable with other contained / local sources — quadrant 2), with the URL
+ fail-up flipping exposure to **exposing** (quadrant 4) when the configured
+ endpoint resolves to a public host. A per-destination trust entry
+ (`policy.trusted_search_engines`) can re-contain a self-hosted instance that
+ happens to sit on a public hostname.
+
+### Per-destination trust (the "I trust Anthropic" case)
+
+A user-managed override that re-labels a specific sink **contained** (e.g. a
+zero-retention Anthropic endpoint, a self-hosted Paperless on a public
+hostname). This is the Exposure-axis counterpart of promoting a collection on
+the Sensitivity axis. Out of scope for the first steps; recorded here as its
+principled home.
+
+## Consequences
+
+**Positive**
+- One coherent model that matches industry DLP / IFC vocabulary.
+- Dual-risk sources (Elasticsearch / Paperless) become expressible.
+- Honest labels: promoting a collection is clearly about *inference
+ authorization*, not *publication*.
+- The escape hatch is explicit and visible, not a silent scope.
+
+**Negative / risks**
+- The egress guardrail is security-critical and has already been through two
+ adversarial review rounds. A big-bang rewrite is high blast radius.
+- Every engine / source / sink needs labels on both axes; some are genuinely
+ ambiguous.
+
+**Therefore: rewrite incrementally, core-first, behind a test net.** The model
+is the chosen direction, but the guardrail is security-critical and has already
+survived two adversarial review rounds — so it lands in stages that each keep
+the egress test suite green:
+
+A. **Classification core** (`security/egress/classification.py`): the
+ `Sensitivity` / `Exposure` types, `classify(component, settings)`, and
+ `evaluate_run(components)` implementing the four-quadrant rule — pure, fully
+ unit-tested against the truth table above, **not yet wired in** (zero
+ behaviour change).
+B. **Wire the PEPs** to the core; re-express the existing scopes in its terms;
+ keep behaviour parity (existing egress tests stay green) while the new
+ capabilities (quadrant 4, dual-risk sources) become reachable.
+C. **UI**: surface the two axes, add **Permissive / "Unprotected"** mode, remove
+ `both`, make collection labels honest.
+D. **Per-destination trust** (the Exposure override — the "trust Anthropic"
+ case) and explicit classification for Elasticsearch / Paperless.
+
+**Status (PR #4882).** All four stages are implemented.
+
+- **A / B** — classification core (`classification.py`) + resolver
+ (`run_classification.py`) + explicit per-element labels on every engine and
+ provider.
+- **C** — the `UNPROTECTED` escape hatch (with the SSRF / cloud-metadata
+ invariant preserved *after* the hatch gate), `both` **fully retired** — removed
+ from the selector, existing rows migrated to `adaptive` by migration 0019, and
+ any residual value (env var / queued snapshot / un-migrated DB) coerced to
+ `adaptive` at read time; `EgressScope.BOTH` survives only as the internal
+ resolution result for an unclassifiable ADAPTIVE primary — a
+ non-dismissible "protection disabled" banner, and the **enforcement flip**:
+ the run-start precheck rejects a two-axis denial as defense-in-depth over the
+ scope PEPs (`UNPROTECTED` evaluates permissive; an uncomputable decision
+ **fails closed** — a denying `audit_error` — not open). This runs at the web
+ `/api/start_research` precheck **and** at the shared worker chokepoint in
+ `run_research_process`, so follow-up / chat / queue runs are covered too; only
+ CLI / programmatic callers that bypass both get the scope PEPs alone (which
+ still force local inference under `private_only` / adaptive-private). The
+ precheck classifies the **primary** engine plus the inference providers;
+ widening to the full resolved engine set is a follow-up (see residuals).
+- **D** — per-destination trust (`policy.trusted_inference_providers` /
+ `policy.trusted_search_engines`) relaxing a trusted off-machine sink to
+ contained, a trust banner, and honest collection-label copy.
+
+**Before it enforces in a shipped release it must pass a fresh adversarial
+review** — the enforcement flip is a behaviour change to a security boundary.
+
+### Known residuals (tracked in issue #4951)
+
+Four rounds of adversarial review established that the run-start audit is
+best-effort defense-in-depth, not a completeness guarantee: it re-derives each
+sink's classification from settings and can diverge from what the run actually
+connects to. The **default `adaptive` config is protected by the scope PEPs**
+(a private primary forces local inference), and retiring `both` removes the
+scope where the audit was the sole guard. These edges remain and are tracked as
+issues rather than blockers:
+
+- **Search axis — Elasticsearch `cloud_id`.** The exposure fail-up inspects
+ `hosts`, not `cloud_id`; a sensitive ES store reachable via `cloud_id` on a
+ permissive scope is classified contained. The engine's own
+ `_cloud_id_forbidden_by_scope` covers `private_only` / `strict`.
+- **Full engine set / agentic expansion.** Enforcement (audit and the scope
+ PEPs' local-inference coupling) keys on the run's *primary* engine; a
+ non-primary sensitive engine pulled in mid-run by expansion is not reflected
+ back into `require_local`.
+- **Dual-risk store on a public host.** A self-hosted store whose URL resolves
+ public classifies PUBLIC_ONLY, so the scope-level local-inference coupling
+ does not fire (the run-start audit still flags it on web paths).
+- **Name-keyed trust drift.** `trusted_inference_providers` is keyed by provider
+ name, not the vetted endpoint URL, and is honored only in the audit, not the
+ boundary PEP.
+- **`LibraryRAGService` direct construction** resolves its primary from the
+ global `search.tool`, so a direct (non-factory) construction can miss the
+ local-embeddings coupling.
+- **Query text** is out of scope by design (see above).
+
+## Open questions — resolution
+
+1. **Deferred.** User-facing axis vocabulary. Internally settled as
+ `Sensitivity{sensitive, non_sensitive}` / `Exposure{contained, exposing}`.
+ The two axes are *not* surfaced as independent UI controls yet — they are
+ expressed through the existing egress-scope selector, the per-collection
+ public flag, and the trust lists. A dedicated two-axis UI is a follow-up.
+2. **Resolved — Unprotected.** Setting value / label / `EgressScope.UNPROTECTED`
+ (the internal enforcement *mode* is separately `Mode.PERMISSIVE`).
+3. **Resolved.** Elasticsearch / Paperless default to **sensitive + contained**;
+ the URL fail-up flips exposure to exposing (quadrant 4) on a public endpoint;
+ `policy.trusted_search_engines` is the explicit override.
+4. **Resolved — no.** The aggregate `library` is always sensitive
+ (`_resolve_collection_is_public` hard-returns private for it).
+5. **Resolved — settings lists.** `policy.trusted_inference_providers` /
+ `policy.trusted_search_engines` (JSON-list settings, mirroring
+ `allowed_local_hostnames`); no dedicated table.
+
+## References
+
+- Egress package: `src/local_deep_research/security/egress/README.md`
+- SELinux modes — enforcing / permissive / disabled
+- DLP: data-classification (sensitivity labels) + destination-trust / egress
+ controls (information-flow control)
diff --git a/docs/egress-modes.md b/docs/egress-modes.md
index 0e7da1a44d..f5129ecdfe 100644
--- a/docs/egress-modes.md
+++ b/docs/egress-modes.md
@@ -25,7 +25,7 @@ search engine, so most people never need to think about it.
| Mode | Search engines | LLM / embeddings | Best for |
|---|---|---|---|
| **Adaptive** *(default)* | follows your primary engine | forced local **only** when the run is private | "just do the sensible thing" |
-| **Both** | any classified engine (public + local) | your configured providers (cloud allowed) | mixing public web + your collections |
+| **Unprotected** | any engine (no restriction) | any provider (cloud allowed) | escape hatch — **not recommended**; disables egress protection (hard SSRF / cloud-metadata blocking still applies) |
| **Public only** | public web/academic engines only | your configured providers | public research; your local collections aren't touched |
| **Private only** | local engines only (collections, local SearXNG/Ollama) | **forced local** — cloud blocked | sensitive work that must stay on the machine |
| **Strict** | **only** your one primary engine | your configured providers | a single, exact source with zero expansion |
@@ -46,16 +46,27 @@ Why it's the default: you choose a search engine anyway, and the privacy
posture "just matches" it. If you make a **private collection** your primary,
the whole run automatically stays local — nothing leaves the box.
-> **Note:** to *mix* a private collection with public engines, or to use a
-> cloud LLM on a private collection, switch to **Both** (or mark the collection
-> public — see below). Adaptive deliberately narrows to match the primary.
-
-## <a id="both"></a>🌐 Both
-
-Any **classified** engine may run — public web/academic engines **and** your
-local collections/library. Your configured LLM and embeddings are used as-is
-(cloud allowed unless you tick the *Require local* toggles). This is the
-pre-policy behaviour: maximum reach, minimum restriction.
+> **Note:** to use a cloud LLM on a private collection, mark the collection
+> **public** (see below) or add the provider to *trusted inference providers*;
+> to drop all restrictions for one run, use **Unprotected**. Adaptive
+> deliberately narrows to match the primary.
+
+## <a id="unprotected"></a>🔓 Unprotected
+
+**Not recommended — an escape hatch.** Egress-scope restrictions are disabled
+for the run: any engine, URL, and LLM/embeddings provider is permitted. The
+hard SSRF and cloud-metadata blocks still apply. A loud, non-dismissible banner
+shows while it is active. Prefer marking a collection **public**, or adding a
+**trusted destination** (`policy.trusted_inference_providers` /
+`policy.trusted_search_engines`) for the specific case, over disabling
+protection wholesale.
+
+> The older **Both** scope (blanket-permit any classified engine) has been
+> **retired**: existing saved `both` configurations are migrated to **Adaptive**
+> (which follows your primary engine and forces local inference for a private
+> primary). If you relied on `both` to use a private collection with a cloud
+> model, mark that collection **public**, or choose **Unprotected** to opt out
+> of protection explicitly.
## <a id="public_only"></a>☁️ Public only
diff --git a/src/local_deep_research/database/migrations/versions/0019_retire_both_egress_scope.py b/src/local_deep_research/database/migrations/versions/0019_retire_both_egress_scope.py
new file mode 100644
index 0000000000..03bde54e1b
--- /dev/null
+++ b/src/local_deep_research/database/migrations/versions/0019_retire_both_egress_scope.py
@@ -0,0 +1,77 @@
+"""Retire the deprecated ``both`` egress scope, migrating users to ``adaptive``.
+
+Background
+==========
+``policy.egress_scope=both`` was the "muddy middle" (ADR-0007, Problem 3): it
+blanket-permitted any classified engine with no per-source protection and no
+signal that protection had been dropped. It is redundant — the protective
+default ``adaptive`` follows the primary engine, and a private collection that
+should be usable with cloud inference is marked *public* per-collection. `both`
+was already removed from the settings selector; this migration finishes the job
+by rewriting existing stored values to ``adaptive`` so those users become
+protected by adaptive's private-primary → local-inference coupling.
+
+``adaptive`` is chosen over ``unprotected`` deliberately: it makes those users
+*safer* (a private primary now forces local inference), and anyone who wants the
+old permissive behaviour can consciously pick ``unprotected``. The egress layer
+also coerces any residual ``both`` (env var, queued snapshot, un-migrated DB) to
+``adaptive`` at read time, so this migration is the storage cleanup, not the sole
+enforcement.
+
+Storage note: the ``settings.value`` column is SQLAlchemy ``JSON`` (strings are
+stored quoted), so the WHERE clause matches the JSON-encoded form (``'"both"'``).
+The ``sa.table`` below is declared **untyped** on purpose — an untyped column
+reads/writes the raw stored value verbatim, whereas attaching ``sa.JSON`` would
+re-encode the bound value and corrupt it. Same pattern as migrations 0013/0018.
+
+Revision ID: 0019
+Revises: 0018
+Create Date: 2026-07-04
+"""
+
+from __future__ import annotations
+
+import json
+
+import sqlalchemy as sa
+from alembic import op
+from loguru import logger
+from sqlalchemy import inspect
+
+revision = "0019"
+down_revision = "0018"
+branch_labels = None
+depends_on = None
+
+EGRESS_SCOPE_KEY = "policy.egress_scope"
+DEPRECATED_SCOPE_JSON = json.dumps("both")
+REPLACEMENT_SCOPE_JSON = json.dumps("adaptive")
+
+# Untyped table definition — raw stored values, no JSON re-encoding.
+_settings = sa.table("settings", sa.column("key"), sa.column("value"))
+
+
+def upgrade() -> None:
+ conn = op.get_bind()
+ if not inspect(conn).has_table("settings"):
+ return
+ result = conn.execute(
+ sa.update(_settings)
+ .where(_settings.c.key == EGRESS_SCOPE_KEY)
+ .where(_settings.c.value == DEPRECATED_SCOPE_JSON)
+ .values(value=REPLACEMENT_SCOPE_JSON)
+ )
+ if result.rowcount:
+ logger.info(
+ "Migrated {} egress-scope setting row(s) from the retired 'both' "
+ "scope to 'adaptive'.",
+ result.rowcount,
+ )
+
+
+def downgrade() -> None:
+ """No-op.
+
+ ``both`` is retired from the selector and coerced to ``adaptive`` at read
+ time, so restoring it would only recreate the deprecated state.
+ """
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index 31e57cf481..27ee3819fb 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -5016,7 +5016,7 @@
},
"policy.egress_scope": {
"category": "policy",
- "description": "EXPERIMENTAL — this egress boundary is new defense-in-depth, not an absolute guarantee yet; don't rely on it as your only protection for highly sensitive data. Restrict which search engines a research run may use. ADAPTIVE (default) = follow your primary engine: a private primary keeps everything local, a public primary allows public engines. STRICT = only the primary engine you picked; PUBLIC_ONLY = any public web/academic engine; PRIVATE_ONLY = any local engine (library, paperless, etc.); BOTH = any classified engine.",
+ "description": "EXPERIMENTAL — this egress boundary is new defense-in-depth, not an absolute guarantee yet; don't rely on it as your only protection for highly sensitive data. Restrict which search engines a research run may use. ADAPTIVE (default) = follow your primary engine: a private primary keeps everything local, a public primary allows public engines. STRICT = only the primary engine you picked; PUBLIC_ONLY = any public web/academic engine; PRIVATE_ONLY = any local engine (library, paperless, etc.); UNPROTECTED = escape hatch that disables egress protection entirely (not recommended; hard SSRF/cloud-metadata blocking still applies).",
"editable": true,
"max_value": null,
"min_value": null,
@@ -5026,10 +5026,6 @@
"label": "Adaptive (default — follows your primary engine)",
"value": "adaptive"
},
- {
- "label": "Both (any classified engine)",
- "value": "both"
- },
{
"label": "Public only (no local collections)",
"value": "public_only"
@@ -5041,6 +5037,10 @@
{
"label": "Strict (only the primary engine)",
"value": "strict"
+ },
+ {
+ "label": "Unprotected (no egress protection — not recommended)",
+ "value": "unprotected"
}
],
"step": null,
@@ -5091,6 +5091,34 @@
"value": [],
"visible": true
},
+ "policy.trusted_inference_providers": {
+ "category": "policy",
+ "description": "EXPERIMENTAL. LLM/embeddings providers you explicitly trust to receive sensitive content — listing one treats it as a 'contained' inference sink even though it is off-machine (e.g. a zero-retention enterprise Anthropic endpoint). Relaxes the two-axis egress classification; use only for providers you have vetted.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Trusted Inference Providers",
+ "options": null,
+ "step": null,
+ "type": "LLM",
+ "ui_element": "json",
+ "value": [],
+ "visible": true
+ },
+ "policy.trusted_search_engines": {
+ "category": "policy",
+ "description": "EXPERIMENTAL. Search engines whose endpoint you explicitly trust — listing one (e.g. a self-hosted Elasticsearch/Paperless on a public hostname) treats it as 'contained' rather than an exposing sink. Relaxes the two-axis egress classification; use only for endpoints you control.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Trusted Search Engines",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "json",
+ "value": [],
+ "visible": true
+ },
"app.warnings.dismiss_egress_policy": {
"category": "internal",
"description": "Permanently hide the 'public search egress enabled' banner (the fresh-install informational one). The critical cloud-LLM and cloud-embeddings banners have their OWN dismiss flags so this can't silently hide them.",
diff --git a/src/local_deep_research/embeddings/providers/base.py b/src/local_deep_research/embeddings/providers/base.py
index 04d72266a6..474359b91b 100644
--- a/src/local_deep_research/embeddings/providers/base.py
+++ b/src/local_deep_research/embeddings/providers/base.py
@@ -5,6 +5,8 @@ from typing import Any, Dict, List, Optional
from langchain_core.embeddings import Embeddings
+from ...security.egress.classification import Exposure
+
class BaseEmbeddingProvider(ABC):
"""
@@ -21,6 +23,12 @@ class BaseEmbeddingProvider(ABC):
requires_api_key = False # Whether this provider requires an API key
supports_local = False # Whether this runs locally
default_model = None # Default embedding model
+ # Egress exposure (ADR-0007): declares whether this is an exposing
+ # inference sink (cloud = exposing, local = contained). Declarative default
+ # only — the egress resolver classifies the provider's ACTUAL endpoint at
+ # run time (run_classification.embeddings_label via evaluate_embeddings), so
+ # a URL-configurable provider is refined then; this documents intent.
+ egress_exposure = Exposure.EXPOSING
@classmethod
@abstractmethod
diff --git a/src/local_deep_research/embeddings/providers/implementations/ollama.py b/src/local_deep_research/embeddings/providers/implementations/ollama.py
index a44fbe1d0d..804fecb545 100644
--- a/src/local_deep_research/embeddings/providers/implementations/ollama.py
+++ b/src/local_deep_research/embeddings/providers/implementations/ollama.py
@@ -12,7 +12,7 @@ from ....utilities.llm_utils import (
_close_inner_ollama_clients,
get_ollama_base_url,
)
-from ..base import BaseEmbeddingProvider
+from ..base import BaseEmbeddingProvider, Exposure
from ....security import safe_get, safe_post
@@ -28,6 +28,7 @@ class OllamaEmbeddingsProvider(BaseEmbeddingProvider):
provider_key = "OLLAMA"
requires_api_key = False
supports_local = True
+ egress_exposure = Exposure.CONTAINED
default_model = "nomic-embed-text" # type: ignore[assignment]
@classmethod
diff --git a/src/local_deep_research/embeddings/providers/implementations/openai.py b/src/local_deep_research/embeddings/providers/implementations/openai.py
index 6511ce2549..fa47c97f35 100644
--- a/src/local_deep_research/embeddings/providers/implementations/openai.py
+++ b/src/local_deep_research/embeddings/providers/implementations/openai.py
@@ -9,7 +9,7 @@ from loguru import logger
from ....config.thread_settings import get_setting_from_snapshot
from ....security.log_sanitizer import redact_secrets
from ....utilities.url_utils import normalize_url
-from ..base import BaseEmbeddingProvider
+from ..base import BaseEmbeddingProvider, Exposure
class OpenAIEmbeddingsProvider(BaseEmbeddingProvider):
@@ -32,6 +32,7 @@ class OpenAIEmbeddingsProvider(BaseEmbeddingProvider):
# cloud-needs-key rule at runtime when no base_url is set.
# Inherits ``requires_api_key = False`` from BaseEmbeddingProvider.
supports_local = False
+ egress_exposure = Exposure.EXPOSING
default_model = "text-embedding-3-small" # type: ignore[assignment]
# Placeholder key used when targeting an OpenAI-compatible local
# server (api_key empty, base_url set). Mirrors the LLM-side
diff --git a/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py b/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py
index bc335edefe..afe653a742 100644
--- a/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py
+++ b/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py
@@ -7,7 +7,7 @@ from langchain_core.embeddings import Embeddings
from loguru import logger
from ....config.thread_settings import get_setting_from_snapshot
-from ..base import BaseEmbeddingProvider
+from ..base import BaseEmbeddingProvider, Exposure
class SentenceTransformersProvider(BaseEmbeddingProvider):
@@ -22,6 +22,7 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
provider_key = "SENTENCE_TRANSFORMERS"
requires_api_key = False
supports_local = True
+ egress_exposure = Exposure.CONTAINED
default_model = "all-MiniLM-L6-v2" # type: ignore[assignment]
# Available models with metadata
diff --git a/src/local_deep_research/llm/providers/base.py b/src/local_deep_research/llm/providers/base.py
index 7859f5cddb..5b3f211545 100644
--- a/src/local_deep_research/llm/providers/base.py
+++ b/src/local_deep_research/llm/providers/base.py
@@ -1,5 +1,7 @@
"""Base class for LLM providers."""
+from ...security.egress.classification import Exposure
+
# Single placeholder for ChatOpenAI(api_key=...) when no real key is
# configured (unauthenticated local LM Studio, llama.cpp, etc.). Subclasses
# MUST NOT override this constant; per-provider drift here was the reason
@@ -67,6 +69,14 @@ class BaseLLMProvider:
# substitute OPTIONAL_API_KEY_PLACEHOLDER) instead of raising.
api_key_optional: bool = False
+ # Egress exposure (ADR-0007): declares whether this is an exposing
+ # inference sink (cloud = exposing, local = contained). Declarative default
+ # only — the egress resolver classifies the provider's ACTUAL endpoint at
+ # run time (run_classification.llm_label via evaluate_llm_endpoint), so a
+ # URL-configurable provider is refined then; this attribute documents intent
+ # and is asserted consistent by test.
+ egress_exposure = Exposure.EXPOSING
+
@classmethod
def create_llm(cls, model_name=None, temperature=0.7, **kwargs):
"""Create and return a LangChain chat model instance.
diff --git a/src/local_deep_research/llm/providers/implementations/anthropic.py b/src/local_deep_research/llm/providers/implementations/anthropic.py
index 008a60d45f..3a42020318 100644
--- a/src/local_deep_research/llm/providers/implementations/anthropic.py
+++ b/src/local_deep_research/llm/providers/implementations/anthropic.py
@@ -7,7 +7,7 @@ from loguru import logger
# the methods that use them so test patches at the source module
# (`local_deep_research.config.thread_settings`) are picked up by the
# function-local imports at call time.
-from ..base import OPTIONAL_API_KEY_PLACEHOLDER
+from ..base import OPTIONAL_API_KEY_PLACEHOLDER, Exposure
from ..openai_base import OpenAICompatibleProvider
from ....security.ssrf_validator import assert_base_url_safe
@@ -29,6 +29,8 @@ class AnthropicProvider(OpenAICompatibleProvider):
# Annotated so subclasses (e.g. the custom-endpoint provider, which may be
# local or cloud) can set is_cloud = None without a type conflict.
is_cloud: bool | None = True
+ # Egress exposure (ADR-0007): cloud inference sink — data leaves the box.
+ egress_exposure = Exposure.EXPOSING
@classmethod
def create_llm(cls, model_name=None, temperature=0.7, **kwargs):
diff --git a/src/local_deep_research/llm/providers/implementations/custom_anthropic_endpoint.py b/src/local_deep_research/llm/providers/implementations/custom_anthropic_endpoint.py
index 9c4ba39e15..c0d1a896f4 100644
--- a/src/local_deep_research/llm/providers/implementations/custom_anthropic_endpoint.py
+++ b/src/local_deep_research/llm/providers/implementations/custom_anthropic_endpoint.py
@@ -10,6 +10,7 @@ from loguru import logger
from ....config.thread_settings import get_setting_from_snapshot
from ....security.log_sanitizer import redact_secrets
+from ..base import Exposure
from .anthropic import AnthropicProvider
@@ -35,6 +36,7 @@ class CustomAnthropicEndpointProvider(AnthropicProvider):
provider_key = "ANTHROPIC_ENDPOINT"
company_name = "Anthropic-Compatible"
is_cloud = None # Unknown — could be local or cloud
+ egress_exposure = Exposure.EXPOSING # URL-configurable; fail closed to exposing until classifier refines by URL
@classmethod
def requires_auth_for_models(cls):
diff --git a/src/local_deep_research/llm/providers/implementations/custom_openai_endpoint.py b/src/local_deep_research/llm/providers/implementations/custom_openai_endpoint.py
index e30d60377c..2a5d3a0c34 100644
--- a/src/local_deep_research/llm/providers/implementations/custom_openai_endpoint.py
+++ b/src/local_deep_research/llm/providers/implementations/custom_openai_endpoint.py
@@ -5,6 +5,7 @@ from loguru import logger
from ....config.thread_settings import get_setting_from_snapshot
from ....security.log_sanitizer import redact_secrets
from ....utilities.url_utils import normalize_url
+from ..base import Exposure
from ..openai_base import OpenAICompatibleProvider
@@ -29,6 +30,7 @@ class CustomOpenAIEndpointProvider(OpenAICompatibleProvider):
provider_key = "OPENAI_ENDPOINT"
company_name = "OpenAI-Compatible"
is_cloud = None # Unknown — could be local or cloud
+ egress_exposure = Exposure.EXPOSING # URL-configurable; fail closed to exposing until classifier refines by URL
@classmethod
def requires_auth_for_models(cls):
diff --git a/src/local_deep_research/llm/providers/implementations/deepseek.py b/src/local_deep_research/llm/providers/implementations/deepseek.py
index 11e23eeb01..c01d742e1a 100644
--- a/src/local_deep_research/llm/providers/implementations/deepseek.py
+++ b/src/local_deep_research/llm/providers/implementations/deepseek.py
@@ -1,5 +1,6 @@
"""DeepSeek LLM provider for Local Deep Research."""
+from ..base import Exposure
from ..openai_base import OpenAICompatibleProvider
@@ -15,6 +16,8 @@ class DeepseekProvider(OpenAICompatibleProvider):
provider_key = "DEEPSEEK"
company_name = "DeepSeek"
is_cloud = True
+ # Egress exposure (ADR-0007): cloud inference sink — data leaves the box.
+ egress_exposure = Exposure.EXPOSING
@classmethod
def requires_auth_for_models(cls):
diff --git a/src/local_deep_research/llm/providers/implementations/google.py b/src/local_deep_research/llm/providers/implementations/google.py
index b359671429..44eb290ce1 100644
--- a/src/local_deep_research/llm/providers/implementations/google.py
+++ b/src/local_deep_research/llm/providers/implementations/google.py
@@ -3,6 +3,7 @@
from loguru import logger
from ....security.log_sanitizer import redact_secrets
+from ..base import Exposure
from ..openai_base import OpenAICompatibleProvider
@@ -23,6 +24,8 @@ class GoogleProvider(OpenAICompatibleProvider):
provider_key = "GOOGLE"
company_name = "Google"
is_cloud = True
+ # Egress exposure (ADR-0007): cloud inference sink — data leaves the box.
+ egress_exposure = Exposure.EXPOSING
@classmethod
def requires_auth_for_models(cls):
diff --git a/src/local_deep_research/llm/providers/implementations/ionos.py b/src/local_deep_research/llm/providers/implementations/ionos.py
index c9237925a3..95d5a21e25 100644
--- a/src/local_deep_research/llm/providers/implementations/ionos.py
+++ b/src/local_deep_research/llm/providers/implementations/ionos.py
@@ -1,5 +1,6 @@
"""IONOS AI Model Hub LLM provider for Local Deep Research."""
+from ..base import Exposure
from ..openai_base import OpenAICompatibleProvider
@@ -15,6 +16,8 @@ class IONOSProvider(OpenAICompatibleProvider):
provider_key = "IONOS"
company_name = "IONOS"
is_cloud = True
+ # Egress exposure (ADR-0007): cloud inference sink — data leaves the box.
+ egress_exposure = Exposure.EXPOSING
@classmethod
def requires_auth_for_models(cls):
diff --git a/src/local_deep_research/llm/providers/implementations/llamacpp.py b/src/local_deep_research/llm/providers/implementations/llamacpp.py
index fbfbe4cb91..6517ef7f0e 100644
--- a/src/local_deep_research/llm/providers/implementations/llamacpp.py
+++ b/src/local_deep_research/llm/providers/implementations/llamacpp.py
@@ -8,6 +8,7 @@ beyond a single endpoint, use the `openai_endpoint` provider directly.
from ....config.constants import DEFAULT_LLAMACPP_URL
from ....utilities.url_utils import normalize_url
+from ..base import Exposure
from ..openai_base import OpenAICompatibleProvider
@@ -32,6 +33,8 @@ class LlamaCppProvider(OpenAICompatibleProvider):
provider_key = "LLAMACPP"
company_name = "llama.cpp"
is_cloud = False # Local provider
+ # Egress exposure (ADR-0007): local inference sink — data stays on the box.
+ egress_exposure = Exposure.CONTAINED
@classmethod
def create_llm(cls, model_name=None, temperature=0.7, **kwargs):
diff --git a/src/local_deep_research/llm/providers/implementations/lmstudio.py b/src/local_deep_research/llm/providers/implementations/lmstudio.py
index 9786ab0951..8632c2786d 100644
--- a/src/local_deep_research/llm/providers/implementations/lmstudio.py
+++ b/src/local_deep_research/llm/providers/implementations/lmstudio.py
@@ -2,6 +2,7 @@
from ....config.constants import DEFAULT_LMSTUDIO_URL
from ....utilities.url_utils import normalize_url
+from ..base import Exposure
from ..openai_base import OpenAICompatibleProvider
@@ -38,6 +39,8 @@ class LMStudioProvider(OpenAICompatibleProvider):
provider_key = "LMSTUDIO"
company_name = "LM Studio"
is_cloud = False # Local provider
+ # Egress exposure (ADR-0007): local inference sink — data stays on the box.
+ egress_exposure = Exposure.CONTAINED
@classmethod
def _get_auth_headers(cls, settings_snapshot=None):
diff --git a/src/local_deep_research/llm/providers/implementations/ollama.py b/src/local_deep_research/llm/providers/implementations/ollama.py
index ad56d408b3..64a45df458 100644
--- a/src/local_deep_research/llm/providers/implementations/ollama.py
+++ b/src/local_deep_research/llm/providers/implementations/ollama.py
@@ -8,7 +8,7 @@ from ....config.thread_settings import get_setting_from_snapshot
from ....utilities.url_utils import normalize_url
from ....security import safe_get
from ....security.ssrf_validator import assert_base_url_safe
-from ..base import BaseLLMProvider
+from ..base import BaseLLMProvider, Exposure
class OllamaProvider(BaseLLMProvider):
@@ -29,6 +29,8 @@ class OllamaProvider(BaseLLMProvider):
provider_key = "OLLAMA"
company_name = "Ollama"
is_cloud = False
+ # Egress exposure (ADR-0007): local inference sink — data stays on the box.
+ egress_exposure = Exposure.CONTAINED
@classmethod
def _get_auth_headers(cls, api_key=None, settings_snapshot=None):
diff --git a/src/local_deep_research/llm/providers/implementations/openai.py b/src/local_deep_research/llm/providers/implementations/openai.py
index 6426154898..b126ada401 100644
--- a/src/local_deep_research/llm/providers/implementations/openai.py
+++ b/src/local_deep_research/llm/providers/implementations/openai.py
@@ -9,6 +9,7 @@ from loguru import logger
# function-local import at call time. Module-level binding here would be
# unaffected by the source-module patch.
from ....security.ssrf_validator import assert_base_url_safe
+from ..base import Exposure
from ..openai_base import OpenAICompatibleProvider
@@ -27,6 +28,8 @@ class OpenAIProvider(OpenAICompatibleProvider):
provider_key = "OPENAI"
company_name = "OpenAI"
is_cloud = True
+ # Egress exposure (ADR-0007): cloud inference sink — data leaves the box.
+ egress_exposure = Exposure.EXPOSING
@classmethod
def create_llm(cls, model_name=None, temperature=0.7, **kwargs):
diff --git a/src/local_deep_research/llm/providers/implementations/openrouter.py b/src/local_deep_research/llm/providers/implementations/openrouter.py
index 0b82332a08..836a4b102a 100644
--- a/src/local_deep_research/llm/providers/implementations/openrouter.py
+++ b/src/local_deep_research/llm/providers/implementations/openrouter.py
@@ -1,5 +1,6 @@
"""OpenRouter LLM provider for Local Deep Research."""
+from ..base import Exposure
from ..openai_base import OpenAICompatibleProvider
@@ -20,6 +21,8 @@ class OpenRouterProvider(OpenAICompatibleProvider):
provider_key = "OPENROUTER"
company_name = "OpenRouter"
is_cloud = True
+ # Egress exposure (ADR-0007): cloud inference sink — data leaves the box.
+ egress_exposure = Exposure.EXPOSING
@classmethod
def requires_auth_for_models(cls):
diff --git a/src/local_deep_research/llm/providers/implementations/xai.py b/src/local_deep_research/llm/providers/implementations/xai.py
index 5a451d2b73..cb507726ae 100644
--- a/src/local_deep_research/llm/providers/implementations/xai.py
+++ b/src/local_deep_research/llm/providers/implementations/xai.py
@@ -1,5 +1,6 @@
"""xAI Grok LLM provider for Local Deep Research."""
+from ..base import Exposure
from ..openai_base import OpenAICompatibleProvider
@@ -18,6 +19,8 @@ class XAIProvider(OpenAICompatibleProvider):
provider_key = "XAI"
company_name = "xAI"
is_cloud = True
+ # Egress exposure (ADR-0007): cloud inference sink — data leaves the box.
+ egress_exposure = Exposure.EXPOSING
@classmethod
def requires_auth_for_models(cls):
diff --git a/src/local_deep_research/notifications/manager.py b/src/local_deep_research/notifications/manager.py
index 2518b9eb38..8458f68695 100644
--- a/src/local_deep_research/notifications/manager.py
+++ b/src/local_deep_research/notifications/manager.py
@@ -313,7 +313,7 @@ class NotificationManager:
"status": "error",
"message": (
"URL refused by egress policy. Set Egress Scope to "
- "'Both' (or pick a local webhook) to test this URL."
+ "'Unprotected' (or pick a local webhook) to test this URL."
),
}
return self.service.test_service(allowed)
diff --git a/src/local_deep_research/security/egress/README.md b/src/local_deep_research/security/egress/README.md
index 048554412c..ea22a57a9d 100644
--- a/src/local_deep_research/security/egress/README.md
+++ b/src/local_deep_research/security/egress/README.md
@@ -28,10 +28,11 @@ engines/destinations are permitted.
| Scope | Meaning |
|---|---|
| `adaptive` *(default)* | **Follow the primary engine.** A private primary → behaves PRIVATE_ONLY; a public primary → PUBLIC_ONLY; an unclassifiable primary → BOTH. Resolved to a concrete scope at run start. Classification uses the engine's **static class flags** (e.g. SearXNG is always public because it queries the internet), not the network location of its server — with one asymmetric **fail-up** exception: a local-nature engine (Elasticsearch, Paperless) whose configured URL resolves to a *public* host is reclassified public, because querying it sends data off the box. The override only ever tightens. |
-| `both` | Any classified engine (the pre-policy behaviour). |
+| `both` | **Retired as a user scope** (ADR-0007). Kept only as the internal ADAPTIVE resolution target for an unclassifiable primary (allow any classified engine). A saved/queued/env `both` value is **coerced to `adaptive`** by `context_from_snapshot`, and migration 0019 rewrites stored rows — it never re-enables the old blanket-permit behaviour on its own. |
| `public_only` | Only public web/academic engines. Local collections excluded. |
| `private_only` | Only local engines (library, collections, Ollama). **Forces local LLM + embeddings inference** so nothing leaves the box. Note: a locally-hosted SearXNG is still treated as *public* because it proxies to internet search engines — only its *connection target* is local, not its *data source*. |
| `strict` | Only the user's *primary* engine; no expansion at all. |
+| `unprotected` | **Escape hatch (not recommended).** Egress-scope restrictions are disabled — any engine / URL / provider is permitted; the hard SSRF + cloud-metadata blocks in `evaluate_url` still apply, and the forced-local inference requirements are lifted. A non-dismissible banner shows while active. |
Two independent toggles refine inference locality (and are **implied** under
PRIVATE_ONLY / Adaptive-private):
@@ -46,6 +47,16 @@ 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.
+**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*
+sink (a public engine or a cloud LLM/embeddings provider). Per-destination trust
+(`policy.trusted_inference_providers` / `policy.trusted_search_engines`) relaxes
+a vouched-for off-machine sink to *contained*; `unprotected` suspends the rule.
+The pure decision core is `classification.py`; the live resolver + audit/enforce
+wiring is `run_classification.py`. See
+[`docs/decisions/0007-egress-two-axis-data-classification.md`](../../../../docs/decisions/0007-egress-two-axis-data-classification.md).
+
---
## 2. Architecture: PDP + PEPs
diff --git a/src/local_deep_research/security/egress/classification.py b/src/local_deep_research/security/egress/classification.py
new file mode 100644
index 0000000000..411e05e986
--- /dev/null
+++ b/src/local_deep_research/security/egress/classification.py
@@ -0,0 +1,187 @@
+"""Two-axis egress data classification — ADR-0007, rollout stage A.
+
+Pure decision logic. Each model a run touches (search engine, collection /
+store, LLM, embeddings) is classified on two **orthogonal** axes:
+
+* **Sensitivity** — of the data the component *sources*: must it never leave the
+ machine? (``SENSITIVE`` / ``NON_SENSITIVE``)
+* **Exposure** — of the *sink* the component represents: does sending data to it
+ put that data off-machine? (``EXPOSING`` / ``CONTAINED``)
+
+:func:`evaluate_run` decides whether a *set* of classified components may run
+together, per the four-quadrant rule in ADR-0007. The core invariant: **a run
+may not let a SENSITIVE source reach an EXPOSING sink.** Because an agentic run
+can turn one engine's results into another engine's query (the LangGraph
+silent-expansion bug class already in our threat model), the rule is evaluated
+over the whole component set, not per individual call.
+
+This module holds the pure decision logic. It is consumed via
+``run_classification``, which resolves live engines/providers, assembles a run,
+and — at the run-start precheck — **enforces** the decision (rejecting a run
+that would let a sensitive source reach an exposing sink), except under the
+``UNPROTECTED`` escape hatch where it evaluates permissive. See
+``docs/decisions/0007-egress-two-axis-data-classification.md``.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import Iterable
+
+
+class Sensitivity(Enum):
+ """Whether the data a component *sources* may leave the machine."""
+
+ NON_SENSITIVE = "non_sensitive"
+ SENSITIVE = "sensitive"
+
+
+class Exposure(Enum):
+ """Whether sending data to a component (as a sink) puts it off-machine."""
+
+ CONTAINED = "contained"
+ EXPOSING = "exposing"
+
+
+class Role(Enum):
+ """How a component participates in a run's data flow.
+
+ A single real component may take more than one role — a search engine is a
+ ``SEARCH_SINK`` for the query *and* a ``SOURCE`` of results; Elasticsearch
+ is a ``SOURCE`` of data *and* a ``SEARCH_SINK`` for the query you send it.
+ Such a component is passed to :func:`evaluate_run` once per role it plays,
+ **using the same** :attr:`Component.name` each time — the self-exclusion in
+ quadrant 4 (a dual-risk store used solo) relies on that shared identity.
+ """
+
+ SOURCE = "source" # contributes data into the run
+ SEARCH_SINK = "search_sink" # receives the query (+ maybe expanded results)
+ INFERENCE_SINK = "inference_sink" # LLM / embeddings — sees all source data
+
+
+class Mode(Enum):
+ """Enforcement mode — SELinux vocabulary (ADR-0007)."""
+
+ ENFORCING = "enforcing" # the invariant is enforced; violations blocked
+ PERMISSIVE = "permissive" # evaluated for warnings, never blocks
+
+
+@dataclass(frozen=True)
+class Label:
+ """A component's position on the two axes."""
+
+ sensitivity: Sensitivity
+ exposure: Exposure
+
+
+@dataclass(frozen=True)
+class Component:
+ """A classified participant in a run.
+
+ ``name`` is a stable identifier (engine name, ``collection_<uuid>``,
+ ``llm:<provider>``, ``embeddings:<provider>``) used for self-exclusion and
+ reporting.
+ """
+
+ name: str
+ role: Role
+ label: Label
+
+
+@dataclass(frozen=True)
+class Decision:
+ """Outcome of :func:`evaluate_run`."""
+
+ allowed: bool
+ reason: str
+ offending: tuple[str, ...] = field(default_factory=tuple)
+
+
+def evaluate_run(
+ components: Iterable[Component], *, mode: Mode = Mode.ENFORCING
+) -> Decision:
+ """Decide whether a set of classified components may run together.
+
+ Implements the four-quadrant rule of ADR-0007:
+
+ 1. ``non-sensitive, contained`` → combines with anything.
+ 2. ``sensitive, contained`` → only with other contained sources.
+ 3. ``non-sensitive, exposing`` → only with non-sensitive sources.
+ 4. ``sensitive + exposing`` → solo, with contained inference.
+
+ The rule assumes the caller passes each real engine as BOTH a ``SOURCE``
+ (carrying its sensitivity) and a ``SEARCH_SINK`` (carrying its exposure)
+ under one shared ``name`` — the quadrant-4 self-exclusion depends on that
+ pairing (see ``run_classification.classify_run``).
+
+ Under :attr:`Mode.PERMISSIVE` the run is always allowed, but the underlying
+ would-be-enforced ``reason`` / ``offending`` are preserved (prefixed
+ ``permissive:``) so the caller can still surface a warning banner.
+ """
+ components = tuple(components)
+ decision = _decide_enforcing(components)
+ if mode is Mode.PERMISSIVE and not decision.allowed:
+ return Decision(
+ True, f"permissive:{decision.reason}", offending=decision.offending
+ )
+ return decision
+
+
+def _decide_enforcing(components: tuple[Component, ...]) -> Decision:
+ """The enforcing four-quadrant decision (mode-agnostic)."""
+ sensitive_names = {
+ c.name
+ for c in components
+ if c.role is Role.SOURCE
+ and c.label.sensitivity is Sensitivity.SENSITIVE
+ }
+
+ # No sensitive data in the run → nothing to protect; any sink is fine.
+ if not sensitive_names:
+ return Decision(True, "no_sensitive_source")
+
+ # (1) Sensitive content always reaches the inference sink (the LLM/embeddings
+ # see every source's data), so an exposing inference sink leaks it.
+ exposing_inference = tuple(
+ sorted(
+ c.name
+ for c in components
+ if c.role is Role.INFERENCE_SINK
+ and c.label.exposure is Exposure.EXPOSING
+ )
+ )
+ if exposing_inference:
+ return Decision(
+ False,
+ "sensitive_to_exposing_inference",
+ offending=exposing_inference,
+ )
+
+ # (2) An exposing search sink may coexist with sensitive data ONLY if it is
+ # itself the sole sensitive source (quadrant 4, solo): returning its own
+ # data to itself is not a new leak. Any *other* sensitive source could be
+ # agentically expanded into a query to that sink → leak. The sink must
+ # ALSO be sensitive itself, so a mere name collision between a
+ # non-sensitive exposing sink and an unrelated sensitive source cannot
+ # be mistaken for the solo dual-risk case.
+ offending_search = tuple(
+ sorted(
+ {
+ sink.name
+ for sink in components
+ if sink.role is Role.SEARCH_SINK
+ and sink.label.exposure is Exposure.EXPOSING
+ and (
+ (sensitive_names - {sink.name})
+ or sink.label.sensitivity is not Sensitivity.SENSITIVE
+ )
+ }
+ )
+ )
+ if offending_search:
+ return Decision(
+ False, "sensitive_to_exposing_search", offending=offending_search
+ )
+
+ return Decision(True, "sensitive_contained")
diff --git a/src/local_deep_research/security/egress/policy.py b/src/local_deep_research/security/egress/policy.py
index 4d24c6091a..9af049d08d 100644
--- a/src/local_deep_research/security/egress/policy.py
+++ b/src/local_deep_research/security/egress/policy.py
@@ -16,6 +16,7 @@ Vocabulary borrowed from XACML / zero-trust:
from __future__ import annotations
+import json
import socket
import threading
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout
@@ -63,13 +64,21 @@ class EgressScope(str, Enum):
- 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: any classified engine (preserves pre-policy behavior).
+ - 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"
@@ -77,6 +86,7 @@ class EgressScope(str, Enum):
PRIVATE_ONLY = "private_only"
BOTH = "both"
ADAPTIVE = "adaptive"
+ UNPROTECTED = "unprotected"
# Code-side single source of truth for the default egress scope, used by
@@ -575,6 +585,12 @@ def evaluate_engine(
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
@@ -1006,6 +1022,13 @@ def evaluate_url(url: str, ctx: EgressContext) -> Decision:
# classification (DNS path has its own handling).
pass
+ # 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")
+
classification = _classify_host(host, ctx)
if ctx.scope == EgressScope.STRICT:
@@ -1075,6 +1098,10 @@ def evaluate_retriever(
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,
@@ -1213,8 +1240,10 @@ def context_from_snapshot(
"""Construct the frozen ``EgressContext`` for a research run.
Reads policy settings out of the snapshot exactly once at run-start.
- Default values preserve backward compatibility: missing keys yield
- the most permissive policy (``BOTH``, no local requirements).
+ 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
@@ -1239,6 +1268,15 @@ def context_from_snapshot(
scope_raw = _get_setting_value(
settings_snapshot, "policy.egress_scope", DEFAULT_EGRESS_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 = EgressScope(str(scope_raw).lower())
except ValueError as exc:
@@ -1303,6 +1341,11 @@ def context_from_snapshot(
if scope == EgressScope.PRIVATE_ONLY:
require_local_llm = True
require_local_embeddings = True
+ elif scope == EgressScope.UNPROTECTED:
+ # Escape hatch: egress protection is off, so the local-inference
+ # requirements are lifted too (any provider is permitted).
+ require_local_llm = False
+ require_local_embeddings = False
return EgressContext(
scope=scope,
@@ -1324,6 +1367,28 @@ def _get_setting_value(snapshot: dict, key: str, 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:
diff --git a/src/local_deep_research/security/egress/run_classification.py b/src/local_deep_research/security/egress/run_classification.py
new file mode 100644
index 0000000000..958cf92994
--- /dev/null
+++ b/src/local_deep_research/security/egress/run_classification.py
@@ -0,0 +1,363 @@
+"""Stage B (ADR-0007): bridge the pure classification core to live engines and
+providers, assemble a run's component set, and decide its admissibility.
+
+Resolution reads each element's *declared* two-axis label (the class attributes
+added in stage A) and applies the dynamic refinements that depend on
+configuration:
+
+ * a self-hosted store's exposure flips to ``EXPOSING`` when its configured
+ URL resolves to a public host (reusing the policy's fail-up classifier), so
+ 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.
+
+``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
+denied run) — except under the ``UNPROTECTED`` escape hatch, where ``audit_run``
+evaluates in permissive mode (always allowed, diagnostic preserved).
+``audit_run`` never raises: if the decision cannot be computed it **fails
+closed**, returning a denying ``Decision`` (reason ``audit_error``) so the run
+is refused visibly rather than silently degrading to the scope PEPs.
+"""
+
+from __future__ import annotations
+
+from typing import Iterable, List, Optional
+
+from loguru import logger
+
+from .classification import (
+ Component,
+ Decision,
+ Exposure,
+ Label,
+ Mode,
+ Role,
+ Sensitivity,
+ evaluate_run,
+)
+
+
+def engine_label(engine_name: str, settings_snapshot, ctx) -> Optional[Label]:
+ """Resolve a search engine's two-axis label, or ``None`` if unknown.
+
+ Reads the engine class's declared ``egress_sensitivity`` /
+ ``egress_exposure`` and applies the configuration-dependent refinements.
+ """
+ from .policy import (
+ _classify_engine_url,
+ _get_engine_class,
+ _resolve_collection_is_public,
+ )
+
+ # Collections / library: the class is not a static engine, and sensitivity
+ # comes from the per-collection is_public flag (public -> non-sensitive).
+ if engine_name == "library" or engine_name.startswith("collection_"):
+ is_public = _resolve_collection_is_public(engine_name, ctx.username)
+ 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)
+
+ cls = _get_engine_class(engine_name)
+ if cls is None:
+ return None # unknown engine — the per-engine PEP still guards it
+
+ sensitivity = getattr(cls, "egress_sensitivity", Sensitivity.SENSITIVE)
+ exposure = getattr(cls, "egress_exposure", Exposure.EXPOSING)
+
+ # Exposure fail-up: a contained store whose configured URL resolves to a
+ # public host leaks the query off the box -> EXPOSING. Only ever tightens,
+ # mirroring the policy's asymmetric URL override.
+ url_setting = getattr(cls, "url_setting", None)
+ if url_setting and exposure is Exposure.CONTAINED:
+ if _classify_engine_url(url_setting, settings_snapshot, ctx) is False:
+ exposure = Exposure.EXPOSING
+
+ # Per-destination trust (ADR-0007 stage D): the user has explicitly vouched
+ # for this engine's endpoint, so treat it as contained (moves a dual-risk
+ # store from quadrant 4 to quadrant 2). Only ever applies to a local-nature
+ # store that failed up on its URL — NEVER to an inherently-public engine
+ # (is_public), so a trusted name can't launder a public search sink.
+ if (
+ exposure is Exposure.EXPOSING
+ and getattr(cls, "is_public", False) is not True
+ and engine_name.lower()
+ in _trusted_names("policy.trusted_search_engines", settings_snapshot)
+ ):
+ exposure = Exposure.CONTAINED
+
+ return Label(sensitivity, exposure)
+
+
+def _require_local_probe(ctx):
+ """A require-local EgressContext used to ask the enforcing PEPs whether a
+ provider's configured endpoint is local. Copies the caller's hostname
+ allow-list / username so classification matches the real run."""
+ from .policy import EgressContext, EgressScope
+
+ return EgressContext(
+ scope=EgressScope.PRIVATE_ONLY,
+ primary_engine=getattr(ctx, "primary_engine", "") or "",
+ require_local_llm=True,
+ require_local_embeddings=True,
+ local_hostnames=getattr(ctx, "local_hostnames", ()) or (),
+ username=getattr(ctx, "username", None),
+ )
+
+
+def _trusted_names(setting_key: str, settings_snapshot) -> set:
+ """Lower-cased set of names the user has explicitly trusted.
+
+ Reads a JSON-list setting (mirroring ``llm.allowed_local_hostnames``);
+ returns an empty set on a missing/malformed value.
+ """
+ if not settings_snapshot:
+ return set()
+ from .policy import _get_setting_value, coerce_str_list
+
+ _, names = coerce_str_list(
+ _get_setting_value(settings_snapshot, setting_key, ())
+ )
+ return {n.lower() for n in names}
+
+
+def _inference_label(provider, evaluate_fn, settings_snapshot, ctx) -> Label:
+ """Shared exposure resolution for an inference sink (LLM or embeddings).
+
+ Decided by the SAME classification the enforcing PEP uses (``evaluate_fn``
+ under a require-local probe): the provider's configured endpoint is
+ CONTAINED iff the PEP would accept it as local, else EXPOSING — keeping the
+ resolver in exact lock-step with enforcement (so a self-hosted endpoint on a
+ local URL is contained, not falsely exposing). Trust then relaxes an
+ exposing sink the user has explicitly vouched for.
+ """
+ p = (provider or "").lower()
+ snapshot = settings_snapshot if settings_snapshot is not None else {}
+ try:
+ allowed = evaluate_fn(
+ p, _require_local_probe(ctx), settings_snapshot=snapshot
+ ).allowed
+ except Exception: # noqa: silent-exception - fail closed to exposing
+ allowed = False
+ exposure = Exposure.CONTAINED if allowed else Exposure.EXPOSING
+ if exposure is Exposure.EXPOSING and p in _trusted_names(
+ "policy.trusted_inference_providers", settings_snapshot
+ ):
+ exposure = Exposure.CONTAINED
+ return Label(Sensitivity.NON_SENSITIVE, exposure)
+
+
+def llm_label(
+ provider: Optional[str], settings_snapshot=None, ctx=None
+) -> Label:
+ """Resolve an LLM provider's label (an inference sink — exposure only)."""
+ from .policy import evaluate_llm_endpoint
+
+ return _inference_label(
+ provider, evaluate_llm_endpoint, settings_snapshot, ctx
+ )
+
+
+def embeddings_label(
+ provider: Optional[str], settings_snapshot=None, ctx=None
+) -> Label:
+ """Resolve an embeddings provider's label (an inference sink)."""
+ from .policy import evaluate_embeddings
+
+ return _inference_label(
+ provider, evaluate_embeddings, settings_snapshot, ctx
+ )
+
+
+def classify_run(
+ settings_snapshot,
+ ctx,
+ *,
+ engines: Iterable[str],
+ llm_provider: Optional[str] = None,
+ embeddings_provider: Optional[str] = None,
+) -> List[Component]:
+ """Assemble the run's classified component set.
+
+ Each search engine contributes two components sharing its name — a
+ ``SOURCE`` (carrying its sensitivity) and a ``SEARCH_SINK`` (carrying its
+ exposure) — so the quadrant-4 self-exclusion in :func:`evaluate_run` works.
+ The LLM and embeddings providers are ``INFERENCE_SINK`` components.
+ """
+ components: List[Component] = []
+ for name in engines:
+ label = engine_label(name, settings_snapshot, ctx)
+ if label is None:
+ # Unknown engine (not in the registry — e.g. a programmatic
+ # retriever): fail CLOSED to the most restrictive quadrant rather
+ # than dropping it, so an unclassified source can never silently
+ # relax the run's admissibility.
+ label = Label(Sensitivity.SENSITIVE, Exposure.EXPOSING)
+ components.append(Component(name, Role.SOURCE, label))
+ components.append(Component(name, Role.SEARCH_SINK, label))
+ if llm_provider:
+ components.append(
+ Component(
+ f"llm:{llm_provider}",
+ Role.INFERENCE_SINK,
+ llm_label(llm_provider, settings_snapshot, ctx),
+ )
+ )
+ if embeddings_provider:
+ components.append(
+ Component(
+ f"embeddings:{embeddings_provider}",
+ Role.INFERENCE_SINK,
+ embeddings_label(embeddings_provider, settings_snapshot, ctx),
+ )
+ )
+ return components
+
+
+def _fail_closed_decision(ctx) -> Decision:
+ """The decision to return when the two-axis rule cannot be computed.
+
+ Refuses the run (reason ``audit_error``) so the failure is visible, except
+ under the ``UNPROTECTED`` escape hatch, which must never block.
+
+ This is called from the ``except`` blocks that handle failures, so it must
+ NOT import ``.policy``: if the triggering failure was itself a ``.policy``
+ import error (its imports are lazy precisely to dodge a circular-import
+ hazard), re-importing here would re-raise and defeat the fail-closed
+ guarantee — ``audit_run`` would raise instead of returning a denial, and
+ the callers' outer handlers would then fail OPEN. ``EgressScope`` is a
+ ``str`` enum, so compare against the literal value with no import.
+ """
+ if getattr(ctx, "scope", None) == "unprotected":
+ return Decision(True, "unprotected")
+ return Decision(False, "audit_error")
+
+
+def audit_run(
+ settings_snapshot,
+ ctx,
+ *,
+ engines: Iterable[str],
+ llm_provider: Optional[str] = None,
+ embeddings_provider: Optional[str] = None,
+) -> Decision:
+ """Compute the four-quadrant decision for a run and LOG it.
+
+ Never raises. On success returns the :class:`Decision`. If the decision
+ cannot be computed it **fails closed** — returns a denying ``Decision``
+ (reason ``audit_error``) so the run is refused and the failure is visible,
+ rather than silently degrading to the scope PEPs. Under the ``UNPROTECTED``
+ escape-hatch scope the decision is evaluated in :attr:`Mode.PERMISSIVE`
+ (always allowed, diagnostic preserved), and an ``audit_error`` under that
+ scope is likewise never blocking — the escape hatch must never refuse.
+ """
+ try:
+ from .policy import EgressScope
+
+ mode = (
+ Mode.PERMISSIVE
+ if getattr(ctx, "scope", None) == EgressScope.UNPROTECTED
+ else Mode.ENFORCING
+ )
+ components = classify_run(
+ settings_snapshot,
+ ctx,
+ engines=engines,
+ llm_provider=llm_provider,
+ embeddings_provider=embeddings_provider,
+ )
+ decision = evaluate_run(components, mode=mode)
+ logger.bind(policy_audit=True).info(
+ "egress two-axis audit",
+ allowed=decision.allowed,
+ reason=decision.reason,
+ offending=decision.offending,
+ )
+ return decision
+ except Exception: # noqa: silent-exception - audit must never break a run
+ logger.bind(policy_audit=True).warning(
+ "egress two-axis audit could not be computed — failing closed",
+ exc_info=True,
+ )
+ return _fail_closed_decision(ctx)
+
+
+def audit_run_from_snapshot(
+ settings_snapshot, ctx, primary_engine, llm_provider=None
+):
+ """Two-axis decision for a run described by its settings snapshot.
+
+ Shared by the ``/api/start_research`` precheck and the worker chokepoint in
+ ``run_research_process`` so every entry point — API, follow-up, chat, queue
+ — evaluates the identical rule, then delegates to :func:`audit_run` (which
+ fails closed to a denying decision when the rule cannot be computed).
+
+ ``llm_provider`` is the run's per-request provider override (the
+ ``model_provider`` kwarg / request field). It **wins** over the snapshot,
+ mirroring ``get_llm`` (``config/llm_config.py``: an explicit provider is
+ used, else the snapshot default). Passing only the snapshot would audit the
+ stored default while the run builds the overridden provider — e.g. a saved
+ local ``ollama`` audited as CONTAINED while the run actually calls a cloud
+ provider chosen for that one run — admitting a leak. A **falsy** override
+ (``None`` or ``""`` — chat passes ``""`` when no provider is set) means "no
+ override": the provider is resolved from the snapshot, the SAME key/default
+ the run uses. Using ``is None`` here would let ``""`` through and
+ ``classify_run``'s truthy guard would then silently drop the LLM sink.
+
+ The LLM and (RAG-only) embeddings providers are read with
+ :func:`get_setting_from_snapshot` using the SAME keys/defaults the run uses,
+ so the check never resolves to a different (safer) value than the run.
+ Embeddings for a library / collection run come from
+ ``local_search_embedding_provider`` (``search_engine_library.py``), NOT the
+ unrelated ``embeddings.provider`` key.
+
+ Resolution runs inside the same fail-closed guard as the decision itself.
+ """
+ try:
+ from ...config.thread_settings import get_setting_from_snapshot
+
+ if not llm_provider:
+ # get_setting_from_snapshot only substitutes the default when the
+ # key is ABSENT; a key present-but-empty returns "" again. Fall back
+ # to the system default so the LLM sink is always classified and
+ # never silently dropped by classify_run's truthy guard.
+ llm_provider = (
+ get_setting_from_snapshot(
+ "llm.provider",
+ "ollama",
+ settings_snapshot=settings_snapshot,
+ )
+ or "ollama"
+ )
+ # Embeddings only leave the box when the run actually embeds — RAG over
+ # a collection / library. A lexical store or a web primary never embeds,
+ # so a configured cloud embedder must not falsely trip the
+ # sensitive->exposing check for those runs. Read the SAME key the RAG
+ # engine uses (search_engine_library.py: local_search_embedding_provider);
+ # embeddings.provider is a different, unused-here setting.
+ embeddings_provider = None
+ if primary_engine == "library" or (
+ isinstance(primary_engine, str)
+ and primary_engine.startswith("collection_")
+ ):
+ embeddings_provider = get_setting_from_snapshot(
+ "local_search_embedding_provider",
+ default="sentence_transformers",
+ settings_snapshot=settings_snapshot,
+ )
+ except Exception: # noqa: silent-exception - resolution must fail closed
+ logger.bind(policy_audit=True).warning(
+ "egress provider resolution failed — failing closed", exc_info=True
+ )
+ return _fail_closed_decision(ctx)
+ return audit_run(
+ settings_snapshot,
+ ctx,
+ engines=[primary_engine],
+ llm_provider=llm_provider,
+ embeddings_provider=embeddings_provider,
+ )
diff --git a/src/local_deep_research/security/egress/validators.py b/src/local_deep_research/security/egress/validators.py
index 71111ca14e..24bc468305 100644
--- a/src/local_deep_research/security/egress/validators.py
+++ b/src/local_deep_research/security/egress/validators.py
@@ -102,3 +102,70 @@ def validate_allowed_local_hostnames(form_data, all_db_settings):
),
}
return None
+
+
+def validate_trusted_search_engines(form_data, all_db_settings):
+ """Reject inherently-public engines from ``policy.trusted_search_engines``.
+
+ Trusting a search engine relaxes its Exposure to CONTAINED — meaningful only
+ for a local-nature store you host (Elasticsearch/Paperless). An inherently
+ public engine (google, searxng, brave, …) genuinely queries the internet, so
+ trusting it would launder a public sink past the two-axis rule. Reject those;
+ local / unknown names are accepted (runtime classification still gates them,
+ and ``engine_label`` also refuses to relax an ``is_public`` engine).
+ """
+ key = "policy.trusted_search_engines"
+ if key not in form_data:
+ return None
+ value = form_data[key]
+ if isinstance(value, str):
+ import json
+
+ try:
+ value = json.loads(value) if value.strip() else []
+ except Exception:
+ return {
+ "key": key,
+ "error": "trusted_search_engines must be a JSON array",
+ }
+ if not isinstance(value, list):
+ return {"key": key, "error": "trusted_search_engines must be a list"}
+
+ from .policy import _get_engine_class
+
+ rejected = []
+ for entry in value:
+ if not isinstance(entry, str) or not entry.strip():
+ continue
+ name = entry.strip().lower()
+ cls = _get_engine_class(name)
+ if cls is not None and getattr(cls, "is_public", False) is True:
+ rejected.append(name)
+ if rejected:
+ return {
+ "key": key,
+ "error": (
+ "These are inherently-public search engines and cannot be "
+ "trusted as contained: " + ", ".join(rejected) + "."
+ ),
+ }
+ return None
+
+
+# The cross-field egress validators every settings-write route must run. Keep
+# the *list* here (single source of truth) so adding one doesn't require a
+# lockstep edit at each save route; each route only supplies its own response
+# shaping around ``first_egress_validation_error``.
+EGRESS_SETTINGS_VALIDATORS = (
+ validate_allowed_local_hostnames,
+ validate_trusted_search_engines,
+)
+
+
+def first_egress_validation_error(form_data, all_db_settings):
+ """Run the egress validators; return the first error dict, or ``None``."""
+ for _validator in EGRESS_SETTINGS_VALIDATORS:
+ err = _validator(form_data, all_db_settings)
+ if err is not None:
+ return err
+ return None
diff --git a/src/local_deep_research/security/egress/warnings.py b/src/local_deep_research/security/egress/warnings.py
index eb2c41d74b..d048795772 100644
--- a/src/local_deep_research/security/egress/warnings.py
+++ b/src/local_deep_research/security/egress/warnings.py
@@ -8,9 +8,9 @@ The audit identified three independent vectors that each deserve their
own banner:
1. **Public search egress enabled** — the active scope permits any public
- engine to fire. Loudest on a fresh install where the default scope is
- ``both``; suppressed via ``ui.egress_warnings_acknowledged`` so first-
- launch isn't a wall of red.
+ engine to fire. The default scope ``adaptive`` can resolve to a
+ public-allowing posture, so this fires on a fresh install too; suppressed
+ via the dismiss flag so first-launch isn't a wall of red.
2. **Cloud LLM enabled** — the user hasn't opted into
``llm.require_local_endpoint`` and the configured provider is one of
the unambiguously-cloud providers. Critical-severity because the
@@ -34,8 +34,9 @@ def check_public_egress_enabled(
) -> Optional[dict]:
"""Banner when the active scope permits public-internet search engines.
- Fires for ``both`` and ``public_only`` (the two scopes that allow
- public engines). Suppressed when the user has acknowledged the
+ Fires for ``adaptive`` (which can resolve to a public posture), ``both``,
+ and ``public_only`` — the scopes that can allow public engines. Suppressed
+ when the user has acknowledged the
egress-policy warnings via the fresh-install flag — otherwise every
new install would face three loud banners before doing anything.
"""
@@ -62,6 +63,72 @@ def check_public_egress_enabled(
}
+def check_unprotected_egress(egress_scope: str) -> Optional[dict]:
+ """Loud, non-dismissible banner when egress protection is turned off.
+
+ The ``unprotected`` escape hatch disables all egress-scope restrictions
+ for the run — any engine / URL / LLM / embeddings provider is permitted
+ (only the hard SSRF and cloud-metadata blocks remain). Deliberately not
+ dismissible: the user should never forget protection is off.
+ """
+ if (egress_scope or "").lower() != "unprotected":
+ return None
+
+ return {
+ "type": "egress_unprotected",
+ "icon": "⚠️",
+ "title": "Egress protection is disabled",
+ "message": (
+ "Egress Scope is set to 'Unprotected' — this run may reach any "
+ "search engine, URL, and LLM/embeddings provider. Only hard SSRF "
+ "and cloud-metadata blocking still applies. Pick another scope "
+ "below to re-enable protection."
+ ),
+ "dismissKey": None,
+ "actionUrl": "#policy_egress_scope",
+ "actionLabel": "Adjust scope",
+ }
+
+
+def check_trusted_destinations(
+ trusted_inference, trusted_engines
+) -> Optional[dict]:
+ """Banner when the user has vouched for off-machine destinations.
+
+ Trusting an inference provider or search engine relaxes the two-axis
+ classification (treats an off-machine sink as contained), so sensitive
+ sources may flow to it. Surfaced so a stale trust entry can't silently keep
+ sending data off-box.
+ """
+ from .policy import coerce_str_list
+
+ names = sorted(
+ {
+ n
+ for n in coerce_str_list(trusted_inference)[1]
+ + coerce_str_list(trusted_engines)[1]
+ if n.strip()
+ }
+ )
+ if not names:
+ return None
+
+ return {
+ "type": "egress_trusted_destinations",
+ "icon": "🤝",
+ "title": "Trusted destinations configured",
+ "message": (
+ "These off-machine destinations are marked trusted, so sensitive "
+ "sources may be combined with them: "
+ + ", ".join(names)
+ + ". Remove any you did not intend."
+ ),
+ "dismissKey": None,
+ "actionUrl": "#policy_egress_scope",
+ "actionLabel": "Review",
+ }
+
+
def check_effective_scope(
egress_scope: str,
effective_scope: str,
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index 5b066174af..6afe087264 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -329,6 +329,64 @@ def _precheck_engine_policy(settings_manager, params, search_engine, username):
),
400,
)
+
+ # Stage C (ADR-0007): enforce the two-axis (sensitivity x exposure)
+ # admissibility as defense-in-depth on top of the scope check. This is
+ # a fast pre-start 400 for the API path; the same rule is also enforced
+ # at the shared run chokepoint in run_research_process, so follow-up /
+ # chat / queue runs are covered too. Under the UNPROTECTED escape hatch
+ # audit_run evaluates in permissive mode (always allowed), so an
+ # explicitly-unprotected run is never blocked. On an internal error
+ # audit_run fails CLOSED (reason "audit_error") so the run is refused
+ # visibly rather than silently degrading to the scope PEPs.
+ #
+ # NOTE: this sees the run's PRIMARY engine only. The per-engine scope
+ # PEP still runs for expanded engines, but it enforces SCOPE, not the
+ # two-axis rule — so a non-primary sensitive engine reaching a cloud
+ # sink under a permissive scope (legacy `both`) is not caught here.
+ # Widening to the full resolved engine set is a follow-up.
+ from ...security.egress.run_classification import (
+ audit_run_from_snapshot,
+ )
+
+ # Same shared entry point the worker chokepoint uses, so both resolve
+ # providers identically (LLM override wins over the snapshot; embeddings
+ # only for RAG primaries) and fail closed the same way.
+ two_axis = audit_run_from_snapshot(
+ policy_snapshot,
+ policy_ctx,
+ search_engine,
+ llm_provider=params.get("model_provider"),
+ )
+ if not two_axis.allowed:
+ logger.bind(policy_audit=True).warning(
+ "POST /api/start_research two-axis egress refused",
+ reason=two_axis.reason,
+ offending=two_axis.offending,
+ )
+ if two_axis.reason == "audit_error":
+ message = (
+ "Egress policy could not verify this run, so it was "
+ "refused (fail-closed). Set Egress Scope to 'Unprotected' "
+ "to override."
+ )
+ else:
+ message = (
+ "Egress policy refused this run: a sensitive source would "
+ f"reach an exposing destination ({two_axis.reason}). Use "
+ "local inference, mark the collection public, or set Egress "
+ "Scope to 'Unprotected' to override."
+ )
+ return (
+ jsonify(
+ {
+ "status": "error",
+ "message": message,
+ "reason": two_axis.reason,
+ }
+ ),
+ 400,
+ )
return None
except Exception:
# Policy module unavailable / internal error → log and fall
@@ -356,6 +414,10 @@ def _apply_policy_overrides(settings_snapshot, params):
settings_snapshot["embeddings.require_local"] = bool(
params["embeddings_require_local"]
)
+ # NOTE: the per-run `custom_endpoint` form value is deliberately NOT
+ # overlaid onto llm.openai_endpoint.url — that kwarg is non-functional
+ # (config/llm_config.py) and the run reads the URL from the DB setting, so
+ # the snapshot already carries the endpoint the run actually uses.
def _research_not_found(research_id, message="Research not found"):
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index bbf7837845..458c1b7f62 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -68,7 +68,7 @@ from ...utilities.url_utils import normalize_url
from ...security.decorators import require_json_body
from ...security.egress.policy import DEFAULT_EGRESS_SCOPE
from ...security.egress.validators import (
- validate_allowed_local_hostnames,
+ first_egress_validation_error,
)
from ..auth.decorators import login_required
from ..utils.request_helpers import parse_bool_arg
@@ -422,12 +422,11 @@ def save_all_settings(
# Fetch all settings and remove non-editable keys
all_db_settings = _filter_editable_settings(form_data, db_session)
- # Reject public hostnames being added to the local-hosts allowlist.
- _hosts_err = validate_allowed_local_hostnames(
- form_data, all_db_settings
- )
- if _hosts_err is not None:
- validation_errors.append(_hosts_err)
+ # Reject public hostnames being added to the local-hosts allowlist, and
+ # inherently-public engines being added to the trusted-engines list.
+ _egress_err = first_egress_validation_error(form_data, all_db_settings)
+ if _egress_err is not None:
+ validation_errors.append(_egress_err)
return (
jsonify(
{
@@ -826,13 +825,10 @@ def save_settings(db_session: Optional[Session] = None, settings_manager=None):
# these; the POST fallback must too, or a JS-disabled client could
# whitelist a public hostname as "local", which the JSON route does
# not permit.
- for _policy_validator in (validate_allowed_local_hostnames,):
- _policy_err = _policy_validator(form_data, all_db_settings)
- if _policy_err is not None:
- flash(
- _policy_err.get("error", "Invalid policy setting"), "error"
- )
- return redirect(url_for("settings.settings_page"))
+ _policy_err = first_egress_validation_error(form_data, all_db_settings)
+ if _policy_err is not None:
+ flash(_policy_err.get("error", "Invalid policy setting"), "error")
+ return redirect(url_for("settings.settings_page"))
# Process each setting
for key, value in form_data.items():
@@ -1136,21 +1132,21 @@ def api_update_setting(key, db_session: Optional[Session] = None):
"policy.egress_scope",
"search.tool",
"llm.allowed_local_hostnames",
+ "policy.trusted_search_engines",
):
_all_db_settings = {
s.key: s for s in db_session.query(Setting).all()
}
- _form = {key: value}
- for _validator in (validate_allowed_local_hostnames,):
- _err = _validator(_form, _all_db_settings)
- if _err is not None:
- logger.bind(policy_audit=True).warning(
- "egress-policy setting rejected at "
- "api_update_setting",
- key=key,
- reason=_err.get("error"),
- )
- return jsonify({"error": _err["error"]}), 400
+ _err = first_egress_validation_error(
+ {key: value}, _all_db_settings
+ )
+ if _err is not None:
+ logger.bind(policy_audit=True).warning(
+ "egress-policy setting rejected at api_update_setting",
+ key=key,
+ reason=_err.get("error"),
+ )
+ return jsonify({"error": _err["error"]}), 400
# Update setting
# Pass the db_session to avoid session lookup issues
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 1abc59015a..7a4a11e3ab 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -964,6 +964,50 @@ def run_research_process(research_id, query, mode, **kwargs):
reason=str(_ctx_err),
)
raise
+
+ # Stage C (ADR-0007): enforce the two-axis (sensitivity x exposure)
+ # rule at this shared chokepoint too. The /api/start_research route
+ # applies it before the run starts, but follow-up / chat / queue
+ # runs reach the worker without that precheck — so evaluate it here,
+ # where every entry point flows through, reusing the context
+ # resolved just above. UNPROTECTED evaluates permissively (never
+ # blocks); on an internal error audit_run fails CLOSED (a denying
+ # decision) so the run is refused, not silently degraded. A refusal
+ # raises PolicyDeniedError, failing the run like the
+ # unevaluable-config path.
+ from ...security.egress.run_classification import (
+ audit_run_from_snapshot,
+ )
+
+ # Pass the run's per-request provider override (model_provider),
+ # which wins over the snapshot in get_llm — otherwise the check
+ # audits the stored default while the run builds the overridden
+ # (possibly cloud) provider.
+ #
+ # NOTE (search-engine axis): _egress_primary is resolved from the
+ # snapshot's search.tool, not the run's per-request search_engine
+ # kwarg. Every current entry point keeps these in sync — the route
+ # precheck audits the request engine directly, and follow-up/chat/
+ # queue derive search_engine FROM search.tool — so the audited and
+ # actual engines match today. A future caller that passes a
+ # per-request search_engine diverging from search.tool without the
+ # route precheck would audit the wrong engine; threading a
+ # search-engine override through here (as done for the LLM) is a
+ # follow-up, alongside widening to the full resolved engine set.
+ _two_axis = audit_run_from_snapshot(
+ settings_snapshot,
+ _egress_ctx,
+ _egress_primary,
+ llm_provider=model_provider,
+ )
+ if not _two_axis.allowed:
+ logger.bind(policy_audit=True).warning(
+ "research worker refused: two-axis egress",
+ research_id=research_id,
+ reason=_two_axis.reason,
+ offending=_two_axis.offending,
+ )
+ raise PolicyDeniedError(_two_axis, target=_egress_primary)
except ImportError:
# security module unavailable — preserve legacy behaviour.
logger.debug("egress audit hook unavailable for research worker")
@@ -2367,7 +2411,36 @@ def run_research_process(research_id, query, mode, **kwargs):
user_friendly_error = str(e)
error_context = {}
- if "Error type: ollama_unavailable" in user_friendly_error:
+ # Egress policy refusal (two-axis rule, or a fail-closed audit_error
+ # from the worker chokepoint) — surface the reason and the override
+ # instead of a generic "unexpected error".
+ from ...security.egress.policy import PolicyDeniedError
+
+ if isinstance(e, PolicyDeniedError):
+ _reason = getattr(e.decision, "reason", "") or "egress_denied"
+ if _reason == "audit_error":
+ user_friendly_error = (
+ "Egress policy could not verify this run, so it was "
+ "refused (fail-closed)."
+ )
+ elif _reason.startswith("sensitive_to_exposing"):
+ # The two-axis rule specifically: a sensitive source would
+ # reach an exposing sink.
+ user_friendly_error = (
+ "Egress policy refused this run: a sensitive source "
+ f"would reach an exposing destination ({_reason})."
+ )
+ else:
+ # Other egress PEPs (scope mismatch, require-local
+ # inference, etc.) — no "sensitive source" is necessarily
+ # involved, so don't claim one.
+ user_friendly_error = (
+ f"Egress policy refused this run ({_reason})."
+ )
+ error_context = {
+ "solution": "Set Egress Scope to 'Unprotected' to override, or use local inference / non-sensitive sources."
+ }
+ elif "Error type: ollama_unavailable" in user_friendly_error:
user_friendly_error = "Ollama AI service is unavailable. Please check that Ollama is running properly on your system."
error_context = {
"solution": "Start Ollama with 'ollama serve' or check if it's installed correctly."
diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.js
index b8e15c4294..48dab25511 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -2359,10 +2359,10 @@
if (!icon) return;
const iconClassByScope = {
adaptive: 'fas fa-shield-alt',
- both: 'fas fa-shield-alt',
public_only: 'fas fa-cloud',
private_only: 'fas fa-home',
strict: 'fas fa-bullseye',
+ unprotected: 'fas fa-unlock',
};
icon.className = iconClassByScope[normalized] || iconClassByScope.adaptive;
}
diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.js
index 2b7c232556..e94e1679c0 100644
--- a/src/local_deep_research/web/static/js/components/settings.js
+++ b/src/local_deep_research/web/static/js/components/settings.js
@@ -2190,6 +2190,7 @@
} else {
// Standard select for other keys
const selectOptions = [];
+ let valueMatched = false;
if (setting.options) {
setting.options.forEach(option => {
// Handle both string options and object options
@@ -2203,13 +2204,30 @@
optionValue = option;
optionLabel = option;
}
- const selected = optionValue === setting.value ? 'selected' : '';
+ const isSelected = optionValue === setting.value;
+ if (isSelected) {
+ valueMatched = true;
+ }
+ const selected = isSelected ? 'selected' : '';
// Escape HTML to prevent XSS attacks
selectOptions.push(
`<option value="${escapeHtml(optionValue)}" ${selected}>${escapeHtml(optionLabel)}</option>`
);
});
}
+ // If the stored value isn't among the current options (e.g. a
+ // deprecated value like the removed "both" egress scope),
+ // surface it as a selected option. Otherwise the control shows
+ // the first option while a different value is still enforced,
+ // and "Save All" would silently rewrite it. Only when a real
+ // options list exists — a select with no catalog (options
+ // null) shouldn't get a lone synthetic "(current)" entry.
+ if (setting.options && !valueMatched && setting.value !== undefined
+ && setting.value !== null && setting.value !== '') {
+ selectOptions.push(
+ `<option value="${escapeHtml(setting.value)}" selected>${escapeHtml(setting.value)} (current)</option>`
+ );
+ }
inputElement = `
<select id="${settingId}" name="${setting.key}"
class="ldr-settings-select ldr-form-control"
diff --git a/src/local_deep_research/web/static/js/research_form.js b/src/local_deep_research/web/static/js/research_form.js
index 3c87c8a40a..45cd12c679 100644
--- a/src/local_deep_research/web/static/js/research_form.js
+++ b/src/local_deep_research/web/static/js/research_form.js
@@ -293,6 +293,22 @@ function displayWarnings(warnings) {
<span aria-hidden="true">→</span>
</a>`
: '';
+ // Only render the dismiss control for warnings that declare a
+ // dismissKey. Banners with dismissKey == null are deliberately
+ // non-dismissible; rendering the button would call dismissWarning('null')
+ // and POST a bogus "null" settings key.
+ const dismissHtml = warning.dismissKey
+ ? `<button onclick="dismissWarning('${esc(warning.dismissKey)}')" style="
+ background: none;
+ border: none;
+ color: inherit;
+ cursor: pointer;
+ padding: 4px;
+ font-size: 16px;
+ flex-shrink: 0;
+ opacity: 0.7;
+ ">&times;</button>`
+ : '';
return `
<div class="ldr-alert ${alertClass} warning-banner warning-${esc(warning.type)}" style="
border-radius: 6px;
@@ -312,16 +328,7 @@ function displayWarnings(warnings) {
</div>
${actionHtml}
</div>
- <button onclick="dismissWarning('${esc(warning.dismissKey)}')" style="
- background: none;
- border: none;
- color: inherit;
- cursor: pointer;
- padding: 4px;
- font-size: 16px;
- flex-shrink: 0;
- opacity: 0.7;
- ">&times;</button>
+ ${dismissHtml}
</div>
`;
}).join('');
diff --git a/src/local_deep_research/web/templates/base.html b/src/local_deep_research/web/templates/base.html
index 7deccdebc9..3bb06d430c 100644
--- a/src/local_deep_research/web/templates/base.html
+++ b/src/local_deep_research/web/templates/base.html
@@ -60,18 +60,24 @@
the dropdown changes (see static/js/components/research.js).
Palette:
- BOTH → no left-border accent (default state, no extra cue)
+ ADAPTIVE → no left-border accent (default; posture follows the
+ primary engine, so there is no fixed cue)
PUBLIC_ONLY → blue #3b82f6 (informational "public sources only")
PRIVATE_ONLY → teal #14a37f (privacy mode)
STRICT → violet #8b5cf6 (locked to a single engine)
- Risk ordering (data exfil): BOTH > PUBLIC_ONLY > STRICT/PRIVATE_ONLY.
- BOTH is the riskiest because it permits local engines AND a cloud
- LLM in the same run — local-data-to-cloud leakage happens through
- the LLM call, not the search egress itself. PUBLIC_ONLY blocks
- local engines so local data never enters the pipeline; that
- active choice is informational (blue), not a deeper warning.
- The "Public search egress enabled" banner does the actual nag.
- Red intentionally avoided.
+ UNPROTECTED → no accent on this card; its caution cue is the
+ light-red Privacy & Egress panel on the research
+ form (research.html) plus a non-dismissible banner.
+ A residual/legacy `both` is coerced to `adaptive` before render, so it
+ also falls through to the no-accent default below.
+ Risk ordering (data exfil): UNPROTECTED > PUBLIC_ONLY > STRICT/PRIVATE_ONLY.
+ UNPROTECTED is the riskiest — it disables egress-scope enforcement and
+ lifts the forced-local inference coupling. ADAPTIVE (default) carries no
+ fixed accent because its real posture depends on the primary engine.
+ PUBLIC_ONLY blocks local engines so local data never enters the
+ pipeline; that active choice is informational (blue), not a deeper
+ warning. The egress banners do the actual nag. Red intentionally
+ avoided on the card itself.
-->
<style>
.ldr-card.ldr-research-card,
@@ -84,9 +90,10 @@
#chat-input {
transition: border-color 0.2s ease, box-shadow 0.2s ease;
}
- /* BOTH (default) has NO body[data-scope] rule — the
- transparent left border above stays, the textarea uses its
- default border, and the warning banner does the nagging. */
+ /* ADAPTIVE (default) and UNPROTECTED have NO body[data-scope] rule —
+ the transparent left border above stays, the textarea uses its
+ default border, and the egress banners do the nagging. (A legacy
+ `both` is coerced to `adaptive`, so it lands here too.) */
body[data-scope="public_only"] .ldr-card.ldr-research-card,
body[data-scope="public_only"] #chat-page,
body[data-scope="public_only"] .ldr-chat-container {
@@ -161,7 +168,7 @@
{% block extra_head %}{% endblock %}
</head>
-<body data-scope="{{ egress_scope or 'both' }}">
+<body data-scope="{{ egress_scope or 'adaptive' }}">
<!-- Skip to content link for keyboard/screen reader users -->
<a href="#main-content" class="ldr-skip-link">Skip to main content</a>
diff --git a/src/local_deep_research/web/templates/pages/collection_create.html b/src/local_deep_research/web/templates/pages/collection_create.html
index 798db4992b..18cbfb6ff7 100644
--- a/src/local_deep_research/web/templates/pages/collection_create.html
+++ b/src/local_deep_research/web/templates/pages/collection_create.html
@@ -51,7 +51,9 @@
Leave unchecked (default) for <strong>private</strong> collections: they
stay off the public internet under Public-only / Adaptive egress scope and
force local LLM/embeddings inference when used, so their contents never
- reach a cloud model. Check this only for non-sensitive content you're happy
+ reach a cloud model. Marking a collection public never uploads or exposes
+ its documents — they always stay local; it only permits cloud inference
+ over them. Check this only for non-sensitive content you're happy
to process with cloud inference.
</div>
</div>
diff --git a/src/local_deep_research/web/templates/pages/collection_details.html b/src/local_deep_research/web/templates/pages/collection_details.html
index 6ab7f0cb06..52bbfc9c0c 100644
--- a/src/local_deep_research/web/templates/pages/collection_details.html
+++ b/src/local_deep_research/web/templates/pages/collection_details.html
@@ -56,8 +56,9 @@
<div class="ldr-form-help" id="collection-is-public-help">
<strong>Private</strong> (default): excluded from runs under Public-only / Adaptive-public
egress scope, and forces local LLM/embeddings inference when used — its contents never
- reach a cloud model. Check this only for non-sensitive content you're happy to process
- with cloud inference.
+ reach a cloud model. Marking a collection public never uploads or exposes its documents —
+ they always stay local; it only permits cloud inference over them. Check this only for
+ non-sensitive content you're happy to process with cloud inference.
<a href="https://github.com/LearningCircuit/local-deep-research/blob/main/docs/egress-modes.md#per-collection-publicprivate" target="_blank" rel="noopener noreferrer">Learn more &#8599;</a>
</div>
</div>
diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.html
index 395042b842..c0ecedafc5 100644
--- a/src/local_deep_research/web/templates/pages/research.html
+++ b/src/local_deep_research/web/templates/pages/research.html
@@ -101,6 +101,9 @@
.ldr-privacy-panel[data-scope="private_only"] .ldr-privacy-panel-header { color:#0f7a5f; }
.ldr-privacy-panel[data-scope="strict"] { border-color:#8b5cf6; background:rgba(139, 92, 246, 0.07); }
.ldr-privacy-panel[data-scope="strict"] .ldr-privacy-panel-header { color:#a78bfa; }
+ /* Unprotected = escape hatch: light-red frame as a caution cue. */
+ .ldr-privacy-panel[data-scope="unprotected"] { border-color:#e05252; background:rgba(224, 82, 82, 0.08); }
+ .ldr-privacy-panel[data-scope="unprotected"] .ldr-privacy-panel-header { color:#e05252; }
/* Local-inference checkboxes adopt the "local = teal" cue when on. */
.ldr-privacy-panel input[type="checkbox"] { accent-color:#14a37f; }
.ldr-experimental-badge { font-size:0.8rem; font-weight:600; color:#d9a441; border:1px solid rgba(217, 164, 65, 0.4); border-radius:4px; padding:0.05rem 0.35rem; margin-left:0.4rem; vertical-align:middle; text-transform:uppercase; letter-spacing:0.02em; cursor:help; }
@@ -116,13 +119,13 @@
</div>
<div class="ldr-form-row" style="margin:0;">
<div class="ldr-form-group ldr-half">
- <label for="policy_egress_scope">{{ tooltip("Egress Scope", "Adaptive (default): follows your primary engine — a private primary keeps everything local, a public primary allows public engines. Public + private: any classified engine. Public only: any public web/academic engine, no local sources. Private only: only local engines (library, paperless, etc.). Primary only: the selected search engine and nothing else.") }}</label>
+ <label for="policy_egress_scope">{{ tooltip("Egress Scope", "Adaptive (default): follows your primary engine — a private primary keeps everything local, a public primary allows public engines. Public only: any public web/academic engine, no local sources. Private only: only local engines (library, paperless, etc.). Primary only: the selected search engine and nothing else. Unprotected: disables egress protection entirely — not recommended (hard SSRF/cloud-metadata blocking still applies).") }}</label>
<select id="policy_egress_scope" name="policy_egress_scope" class="ldr-form-control">
<option value="adaptive" {% if not settings.policy_egress_scope or settings.policy_egress_scope == "adaptive" %}selected{% endif %}>Adaptive (default — follows primary)</option>
- <option value="both" {% if settings.policy_egress_scope == "both" %}selected{% endif %}>Public + private (any engine)</option>
<option value="public_only" {% if settings.policy_egress_scope == "public_only" %}selected{% endif %}>Public only (no local)</option>
<option value="private_only" {% if settings.policy_egress_scope == "private_only" %}selected{% endif %}>Private only (no internet)</option>
<option value="strict" {% if settings.policy_egress_scope == "strict" %}selected{% endif %}>Primary only (single engine)</option>
+ <option value="unprotected" {% if settings.policy_egress_scope == "unprotected" %}selected{% endif %}>Unprotected (no protection — not recommended)</option>
</select>
<span class="ldr-input-help" id="policy_egress_scope_help">Limits which search engines this run may use. <a href="https://github.com/LearningCircuit/local-deep-research/blob/main/docs/egress-modes.md" target="_blank" rel="noopener noreferrer">What does each mode do? &#8599;</a></span>
</div>
@@ -138,7 +141,7 @@
</label>
</div>
</div>
- <span class="ldr-input-help" style="display:block; margin-top:0.5rem;">These controls decide what data leaves your machine for this run. They override the corresponding global settings just for this research. Configure the model and search engine in Advanced Options below.</span>
+ <span class="ldr-input-help" style="display:block; margin-top:0.5rem;">These controls decide what data leaves your machine for this run. They override the corresponding global settings just for this research. Configure the model and search engine in Advanced Options below. <strong>Your question itself is sent to any public search engines this run uses</strong> — we can't protect query content, so choose sources appropriate to how sensitive your question is.</span>
</div>
</div>
diff --git a/src/local_deep_research/web/warning_checks/__init__.py b/src/local_deep_research/web/warning_checks/__init__.py
index 5faf824fbf..647d9eba7e 100644
--- a/src/local_deep_research/web/warning_checks/__init__.py
+++ b/src/local_deep_research/web/warning_checks/__init__.py
@@ -32,6 +32,8 @@ from ...security.egress.warnings import (
check_cloud_llm_enabled,
check_effective_scope,
check_public_egress_enabled,
+ check_trusted_destinations,
+ check_unprotected_egress,
)
from ...constants import DEFAULT_SEARCH_TOOL
@@ -140,6 +142,12 @@ def calculate_warnings() -> List[dict]:
primary_engine = settings_manager.get_setting(
"search.tool", DEFAULT_SEARCH_TOOL
)
+ trusted_inference = settings_manager.get_setting(
+ "policy.trusted_inference_providers", []
+ )
+ trusted_search = settings_manager.get_setting(
+ "policy.trusted_search_engines", []
+ )
# Resolve the EFFECTIVE posture so the banners are accurate. For
# `adaptive`, this turns the opaque "follows the primary" into a
@@ -226,6 +234,18 @@ def calculate_warnings() -> List[dict]:
if w:
warnings.append(w)
+ # Loud, non-dismissible banner when protection is turned off.
+ w = _safe_check(check_unprotected_egress, egress_scope)
+ if w:
+ warnings.append(w)
+
+ # Trusted off-machine destinations (stage D) relax classification.
+ w = _safe_check(
+ check_trusted_destinations, trusted_inference, trusted_search
+ )
+ if w:
+ warnings.append(w)
+
w = _safe_check(
check_cloud_llm_enabled,
provider,
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
index 08cd3a5e18..d5f118c9bf 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
@@ -6,7 +6,7 @@ from loguru import logger
from ...constants import SNIPPET_LENGTH_SHORT
from ..rate_limiting import RateLimitError
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
class ArXivSearchEngine(BaseSearchEngine):
@@ -14,6 +14,8 @@ class ArXivSearchEngine(BaseSearchEngine):
# Mark as public search engine
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
# Not a generic search engine (specialized for academic papers)
is_generic = False
# Scientific/academic search engine
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_brave.py b/src/local_deep_research/web_search_engines/engines/search_engine_brave.py
index f31bcb317f..c1477f4fe4 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_brave.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_brave.py
@@ -5,7 +5,7 @@ from langchain_core.language_models import BaseLLM
from loguru import logger
from ..rate_limiting import RateLimitError
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
class BraveSearchEngine(BaseSearchEngine):
@@ -13,6 +13,8 @@ class BraveSearchEngine(BaseSearchEngine):
# Mark as public search engine
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
# Mark as generic search engine (general web search)
is_generic = True
# secrets to redact from error messages (see BaseSearchEngine._scrub_error)
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py b/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py
index ba8197d37e..5c2631f3cc 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py
@@ -5,7 +5,7 @@ from langchain_core.language_models import BaseLLM
from loguru import logger
from ..rate_limiting import RateLimitError
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
class DuckDuckGoSearchEngine(BaseSearchEngine):
@@ -13,6 +13,8 @@ class DuckDuckGoSearchEngine(BaseSearchEngine):
# Mark as public search engine
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
# Mark as generic search engine (general web search)
is_generic = True
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py
index d2532d31f3..72ef711a94 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py
@@ -5,7 +5,7 @@ from elasticsearch import Elasticsearch
from langchain_core.language_models import BaseLLM
from ...constants import SNIPPET_LENGTH_SHORT
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
from ...constants import DEFAULT_SEARCH_TOOL
@@ -15,6 +15,11 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
is_local = True
is_lexical = True
needs_llm_relevance_filter = True
+ # Egress (ADR-0007): a local document store — sensitive, contained. The
+ # url_setting fail-up reclassifies exposure to EXPOSING when hosts resolve
+ # public (quadrant 4: usable only by itself, contained inference).
+ egress_sensitivity = Sensitivity.SENSITIVE
+ egress_exposure = Exposure.CONTAINED
# secrets to redact from error messages (see BaseSearchEngine._scrub_error)
_secret_attrs = ("_api_key", "_password")
# url_setting feeds the PDP's fail-up URL override: when the configured
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_exa.py b/src/local_deep_research/web_search_engines/engines/search_engine_exa.py
index a364edc035..f371c130fb 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_exa.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_exa.py
@@ -6,7 +6,7 @@ from loguru import logger
from ...security.safe_requests import safe_post
from ..rate_limiting import RateLimitError
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
class ExaSearchEngine(BaseSearchEngine):
@@ -14,6 +14,8 @@ class ExaSearchEngine(BaseSearchEngine):
# Mark as public search engine
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
# Mark as generic search engine (general web search)
is_generic = True
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_github.py b/src/local_deep_research/web_search_engines/engines/search_engine_github.py
index 2dcc6ba733..74e5f7341c 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_github.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_github.py
@@ -10,7 +10,7 @@ from ...config import llm_config
from ...constants import USER_AGENT
from ...security.safe_requests import safe_get
from ...utilities.json_utils import extract_json, get_llm_response_text
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
_VALID_SEARCH_TYPES = frozenset({"repositories", "code", "issues", "users"})
@@ -23,6 +23,8 @@ class GitHubSearchEngine(BaseSearchEngine):
"""
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
is_code = True
is_lexical = True
needs_llm_relevance_filter = True
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py b/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py
index f7c7917b99..4698b99f7c 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py
@@ -8,7 +8,7 @@ from requests.exceptions import RequestException
from ...security.safe_requests import safe_get
from ..rate_limiting import RateLimitError
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
class GooglePSESearchEngine(BaseSearchEngine):
@@ -16,6 +16,8 @@ class GooglePSESearchEngine(BaseSearchEngine):
# Mark as public search engine
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
# Mark as generic search engine (general web search)
is_generic = True
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py b/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py
index 2ecbaea79d..90f2fca4df 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py
@@ -7,7 +7,7 @@ from loguru import logger
from ...utilities.search_utilities import remove_think_tags
from ...security.safe_requests import safe_get
from ..rate_limiting import RateLimitError
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
class GuardianSearchEngine(BaseSearchEngine):
@@ -15,6 +15,8 @@ class GuardianSearchEngine(BaseSearchEngine):
# Mark as public search engine
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
def __init__(
self,
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_gutenberg.py b/src/local_deep_research/web_search_engines/engines/search_engine_gutenberg.py
index 06e4f8ebf5..929d7faaf8 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_gutenberg.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_gutenberg.py
@@ -9,7 +9,7 @@ from loguru import logger
from ...constants import USER_AGENT
from ...security.safe_requests import safe_get
from ..rate_limiting import RateLimitError
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
class GutenbergSearchEngine(BaseSearchEngine):
@@ -21,6 +21,8 @@ class GutenbergSearchEngine(BaseSearchEngine):
"""
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
is_generic = False
is_scientific = False
is_books = True
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_library.py b/src/local_deep_research/web_search_engines/engines/search_engine_library.py
index d1b2ee90ce..131a0575af 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_library.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_library.py
@@ -8,7 +8,7 @@ import os
from typing import List, Dict, Any, Optional
from loguru import logger
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
from ...constants import SNIPPET_LENGTH_LONG
from ...research_library.services.library_rag_service import LibraryRAGService
from ...research_library.services.library_service import LibraryService
@@ -29,6 +29,10 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
# Mark as local RAG engine
is_local = True
+ # Egress (ADR-0007): a local document store — sensitive data, kept on-box.
+ egress_sensitivity = Sensitivity.SENSITIVE
+ egress_exposure = Exposure.CONTAINED
+
def __init__(
self,
llm: Optional[Any] = None,
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_mojeek.py b/src/local_deep_research/web_search_engines/engines/search_engine_mojeek.py
index 585a5a2d05..d30b927255 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_mojeek.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_mojeek.py
@@ -5,7 +5,7 @@ from loguru import logger
from ...security.safe_requests import safe_get
from ..rate_limiting import RateLimitError
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
class MojeekSearchEngine(BaseSearchEngine):
@@ -18,6 +18,8 @@ class MojeekSearchEngine(BaseSearchEngine):
# Mark as public search engine
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
# Mark as generic search engine (general web search)
is_generic = True
is_lexical = True
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py b/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py
index 4d04860cdf..8742b2a3b4 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py
@@ -8,7 +8,7 @@ from loguru import logger
from ...constants import SNIPPET_LENGTH_LONG, USER_AGENT
from ...security.safe_requests import safe_get
from ..rate_limiting import RateLimitError
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
class NasaAdsSearchEngine(BaseSearchEngine):
@@ -16,6 +16,8 @@ class NasaAdsSearchEngine(BaseSearchEngine):
# Mark as public search engine
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
# Scientific/astronomy/astrophysics search engine
is_scientific = True
is_lexical = True
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py b/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py
index 3740923f6a..71dcc7679b 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py
@@ -8,7 +8,7 @@ from loguru import logger
from ...constants import SNIPPET_LENGTH_LONG, USER_AGENT
from ...security.safe_requests import safe_get
from ..rate_limiting import RateLimitError
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
class OpenAlexSearchEngine(BaseSearchEngine):
@@ -16,6 +16,8 @@ class OpenAlexSearchEngine(BaseSearchEngine):
# Mark as public search engine
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
# Scientific/academic search engine
is_scientific = True
is_lexical = True
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_openlibrary.py b/src/local_deep_research/web_search_engines/engines/search_engine_openlibrary.py
index 3cacdea7b0..825e5c714d 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_openlibrary.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_openlibrary.py
@@ -10,7 +10,7 @@ from loguru import logger
from ...constants import USER_AGENT
from ...security.safe_requests import safe_get
from ..rate_limiting import RateLimitError
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
class OpenLibrarySearchEngine(BaseSearchEngine):
@@ -22,6 +22,8 @@ class OpenLibrarySearchEngine(BaseSearchEngine):
"""
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
is_generic = False
is_scientific = False
is_books = True # New category for book search
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_paperless.py b/src/local_deep_research/web_search_engines/engines/search_engine_paperless.py
index b62973ff62..eb8c644def 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_paperless.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_paperless.py
@@ -14,7 +14,7 @@ from urllib.parse import urljoin
from langchain_core.language_models import BaseLLM
from loguru import logger
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
from ...security import safe_get
@@ -24,6 +24,11 @@ class PaperlessSearchEngine(BaseSearchEngine):
is_local = True
is_lexical = True
needs_llm_relevance_filter = True
+ # Egress (ADR-0007): a local document store — sensitive, contained. The
+ # url_setting fail-up reclassifies exposure to EXPOSING when api_url is a
+ # public host (quadrant 4: usable only by itself, contained inference).
+ egress_sensitivity = Sensitivity.SENSITIVE
+ egress_exposure = Exposure.CONTAINED
# secrets to redact from error messages (see BaseSearchEngine._scrub_error)
_secret_attrs = ("api_token",)
# url_setting feeds the PDP's fail-up URL override: if the configured
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_pubchem.py b/src/local_deep_research/web_search_engines/engines/search_engine_pubchem.py
index f78680b887..7e89388018 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_pubchem.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_pubchem.py
@@ -9,7 +9,7 @@ from loguru import logger
from ...constants import USER_AGENT
from ...security.safe_requests import safe_get
from ..rate_limiting import RateLimitError
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
class PubChemSearchEngine(BaseSearchEngine):
@@ -21,6 +21,8 @@ class PubChemSearchEngine(BaseSearchEngine):
"""
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
is_generic = False
is_scientific = True
is_code = False
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py
index 9c1547f4e6..4b4b2ae2af 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py
@@ -9,7 +9,7 @@ from loguru import logger
from ...constants import SNIPPET_LENGTH_LONG
from ...security.safe_requests import safe_get
from ..rate_limiting import RateLimitError
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
class PubMedSearchEngine(BaseSearchEngine):
@@ -20,6 +20,8 @@ class PubMedSearchEngine(BaseSearchEngine):
# Mark as public search engine
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
# Scientific/medical search engine
is_scientific = True
is_lexical = True
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_scaleserp.py b/src/local_deep_research/web_search_engines/engines/search_engine_scaleserp.py
index 3d8900abd9..7fb08bc9db 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_scaleserp.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_scaleserp.py
@@ -4,7 +4,7 @@ import requests
from langchain_core.language_models import BaseLLM
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
from ..rate_limiting import RateLimitError
from ...security import safe_get
@@ -14,6 +14,8 @@ class ScaleSerpSearchEngine(BaseSearchEngine):
# Mark as public search engine
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
# Mark as generic search engine (general web search via Google)
is_generic = True
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
index fc86bfd797..3647e60400 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
@@ -8,7 +8,7 @@ from langchain_core.language_models import BaseLLM
from loguru import logger
from ...security.safe_requests import safe_get
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
@enum.unique
@@ -31,6 +31,8 @@ class SearXNGSearchEngine(BaseSearchEngine):
# Mark as public search engine
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
# Mark as generic search engine (general web search)
is_generic = True
# The egress engine-selection gate uses the static is_public flag above —
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py b/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py
index 9436cfc2ff..0b6e2b602d 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py
@@ -9,7 +9,7 @@ from urllib3.util import Retry
from ...constants import SNIPPET_LENGTH_SHORT
from ..rate_limiting import RateLimitError
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
from ...security import SafeSession
@@ -21,6 +21,8 @@ class SemanticScholarSearchEngine(BaseSearchEngine):
# Mark as public search engine
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
# Scientific/academic search engine
is_scientific = True
is_lexical = True
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py b/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py
index 16917b2136..44206b2ad2 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py
@@ -5,7 +5,7 @@ from langchain_community.utilities import SerpAPIWrapper
from langchain_core.language_models import BaseLLM
from ..rate_limiting import RateLimitError
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
class SerpAPISearchEngine(BaseSearchEngine):
@@ -13,6 +13,8 @@ class SerpAPISearchEngine(BaseSearchEngine):
# Mark as public search engine
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
# Mark as generic search engine (general web search via Google)
is_generic = True
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_serper.py b/src/local_deep_research/web_search_engines/engines/search_engine_serper.py
index 8f079b9121..dfe6b90559 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_serper.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_serper.py
@@ -4,7 +4,7 @@ import requests
from langchain_core.language_models import BaseLLM
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
from ..rate_limiting import RateLimitError
from ...security import safe_post
@@ -14,6 +14,8 @@ class SerperSearchEngine(BaseSearchEngine):
# Mark as public search engine
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
# Mark as generic search engine (general web search via Google)
is_generic = True
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_stackexchange.py b/src/local_deep_research/web_search_engines/engines/search_engine_stackexchange.py
index b8038186dd..ad633db4b8 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_stackexchange.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_stackexchange.py
@@ -12,7 +12,7 @@ from loguru import logger
from ...constants import USER_AGENT
from ...security.safe_requests import safe_get
from ..rate_limiting import RateLimitError
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
class StackExchangeSearchEngine(BaseSearchEngine):
@@ -24,6 +24,8 @@ class StackExchangeSearchEngine(BaseSearchEngine):
"""
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
is_generic = False
is_scientific = False
is_code = True
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py b/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py
index 6b85cdd259..0d70dd9c73 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py
@@ -6,7 +6,7 @@ from loguru import logger
from ...security.safe_requests import safe_post
from ..rate_limiting import RateLimitError
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
class TavilySearchEngine(BaseSearchEngine):
@@ -14,6 +14,8 @@ class TavilySearchEngine(BaseSearchEngine):
# Mark as public search engine
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
# Mark as generic search engine (general web search)
is_generic = True
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_tinyfish.py b/src/local_deep_research/web_search_engines/engines/search_engine_tinyfish.py
index 0c2e9cca5c..2b72cca5e5 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_tinyfish.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_tinyfish.py
@@ -7,13 +7,15 @@ from loguru import logger
from ...security import safe_get, safe_post
from ..rate_limiting import RateLimitError
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
class TinyFishSearchEngine(BaseSearchEngine):
"""TinyFish Search + Fetch API search engine implementation."""
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
is_generic = True
SEARCH_URL = "https://api.search.tinyfish.ai"
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py b/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
index 767930b48c..6e0bf78472 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
@@ -7,7 +7,7 @@ from loguru import logger
from ...research_library.downloaders.extraction import extract_content
from ...security.safe_requests import safe_get
from ..rate_limiting import RateLimitError
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
class WaybackSearchEngine(BaseSearchEngine):
@@ -18,6 +18,8 @@ class WaybackSearchEngine(BaseSearchEngine):
# Mark as public search engine
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
def __init__(
self,
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wikinews.py b/src/local_deep_research/web_search_engines/engines/search_engine_wikinews.py
index d758935221..a9946b6800 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_wikinews.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wikinews.py
@@ -11,7 +11,7 @@ from loguru import logger
from ...constants import USER_AGENT
from ...utilities.json_utils import extract_json, get_llm_response_text
from ...utilities.search_utilities import remove_think_tags, LANGUAGE_CODE_MAP
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
from ...security import safe_get
HEADERS = {"User-Agent": USER_AGENT}
@@ -49,6 +49,8 @@ class WikinewsSearchEngine(BaseSearchEngine):
# Mark as public and news search engine
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
is_news = True
is_lexical = True
needs_llm_relevance_filter = True
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py b/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py
index 378abe9063..7b8a3f2a97 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py
@@ -6,7 +6,7 @@ import wikipedia
from langchain_core.language_models import BaseLLM
from loguru import logger
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
# Wikipedia / MediaWiki returns a non-JSON HTML body with HTTP 429 when a
@@ -27,6 +27,8 @@ class WikipediaSearchEngine(BaseSearchEngine):
# Mark as public search engine
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
is_lexical = True
needs_llm_relevance_filter = True
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_zenodo.py b/src/local_deep_research/web_search_engines/engines/search_engine_zenodo.py
index 74acce1371..826a82f3de 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_zenodo.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_zenodo.py
@@ -11,7 +11,7 @@ from loguru import logger
from ...constants import USER_AGENT
from ...security.safe_requests import safe_get
from ..rate_limiting import RateLimitError
-from ..search_engine_base import BaseSearchEngine
+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
class ZenodoSearchEngine(BaseSearchEngine):
@@ -23,6 +23,8 @@ class ZenodoSearchEngine(BaseSearchEngine):
"""
is_public = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
is_generic = False
is_scientific = True
is_code = False
diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.py
index 60dca8ac0e..0b93092e51 100644
--- a/src/local_deep_research/web_search_engines/search_engine_base.py
+++ b/src/local_deep_research/web_search_engines/search_engine_base.py
@@ -19,6 +19,7 @@ from ..utilities.type_utils import unwrap_setting
from ..config.constants import DEFAULT_MAX_FILTERED_RESULTS
from ..config.thread_settings import get_setting_from_snapshot
from ..security.log_sanitizer import redact_secrets, sanitize_error_message
+from ..security.egress.classification import Exposure, Sensitivity
from ..utilities.thread_context import clear_search_context, set_search_context
from .rate_limiting import RateLimitError, get_tracker
@@ -127,6 +128,16 @@ class BaseSearchEngine(ABC):
# Local engines search private document collections stored locally
is_local = False
+ # Egress data classification (ADR-0007). Two orthogonal axes, declared
+ # explicitly per engine alongside is_public/is_local. The defaults fail
+ # closed: an engine that forgets to classify itself is treated as the most
+ # restrictive quadrant (sensitive data + exposing sink → usable only by
+ # itself). Engines whose label depends on configuration (a collection's
+ # is_public flag, a self-hosted store's URL) are refined by the classifier
+ # at run time; these constants are the static fallback.
+ egress_sensitivity = Sensitivity.SENSITIVE
+ egress_exposure = Exposure.EXPOSING
+
# Class attribute to indicate if this is a news search engine
# News engines specialize in news articles and current events
is_news = False
diff --git a/tests/database/test_alembic_migrations.py b/tests/database/test_alembic_migrations.py
index d7a9f4df40..f4aa6a9a1b 100644
--- a/tests/database/test_alembic_migrations.py
+++ b/tests/database/test_alembic_migrations.py
@@ -6050,6 +6050,11 @@ class TestMigrationSafetyGuards:
# 0018: restoring 'mcp'/'agentic' strategy references would recreate
# broken state — that strategy no longer exists in the codebase.
"0018_remove_mcp_strategy.py",
+ # 0019: the 'both' -> 'adaptive' coercion is lossy — after upgrade a
+ # row is indistinguishable from an originally-'adaptive' one, so a
+ # downgrade cannot know which rows to restore. Rewriting 'adaptive'
+ # back to 'both' would clobber the legitimate default. No-op by design.
+ "0019_retire_both_egress_scope.py",
}
# Migrations whose downgrade is intentionally NotImplementedError
diff --git a/tests/database/test_migration_0018_remove_mcp_strategy.py b/tests/database/test_migration_0018_remove_mcp_strategy.py
index 4831697702..af98a14c2d 100644
--- a/tests/database/test_migration_0018_remove_mcp_strategy.py
+++ b/tests/database/test_migration_0018_remove_mcp_strategy.py
@@ -368,12 +368,7 @@ class TestMigration0018HeadAlignment:
rev_0018 = script.get_revision("0018")
assert rev_0018.down_revision == "0017"
- def test_head_revision_is_0018(self):
- # 0018 is now the latest revision. The head-alignment guard lives in
- # the newest migration's test file (moved here from the 0017 test
- # when this migration was rechained onto 0017 during the main merge).
- from local_deep_research.database.alembic_runner import (
- get_head_revision,
- )
-
- assert get_head_revision() == "0018"
+ # NOTE: the head-alignment guard (assert head == latest) now lives in the
+ # newest migration's test file — see TestMigration0019HeadAlignment in
+ # test_migration_0019_retire_both_egress_scope.py. 0018 is no longer the
+ # head, so asserting it here would break every future migration.
diff --git a/tests/database/test_migration_0019_retire_both_egress_scope.py b/tests/database/test_migration_0019_retire_both_egress_scope.py
new file mode 100644
index 0000000000..a8f296cfb3
--- /dev/null
+++ b/tests/database/test_migration_0019_retire_both_egress_scope.py
@@ -0,0 +1,152 @@
+"""Tests for migration 0019: retire the 'both' egress scope.
+
+Pins the upgrade semantics:
+- ``policy.egress_scope`` rows holding ``both`` are rewritten to ``adaptive``;
+ every other (concrete) scope is preserved untouched.
+- The settings ``value`` column stores JSON text (``"both"`` with quotes); the
+ rewritten value must be stored as ``"adaptive"`` (single JSON encoding) — a
+ raw-bytes assertion guards against double-encoding (see migration 0018).
+- Idempotency: re-running the upgrade is a no-op.
+- A DB with no matching row upgrades cleanly (rowcount 0, no error).
+"""
+
+import json
+
+import pytest
+from alembic import command
+from sqlalchemy import create_engine, text
+
+from local_deep_research.database.alembic_runner import get_alembic_config
+
+EGRESS_SCOPE_KEY = "policy.egress_scope"
+
+
+def _run_upgrade_to(engine, revision):
+ config = get_alembic_config(engine)
+ with engine.begin() as conn:
+ config.attributes["connection"] = conn
+ command.upgrade(config, revision)
+
+
+def _seed_setting(engine, key, value):
+ with engine.begin() as conn:
+ conn.execute(
+ text(
+ "INSERT INTO settings "
+ "(key, value, type, name, ui_element, visible, editable) "
+ "VALUES (:key, :value, 'app', :name, 'select', 1, 1)"
+ ),
+ {"key": key, "value": json.dumps(value), "name": key},
+ )
+
+
+def _read_setting(engine, key):
+ with engine.begin() as conn:
+ row = conn.execute(
+ text("SELECT value FROM settings WHERE key = :key"),
+ {"key": key},
+ ).fetchone()
+ if row is None:
+ return None
+ raw = row[0]
+ return json.loads(raw) if isinstance(raw, str) else raw
+
+
+def _read_setting_raw(engine, key):
+ """Return the stored bytes of ``settings.value`` without decoding."""
+ with engine.begin() as conn:
+ row = conn.execute(
+ text("SELECT value FROM settings WHERE key = :key"),
+ {"key": key},
+ ).fetchone()
+ return None if row is None else row[0]
+
+
+def migrated_to_0018_engine(tmp_path):
+ """Database fully migrated through 0018 (the revision before 0019)."""
+ db_path = tmp_path / "test_0019.db"
+ engine = create_engine(f"sqlite:///{db_path}")
+ _run_upgrade_to(engine, "0018")
+ yield engine
+ engine.dispose()
+
+
+class TestMigration0019RetireBoth:
+ def test_both_rewritten_to_adaptive(self, migrated_to_0018_engine):
+ engine = migrated_to_0018_engine
+ _seed_setting(engine, EGRESS_SCOPE_KEY, "both")
+
+ _run_upgrade_to(engine, "0019")
+
+ assert _read_setting(engine, EGRESS_SCOPE_KEY) == "adaptive"
+
+ def test_rewritten_value_stored_single_encoded(
+ self, migrated_to_0018_engine
+ ):
+ """The stored bytes must be ``"adaptive"`` (single JSON encoding), not a
+ double-encoded ``"\\"adaptive\\""``. This is what catches a WHERE-clause
+ desync from the on-disk JSON form."""
+ engine = migrated_to_0018_engine
+ _seed_setting(engine, EGRESS_SCOPE_KEY, "both")
+
+ _run_upgrade_to(engine, "0019")
+
+ assert _read_setting_raw(engine, EGRESS_SCOPE_KEY) == json.dumps(
+ "adaptive"
+ )
+
+ @pytest.mark.parametrize(
+ "concrete",
+ ["adaptive", "public_only", "private_only", "strict", "unprotected"],
+ )
+ def test_concrete_scope_preserved(self, migrated_to_0018_engine, concrete):
+ engine = migrated_to_0018_engine
+ _seed_setting(engine, EGRESS_SCOPE_KEY, concrete)
+
+ _run_upgrade_to(engine, "0019")
+
+ assert _read_setting(engine, EGRESS_SCOPE_KEY) == concrete
+
+ def test_upgrade_is_idempotent(self, migrated_to_0018_engine):
+ engine = migrated_to_0018_engine
+ _seed_setting(engine, EGRESS_SCOPE_KEY, "both")
+
+ _run_upgrade_to(engine, "0019")
+ _run_upgrade_to(engine, "0019")
+
+ assert _read_setting(engine, EGRESS_SCOPE_KEY) == "adaptive"
+
+ def test_missing_row_is_a_clean_noop(self, migrated_to_0018_engine):
+ engine = migrated_to_0018_engine
+
+ _run_upgrade_to(engine, "0019")
+
+ assert _read_setting(engine, EGRESS_SCOPE_KEY) is None
+
+
+class TestMigration0019HeadAlignment:
+ """Head-alignment guard. By convention this lives in the newest
+ migration's test file (moved here from the 0018 test file when 0019 was
+ added). Catches a new migration landing without the chain being wired up."""
+
+ def test_0019_chains_correctly_to_0018(self):
+ from alembic.config import Config
+ from alembic.script import ScriptDirectory
+
+ from local_deep_research.database.alembic_runner import (
+ get_migrations_dir,
+ )
+
+ config = Config()
+ config.set_main_option("script_location", str(get_migrations_dir()))
+ script = ScriptDirectory.from_config(config)
+ rev_0019 = script.get_revision("0019")
+ assert rev_0019.down_revision == "0018"
+
+ def test_head_revision_is_0019(self):
+ from local_deep_research.database.alembic_runner import (
+ get_head_revision,
+ )
+
+ assert get_head_revision() == "0019"
diff --git a/tests/notifications/test_manager.py b/tests/notifications/test_manager.py
index bea055f134..3b4249a3bf 100644
--- a/tests/notifications/test_manager.py
+++ b/tests/notifications/test_manager.py
@@ -858,10 +858,23 @@ class TestEgressPolicyURLFilter:
# Only the LOCAL http webhook survives; vendor schemes + public host dropped.
assert out == "http://127.0.0.1/h"
- def test_both_scope_passes_vendor_schemes(self):
+ def test_retired_both_coerces_to_adaptive(self):
+ # `both` is retired (ADR-0007): it coerces to ADAPTIVE, which with the
+ # default public primary (searxng) resolves PUBLIC_ONLY. Vendor schemes
+ # still pass (only PRIVATE_ONLY refuses them), but the LOCAL http
+ # webhook is now dropped because public_only blocks private hosts.
mgr = self._mgr("both")
out = mgr._filter_urls_by_egress_policy("slack://t http://127.0.0.1/h")
assert "slack://t" in out
+ assert "http://127.0.0.1/h" not in out
+
+ def test_unprotected_scope_passes_all_urls(self):
+ # The escape hatch that replaces the old permissive `both`: vendor
+ # schemes AND a local http webhook both pass (egress protection off;
+ # the hard SSRF/metadata block still applies to metadata IPs).
+ mgr = self._mgr("unprotected")
+ out = mgr._filter_urls_by_egress_policy("slack://t http://127.0.0.1/h")
+ assert "slack://t" in out
assert "http://127.0.0.1/h" in out
def test_public_only_blocks_private_http_keeps_public(self):
diff --git a/tests/research_library/routes/test_rag_routes.py b/tests/research_library/routes/test_rag_routes.py
index f144b02226..d97b45b5c6 100644
--- a/tests/research_library/routes/test_rag_routes.py
+++ b/tests/research_library/routes/test_rag_routes.py
@@ -83,11 +83,12 @@ class TestGetRagService:
"""Create mock settings manager."""
mock = Mock()
mock.get_setting.side_effect = lambda key, default=None: {
- # Explicit permissive scope: these tests exercise the settings
+ # Explicit escape-hatch scope: these tests exercise the settings
# plumbing with FAKE provider names; the registered default
# (adaptive) would resolve PRIVATE_ONLY for the library and
- # deny them as provider_unknown.
- "policy.egress_scope": "both",
+ # deny them as provider_unknown. "unprotected" disables egress
+ # protection for the run ("both" is retired per ADR-0007).
+ "policy.egress_scope": "unprotected",
"local_search_embedding_model": "test-model",
"local_search_embedding_provider": "sentence_transformers",
"local_search_chunk_size": "1000",
diff --git a/tests/security/test_egress_classification.py b/tests/security/test_egress_classification.py
new file mode 100644
index 0000000000..263d443cd0
--- /dev/null
+++ b/tests/security/test_egress_classification.py
@@ -0,0 +1,248 @@
+"""Truth-table tests for the two-axis egress classification core (ADR-0007).
+
+Stage A: the core is pure and not yet wired into any PEP. These tests pin the
+four-quadrant combination rule so later wiring can't silently change it.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from local_deep_research.security.egress.classification import (
+ Component,
+ Exposure,
+ Label,
+ Mode,
+ Role,
+ Sensitivity,
+ evaluate_run,
+)
+
+S = Sensitivity.SENSITIVE
+NS = Sensitivity.NON_SENSITIVE
+EXP = Exposure.EXPOSING
+CON = Exposure.CONTAINED
+
+
+# ---------------------------------------------------------------------------
+# Helpers — build the components a realistic run is made of
+# ---------------------------------------------------------------------------
+
+
+def source(name: str, sens: Sensitivity, exp: Exposure = CON) -> Component:
+ return Component(name, Role.SOURCE, Label(sens, exp))
+
+
+def search_sink(name: str, exp: Exposure, sens: Sensitivity = NS) -> Component:
+ return Component(name, Role.SEARCH_SINK, Label(sens, exp))
+
+
+def inference(name: str, exp: Exposure) -> Component:
+ return Component(name, Role.INFERENCE_SINK, Label(NS, exp))
+
+
+def web_engine(name: str) -> list[Component]:
+ """A public web engine: a non-sensitive source AND an exposing search sink."""
+ return [source(name, NS), search_sink(name, EXP)]
+
+
+def dual_risk_store(name: str) -> list[Component]:
+ """Quadrant 4: a sensitive source that is also an exposing search sink."""
+ return [source(name, S, EXP), search_sink(name, EXP, S)]
+
+
+LOCAL_LLM = inference("llm:ollama", CON)
+CLOUD_LLM = inference("llm:anthropic", EXP)
+
+
+# ---------------------------------------------------------------------------
+# Quadrant 1 — non-sensitive + contained: combines with anything
+# ---------------------------------------------------------------------------
+
+
+def test_all_non_sensitive_allows_any_sink():
+ run = [
+ source("collection_public", NS),
+ *web_engine("google"),
+ CLOUD_LLM,
+ ]
+ d = evaluate_run(run)
+ assert d.allowed
+ assert d.reason == "no_sensitive_source"
+
+
+# ---------------------------------------------------------------------------
+# Quadrant 2 — sensitive + contained: only with other contained sources
+# ---------------------------------------------------------------------------
+
+
+def test_sensitive_collection_with_local_llm_allowed():
+ run = [source("collection_private", S), LOCAL_LLM]
+ d = evaluate_run(run)
+ assert d.allowed
+ assert d.reason == "sensitive_contained"
+
+
+def test_two_sensitive_collections_with_local_llm_allowed():
+ run = [source("collection_a", S), source("collection_b", S), LOCAL_LLM]
+ assert evaluate_run(run).allowed
+
+
+def test_sensitive_collection_with_cloud_llm_denied():
+ run = [source("collection_private", S), CLOUD_LLM]
+ d = evaluate_run(run)
+ assert not d.allowed
+ assert d.reason == "sensitive_to_exposing_inference"
+ assert d.offending == ("llm:anthropic",)
+
+
+def test_sensitive_collection_with_public_engine_denied():
+ run = [source("collection_private", S), *web_engine("arxiv"), LOCAL_LLM]
+ d = evaluate_run(run)
+ assert not d.allowed
+ assert d.reason == "sensitive_to_exposing_search"
+ assert d.offending == ("arxiv",)
+
+
+# ---------------------------------------------------------------------------
+# Quadrant 3 — non-sensitive + exposing: only with non-sensitive sources
+# ---------------------------------------------------------------------------
+
+
+def test_public_engine_with_public_collection_and_cloud_llm_allowed():
+ run = [
+ source("collection_public", NS),
+ *web_engine("google"),
+ CLOUD_LLM,
+ ]
+ assert evaluate_run(run).allowed
+
+
+# ---------------------------------------------------------------------------
+# Quadrant 4 — sensitive + exposing: solo, with contained inference
+# ---------------------------------------------------------------------------
+
+
+def test_dual_risk_store_solo_with_local_inference_allowed():
+ run = [*dual_risk_store("elasticsearch"), LOCAL_LLM]
+ d = evaluate_run(run)
+ assert d.allowed
+ assert d.reason == "sensitive_contained"
+
+
+def test_dual_risk_store_with_cloud_inference_denied():
+ run = [*dual_risk_store("elasticsearch"), CLOUD_LLM]
+ d = evaluate_run(run)
+ assert not d.allowed
+ assert d.reason == "sensitive_to_exposing_inference"
+
+
+def test_dual_risk_store_with_other_sensitive_source_denied():
+ run = [
+ *dual_risk_store("elasticsearch"),
+ source("collection_private", S),
+ LOCAL_LLM,
+ ]
+ d = evaluate_run(run)
+ assert not d.allowed
+ assert d.reason == "sensitive_to_exposing_search"
+ assert d.offending == ("elasticsearch",)
+
+
+def test_two_dual_risk_stores_denied():
+ run = [
+ *dual_risk_store("es_a"),
+ *dual_risk_store("es_b"),
+ LOCAL_LLM,
+ ]
+ assert not evaluate_run(run).allowed
+
+
+# ---------------------------------------------------------------------------
+# Exposing embeddings count as an exposing inference sink
+# ---------------------------------------------------------------------------
+
+
+def test_sensitive_with_cloud_embeddings_denied():
+ run = [
+ source("collection_private", S),
+ LOCAL_LLM,
+ inference("embeddings:openai", EXP),
+ ]
+ d = evaluate_run(run)
+ assert not d.allowed
+ assert d.reason == "sensitive_to_exposing_inference"
+ assert d.offending == ("embeddings:openai",)
+
+
+# ---------------------------------------------------------------------------
+# Permissive mode suspends the invariant (caller still warns)
+# ---------------------------------------------------------------------------
+
+
+ "run",
+ [
+ [source("collection_private", S), CLOUD_LLM],
+ [source("collection_private", S), *web_engine("arxiv"), LOCAL_LLM],
+ [*dual_risk_store("es"), CLOUD_LLM],
+ ],
+)
+def test_permissive_mode_always_allows(run):
+ enforced = evaluate_run(run)
+ assert not enforced.allowed # denied when enforcing
+ d = evaluate_run(run, mode=Mode.PERMISSIVE)
+ assert d.allowed
+ # The would-be-enforced diagnostic is preserved for the stage-C banner.
+ assert d.reason == f"permissive:{enforced.reason}"
+ assert d.offending == enforced.offending
+
+
+def test_quadrant4_store_plus_second_exposing_engine_denied():
+ # A dual-risk store is only allowed SOLO. Add a public web engine and the
+ # store's sensitive data can now reach that foreign exposing sink -> deny.
+ # The store's OWN sink is not offending (returning its data to itself is
+ # not a new leak); only the foreign "arxiv" sink is reported.
+ run = [*dual_risk_store("es"), *web_engine("arxiv"), LOCAL_LLM]
+ d = evaluate_run(run)
+ assert not d.allowed
+ assert d.reason == "sensitive_to_exposing_search"
+ assert d.offending == ("arxiv",)
+
+
+def test_name_collision_does_not_exempt_non_sensitive_sink():
+ # A NON-sensitive exposing search sink that merely shares a name with an
+ # unrelated sensitive source must NOT be treated as the solo dual-risk case.
+ run = [
+ Component("x", Role.SOURCE, Label(S, CON)), # sensitive source "x"
+ Component("x", Role.SEARCH_SINK, Label(NS, EXP)), # unrelated sink "x"
+ LOCAL_LLM,
+ ]
+ d = evaluate_run(run)
+ assert not d.allowed
+ assert d.reason == "sensitive_to_exposing_search"
+
+
+def test_multi_violation_inference_takes_precedence():
+ run = [
+ source("collection_private", S),
+ *web_engine("google"),
+ CLOUD_LLM,
+ ]
+ # Inference leak is checked first; the exposing search engine is masked.
+ d = evaluate_run(run)
+ assert not d.allowed
+ assert d.reason == "sensitive_to_exposing_inference"
+
+
+# ---------------------------------------------------------------------------
+# Degenerate inputs
+# ---------------------------------------------------------------------------
+
+
+def test_empty_run_allowed():
+ assert evaluate_run([]).allowed
+
+
+def test_only_contained_inference_no_sources_allowed():
+ assert evaluate_run([LOCAL_LLM]).allowed
diff --git a/tests/security/test_egress_langgraph_tool_filter.py b/tests/security/test_egress_langgraph_tool_filter.py
index 3478ca8cdb..6706b3edc5 100644
--- a/tests/security/test_egress_langgraph_tool_filter.py
+++ b/tests/security/test_egress_langgraph_tool_filter.py
@@ -232,8 +232,12 @@ class TestStrictFilter:
# ---------------------------------------------------------------------------
-class TestBothScopeAllowsAll:
- def test_public_and_private_engines_both_present(self):
+class TestRetiredBothScopeBehavesAsAdaptive:
+ def test_both_coerces_to_adaptive_and_follows_primary(self):
+ # `both` is retired (ADR-0007): it no longer means "allow all". It
+ # coerces to ADAPTIVE, which follows the primary — here the default
+ # public primary (searxng) resolves PUBLIC_ONLY, so the private engine
+ # is dropped rather than combined with the public one.
names, _ = _build_tool_names(
"both",
{
@@ -241,7 +245,7 @@ class TestBothScopeAllowsAll:
_PRIVATE_ENGINE: {"description": "docs"},
},
)
- assert _specialized(names) == {_PUBLIC_ENGINE, _PRIVATE_ENGINE}
+ assert _specialized(names) == {_PUBLIC_ENGINE}
# ---------------------------------------------------------------------------
diff --git a/tests/security/test_egress_pep_coverage.py b/tests/security/test_egress_pep_coverage.py
index 5c9c0e6fd5..ef8ee90431 100644
--- a/tests/security/test_egress_pep_coverage.py
+++ b/tests/security/test_egress_pep_coverage.py
@@ -286,10 +286,16 @@ class TestEnforceEmbeddingsPolicy:
return _enforce_embeddings_policy(provider, self._mgr(settings), "u")
- def test_noop_when_scope_both_and_require_local_false(self):
- # Explicit BOTH scope + no flag => any provider passes (returns
- # None, no raise).
- assert (
+ def test_retired_both_coerces_to_adaptive_forcing_local(self):
+ # `both` is retired (ADR-0007): it coerces to ADAPTIVE, and the RAG gate
+ # classifies against the library corpus (sensitive) -> PRIVATE_ONLY ->
+ # local embeddings forced -> a cloud provider is DENIED even with the
+ # require_local flag left False.
+ from local_deep_research.security.egress.policy import (
+ PolicyDeniedError,
+ )
+
+ with pytest.raises(PolicyDeniedError):
self._enforce(
"openai",
{
@@ -297,8 +303,6 @@ class TestEnforceEmbeddingsPolicy:
"embeddings.require_local": False,
},
)
- is None
- )
def test_adaptive_default_denies_cloud_for_library(self):
# A missing scope falls back to the registered default ADAPTIVE.
diff --git a/tests/security/test_egress_policy.py b/tests/security/test_egress_policy.py
index 9b11e723a5..05b47e9681 100644
--- a/tests/security/test_egress_policy.py
+++ b/tests/security/test_egress_policy.py
@@ -1283,13 +1283,17 @@ def test_rag_factory_allows_openai_pointed_at_local_endpoint():
)
-def test_rag_factory_passes_through_when_scope_both():
- """Under an explicit BOTH scope with require_local False, OpenAI
- embeddings are permitted."""
+def test_rag_factory_denies_cloud_when_retired_both_coerces_to_adaptive():
+ """`both` is retired (ADR-0007) and coerces to ADAPTIVE. The RAG gate
+ classifies against the library corpus (sensitive) -> PRIVATE_ONLY -> local
+ embeddings forced -> a cloud provider is DENIED even with require_local
+ left False."""
+ import pytest
from unittest.mock import MagicMock
from local_deep_research.research_library.services import (
rag_service_factory,
)
+ from local_deep_research.security.egress.policy import PolicyDeniedError
fake_settings = MagicMock()
fake_settings.get_setting.side_effect = lambda key, *args, **kwargs: {
@@ -1299,10 +1303,10 @@ def test_rag_factory_passes_through_when_scope_both():
"embeddings.ollama.url": "",
}.get(key)
- # Should not raise — BOTH imposes no local requirement.
- rag_service_factory._enforce_embeddings_policy(
- "openai", fake_settings, username="alice"
- )
+ with pytest.raises(PolicyDeniedError):
+ rag_service_factory._enforce_embeddings_policy(
+ "openai", fake_settings, username="alice"
+ )
def test_rag_factory_denies_cloud_under_adaptive_default():
diff --git a/tests/security/test_egress_run_classification.py b/tests/security/test_egress_run_classification.py
new file mode 100644
index 0000000000..2184bd00e1
--- /dev/null
+++ b/tests/security/test_egress_run_classification.py
@@ -0,0 +1,499 @@
+"""Tests for the stage-B egress resolver/assembly/audit (ADR-0007).
+
+Covers label resolution from declared attributes + dynamic refinements
+(collection is_public, store URL fail-up), run assembly, and the audit-mode
+decision (which must never raise).
+"""
+
+from __future__ import annotations
+
+from unittest.mock import patch
+
+from local_deep_research.security.egress import run_classification as rc
+from local_deep_research.security.egress.classification import (
+ Exposure,
+ Label,
+ Role,
+ Sensitivity,
+)
+from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+)
+
+S = Sensitivity.SENSITIVE
+NS = Sensitivity.NON_SENSITIVE
+EXP = Exposure.EXPOSING
+CON = Exposure.CONTAINED
+
+POLICY = "local_deep_research.security.egress.policy"
+
+
+def ctx(primary: str = "arxiv", username=None) -> EgressContext:
+ return EgressContext(
+ scope=EgressScope.BOTH,
+ primary_engine=primary,
+ require_local_llm=False,
+ require_local_embeddings=False,
+ username=username,
+ )
+
+
+class _PublicEngine:
+ egress_sensitivity = NS
+ egress_exposure = EXP
+
+
+class _LocalStore:
+ egress_sensitivity = S
+ egress_exposure = CON
+ url_setting = "search.engine.web.paperless.default_params.api_url"
+
+
+# ---------------------------------------------------------------------------
+# engine_label — static engines + URL fail-up
+# ---------------------------------------------------------------------------
+
+
+def test_public_engine_label():
+ with patch(f"{POLICY}._get_engine_class", return_value=_PublicEngine):
+ assert rc.engine_label("arxiv", {}, ctx()) == Label(NS, EXP)
+
+
+def test_unknown_engine_label_is_none():
+ with patch(f"{POLICY}._get_engine_class", return_value=None):
+ assert rc.engine_label("mystery", {}, ctx()) is None
+
+
+def test_local_store_contained_on_local_url():
+ with (
+ patch(f"{POLICY}._get_engine_class", return_value=_LocalStore),
+ patch(f"{POLICY}._classify_engine_url", return_value=True),
+ ):
+ assert rc.engine_label("paperless", {}, ctx()) == Label(S, CON)
+
+
+def test_local_store_fails_up_to_exposing_on_public_url():
+ # Quadrant 4: sensitive data + exposing sink (public host).
+ with (
+ patch(f"{POLICY}._get_engine_class", return_value=_LocalStore),
+ patch(f"{POLICY}._classify_engine_url", return_value=False),
+ ):
+ assert rc.engine_label("paperless", {}, ctx()) == Label(S, EXP)
+
+
+# ---------------------------------------------------------------------------
+# engine_label — collections / library (sensitivity from is_public)
+# ---------------------------------------------------------------------------
+
+
+def test_private_collection_is_sensitive():
+ with patch(f"{POLICY}._resolve_collection_is_public", return_value=False):
+ assert rc.engine_label("collection_abc", {}, ctx()) == Label(S, CON)
+
+
+def test_public_collection_is_non_sensitive():
+ with patch(f"{POLICY}._resolve_collection_is_public", return_value=True):
+ assert rc.engine_label("collection_abc", {}, ctx()) == Label(NS, CON)
+
+
+def test_library_aggregate_is_sensitive():
+ with patch(f"{POLICY}._resolve_collection_is_public", return_value=False):
+ assert rc.engine_label("library", {}, ctx()) == Label(S, CON)
+
+
+# ---------------------------------------------------------------------------
+# provider labels (inference sinks — exposure only)
+# ---------------------------------------------------------------------------
+
+
+def test_llm_labels():
+ assert rc.llm_label("ollama") == Label(NS, CON)
+ assert rc.llm_label("anthropic") == Label(NS, EXP)
+ assert rc.llm_label("totally-unknown") == Label(NS, EXP) # fail closed
+
+
+def test_embeddings_labels():
+ assert rc.embeddings_label("ollama") == Label(NS, CON)
+ assert rc.embeddings_label("sentence_transformers") == Label(NS, CON)
+ assert rc.embeddings_label("openai") == Label(NS, EXP)
+
+
+# ---------------------------------------------------------------------------
+# classify_run — assembly into SOURCE + SEARCH_SINK + INFERENCE_SINK
+# ---------------------------------------------------------------------------
+
+
+def test_classify_run_assembles_roles():
+ with patch.object(rc, "engine_label", return_value=Label(NS, EXP)):
+ comps = rc.classify_run(
+ {}, ctx(), engines=["arxiv"], llm_provider="anthropic"
+ )
+ got = {(c.name, c.role) for c in comps}
+ assert got == {
+ ("arxiv", Role.SOURCE),
+ ("arxiv", Role.SEARCH_SINK),
+ ("llm:anthropic", Role.INFERENCE_SINK),
+ }
+
+
+def test_classify_run_fails_closed_on_unknown_engine():
+ with patch.object(rc, "engine_label", return_value=None):
+ comps = rc.classify_run(
+ {}, ctx(), engines=["mystery"], llm_provider="ollama"
+ )
+ # Unknown engine is NOT dropped — it fails closed to sensitive+exposing.
+ by = {(c.name, c.role): c for c in comps}
+ assert by[("mystery", Role.SOURCE)].label == Label(S, EXP)
+ assert ("mystery", Role.SEARCH_SINK) in by
+ assert ("llm:ollama", Role.INFERENCE_SINK) in by
+
+
+# ---------------------------------------------------------------------------
+# audit_run — decision + never-raises contract
+# ---------------------------------------------------------------------------
+
+
+def test_audit_run_denies_sensitive_plus_cloud_llm():
+ with patch.object(rc, "engine_label", return_value=Label(S, CON)):
+ d = rc.audit_run(
+ {}, ctx(), engines=["collection_x"], llm_provider="anthropic"
+ )
+ assert d is not None and not d.allowed
+ assert d.reason == "sensitive_to_exposing_inference"
+
+
+def test_audit_run_allows_public_plus_local_llm():
+ with patch.object(rc, "engine_label", return_value=Label(NS, EXP)):
+ d = rc.audit_run({}, ctx(), engines=["arxiv"], llm_provider="ollama")
+ assert d is not None and d.allowed
+
+
+def test_audit_run_permissive_under_unprotected_scope():
+ # A normally-denied combo is ALLOWED (permissive) under the escape hatch,
+ # with the diagnostic preserved.
+ unprot = EgressContext(
+ scope=EgressScope.UNPROTECTED,
+ primary_engine="arxiv",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+ with patch.object(rc, "engine_label", return_value=Label(S, CON)):
+ d = rc.audit_run(
+ {}, unprot, engines=["collection_x"], llm_provider="anthropic"
+ )
+ assert d is not None and d.allowed
+ assert d.reason.startswith("permissive:")
+
+
+def test_audit_run_fails_closed_on_internal_error():
+ # An uncomputable decision must refuse the run (fail closed) and never
+ # raise — silent degradation to the scope PEPs would hide the failure.
+ with patch.object(rc, "engine_label", side_effect=RuntimeError("boom")):
+ d = rc.audit_run({}, ctx(), engines=["x"], llm_provider="ollama")
+ assert d is not None and not d.allowed and d.reason == "audit_error"
+
+
+def test_fail_closed_decision_needs_no_policy_import():
+ # _fail_closed_decision runs from the except blocks that handle failures
+ # (including a .policy import failure), so it must NOT import .policy. It
+ # denies for a normal ctx and allows only under unprotected, using the
+ # ctx's str-enum scope value directly.
+ assert not rc._fail_closed_decision(ctx()).allowed
+ unprot = EgressContext(
+ scope=EgressScope.UNPROTECTED,
+ primary_engine="arxiv",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+ assert rc._fail_closed_decision(unprot).allowed
+
+
+def test_audit_run_internal_error_never_blocks_under_unprotected():
+ # Fail-closed must not override the escape hatch: an internal error under
+ # UNPROTECTED is still allowed.
+ unprot = EgressContext(
+ scope=EgressScope.UNPROTECTED,
+ primary_engine="arxiv",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+ with patch.object(rc, "engine_label", side_effect=RuntimeError("boom")):
+ d = rc.audit_run({}, unprot, engines=["x"], llm_provider="ollama")
+ assert d is not None and d.allowed
+
+
+def test_audit_run_unknown_engine_fails_closed_and_denies():
+ # Unknown engine -> sensitive+exposing source; a cloud LLM -> exposing
+ # inference sink -> the run is denied (not silently allowed).
+ with patch.object(rc, "engine_label", return_value=None):
+ d = rc.audit_run(
+ {}, ctx(), engines=["mystery"], llm_provider="anthropic"
+ )
+ assert d is not None and not d.allowed
+ assert d.reason == "sensitive_to_exposing_inference"
+
+
+# ---------------------------------------------------------------------------
+# audit_run_from_snapshot — shared route/worker entry point (covers all run
+# entry points: API precheck, follow-up, chat, queue)
+# ---------------------------------------------------------------------------
+
+
+def test_audit_run_from_snapshot_denies_private_collection_plus_cloud_llm():
+ # The worker-chokepoint case that a follow-up / chat / queue run reaches:
+ # a private collection primary + a cloud LLM under a `both` scope must be
+ # refused, matching the /api/start_research route.
+ snap = {"llm.provider": "anthropic"}
+ with patch.object(rc, "engine_label", return_value=Label(S, CON)):
+ d = rc.audit_run_from_snapshot(
+ snap, ctx(primary="collection_x"), "collection_x"
+ )
+ assert d is not None and not d.allowed
+ assert d.reason == "sensitive_to_exposing_inference"
+
+
+def test_audit_run_from_snapshot_unwraps_dict_wrapped_snapshot():
+ # get_all_settings snapshots store each value as {"value": ...}; the helper
+ # must unwrap it, else the LLM provider is dropped and the check is blind.
+ snap = {"llm.provider": {"value": "anthropic"}}
+ with patch.object(rc, "engine_label", return_value=Label(S, CON)):
+ d = rc.audit_run_from_snapshot(
+ snap, ctx(primary="collection_x"), "collection_x"
+ )
+ assert d is not None and not d.allowed
+
+
+def test_audit_run_from_snapshot_permissive_under_unprotected():
+ unprot = EgressContext(
+ scope=EgressScope.UNPROTECTED,
+ primary_engine="collection_x",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+ with patch.object(rc, "engine_label", return_value=Label(S, CON)):
+ d = rc.audit_run_from_snapshot(
+ {"llm.provider": "anthropic"}, unprot, "collection_x"
+ )
+ assert d is not None and d.allowed
+
+
+def test_audit_run_from_snapshot_missing_llm_provider_uses_run_default():
+ # A snapshot without llm.provider must resolve to the run's own default
+ # (ollama, local) via get_setting_from_snapshot — the same value the run
+ # would use — not be silently read as "no LLM". Sensitive source + local
+ # default inference is quadrant 2 (allowed), matching the run's behaviour.
+ with patch.object(rc, "engine_label", return_value=Label(S, CON)):
+ d = rc.audit_run_from_snapshot(
+ {}, ctx(primary="collection_x"), "collection_x"
+ )
+ assert d is not None and d.allowed
+
+
+def test_audit_run_from_snapshot_includes_embeddings_for_collection():
+ # A RAG run over a collection embeds, so a cloud embedder is an exposing
+ # sink for the sensitive source -> refused even with a local LLM. The RAG
+ # engine reads local_search_embedding_provider, so the audit must too.
+ snap = {
+ "llm.provider": "ollama",
+ "local_search_embedding_provider": "openai",
+ }
+ with patch.object(rc, "engine_label", return_value=Label(S, CON)):
+ d = rc.audit_run_from_snapshot(
+ snap, ctx(primary="collection_x"), "collection_x"
+ )
+ assert d is not None and not d.allowed
+
+
+def test_audit_run_from_snapshot_ignores_embeddings_for_lexical_store():
+ # A non-collection sensitive store (paperless/elasticsearch) never embeds,
+ # so a configured cloud embedder must NOT be pulled in: sensitive source +
+ # local LLM is admissible (quadrant 2), not refused.
+ snap = {
+ "llm.provider": "ollama",
+ "local_search_embedding_provider": "openai",
+ }
+ with patch.object(rc, "engine_label", return_value=Label(S, CON)):
+ d = rc.audit_run_from_snapshot(
+ snap, ctx(primary="paperless"), "paperless"
+ )
+ assert d is not None and d.allowed
+
+
+def test_audit_run_from_snapshot_empty_llm_provider_resolves_from_snapshot():
+ # Chat passes model_provider="" (not None) when no override is set. An empty
+ # string must be treated as "resolve from snapshot", not passed through —
+ # else classify_run's truthy guard silently drops the LLM sink and a
+ # sensitive source + cloud LLM is wrongly allowed.
+ snap = {"llm.provider": "anthropic"} # cloud provider in the snapshot
+ with patch.object(rc, "engine_label", return_value=Label(S, CON)):
+ d = rc.audit_run_from_snapshot(
+ snap, ctx(primary="collection_x"), "collection_x", llm_provider=""
+ )
+ assert d is not None and not d.allowed
+ assert d.reason == "sensitive_to_exposing_inference"
+
+
+def test_audit_run_from_snapshot_audits_llm_provider_override():
+ # The run's per-request model_provider WINS over the snapshot (get_llm uses
+ # the explicit arg). A saved local default must not mask a cloud override
+ # chosen for this one run — else queue/follow-up/chat runs leak.
+ snap = {"llm.provider": "ollama"} # saved default is local/contained
+ with patch.object(rc, "engine_label", return_value=Label(S, CON)):
+ d = rc.audit_run_from_snapshot(
+ snap,
+ ctx(primary="collection_x"),
+ "collection_x",
+ llm_provider="anthropic", # per-request cloud override
+ )
+ assert d is not None and not d.allowed
+ assert d.reason == "sensitive_to_exposing_inference"
+
+
+def test_audit_run_from_snapshot_fails_closed_on_bad_snapshot():
+ # Provider resolution runs inside the fail-closed guard: a malformed
+ # snapshot refuses the run rather than escaping the helper uncaught.
+ d = rc.audit_run_from_snapshot(
+ "not-a-dict", ctx(primary="collection_x"), "collection_x"
+ )
+ assert d is not None and not d.allowed and d.reason == "audit_error"
+
+
+# ---------------------------------------------------------------------------
+# provider endpoint URL fail-up (only ever tightens)
+# ---------------------------------------------------------------------------
+
+
+def test_llm_label_local_custom_endpoint_is_contained():
+ # A self-hosted OpenAI-compatible endpoint on a local IP must be CONTAINED
+ # (regression: previously mislabeled EXPOSING -> false 400 on local runs).
+ snap = {"llm.openai_endpoint.url": "http://127.0.0.1:8000/v1"}
+ assert rc.llm_label("openai_endpoint", snap, ctx()) == Label(NS, CON)
+
+
+def test_llm_label_public_custom_endpoint_is_exposing():
+ snap = {"llm.openai_endpoint.url": "http://8.8.8.8:8000/v1"}
+ assert rc.llm_label("openai_endpoint", snap, ctx()) == Label(NS, EXP)
+
+
+# ---------------------------------------------------------------------------
+# Real declared label values — guards against a typo in any engine class
+# ---------------------------------------------------------------------------
+
+
+def test_registered_engines_declare_consistent_labels():
+ from local_deep_research.security.egress.policy import _get_engine_class
+ from local_deep_research.web_search_engines.engine_registry import (
+ ENGINE_REGISTRY,
+ )
+
+ assert ENGINE_REGISTRY, "engine registry unexpectedly empty"
+ checked = 0
+ for name in ENGINE_REGISTRY:
+ cls = _get_engine_class(name) # the real class the resolver reads
+ if cls is None:
+ continue
+ sens = getattr(cls, "egress_sensitivity", None)
+ exp = getattr(cls, "egress_exposure", None)
+ assert sens is not None, f"{name} missing egress_sensitivity"
+ assert exp is not None, f"{name} missing egress_exposure"
+ if getattr(cls, "is_public", False):
+ assert sens is Sensitivity.NON_SENSITIVE, name
+ assert exp is Exposure.EXPOSING, name
+ elif getattr(cls, "is_local", False):
+ assert sens is Sensitivity.SENSITIVE, name
+ assert exp is Exposure.CONTAINED, name
+ checked += 1
+ assert checked > 10, f"only checked {checked} engines"
+
+
+def test_llm_provider_declared_exposure_matches_resolver():
+ # The resolver classifies a provider's endpoint via the enforcing PEP; with
+ # no configured URL it falls back to the static cloud/local split. Assert
+ # the resolver AND (where the class is resolvable) the declared attribute
+ # agree, across every statically-classifiable provider — url-configurable
+ # ones (openai_endpoint / anthropic_endpoint) are refined by URL and are
+ # covered by the dedicated local/public endpoint tests above.
+ from local_deep_research.llm.providers import get_provider_class
+
+ expected = {
+ "ollama": Exposure.CONTAINED,
+ "lmstudio": Exposure.CONTAINED,
+ "llamacpp": Exposure.CONTAINED,
+ "openai": Exposure.EXPOSING,
+ "anthropic": Exposure.EXPOSING,
+ "google": Exposure.EXPOSING,
+ "openrouter": Exposure.EXPOSING,
+ "deepseek": Exposure.EXPOSING,
+ "xai": Exposure.EXPOSING,
+ "ionos": Exposure.EXPOSING,
+ }
+ for name, exp in expected.items():
+ assert rc.llm_label(name).exposure is exp, name
+ cls = None
+ try:
+ cls = get_provider_class(name) or get_provider_class(name.upper())
+ except Exception:
+ cls = None
+ if cls is not None:
+ assert getattr(cls, "egress_exposure", None) is exp, name
+
+
+# ---------------------------------------------------------------------------
+# Per-destination trust (stage D) — relaxes an exposing sink to contained
+# ---------------------------------------------------------------------------
+
+
+def test_llm_trust_relaxes_cloud_provider_to_contained():
+ trusted = {"policy.trusted_inference_providers": ["anthropic"]}
+ assert rc.llm_label("anthropic", trusted, ctx()).exposure is CON
+ # untrusted cloud stays exposing
+ assert rc.llm_label("anthropic", {}, ctx()).exposure is EXP
+
+
+def test_embeddings_trust_relaxes_cloud_provider_to_contained():
+ trusted = {"policy.trusted_inference_providers": ["openai"]}
+ assert rc.embeddings_label("openai", trusted, ctx()).exposure is CON
+
+
+def test_engine_trust_relaxes_exposing_store_to_contained():
+ # A sensitive store on a public URL is quadrant 4 (exposing); trusting it
+ # moves exposure to contained while keeping its data sensitive.
+ trusted = {"policy.trusted_search_engines": ["paperless"]}
+ with (
+ patch(f"{POLICY}._get_engine_class", return_value=_LocalStore),
+ patch(f"{POLICY}._classify_engine_url", return_value=False),
+ ):
+ assert rc.engine_label("paperless", trusted, ctx()) == Label(S, CON)
+
+
+def test_trusted_names_handles_json_string_and_garbage():
+ assert rc._trusted_names("k", {"k": '["Anthropic", "ollama"]'}) == {
+ "anthropic",
+ "ollama",
+ }
+ assert rc._trusted_names("k", {"k": "not json"}) == set()
+ assert rc._trusted_names("k", None) == set()
+
+
+def test_trusted_cloud_llm_allows_sensitive_run_end_to_end():
+ # The stage-D payoff: a sensitive source + a TRUSTED cloud LLM is allowed.
+ trusted = {"policy.trusted_inference_providers": ["anthropic"]}
+ with patch.object(rc, "engine_label", return_value=Label(S, CON)):
+ d = rc.audit_run(
+ trusted, ctx(), engines=["collection_x"], llm_provider="anthropic"
+ )
+ assert d is not None and d.allowed
+
+
+def test_engine_trust_does_not_relax_public_engine():
+ # Trusting an inherently-public engine must NOT contain it (no laundering
+ # a public search sink past the sensitive->exposing rule).
+ class _PublicWithName:
+ is_public = True
+ egress_sensitivity = NS
+ egress_exposure = EXP
+
+ trusted = {"policy.trusted_search_engines": ["searxng"]}
+ with patch(f"{POLICY}._get_engine_class", return_value=_PublicWithName):
+ assert rc.engine_label("searxng", trusted, ctx()) == Label(NS, EXP)
diff --git a/tests/security/test_egress_unprotected.py b/tests/security/test_egress_unprotected.py
new file mode 100644
index 0000000000..491c49a9b6
--- /dev/null
+++ b/tests/security/test_egress_unprotected.py
@@ -0,0 +1,119 @@
+"""Escape-hatch (UNPROTECTED scope) tests — ADR-0007 stage C.
+
+UNPROTECTED disables the egress-scope restrictions (the opt-out) but must NOT
+lift the hard SSRF / cloud-metadata invariant, and must lift the forced
+local-inference requirements.
+"""
+
+from __future__ import annotations
+
+from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+ context_from_snapshot,
+ evaluate_engine,
+ evaluate_llm_endpoint,
+ evaluate_retriever,
+ evaluate_url,
+)
+
+
+def unprot_ctx(primary: str = "arxiv") -> EgressContext:
+ return EgressContext(
+ scope=EgressScope.UNPROTECTED,
+ primary_engine=primary,
+ require_local_llm=False,
+ require_local_embeddings=False,
+ )
+
+
+def test_engine_any_allowed_under_unprotected():
+ # A normally-unclassified/unknown engine is permitted by the escape hatch.
+ d = evaluate_engine(
+ "some_unknown_engine", unprot_ctx(), settings_snapshot={}
+ )
+ assert d.allowed
+ assert d.reason == "egress_unprotected"
+
+
+def test_retriever_allowed_under_unprotected():
+ assert evaluate_retriever("anything", unprot_ctx()).allowed
+
+
+def test_url_public_allowed_under_unprotected():
+ assert evaluate_url("http://example.com/", unprot_ctx()).allowed
+
+
+def test_metadata_ssrf_still_blocked_under_unprotected():
+ # The hard invariant survives the escape hatch.
+ d = evaluate_url("http://169.254.169.254/latest/meta-data/", unprot_ctx())
+ assert not d.allowed
+
+
+def test_cloud_llm_allowed_under_unprotected():
+ # require_local_llm is False under the hatch -> cloud provider allowed.
+ assert evaluate_llm_endpoint(
+ "openai", unprot_ctx(), settings_snapshot={}
+ ).allowed
+
+
+def test_context_unprotected_lifts_local_requirements():
+ # Even with the require-local flags saved on, UNPROTECTED lifts them.
+ snap = {
+ "policy.egress_scope": "unprotected",
+ "llm.require_local_endpoint": True,
+ "embeddings.require_local": True,
+ "search.tool": "arxiv",
+ }
+ ctx = context_from_snapshot(snap, "arxiv")
+ assert ctx.scope is EgressScope.UNPROTECTED
+ assert ctx.require_local_llm is False
+ assert ctx.require_local_embeddings is False
+
+
+def test_unprotected_warning_fires_and_is_non_dismissible():
+ from local_deep_research.security.egress.warnings import (
+ check_unprotected_egress,
+ )
+
+ w = check_unprotected_egress("unprotected")
+ assert w is not None
+ assert w["type"] == "egress_unprotected"
+ assert w["dismissKey"] is None # non-dismissible
+ assert check_unprotected_egress("adaptive") is None
+ assert check_unprotected_egress("private_only") is None
+
+
+def test_trusted_destinations_warning():
+ from local_deep_research.security.egress.warnings import (
+ check_trusted_destinations,
+ )
+
+ assert check_trusted_destinations([], []) is None
+ w = check_trusted_destinations(["anthropic"], [])
+ assert w is not None
+ assert w["type"] == "egress_trusted_destinations"
+ assert "anthropic" in w["message"]
+ # tolerates the JSON-string shape a snapshot may carry
+ w2 = check_trusted_destinations('["openai"]', "[]")
+ assert w2 is not None and "openai" in w2["message"]
+
+
+def test_validate_trusted_search_engines_rejects_public():
+ from local_deep_research.security.egress.validators import (
+ validate_trusted_search_engines,
+ )
+
+ # An inherently-public engine cannot be trusted (would launder a sink).
+ err = validate_trusted_search_engines(
+ {"policy.trusted_search_engines": ["searxng"]}, {}
+ )
+ assert err is not None and "searxng" in err["error"]
+ # A local-nature store / unknown name is accepted (runtime still gates).
+ assert (
+ validate_trusted_search_engines(
+ {"policy.trusted_search_engines": ["elasticsearch"]}, {}
+ )
+ is None
+ )
+ assert validate_trusted_search_engines({}, {}) is None
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index 47e718bd14..7359e53113 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -2183,7 +2183,7 @@
},
"policy.egress_scope": {
"category": "policy",
- "description": "EXPERIMENTAL — this egress boundary is new defense-in-depth, not an absolute guarantee yet; don't rely on it as your only protection for highly sensitive data. Restrict which search engines a research run may use. ADAPTIVE (default) = follow your primary engine: a private primary keeps everything local, a public primary allows public engines. STRICT = only the primary engine you picked; PUBLIC_ONLY = any public web/academic engine; PRIVATE_ONLY = any local engine (library, paperless, etc.); BOTH = any classified engine.",
+ "description": "EXPERIMENTAL — this egress boundary is new defense-in-depth, not an absolute guarantee yet; don't rely on it as your only protection for highly sensitive data. Restrict which search engines a research run may use. ADAPTIVE (default) = follow your primary engine: a private primary keeps everything local, a public primary allows public engines. STRICT = only the primary engine you picked; PUBLIC_ONLY = any public web/academic engine; PRIVATE_ONLY = any local engine (library, paperless, etc.); UNPROTECTED = escape hatch that disables egress protection entirely (not recommended; hard SSRF/cloud-metadata blocking still applies).",
"editable": true,
"max_value": null,
"min_value": null,
@@ -2193,10 +2193,6 @@
"label": "Adaptive (default — follows your primary engine)",
"value": "adaptive"
},
- {
- "label": "Both (any classified engine)",
- "value": "both"
- },
{
"label": "Public only (no local collections)",
"value": "public_only"
@@ -2208,6 +2204,10 @@
{
"label": "Strict (only the primary engine)",
"value": "strict"
+ },
+ {
+ "label": "Unprotected (no egress protection — not recommended)",
+ "value": "unprotected"
}
],
"step": null,
@@ -2216,6 +2216,34 @@
"value": "adaptive",
"visible": true
},
+ "policy.trusted_inference_providers": {
+ "category": "policy",
+ "description": "EXPERIMENTAL. LLM/embeddings providers you explicitly trust to receive sensitive content — listing one treats it as a 'contained' inference sink even though it is off-machine (e.g. a zero-retention enterprise Anthropic endpoint). Relaxes the two-axis egress classification; use only for providers you have vetted.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Trusted Inference Providers",
+ "options": null,
+ "step": null,
+ "type": "LLM",
+ "ui_element": "json",
+ "value": [],
+ "visible": true
+ },
+ "policy.trusted_search_engines": {
+ "category": "policy",
+ "description": "EXPERIMENTAL. Search engines whose endpoint you explicitly trust — listing one (e.g. a self-hosted Elasticsearch/Paperless on a public hostname) treats it as 'contained' rather than an exposing sink. Relaxes the two-axis egress classification; use only for endpoints you control.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Trusted Search Engines",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "json",
+ "value": [],
+ "visible": true
+ },
"rag.indexing_batch_size": {
"category": "research_library",
"description": "Number of documents to process in parallel during RAG indexing. Higher values are faster but use more memory.",
diff --git a/tests/test_api_key_configuration.py b/tests/test_api_key_configuration.py
index 90250c63f4..f68c0cdd5b 100644
--- a/tests/test_api_key_configuration.py
+++ b/tests/test_api_key_configuration.py
@@ -128,10 +128,11 @@ class TestAPIKeyConfiguration:
# "library" is a PRIVATE engine, so under the default adaptive
# egress scope it would resolve to PRIVATE_ONLY and force
# local LLM — denying the remote openai_endpoint provider this
- # test configures. Pin the scope to "both" so the test stays
+ # test configures. Pin the scope to "unprotected" (the escape
+ # hatch; "both" is retired per ADR-0007) so the test stays
# about LLM-provider config, not egress.
"search.tool": "library",
- "policy.egress_scope": "both",
+ "policy.egress_scope": "unprotected",
"search.max_results": 10,
"search.cross_engine_max_results": 100,
"search.cross_engine_use_reddit": False,
diff --git a/tests/test_llm_provider_integration.py b/tests/test_llm_provider_integration.py
index 62bca605e8..6375bd715b 100644
--- a/tests/test_llm_provider_integration.py
+++ b/tests/test_llm_provider_integration.py
@@ -125,11 +125,12 @@ class TestLLMProviderIntegration:
# available engine once an instance URL is configured (it isn't
# here) and the research path instantiates the engine. Point it at
# the always-available "library" engine instead. "library" is
- # PRIVATE, so pin the egress scope to "both" — otherwise the
- # default adaptive scope resolves to PRIVATE_ONLY, forces local
- # LLM, and denies the OpenRouter provider this test configures.
+ # PRIVATE, so pin the egress scope to "unprotected" (the escape
+ # hatch; "both" is retired per ADR-0007) — otherwise the default
+ # adaptive scope resolves to PRIVATE_ONLY, forces local LLM, and
+ # denies the OpenRouter provider this test configures.
settings_snapshot["search.tool"]["value"] = "library"
- settings_snapshot["policy.egress_scope"] = {"value": "both"}
+ settings_snapshot["policy.egress_scope"] = {"value": "unprotected"}
# Verify settings are correct - get_all_settings returns nested dicts
assert (
diff --git a/tests/ui_tests/test_egress_policy_ui.js b/tests/ui_tests/test_egress_policy_ui.js
index 67bd8f7f73..67a52c8202 100644
--- a/tests/ui_tests/test_egress_policy_ui.js
+++ b/tests/ui_tests/test_egress_policy_ui.js
@@ -47,6 +47,7 @@ const SCOPE_PALETTE = {
public_only: { border: 'rgb(59, 130, 246)', name: 'blue-500' },
private_only: { border: 'rgb(20, 163, 127)', name: 'teal-600' },
strict: { border: 'rgb(139, 92, 246)', name: 'violet-500' },
+ unprotected: { border: 'rgb(224, 82, 82)', name: 'red-caution' },
};
// Tally of pass / fail per assertion so the final report is informative.
@@ -178,7 +179,7 @@ async function main() {
'#policy_egress_scope option',
(els) => els.map((o) => ({ value: o.value, text: o.textContent.trim() })),
);
- const wantVals = ['adaptive', 'both', 'public_only', 'private_only', 'strict'];
+ const wantVals = ['adaptive', 'public_only', 'private_only', 'strict', 'unprotected'];
const haveVals = opts.map((o) => o.value);
const ok = wantVals.every((v) => haveVals.includes(v));
record(
@@ -197,8 +198,8 @@ async function main() {
// nagging in text.
// -----------------------------------------------------------
await run('3. Default scope shows no accent cue', async () => {
- const bodyScope = await selectScope(page, 'both');
- record('body-scope-both', bodyScope === 'both', `data-scope=${bodyScope}`);
+ const bodyScope = await selectScope(page, 'adaptive');
+ record('body-scope-adaptive', bodyScope === 'adaptive', `data-scope=${bodyScope}`);
const cardColor = await readCardBorderColor(page);
// The default rule above sets border-left to "5px solid
@@ -209,15 +210,15 @@ async function main() {
cardColor === 'rgba(0, 0, 0, 0)' ||
cardColor === 'transparent';
record(
- 'card-color-both-transparent',
+ 'card-color-adaptive-transparent',
isTransparent,
`border-left-color=${cardColor}`,
);
const panelScope = await readPanelDataScope(page);
- record('panel-data-scope-both', panelScope === 'both', `panel=${panelScope}`);
+ record('panel-data-scope-adaptive', panelScope === 'adaptive', `panel=${panelScope}`);
- await screenshot(page, '02-scope-both');
+ await screenshot(page, '02-scope-adaptive');
});
// -----------------------------------------------------------
@@ -401,7 +402,7 @@ async function main() {
timeout: 30000,
});
await page.waitForSelector('#policy_egress_scope', { timeout: 10000 });
- await selectScope(page, 'both');
+ await selectScope(page, 'adaptive');
});
// -----------------------------------------------------------
@@ -417,19 +418,19 @@ async function main() {
timeout: 30000,
});
await page.waitForSelector('#policy_egress_scope', { timeout: 10000 });
- await selectScope(page, 'both');
+ await selectScope(page, 'adaptive');
const bannerText = await page.evaluate(() => document.body.innerText);
const hasEgressBanner =
/Public search egress/i.test(bannerText)
|| /egress/i.test(bannerText);
record(
- 'egress-banner-present-on-both',
+ 'egress-banner-present-on-adaptive',
true, // soft assertion — banner may be acked on this user
hasEgressBanner ? 'visible' : 'absent (likely already acked)',
);
- await screenshot(page, '10-warning-banners-both');
+ await screenshot(page, '10-warning-banners-adaptive');
// Switch to private_only and verify the warning text is gone
// for the public-egress banner (other banners may remain).
@@ -511,7 +512,7 @@ async function main() {
// Clean up.
if (llmReloaded) await page.click('#llm_require_local_endpoint');
- await selectScope(page, 'both');
+ await selectScope(page, 'adaptive');
});
// -----------------------------------------------------------
@@ -547,7 +548,7 @@ async function main() {
timeout: 30000,
});
await page.waitForSelector('#policy_egress_scope', { timeout: 10000 });
- await selectScope(page, 'both');
+ await selectScope(page, 'adaptive');
});
} catch (err) {
diff --git a/tests/web/routes/test_research_routes_policy.py b/tests/web/routes/test_research_routes_policy.py
index 29c410759f..57ee65ee3d 100644
--- a/tests/web/routes/test_research_routes_policy.py
+++ b/tests/web/routes/test_research_routes_policy.py
@@ -136,3 +136,51 @@ class TestPrecheckEnginePolicy:
result = _precheck_engine_policy(mgr, params, "library", "user")
assert result is not None
assert result[1] == 400
+
+ # --- two-axis enforcement (ADR-0007 stage C) ---
+
+ def test_two_axis_denies_sensitive_source_plus_cloud_llm(self, app_ctx):
+ # STRICT lets a private-collection primary + cloud LLM pass the SCOPE
+ # check (strict is orthogonal to inference), but the two-axis rule
+ # refuses it: a sensitive source would reach an exposing inference sink.
+ mgr = _mgr({"policy.egress_scope": "strict"}, primary="collection_x")
+ result = _precheck_engine_policy(
+ mgr, {"model_provider": "anthropic"}, "collection_x", "user"
+ )
+ assert result is not None
+ assert result[1] == 400
+ assert (
+ result[0].get_json()["reason"] == "sensitive_to_exposing_inference"
+ )
+
+ def test_two_axis_allows_sensitive_source_plus_local_llm(self, app_ctx):
+ # Same private primary but a LOCAL LLM => two-axis allows => continue.
+ mgr = _mgr({"policy.egress_scope": "strict"}, primary="collection_x")
+ result = _precheck_engine_policy(
+ mgr, {"model_provider": "ollama"}, "collection_x", "user"
+ )
+ assert result is None
+
+ def test_unprotected_scope_bypasses_two_axis(self, app_ctx):
+ # The escape hatch: the otherwise-denied combo is permitted under
+ # UNPROTECTED (audit_run evaluates permissive), so no 400.
+ mgr = _mgr(
+ {"policy.egress_scope": "unprotected"}, primary="collection_x"
+ )
+ result = _precheck_engine_policy(
+ mgr, {"model_provider": "anthropic"}, "collection_x", "user"
+ )
+ assert result is None
+
+ def test_lexical_primary_with_cloud_embeddings_not_denied(self, app_ctx):
+ # A lexical store (paperless) never embeds, so a configured cloud
+ # embedder must NOT falsely trip the two-axis check: STRICT + paperless
+ # primary + local LLM + cloud embeddings -> allowed (no embeddings sink).
+ mgr = _mgr(
+ {"policy.egress_scope": "strict", "embeddings.provider": "openai"},
+ primary="paperless",
+ )
+ result = _precheck_engine_policy(
+ mgr, {"model_provider": "ollama"}, "paperless", "user"
+ )
+ assert result is None
diff --git a/tests/web/routes/test_settings_routes.py b/tests/web/routes/test_settings_routes.py
index 6b9d1efd4e..e5955d3c1b 100644
--- a/tests/web/routes/test_settings_routes.py
+++ b/tests/web/routes/test_settings_routes.py
@@ -516,6 +516,38 @@ class TestValidateSettingExtended:
valid, msg = validate_setting(setting, "option2")
assert valid is True
+ def test_validate_retired_egress_scope_both_rejected(self):
+ """policy.egress_scope 'both' is retired (ADR-0007 / migration 0019):
+ existing rows are migrated to 'adaptive' and any residual value is
+ coerced at read time, so 'both' is no longer a valid value to save."""
+ from local_deep_research.web.routes.settings_routes import (
+ validate_setting,
+ )
+ from local_deep_research.web.models.settings import (
+ BaseSetting,
+ SettingType,
+ )
+
+ setting = BaseSetting(
+ key="policy.egress_scope",
+ value="adaptive",
+ type=SettingType.APP,
+ name="Egress Scope",
+ ui_element="select",
+ options=[
+ {"value": "adaptive", "label": "Adaptive"},
+ {"value": "public_only", "label": "Public only"},
+ {"value": "private_only", "label": "Private only"},
+ {"value": "strict", "label": "Strict"},
+ {"value": "unprotected", "label": "Unprotected"},
+ ],
+ )
+ valid, _ = validate_setting(setting, "both")
+ assert valid is False
+ # A supported value still validates.
+ valid, _ = validate_setting(setting, "private_only")
+ assert valid is True
+
def test_validate_textarea_setting(self):
"""Test validating textarea setting."""
from local_deep_research.web.routes.settings_routes import (