~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(security): operator-gate unprotected egress and harden policy-sensitive consumers (#5148)
LearningCircuit87537d9ecf5b
diff --git a/SECURITY.md b/SECURITY.mdindex 35ab523fc4..0e3d8fe708 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 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.+- **Settings tampering**: `unprotected` is unavailable unless the operator explicitly sets `LDR_POLICY_ALLOW_UNPROTECTED_EGRESS=true`. When enabled, an adversary with write access to a user's per-user settings DB can flip `policy.egress_scope` to that escape hatch and disable normal egress enforcement (the retired `both` value no longer does this — it is coerced to the protective `adaptive` scope). Migration `0027` likewise rewrites legacy stored and queued `unprotected` selections to `adaptive` on upgrade, so turning the gate on later doesn't silently reactivate choices made before the capability boundary existed; while it stays off, new `unprotected` writes are rejected and any residual or tampered queued value is coerced to `adaptive` at dispatch with a `policy_audit` warning. 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/+classify-host-mixed-dns.security.md b/changelog.d/+classify-host-mixed-dns.security.mdnew file mode 100644index 0000000000..5f79b4041b--- /dev/null+++ b/changelog.d/+classify-host-mixed-dns.security.md@@ -0,0 +1,4 @@+Host classification now treats a hostname as local only when **every**+resolved address is private, and fails closed on resolution errors. This+closes a mixed-DNS SSRF bypass where a single private answer among public+ones could mark an otherwise-public host as trusted-local.diff --git a/changelog.d/+rag-configure-transaction.bugfix.md b/changelog.d/+rag-configure-transaction.bugfix.mdnew file mode 100644index 0000000000..c9fcf2f3b1--- /dev/null+++ b/changelog.d/+rag-configure-transaction.bugfix.md@@ -0,0 +1 @@+RAG configuration changes now update saved settings and the selected index atomically, preventing searches from observing mismatched configuration state.diff --git a/changelog.d/+rag-index-identity.feature.md b/changelog.d/+rag-index-identity.feature.mdnew file mode 100644index 0000000000..c048ad95a5--- /dev/null+++ b/changelog.d/+rag-index-identity.feature.md@@ -0,0 +1,4 @@+A collection can now hold multiple RAG indexes for the same embedding model+when they differ in chunking or vector-index configuration, so changing the+chunk size or index type no longer overwrites an existing index. A database+migration relaxes the previous per-collection+model uniqueness accordingly.diff --git a/changelog.d/+settings-env-lock-enforced-on-mutations.security.md b/changelog.d/+settings-env-lock-enforced-on-mutations.security.mdnew file mode 100644index 0000000000..1c4a801b25--- /dev/null+++ b/changelog.d/+settings-env-lock-enforced-on-mutations.security.md@@ -0,0 +1,5 @@+Environment-locked settings can no longer be overwritten or deleted through+programmatic settings mutations. Scheduler, RAG, and model-discovery paths+now also fail closed (rather than falling back to defaults) when the effective+settings snapshot cannot be built, so a corrupted or missing snapshot never+downgrades egress protection.diff --git a/changelog.d/+settings-env-value-redaction.security.md b/changelog.d/+settings-env-value-redaction.security.mdnew file mode 100644index 0000000000..107cc3c968--- /dev/null+++ b/changelog.d/+settings-env-value-redaction.security.md@@ -0,0 +1,4 @@+Reading a single environment-overridden secret setting (e.g. an API key+supplied via an `LDR_*` variable) through the settings API no longer returns+the value in plaintext — it is now redacted like every other settings+response.diff --git a/changelog.d/+unprotected-egress-operator-gate.security.md b/changelog.d/+unprotected-egress-operator-gate.security.mdnew file mode 100644index 0000000000..3526d1a6a6--- /dev/null+++ b/changelog.d/+unprotected-egress-operator-gate.security.md@@ -0,0 +1,10 @@+The `unprotected` egress scope is now disabled by default and requires the+server operator to set `LDR_POLICY_ALLOW_UNPROTECTED_EGRESS=true`. Migration+`0027` rewrites legacy stored and queued `unprotected` selections to+`adaptive`, so a later operator opt-in can't silently reactivate them.+Environment policy overrides are reapplied when queued work is dispatched.+While the gate is off, new `unprotected` writes (settings save, per-research+override) are rejected, and any residual or tampered queued value is coerced+to `adaptive` at dispatch with a `policy_audit` warning. Operator-enabled+`unprotected` remains supported, and the hard SSRF and cloud-metadata blocks+apply in every scope.diff --git a/changelog.d/5148.security.md b/changelog.d/5148.security.mdnew file mode 100644index 0000000000..88f25c27a5--- /dev/null+++ b/changelog.d/5148.security.md@@ -0,0 +1 @@+Explicit `max_results` and `time_period` overrides are now validated, retain precedence over queued values, and invalid persisted queued values are safely rejected instead of triggering transient retries.diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex 7fc04d0d65..6fe621eb8e 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -9,7 +9,7 @@ To override a setting using an environment variable, convert the key to uppercasFor example, `app.debug` becomes `LDR_APP_DEBUG`.Configuration Priority: Environment Variables > Web UI Config (Database) > Default Values-> Environmental Variables are used to override default values, easing installation, while allowing for adjustments to configuration via Web UI. When an environment variable is set, it takes precedence over any value stored in the database, and the Web UI marks that setting as non-editable. Programmatic writes (via the settings API or `import_settings`) still succeed but are silently shadowed by the env value on read.+> Environmental Variables are used to override default values, easing installation, while allowing for adjustments to configuration via Web UI. When an environment variable is set, it takes precedence over any value stored in the database, and the Web UI marks that setting as non-editable. Single-setting API updates and deletes are rejected while the setting is environment-locked; low-level programmatic imports that do not request environment-lock preservation may still be stored but remain shadowed by the environment value on read.## Pre-Database (Env-Only) Settings@@ -39,6 +39,7 @@ They are not available in the Web UI because they are needed to start the applic| `LDR_NEWS_SCHEDULER_ENABLED` | Boolean | `True` | No | | Enable or disable the news subscription scheduler | News Scheduler | || `LDR_NOTIFICATIONS_ALLOW_OUTBOUND` | Boolean | `False` | No | | Master switch for outbound notification webhooks (Apprise). Disabled by default because Apprise re-resolves DNS at send time, leaving a DNS-rebinding TOCTOU window that cannot be closed in code (Apprise exposes no Session/DNS hook). See SECURITY.md 'Notification Webhook SSRF' for details. Set to true only after reviewing the residual risk. Distinct from the per-user notifications.enabled toggle in the settings UI: this is the server-level operator gate, env-only so it cannot be flipped via the user-writable settings API. | Security | || `LDR_NOTIFICATIONS_ALLOW_PRIVATE_IPS` | Boolean | `False` | No | | Allow notification webhooks to target private/local IP addresses. Environment-only to prevent SSRF bypass via the user-writable settings API. Only enable this if your notification endpoints are on a trusted local network. | Security | |+| `LDR_POLICY_ALLOW_UNPROTECTED_EGRESS` | Boolean | `False` | No | | Allow users to select the UNPROTECTED egress scope. Disabled by default; this is an environment-only operator gate and cannot be changed through the user-writable settings API. Hard SSRF and cloud-metadata protections remain active when enabled. | Security | || `LDR_SECURITY_ALLOW_NAT64` | Boolean | `False` | No | | Allow outbound traffic to NAT64 prefixes (64:ff9b::/96 RFC 6052 well-known and 64:ff9b:1::/48 RFC 8215 local-use). Disabled by default to close the IPv6-wrapped SSRF bypass class — on hosts configured with NAT64 routes, attacker-supplied URLs can wrap cloud-metadata or RFC1918 destinations through these prefixes. Enable only on IPv6-only deployments (DNS64+NAT64) where outbound IPv4 traffic is synthesized through this prefix and the operator has accepted the residual SSRF risk. 6to4 (2002::/16), Teredo (2001::/32), and the discard prefix (100::/64) remain unconditionally blocked because they have no live legitimate use in 2026. The cloud-metadata block (ALWAYS_BLOCKED_METADATA_IPS) still applies via embedded-IPv4 extraction — see SECURITY.md. | Security | || `LDR_SECURITY_CORS_ALLOWED_ORIGINS` | String | `None` | No | | Allowed CORS origins for API routes (comma-separated). Use '*' for all origins, empty for same-origin only. Example: 'https://example.com,https://app.example.com' | Security | || `LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS` | String | `None` | No | | Allowed origins for WebSocket/Socket.IO connections (comma-separated). Unset or empty means same-origin only (default); use '*' to allow all origins. Example: 'https://example.com,https://app.example.com' | Security | |@@ -187,7 +188,7 @@ 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.); UNPROTECTED = escape hatch that disables egress protection entirely (not recommended; hard SSRF/cloud-metadata blocking still applies). | 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 = operator-enabled escape hatch that disables egress protection entirely (not recommended; requires LDR_POLICY_ALLOW_UNPROTECTED_EGRESS=true; 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` | Maximum number of documents grouped into a single SSE progress batch on /api/rag/index-all. Documents within a batch are processed in parallel via rag.indexing_max_parallel_docs. Higher values reduce SSE overhead but increase the unit of cancellation. | APP |diff --git a/docs/egress-modes.md b/docs/egress-modes.mdindex f5129ecdfe..f1c8fd659a 100644--- a/docs/egress-modes.md+++ b/docs/egress-modes.md@@ -53,7 +53,7 @@ the whole run automatically stays local — nothing leaves the box.## <a id="unprotected"></a>🔓 Unprotected-**Not recommended — an escape hatch.** Egress-scope restrictions are disabled+**Not recommended — an operator-enabled escape hatch.** This mode is unavailable by default. The server operator must set `LDR_POLICY_ALLOW_UNPROTECTED_EGRESS=true` and restart the application. When enabled, egress-scope restrictions are disabledfor the run: any engine, URL, and LLM/embeddings provider is permitted. Thehard SSRF and cloud-metadata blocks still apply. A loud, non-dismissible bannershows while it is active. Prefer marking a collection **public**, or adding a@@ -61,6 +61,13 @@ shows while it is active. Prefer marking a collection **public**, or adding a`policy.trusted_search_engines`) for the specific case, over disablingprotection wholesale.+> Legacy `unprotected` selections (saved settings and already-queued+> research snapshots) are migrated to **Adaptive** by migration `0027` on+> upgrade, so they won't silently reactivate if an operator later turns the+> gate on. While the gate stays off, choosing `unprotected` for a new run or+> saving it as your default is refused; a queued run that still carries a+> residual `unprotected` snapshot runs as **Adaptive** instead.+> 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 privatediff --git a/docs/env_configuration.md b/docs/env_configuration.mdindex ce6da9b33a..37086dc756 100644--- a/docs/env_configuration.md+++ b/docs/env_configuration.md@@ -27,6 +27,8 @@ For example:> **Important:** Environment variables **override** UI settings and lock them — the setting becomes read-only in the UI until the environment variable is removed. For settings you may want to adjust later, use the Web UI instead.>> **Note on empty values:** Empty environment variables (e.g., `LDR_LLM_PROVIDER=""`) are treated as **not set** — they will not override anything and the setting remains editable in the UI. This is by design: deployment tools like Unraid and Docker Compose templates often create all environment variables even when fields are left blank. Only non-empty values act as overrides. To remove an override, delete the environment variable entirely rather than setting it to an empty string. To explicitly block a setting, set it to any non-empty invalid value (e.g., `DISABLED`).+>+> **Per-run overrides:** When starting research via the API or web UI, explicit per-run parameters (`max_results`, `time_period`, `iterations`, `questions_per_iteration`, `strategy`) take precedence over both database settings **and** environment variable overrides for that specific run. Environment variables still lock the stored setting and UI; the per-run exception applies only to the explicit request payload, not to persisted configuration.For the complete list of all settings, their environment variable names, and default values, see [CONFIGURATION.md](CONFIGURATION.md).diff --git a/scripts/generate_config_docs.py b/scripts/generate_config_docs.pyindex 84d676ec9b..5a9dc11396 100755--- a/scripts/generate_config_docs.py+++ b/scripts/generate_config_docs.py@@ -245,7 +245,7 @@ def generate_docs_content(root_dir: Optional[Path] = None) -> str:"For example, `app.debug` becomes `LDR_APP_DEBUG`.","","Configuration Priority: Environment Variables > Web UI Config (Database) > Default Values",- "> Environmental Variables are used to override default values, easing installation, while allowing for adjustments to configuration via Web UI. When an environment variable is set, it takes precedence over any value stored in the database, and the Web UI marks that setting as non-editable. Programmatic writes (via the settings API or `import_settings`) still succeed but are silently shadowed by the env value on read.",+ "> Environmental Variables are used to override default values, easing installation, while allowing for adjustments to configuration via Web UI. When an environment variable is set, it takes precedence over any value stored in the database, and the Web UI marks that setting as non-editable. Single-setting API updates and deletes are rejected while the setting is environment-locked; low-level programmatic imports that do not request environment-lock preservation may still be stored but remain shadowed by the environment value on read.","",]diff --git a/src/local_deep_research/api/settings_utils.py b/src/local_deep_research/api/settings_utils.pyindex 3d2b799673..c9b487f660 100644--- a/src/local_deep_research/api/settings_utils.py+++ b/src/local_deep_research/api/settings_utils.py@@ -71,14 +71,6 @@ class InMemorySettingsManager(ISettingsManager):for key, setting_data in defaults.items():self._settings[key] = setting_data.copy()- # Check environment variable override- env_value = check_env_setting(key)- if env_value is not None:- # Use the typed value conversion- self._settings[key]["value"] = self._get_typed_value(- setting_data, env_value- )-# Load search engine configurations from individual JSON filesfrom importlib import resourcesimport json@@ -112,6 +104,10 @@ class InMemorySettingsManager(ISettingsManager):"""Get a setting value."""if key in self._settings:setting_data = self._settings[key]+ if check_env:+ env_value = check_env_setting(key)+ if env_value is not None:+ return self._get_typed_value(setting_data, env_value)value = setting_data.get("value", default)# Ensure the value has the correct typereturn self._get_typed_value(setting_data, value)@@ -126,15 +122,50 @@ class InMemorySettingsManager(ISettingsManager):return Truereturn False- def get_all_settings(self) -> dict[str, Any]:+ def get_all_settings(+ self,+ bypass_cache: bool = False,+ include_environment_overrides: bool = True,+ strict: bool = False,+ ) -> dict[str, Any]:"""Get all settings with metadata."""- return copy.deepcopy(self._settings)+ result = copy.deepcopy(self._settings)+ if include_environment_overrides:+ for key, setting_data in result.items():+ if (+ not isinstance(setting_data, dict)+ or "value" not in setting_data+ ):+ continue+ env_value = check_env_setting(key)+ if env_value is not None:+ setting_data["value"] = self._get_typed_value(+ setting_data, env_value+ )+ setting_data["editable"] = False+ return resultdef load_from_defaults_file(self, commit: bool = True, **kwargs: Any) -> None:- """Reload defaults (already done in __init__)."""+ """Reload defaults while honoring environment-lock preservation."""+ preserve_locked = bool(kwargs.get("preserve_environment_locked", False))+ preserved_values = (+ {+ key: copy.deepcopy(value["value"])+ for key, value in self._settings.items()+ if isinstance(value, dict)+ and "value" in value+ and check_env_setting(key) is not None+ }+ if preserve_locked+ else {}+ )+ self._settings.clear()self._load_defaults()+ for key, value in preserved_values.items():+ if key in self._settings:+ self._settings[key]["value"] = valuedef create_or_update_setting(self, setting: dict[str, Any] | Any, commit: bool = True@@ -165,9 +196,9 @@ class InMemorySettingsManager(ISettingsManager):value = self.get_setting(key, default, check_env)return to_bool(value, default)- def get_settings_snapshot(self) -> dict[str, Any]:+ def get_settings_snapshot(self, strict: bool = False) -> dict[str, Any]:"""Get a simplified settings snapshot with just key-value pairs."""- all_settings = self.get_all_settings()+ all_settings = self.get_all_settings(strict=strict)snapshot = {}for key, setting in all_settings.items():if isinstance(setting, dict) and "value" in setting:@@ -182,19 +213,47 @@ class InMemorySettingsManager(ISettingsManager):commit: bool = True,overwrite: bool = True,delete_extra: bool = False,+ preserve_environment_locked: bool = False,) -> None:"""Import settings from a dictionary."""if delete_extra:+ preserved = (+ {+ key: copy.deepcopy(value)+ for key, value in self._settings.items()+ if check_env_setting(key) is not None+ }+ if preserve_environment_locked+ else {}+ )self._settings.clear()+ self._settings.update(preserved)for key, value in settings_data.items():- if overwrite or key not in self._settings:+ existing_setting = self._settings.get(key)+ preserve_value = (+ preserve_environment_locked+ and check_env_setting(key) is not None+ and isinstance(existing_setting, dict)+ and "value" in existing_setting+ )+ if preserve_value and not isinstance(value, dict):+ # A bare-scalar import carries no metadata to merge; keep+ # the stored env-locked entry untouched.+ continue+ if overwrite or key not in self._settings or preserve_value:# Ensure proper type handling for imported settings+ setting_values = (+ value.copy() if isinstance(value, dict) else value+ )if isinstance(value, dict) and "value" in value:typed_value = self._get_typed_value(value, value["value"])- value = value.copy()- value["value"] = typed_value- self._settings[key] = value+ setting_values["value"] = typed_value+ if preserve_value:+ setting_values["value"] = copy.deepcopy(+ existing_setting["value"]+ )+ self._settings[key] = setting_valuesdef get_default_settings_snapshot() -> dict[str, Any]:diff --git a/src/local_deep_research/database/migrations/versions/0027_disable_legacy_unprotected_egress.py b/src/local_deep_research/database/migrations/versions/0027_disable_legacy_unprotected_egress.pynew file mode 100644index 0000000000..a23821853e--- /dev/null+++ b/src/local_deep_research/database/migrations/versions/0027_disable_legacy_unprotected_egress.py@@ -0,0 +1,133 @@+"""Reset legacy unprotected egress selections to the protective default.++The unprotected escape hatch is now operator-gated and disabled by default.+Rewriting existing rows prevents a later operator opt-in from silently+reactivating choices made before that capability boundary existed.++What this migration does:+1. settings: rows whose ``policy.egress_scope`` decodes to a legacy+ ``unprotected`` value (any case/padding) are rewritten to ``adaptive``.+2. queued_researches: each ``settings_snapshot`` JSON blob is inspected for+ the same key — both the wrapped submission shape (a nested+ ``settings_snapshot`` dict) and the legacy flat shape, holding either a+ bare scalar or a ``{"value": ...}`` metadata dict — and matching entries+ are rewritten to ``adaptive``. Only rows that actually change are+ re-serialized; malformed or unrecognized snapshots are left untouched.++Revision ID: 0027+Revises: 0026+"""++from __future__ import annotations++import json++import sqlalchemy as sa+from alembic import op+from loguru import logger+from sqlalchemy import inspect++revision = "0027"+down_revision = "0026"+branch_labels = None+depends_on = None++EGRESS_SCOPE_KEY = "policy.egress_scope"+REPLACEMENT_SCOPE_JSON = json.dumps("adaptive")++_settings = sa.table("settings", sa.column("key"), sa.column("value"))+_queued = sa.table(+ "queued_researches", sa.column("id"), sa.column("settings_snapshot")+)+++def _is_legacy_unprotected(scope) -> bool:+ return isinstance(scope, str) and scope.strip().lower() == "unprotected"+++def _rewrite_queued_research_snapshots(conn) -> None:+ rows = conn.execute(+ sa.select(_queued.c.id, _queued.c.settings_snapshot)+ ).fetchall()++ rewritten = 0+ for row_id, raw in rows:+ if not raw:+ continue+ try:+ snapshot = json.loads(raw) if isinstance(raw, str) else raw+ except (TypeError, json.JSONDecodeError):+ continue+ if not isinstance(snapshot, dict):+ continue++ settings = snapshot+ if "settings_snapshot" in snapshot:+ settings = snapshot["settings_snapshot"]+ if not isinstance(settings, dict):+ continue++ entry = settings.get(EGRESS_SCOPE_KEY)+ if isinstance(entry, dict):+ if not _is_legacy_unprotected(entry.get("value")):+ continue+ entry["value"] = "adaptive"+ elif _is_legacy_unprotected(entry):+ settings[EGRESS_SCOPE_KEY] = "adaptive"+ else:+ continue++ conn.execute(+ sa.update(_queued)+ .where(_queued.c.id == row_id)+ .values(settings_snapshot=json.dumps(snapshot))+ )+ rewritten += 1++ if rewritten:+ logger.info(+ "Reset legacy unprotected egress scopes in {} queued research row(s).",+ rewritten,+ )+++def upgrade() -> None:+ conn = op.get_bind()+ inspector = inspect(conn)+ if inspector.has_table("settings"):+ rows = conn.execute(+ sa.select(_settings.c.value).where(+ _settings.c.key == EGRESS_SCOPE_KEY+ )+ ).all()+ matched = False+ for (raw_value,) in rows:+ try:+ decoded = (+ json.loads(raw_value)+ if isinstance(raw_value, str)+ else raw_value+ )+ except (TypeError, json.JSONDecodeError):+ continue+ if _is_legacy_unprotected(decoded):+ matched = True+ break++ if matched:+ result = conn.execute(+ sa.update(_settings)+ .where(_settings.c.key == EGRESS_SCOPE_KEY)+ .values(value=REPLACEMENT_SCOPE_JSON)+ )+ logger.info(+ "Reset {} legacy unprotected egress-scope row(s) to adaptive.",+ result.rowcount,+ )++ if inspector.has_table("queued_researches"):+ _rewrite_queued_research_snapshots(conn)+++def downgrade() -> None:+ """No-op: restoring a disabled escape hatch would weaken policy."""diff --git a/src/local_deep_research/database/migrations/versions/0028_expand_rag_index_identity.py b/src/local_deep_research/database/migrations/versions/0028_expand_rag_index_identity.pynew file mode 100644index 0000000000..de37cf78c9--- /dev/null+++ b/src/local_deep_research/database/migrations/versions/0028_expand_rag_index_identity.py@@ -0,0 +1,74 @@+"""Allow one RAG index per full configuration.++The old uniqueness rule allowed only one row for a collection, model, and+provider. Chunking and vector-index configuration can change independently, so+that rule rejects valid, distinct indexes.++Downgrade is lossless only when no rows share the old unique key. It refuses+otherwise rather than deleting full-configuration indexes to re-create the+obsolete constraint.++Revision ID: 0028+Revises: 0027+"""++from alembic import op+from sqlalchemy import inspect, text+++revision = "0028"+down_revision = "0027"+branch_labels = None+depends_on = None++_TABLE = "rag_indices"+_CONSTRAINT = "uix_collection_model"+++def _has_unique_constraint() -> bool:+ bind = op.get_bind()+ inspector = inspect(bind)+ if not inspector.has_table(_TABLE):+ return False+ return _CONSTRAINT in {+ constraint["name"]+ for constraint in inspector.get_unique_constraints(_TABLE)+ }+++def upgrade() -> None:+ if not _has_unique_constraint():+ return+ with op.batch_alter_table(_TABLE) as batch_op:+ batch_op.drop_constraint(_CONSTRAINT, type_="unique")+++def downgrade() -> None:+ if _has_unique_constraint():+ return+ bind = op.get_bind()+ if not inspect(bind).has_table(_TABLE):+ return+ duplicates = bind.execute(+ text(+ "SELECT COUNT(*) FROM ("+ " SELECT 1 FROM rag_indices"+ " GROUP BY collection_name, embedding_model, embedding_model_type"+ " HAVING COUNT(*) > 1"+ ")"+ )+ ).scalar()+ if duplicates:+ raise RuntimeError(+ f"Cannot downgrade past 0028: {duplicates} "+ "(collection_name, embedding_model, embedding_model_type) group(s) "+ "in rag_indices have multiple full configurations, which the "+ "re-created uix_collection_model UNIQUE constraint forbids. "+ "Downgrade refuses to delete indexes; remove or consolidate the "+ "extra configurations manually before downgrading."+ )+ with op.batch_alter_table(_TABLE) as batch_op:+ batch_op.create_unique_constraint(+ _CONSTRAINT,+ ["collection_name", "embedding_model", "embedding_model_type"],+ )diff --git a/src/local_deep_research/database/models/library.py b/src/local_deep_research/database/models/library.pyindex 824ba9777e..05cb513380 100644--- a/src/local_deep_research/database/models/library.py+++ b/src/local_deep_research/database/models/library.py@@ -765,7 +765,7 @@ class LibraryStatistics(Base):class RAGIndex(Base):"""Tracks FAISS indices for RAG collections.- Each collection+embedding_model combination has its own FAISS index.+ Each full embedding and chunking configuration has its own FAISS index."""__tablename__ = "rag_indices"@@ -852,14 +852,7 @@ class RAGIndex(Base):UtcDateTime, nullable=True) # Last time index was searched- # Ensure one active index per collection+model__table_args__ = (- UniqueConstraint(- "collection_name",- "embedding_model",- "embedding_model_type",- name="uix_collection_model",- ),Index("idx_collection_current", "collection_name", "is_current"),)diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex d268da0637..31e24ca209 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -5265,7 +5265,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.); UNPROTECTED = escape hatch that disables egress protection entirely (not recommended; hard SSRF/cloud-metadata blocking still applies).",+ "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 = operator-enabled escape hatch that disables egress protection entirely (not recommended; requires LDR_POLICY_ALLOW_UNPROTECTED_EGRESS=true; hard SSRF/cloud-metadata blocking still applies).","editable": true,"max_value": null,"min_value": null,diff --git a/src/local_deep_research/exceptions.py b/src/local_deep_research/exceptions.pyindex b05ceaf8c8..7558a92ef8 100644--- a/src/local_deep_research/exceptions.py+++ b/src/local_deep_research/exceptions.py@@ -55,3 +55,9 @@ class DuplicateResearchError(Exception):"""pass+++class InvalidQueuedResearchOverridesError(Exception):+ """Raised when persisted queued search overrides fail validation."""++ passdiff --git a/src/local_deep_research/mcp/server.py b/src/local_deep_research/mcp/server.pyindex 0135f80449..34bea267f1 100644--- a/src/local_deep_research/mcp/server.py+++ b/src/local_deep_research/mcp/server.py@@ -49,6 +49,7 @@ from local_deep_research.search_system_factory import ()from ..utilities.type_utils import unwrap_settingfrom ..constants import DEFAULT_SEARCH_TOOL+from ..security.egress.policy import PolicyDeniedError# Create FastMCP server instancemcp = FastMCP(@@ -82,6 +83,33 @@ def _classify_error(error_msg: str) -> str:return "unknown"+def _policy_denied_response(+ error: PolicyDeniedError, operation: str+) -> Dict[str, Any]:+ """Build a machine-readable, leak-safe response for a PolicyDeniedError.++ The PDP's short ``reason`` code (e.g. ``scope_mismatch_private_only``) is+ safe to surface -- it is a machine code, never user content. The+ ``target`` attribute is not (engine names / URLs may carry user content+ or internal hostnames), so it is logged at audit level but never returned+ to the client. Fail-closed is preserved by construction: this helper only+ runs after the PEP has already raised, so the underlying engine run has+ already been blocked.+ """+ reason = error.decision.reason+ logger.bind(policy_audit=True).warning(+ "MCP tool denied by egress policy",+ operation=operation,+ reason=reason,+ )+ return {+ "status": "error",+ "error_type": "policy_denied",+ "reason": reason,+ "error": f"{operation} denied by egress policy: {reason}.",+ }++class ValidationError(Exception):"""Raised when parameter validation fails."""@@ -395,6 +423,8 @@ def quick_research(except ValidationError as e:logger.warning("Validation failed for quick research")return _error_result(e, error_type="validation_error")+ except PolicyDeniedError as e:+ return _policy_denied_response(e, "Quick research")except Exception as e:logger.exception(f"Quick research failed for query: {query[:100] if query else 'empty'}"@@ -478,6 +508,8 @@ def detailed_research(except ValidationError as e:logger.warning("Validation failed for detailed research")return _error_result(e, error_type="validation_error")+ except PolicyDeniedError as e:+ return _policy_denied_response(e, "Detailed research")except Exception as e:logger.exception(f"Detailed research failed for query: {query[:100] if query else 'empty'}"@@ -548,6 +580,8 @@ def generate_report(except ValidationError as e:logger.warning("Validation failed for report generation")return _error_result(e, error_type="validation_error")+ except PolicyDeniedError as e:+ return _policy_denied_response(e, "Report generation")except Exception as e:logger.exception(f"Report generation failed for query: {query[:100] if query else 'empty'}"@@ -621,6 +655,8 @@ def analyze_documents(except ValidationError as e:logger.warning("Validation failed for document analysis")return _error_result(e, error_type="validation_error")+ except PolicyDeniedError as e:+ return _policy_denied_response(e, "Document analysis")except Exception as e:logger.exception(f"Document analysis failed for collection: {collection_name if collection_name else 'empty'}"@@ -727,6 +763,8 @@ def search(except ValidationError as e:logger.warning("Validation failed for search")return _error_result(e, error_type="validation_error")+ except PolicyDeniedError as e:+ return _policy_denied_response(e, "Search")except Exception as e:logger.exception(f"Search failed for query: {query[:100] if query else 'empty'}"diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.pyindex e16a01a3af..52757976d9 100644--- a/src/local_deep_research/research_library/routes/rag_routes.py+++ b/src/local_deep_research/research_library/routes/rag_routes.py@@ -53,7 +53,7 @@ from ...web.utils.request_helpers import parse_bool_argfrom ...utilities.db_utils import get_settings_managerfrom ...utilities.resource_utils import safe_closefrom ..services.library_rag_service import LibraryRAGService-from ...settings.manager import SettingsManager+from ...settings.manager import SettingsManager, check_env_settingfrom ...security.file_upload_validator import FileUploadValidatorfrom ...security.rate_limiter import (upload_rate_limit_ip,@@ -256,6 +256,20 @@ def _get_text_separators(settings):return text_separators+def _parse_configured_text_separators(value):+ separators = value+ if isinstance(value, str):+ try:+ separators = json.loads(value)+ except json.JSONDecodeError:+ return None+ if not isinstance(separators, list) or not all(+ isinstance(separator, str) for separator in separators+ ):+ return None+ return separators++# Module prefix for exceptions DEFINED inside LDR itself. An exception whose# class lives under ``local_deep_research`` is something only we can fix, so we# steer the user to file a bug instead of second-guessing their model choice.@@ -618,14 +632,33 @@ def get_available_models():"""Get list of available embedding providers and models."""try:from ...embeddings.embeddings_config import _get_provider_classes+ from ...security.egress.policy import (+ Decision,+ PolicyDeniedError,+ )- # Get current settings for providers+ # Get current settings for providers. STRICT snapshot is mandatory+ # at this policy-sensitive seam: a non-strict read silently falls+ # back to JSON defaults when the underlying settings query fails+ # (SQLAlchemyError / stale enum row), and a defaults-only snapshot+ # can lack the operator-selected scope/provider inputs that the+ # local-only posture is supposed to enforce. We refuse before any+ # provider discovery, credential read, or network probe instead of+ # admitting a cloud embedder under a permissive fallback.settings = get_settings_manager()- settings_snapshot = (- settings.get_all_settings()- if hasattr(settings, "get_all_settings")- else {}- )+ try:+ settings_snapshot = (+ settings.get_all_settings(strict=True)+ if hasattr(settings, "get_all_settings")+ else {}+ )+ except PolicyDeniedError:+ raise+ except Exception as exc:+ raise PolicyDeniedError(+ Decision(False, "settings_unavailable"),+ target="available_rag_models",+ ) from exc# Get provider classesprovider_classes = _get_provider_classes()@@ -731,6 +764,29 @@ def get_available_models():})except Exception as e:+ # Egress policy denial (incl. settings_unavailable) → clean 4xx/5xx+ # so the caller distinguishes a refused probe from a server crash.+ from ...security.egress.policy import PolicyDeniedError as _PDE++ if isinstance(e, _PDE):+ reason = e.decision.reason+ status_code = 503 if reason == "settings_unavailable" else 400+ logger.bind(policy_audit=True).info(+ "available-models refused by egress policy",+ reason=reason,+ target=e.target,+ )+ return jsonify(+ {+ "success": False,+ "error": (+ "Settings are currently unavailable; cannot safely "+ "enumerate embedding models."+ )+ if reason == "settings_unavailable"+ else f"Available-models request refused ({reason}).",+ }+ ), status_codereturn handle_api_error("getting available models", e)@@ -1049,8 +1105,7 @@ def configure_rag():Change RAG configuration (embedding model, chunk size, etc.).This will create a new index with the new configuration."""- import json as json_lib-+ db_session = Nonetry:data = request.get_json()embedding_model = data.get("embedding_model")@@ -1083,35 +1138,72 @@ def configure_rag():}), 400+ text_separators = _parse_configured_text_separators(text_separators)+ if text_separators is None:+ return jsonify(+ {+ "success": False,+ "error": "text_separators must be a JSON array of strings",+ }+ ), 400+# Save settings to databasesettings = get_settings_manager()- settings.set_setting("local_search_embedding_model", embedding_model)- settings.set_setting(- "local_search_embedding_provider", embedding_provider+ db_session = settings.db_session+ if db_session is None:+ return jsonify(+ {+ "success": False,+ "error": "Unable to save RAG configuration. No changes were applied.",+ }+ ), 500+ requested_settings = (+ ("local_search_embedding_model", embedding_model),+ ("local_search_embedding_provider", embedding_provider),+ ("local_search_chunk_size", int(chunk_size)),+ ("local_search_chunk_overlap", int(chunk_overlap)),+ ("local_search_splitter_type", splitter_type),+ ("local_search_text_separators", text_separators),+ ("local_search_distance_metric", distance_metric),+ ("local_search_normalize_vectors", bool(normalize_vectors)),+ ("local_search_index_type", index_type),)- settings.set_setting("local_search_chunk_size", int(chunk_size))- settings.set_setting("local_search_chunk_overlap", int(chunk_overlap))+ requested_setting_keys = [key for key, _value in requested_settings]- # Save new advanced settings- settings.set_setting("local_search_splitter_type", splitter_type)+ if settings.settings_locked:+ return jsonify(+ {+ "success": False,+ "error": "RAG configuration is locked by app.lock_settings",+ }+ ), 403++ environment_locked_keys = [+ key+ for key, _value in requested_settings+ if check_env_setting(key) is not None+ ]+ if environment_locked_keys:+ return jsonify(+ {+ "success": False,+ "error": (+ "Settings "+ f"{', '.join(environment_locked_keys)} "+ "are environment-locked"+ ),+ }+ ), 403- # The setting is registered with ui_element "json", so store the- # separators as a proper list. A string payload (e.g. a textarea- # value) is parsed into a list first; if it is not valid JSON it is- # stored as-is so the UI validation layer can flag it.- if isinstance(text_separators, str):- try:- text_separators = json_lib.loads(text_separators)- except json_lib.JSONDecodeError:- logger.debug(- "Invalid JSON for text_separators input; storing raw string for validation"- )- settings.set_setting("local_search_text_separators", text_separators)- settings.set_setting("local_search_distance_metric", distance_metric)- settings.set_setting(- "local_search_normalize_vectors", bool(normalize_vectors)- )- settings.set_setting("local_search_index_type", index_type)+ for key, value in requested_settings:+ if not settings.set_setting(key, value, commit=False):+ db_session.rollback()+ return jsonify(+ {+ "success": False,+ "error": "Unable to save RAG configuration. No changes were applied.",+ }+ ), 500# If collection_id is provided, update that collection's configurationif collection_id:@@ -1123,35 +1215,37 @@ def configure_rag():chunk_size=int(chunk_size),chunk_overlap=int(chunk_overlap),splitter_type=splitter_type,- text_separators=text_separators- if isinstance(text_separators, list)- else DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS,+ text_separators=text_separators,distance_metric=distance_metric,normalize_vectors=normalize_vectors,index_type=index_type,) as new_rag_service:# Get or create new index with this configurationrag_index = new_rag_service._get_or_create_rag_index(- collection_id+ collection_id, db_session=db_session, commit=False)-- return jsonify(- {- "success": True,- "message": "Configuration updated for collection. You can now index documents with the new settings.",- "index_hash": rag_index.index_hash,- }- )- else:- # Just saving default settings without updating a specific collection+ db_session.commit()+ settings.emit_settings_changed_after_commit(requested_setting_keys)return jsonify({"success": True,- "message": "Default embedding settings saved successfully. New collections will use these settings.",+ "message": "Configuration updated for collection. You can now index documents with the new settings.",+ "index_hash": rag_index.index_hash,})+ # Just saving default settings without updating a specific collection+ db_session.commit()+ settings.emit_settings_changed_after_commit(requested_setting_keys)+ return jsonify(+ {+ "success": True,+ "message": "Default embedding settings saved successfully. New collections will use these settings.",+ }+ )except Exception as e:+ if db_session is not None:+ db_session.rollback()return handle_api_error("configuring RAG", e)diff --git a/src/local_deep_research/research_library/services/library_rag_service.py b/src/local_deep_research/research_library/services/library_rag_service.pyindex 0d7eb88744..d731f3fd7d 100644--- a/src/local_deep_research/research_library/services/library_rag_service.py+++ b/src/local_deep_research/research_library/services/library_rag_service.py@@ -11,6 +11,7 @@ Handles indexing and searching library documents using RAG:import threadingimport time+import jsonfrom contextlib import contextmanagerfrom dataclasses import dataclassfrom datetime import datetime, UTC@@ -24,8 +25,10 @@ from langchain_core.documents import Document as LangchainDocumentfrom loguru import loggerfrom sqlalchemy import funcfrom sqlalchemy.exc import IntegrityError+from sqlalchemy.orm import Sessionfrom ...config.paths import get_cache_directory+from ...constants import DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORSfrom ...database.models.library import (Document,DocumentChunk,@@ -342,17 +345,41 @@ class LibraryRAGService:if embedding_manager is not None:self.embedding_manager = embedding_managerelse:- # Initialize embedding manager with library collection- # Load the complete user settings snapshot from database using the proper method+ # Load the complete user settings snapshot from database using the+ # proper method.+ #+ # STRICT snapshot is mandatory at this seam: a non-strict read+ # silently falls back to the JSON defaults when the underlying+ # settings query fails (SQLAlchemyError / stale enum row). Those+ # defaults can lack an operator-selected cloud embedding+ # provider's classification inputs and admit a cloud embedder+ # under a local-only posture. We refuse before any+ # LocalEmbeddingManager construction instead.from ...settings.manager import SettingsManager+ from ...security.egress.policy import (+ Decision,+ PolicyDeniedError,+ )# Use proper database session for SettingsManager# Note: using _db_password (backing field) directly here because the# db_password property setter propagates to embedding_manager/integrity_manager,# which are still None at this point in __init__.- with get_user_db_session(username, self._db_password) as session:- settings_manager = SettingsManager(session)- settings_snapshot = settings_manager.get_settings_snapshot()+ try:+ with get_user_db_session(+ username, self._db_password+ ) as session:+ settings_manager = SettingsManager(session)+ settings_snapshot = settings_manager.get_settings_snapshot(+ strict=True+ )+ except PolicyDeniedError:+ raise+ except Exception as exc:+ raise PolicyDeniedError(+ Decision(False, "settings_unavailable"),+ target=embedding_provider,+ ) from exc# Add the specific settings needed for this RAG servicesettings_snapshot.update(@@ -370,23 +397,23 @@ class LibraryRAGService:# is covered, not just the factory. Skipped when an# ``embedding_manager`` is injected (tests / advanced flows)# — those callers vouch for the manager themselves.+ #+ # Build the context from the ACTUAL scope (not a hardcoded+ # BOTH) so PRIVATE_ONLY forces local embeddings even when the+ # raw embeddings.require_local flag is at its default False —+ # context_from_snapshot applies that coupling. Resolve the+ # primary via the shared helper (single source of truth)+ # instead of the old search.tool + searxng fallback, which+ # was a fail-OPEN: a missing primary defaulted to the public+ # searxng so the scope relaxed and a cloud embedder could be+ # admitted. A missing primary now raises -> fail closed via+ # the ValueError handler below.from ...security.egress.policy import (- Decision,- PolicyDeniedError,context_from_snapshot,evaluate_embeddings,resolve_run_primary_engine,)- # Build the context from the ACTUAL scope (not a hardcoded- # BOTH) so PRIVATE_ONLY forces local embeddings even when the- # raw embeddings.require_local flag is at its default False —- # context_from_snapshot applies that coupling. Resolve the primary- # via the shared helper (single source of truth) instead of the old- # search.tool + searxng fallback, which was a fail-OPEN: a missing- # primary defaulted to the public searxng so the scope relaxed and a- # cloud embedder could be admitted. A missing primary now raises ->- # fail closed via the ValueError handler below.try:primary = resolve_run_primary_engine(settings_snapshot)policy_ctx = context_from_snapshot(@@ -491,11 +518,74 @@ class LibraryRAGService:embedding_model_type: str,) -> str:"""Generate hash for index identification."""- hash_input = (- f"{collection_name}:{embedding_model}:{embedding_model_type}"+ identity = {+ "chunk_overlap": self.chunk_overlap,+ "chunk_size": self.chunk_size,+ "collection_name": collection_name,+ "distance_metric": self.distance_metric,+ "embedding_model": embedding_model,+ "embedding_provider": embedding_model_type,+ "index_type": self.index_type,+ "normalize_vectors": self.normalize_vectors,+ "splitter_type": self.splitter_type,+ "text_separators": self.text_separators,+ }+ hash_input = json.dumps(+ identity, ensure_ascii=False, separators=(",", ":"), sort_keys=True)return hashlib.sha256(hash_input.encode()).hexdigest()+ def _matches_current_index_configuration(self, rag_index: RAGIndex) -> bool:+ stored_provider = rag_index.embedding_model_type+ if isinstance(stored_provider, EmbeddingProvider):+ stored_provider = stored_provider.value+ stored_separators = rag_index.text_separators+ if stored_separators is None:+ stored_separators = DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS+ if not isinstance(stored_separators, list) or not all(+ isinstance(separator, str) for separator in stored_separators+ ):+ return False+ return (+ rag_index.embedding_model == self.embedding_model+ and stored_provider == self.embedding_provider+ and rag_index.chunk_size == self.chunk_size+ and rag_index.chunk_overlap == self.chunk_overlap+ and (rag_index.splitter_type or "recursive") == self.splitter_type+ and stored_separators == self.text_separators+ and (rag_index.distance_metric or "cosine") == self.distance_metric+ and (+ rag_index.normalize_vectors+ if rag_index.normalize_vectors is not None+ else True+ )+ == self.normalize_vectors+ and (rag_index.index_type or "flat") == self.index_type+ )++ def _find_matching_rag_index(+ self, db_session: Session, collection_name: str, index_hash: str+ ) -> RAGIndex | None:+ rag_index = (+ db_session.query(RAGIndex).filter_by(index_hash=index_hash).first()+ )+ if rag_index is not None:+ return rag_index++ candidates = (+ db_session.query(RAGIndex)+ .filter_by(+ collection_name=collection_name,+ embedding_model=self.embedding_model,+ embedding_model_type=EmbeddingProvider(self.embedding_provider),+ )+ .all()+ )+ for candidate in candidates:+ if self._matches_current_index_configuration(candidate):+ return candidate+ return None+def _get_index_path(self, index_hash: str) -> Path:"""Get path for FAISS index file.@@ -677,7 +767,12 @@ class LibraryRAGService:)def _get_or_create_rag_index(- self, collection_id: str, *, promote_current: bool = True+ self,+ collection_id: str,+ *,+ promote_current: bool = True,+ db_session: Session | None = None,+ commit: bool = True,) -> RAGIndex:"""Get or create RAGIndex record for the current configuration.@@ -688,97 +783,104 @@ class LibraryRAGService:only an actual write (index) should. Creating a brand-new index stillpromotes it regardless (it's the collection's only index for that config)."""- with get_user_db_session(self.username, self.db_password) as session:- # Use collection_<uuid> format- collection_name = f"collection_{collection_id}"- index_hash = self._get_index_hash(- collection_name, self.embedding_model, self.embedding_provider- )+ if db_session is None:+ with get_user_db_session(+ self.username, self.db_password+ ) as session:+ return self._get_or_create_rag_index_in_session(+ session,+ collection_id,+ promote_current=promote_current,+ commit=commit,+ )+ return self._get_or_create_rag_index_in_session(+ db_session,+ collection_id,+ promote_current=promote_current,+ commit=commit,+ )- # Try to get existing index- rag_index = (- session.query(RAGIndex).filter_by(index_hash=index_hash).first()+ def _get_or_create_rag_index_in_session(+ self,+ db_session: Session,+ collection_id: str,+ *,+ promote_current: bool,+ commit: bool,+ ) -> RAGIndex:+ collection_name = f"collection_{collection_id}"+ index_hash = self._get_index_hash(+ collection_name, self.embedding_model, self.embedding_provider+ )+ rag_index = self._find_matching_rag_index(+ db_session, collection_name, index_hash+ )+ created = False++ if rag_index is None:+ index_path = self._get_index_path(index_hash)+ embedding_manager = self.embedding_manager+ if embedding_manager is None:+ raise RuntimeError(+ "Cannot create an index after closing the service"+ )+ embedding_dim = len(+ embedding_manager.embeddings.embed_query("test"))-- if not rag_index:- # A new index (e.g. an embedding-model change yields a new- # index_hash) supersedes any prior current index for this- # collection. Demote the old current row(s) FIRST so exactly one- # row is ever is_current=True — every read path resolves "the"- # current index via filter_by(is_current=True).first(), which- # would otherwise return an arbitrary one of several.- session.query(RAGIndex).filter_by(- collection_name=collection_name, is_current=True- ).update({"is_current": False})-- # Create new index record- index_path = self._get_index_path(index_hash)-- # Get embedding dimension by embedding a test string- test_embedding = self.embedding_manager.embeddings.embed_query(- "test"+ candidate = RAGIndex(+ collection_name=collection_name,+ embedding_model=self.embedding_model,+ embedding_model_type=EmbeddingProvider(self.embedding_provider),+ embedding_dimension=embedding_dim,+ index_path=str(index_path),+ index_hash=index_hash,+ chunk_size=self.chunk_size,+ chunk_overlap=self.chunk_overlap,+ splitter_type=self.splitter_type,+ text_separators=self.text_separators,+ distance_metric=self.distance_metric,+ normalize_vectors=self.normalize_vectors,+ index_type=self.index_type,+ chunk_count=0,+ total_documents=0,+ status=RAGIndexStatus.ACTIVE,+ is_current=False,+ )+ try:+ with db_session.begin_nested():+ db_session.add(candidate)+ db_session.flush()+ except IntegrityError:+ rag_index = self._find_matching_rag_index(+ db_session, collection_name, index_hash)- embedding_dim = len(test_embedding)-- rag_index = RAGIndex(- collection_name=collection_name,- embedding_model=self.embedding_model,- embedding_model_type=EmbeddingProvider(- self.embedding_provider- ),- embedding_dimension=embedding_dim,- index_path=str(index_path),- index_hash=index_hash,- chunk_size=self.chunk_size,- chunk_overlap=self.chunk_overlap,- splitter_type=self.splitter_type,- text_separators=self.text_separators,- distance_metric=self.distance_metric,- normalize_vectors=self.normalize_vectors,- index_type=self.index_type,- chunk_count=0,- total_documents=0,- status=RAGIndexStatus.ACTIVE,- is_current=True,+ if rag_index is None:+ raise+ logger.info(+ f"Using concurrently created RAG index: {index_hash}")- session.add(rag_index)- try:- session.commit()- except IntegrityError:- session.rollback()- rag_index = (- session.query(RAGIndex)- .filter_by(index_hash=index_hash)- .first()- )- if rag_index is None:- raise- logger.info(- f"Using concurrently created RAG index: {index_hash}"- )- else:- session.refresh(rag_index)- logger.info(f"Created new RAG index: {index_hash}")- elif promote_current and not rag_index.is_current:- # An existing index for THIS (collection, model) config is being- # reused (on a WRITE path) but is not marked current. After an- # embedding-model switch-and-revert (A -> B -> back to A), row A- # was demoted when B was created and never re-promoted, so "the- # current index" bookkeeping (filter_by(is_current=True)) would- # keep pointing at the now-inactive B. Demote any other current- # row for this collection and promote this one, mirroring the- # create branch. Gated on promote_current so a read-path search- # under a stale config can't steal the current pointer.- session.query(RAGIndex).filter(- RAGIndex.collection_name == collection_name,- RAGIndex.is_current.is_(True),- RAGIndex.id != rag_index.id,- ).update({"is_current": False})- rag_index.is_current = True- session.commit()- session.refresh(rag_index)-- return rag_index+ else:+ rag_index = candidate+ created = True+ logger.info(f"Created new RAG index: {index_hash}")++ mutated = created or (promote_current and not rag_index.is_current)+ if mutated:+ db_session.query(RAGIndex).filter(+ RAGIndex.collection_name == collection_name,+ RAGIndex.is_current.is_(True),+ RAGIndex.id != rag_index.id,+ ).update({"is_current": False})+ rag_index.is_current = True++ # Only commit when this call actually created or promoted an index.+ # A pure read-through of an existing current index must stay a no-op+ # so it can't consume a caller's pending write (e.g. the fault the+ # index-finalize self-heal backstop guards against).+ if commit and mutated:+ db_session.commit()+ db_session.refresh(rag_index)+ return rag_indexdef _quarantine_corrupt_index(self, index_path: Path, reason: str) -> None:"""Rename a corrupted FAISS index to ``<path>.corrupt-<ns>``@@ -2327,8 +2429,8 @@ class LibraryRAGService:collection_name, self.embedding_model, self.embedding_provider)with get_user_db_session(self.username, self.db_password) as session:- rag_index = (- session.query(RAGIndex).filter_by(index_hash=index_hash).first()+ rag_index = self._find_matching_rag_index(+ session, collection_name, index_hash)if rag_index is None:# Collection was never indexed with this configuration —diff --git a/src/local_deep_research/scheduler/background.py b/src/local_deep_research/scheduler/background.pyindex 5da703f7a9..f6a009b62b 100644--- a/src/local_deep_research/scheduler/background.py+++ b/src/local_deep_research/scheduler/background.py@@ -858,31 +858,51 @@ class BackgroundJobScheduler:f"for {username} with {settings.interval_seconds}s interval")- def _arm_egress_backstop(self, settings_manager, username: str) -> None:+ def _arm_egress_backstop(self, settings_manager, username: str) -> bool:"""Set the audit-hook egress context from the user's saved settings soscheduled document downloads run under the same secondary net as an- interactive research run. Best-effort and never raises — a backstop- failure must not break the scheduler; the DownloadService PEP remains- the primary gate. Cleared by the caller's @thread_cleanup on exit.+ interactive research run. Returns False when policy setup itself fails,+ because scheduled document work must not run without its policy+ snapshot. Other backstop failures remain best-effort; the+ DownloadService PEP remains the primary gate. Cleared by the caller's+ @thread_cleanup on exit."""try:from ..security.egress.audit_hook import set_active_context- from ..security.egress.policy import context_from_snapshot+ from ..security.egress.policy import (+ context_from_snapshot,+ resolve_run_primary_engine,+ )- snapshot = settings_manager.get_settings_snapshot()+ snapshot = settings_manager.get_settings_snapshot(strict=True)if not isinstance(snapshot, dict):- return- primary = settings_manager.get_setting(- "search.tool", DEFAULT_SEARCH_TOOL- )- ctx = context_from_snapshot(- snapshot, primary or DEFAULT_SEARCH_TOOL, username=username+ logger.bind(policy_audit=True).warning(+ "doc scheduler: egress policy setup failed; skipping scheduled work"+ )+ return False+ # Derive the primary engine from the SAME strict snapshot above+ # rather than a second, non-strict ``get_setting("search.tool",+ # DEFAULT_SEARCH_TOOL)`` call. A non-strict read could fall back to+ # the public DEFAULT_SEARCH_TOOL and silently widen the run's+ # adaptive scope. ``resolve_run_primary_engine`` is the single+ # source of truth used by the run-scoped PEPs; with no ``default``+ # it raises ValueError when ``search.tool`` is missing/blank, which+ # the outer except catches → fail-closed (no scheduled work).+ primary = resolve_run_primary_engine(snapshot)+ ctx = context_from_snapshot(snapshot, primary, username=username)+ except Exception:+ logger.bind(policy_audit=True).warning(+ "doc scheduler: egress policy setup failed; skipping scheduled work")+ return False++ try:set_active_context(ctx)except Exception:logger.bind(policy_audit=True).debug("doc scheduler: egress backstop not armed", exc_info=True)+ return True@thread_cleanupdef _process_user_documents(self, username: str):@@ -958,7 +978,8 @@ class BackgroundJobScheduler:# still gates each fetch (primary); this restores defense-in-# depth parity with an interactive run. @thread_cleanup clears# the context when this method returns.- self._arm_egress_backstop(settings_manager, username)+ if not self._arm_egress_backstop(settings_manager, username):+ return# Query for completed research since last runlogger.debug(@@ -1047,19 +1068,19 @@ class BackgroundJobScheduler:# explicitly per the pre-commit thread-safety check.try:user_settings_snapshot = (- settings_manager.get_settings_snapshot()+ settings_manager.get_settings_snapshot(strict=True)+ )+ except Exception:+ logger.bind(policy_audit=True).warning(+ "doc scheduler: egress policy setup failed; skipping scheduled work")- except Exception as e:- # ``password`` is live in this frame (it opened the- # surrounding ``get_user_db_session``). Drop traceback- # + redact str(e) to avoid leaking the SQLCipher- # master password.- safe_msg = redact_secrets(str(e), password)- logger.warning(- f"[DOC_SCHEDULER] Could not build settings snapshot: "- f"{safe_msg} — downloads will not be scope-gated"+ return++ if not isinstance(user_settings_snapshot, dict):+ logger.bind(policy_audit=True).warning(+ "doc scheduler: egress policy setup failed; skipping scheduled work")- user_settings_snapshot = None+ returnprocessed_count = 0for research in research_sessions:@@ -1369,7 +1390,8 @@ class BackgroundJobScheduler:# download, but embedding providers may make network calls;# this keeps defense-in-depth parity with an interactive run.# Cleared by @thread_cleanup on exit.- self._arm_egress_backstop(settings_manager, username)+ if not self._arm_egress_backstop(settings_manager, username):+ return# Resolve the parallel-worker count from the user's saved# settings so a configured ``rag.indexing_max_parallel_docs``diff --git a/src/local_deep_research/security/egress/README.md b/src/local_deep_research/security/egress/README.mdindex d7f1de05c1..a5d23c4031 100644--- a/src/local_deep_research/security/egress/README.md+++ b/src/local_deep_research/security/egress/README.md@@ -32,7 +32,7 @@ engines/destinations are permitted.| `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. |+| `unprotected` | **Operator-enabled escape hatch (not recommended).** Set `LDR_POLICY_ALLOW_UNPROTECTED_EGRESS=true` to make this mode available; it is disabled by default. When enabled, 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. Migration `0027` rewrites legacy stored and queued `unprotected` selections to `adaptive` so a later opt-in can't silently reactivate them; see the Settings-tampering caveat below for what happens to residual values while the gate is off. |Two independent toggles refine inference locality (and are **implied** underPRIVATE_ONLY / Adaptive-private):@@ -171,8 +171,22 @@ silent-expansion timing leak."local" inference at a cloud endpoint, or who marks a collection **public**,is making an informed choice.- **Settings tampering.** An attacker who can write a user's per-user- (SQLCipher) settings DB can flip the scope to `both` and disable enforcement.- Policy-key changes emit `policy_audit=True` audit log lines.+ (SQLCipher) settings DB cannot use the retired `both` value or+ operator-disabled `unprotected` to widen egress. A saved/queued/env+ `both` value is coerced back to `adaptive` by `context_from_snapshot`+ (the internal `EgressScope.BOTH` produced by adaptive resolution is a+ separate code path the user never picks). Migration `0027` does the+ same one-time rewrite for legacy `unprotected` values in the `settings`+ table and in `queued_researches.settings_snapshot`. At runtime the+ `LDR_POLICY_ALLOW_UNPROTECTED_EGRESS` gate (default off) still applies:+ saving `unprotected` or submitting it as a per-research override is+ rejected with `PolicyDeniedError("unprotected_egress_disabled")`, while+ a queued snapshot still carrying a residual or tampered `unprotected`+ value is coerced to `adaptive` at dispatch and logs a `policy_audit`+ warning (an unrecognised value refuses the run rather than fall back to+ `BOTH`). A per-user DB value cannot enable `unprotected` on its own;+ only the operator env var can. Policy-key changes emit+ `policy_audit=True` audit log lines.---diff --git a/src/local_deep_research/security/egress/__init__.py b/src/local_deep_research/security/egress/__init__.pyindex 7caf43dcd1..18a4351ebc 100644--- a/src/local_deep_research/security/egress/__init__.py+++ b/src/local_deep_research/security/egress/__init__.py@@ -20,6 +20,7 @@ from .policy import (MAX_DENIED_FETCHES_PER_RUN,PolicyDeniedError,context_from_snapshot,+ build_run_egress_context,classify_engine,evaluate_embeddings,evaluate_engine,@@ -47,6 +48,7 @@ __all__ = ["MAX_DENIED_FETCHES_PER_RUN","PolicyDeniedError","context_from_snapshot",+ "build_run_egress_context","classify_engine","evaluate_embeddings","evaluate_engine",diff --git a/src/local_deep_research/security/egress/policy.py b/src/local_deep_research/security/egress/policy.pyindex 6934754dd3..7cdc6fd7a9 100644--- a/src/local_deep_research/security/egress/policy.py+++ b/src/local_deep_research/security/egress/policy.py@@ -22,7 +22,7 @@ import threadingfrom concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutfrom dataclasses import dataclass, fieldfrom enum import Enum-from typing import Optional+from typing import Literal, Optionalfrom urllib.parse import unquote, urlsplitfrom loguru import logger@@ -89,6 +89,23 @@ class EgressScope(str, Enum):UNPROTECTED = "unprotected"+USER_SELECTABLE_PROTECTED_SCOPES = frozenset(+ {+ EgressScope.ADAPTIVE,+ EgressScope.PUBLIC_ONLY,+ EgressScope.PRIVATE_ONLY,+ EgressScope.STRICT,+ }+)+++def unprotected_egress_allowed() -> bool:+ """Return whether the operator enabled the unprotected escape hatch."""+ from ...settings.env_registry import get_env_setting++ return bool(get_env_setting("policy.allow_unprotected_egress", False))++# Code-side single source of truth for the default egress scope, used by# every reader that needs a fallback for a MISSING policy.egress_scope key# (partial snapshots from the programmatic API, un-bootstrapped settings@@ -165,6 +182,62 @@ class PolicyDeniedError(RuntimeError):super().__init__(f"policy_denied: {decision.reason}")+def parse_user_egress_scope(+ raw: object,+ *,+ disabled_unprotected: Literal["reject", "adaptive"] = "reject",+) -> EgressScope:+ """Parse a user-facing scope and enforce the operator escape-hatch gate.++ BOTH is deliberately absent from the protected allowlist: it remains an+ internal adaptive-resolution result, not a value users may select. Runtime+ readers can request the protective adaptive fallback for stale queued+ unprotected values; request and settings writers use the default hard+ rejection.+ """+ if disabled_unprotected not in {"reject", "adaptive"}:+ raise ValueError("disabled_unprotected must be 'reject' or 'adaptive'")+ if not isinstance(raw, str):+ raise PolicyDeniedError(+ Decision(False, "unknown_egress_scope"), target=str(raw)+ )+ normalized = raw.strip().lower()+ try:+ scope = EgressScope(normalized)+ except ValueError as exc:+ raise PolicyDeniedError(+ Decision(False, "unknown_egress_scope"), target=str(raw)+ ) from exc+ if scope in USER_SELECTABLE_PROTECTED_SCOPES:+ return scope+ if scope == EgressScope.UNPROTECTED:+ if unprotected_egress_allowed():+ return scope+ if disabled_unprotected == "adaptive":+ return EgressScope.ADAPTIVE+ raise PolicyDeniedError(+ Decision(False, "unprotected_egress_disabled"), target=str(raw)+ )+ raise PolicyDeniedError(+ Decision(False, "unknown_egress_scope"), target=str(raw)+ )+++def effective_scope_for_display(raw: object) -> str:+ """Return a canonical, presentation-safe user scope value.++ Invalid values, retired both, and operator-disabled unprotected selections+ render as the protective default. This helper is presentation only;+ enforcement remains in context_from_snapshot and its PEPs.+ """+ try:+ return parse_user_egress_scope(+ raw, disabled_unprotected="adaptive"+ ).value+ except PolicyDeniedError:+ return DEFAULT_EGRESS_SCOPE++def _is_nat64_wrapped_metadata(hostname: str) -> bool:"""True iff ``hostname`` parses as an IPv6 NAT64 address wrapping acloud-metadata IPv4 (AWS / Azure / GCE / etc).@@ -322,11 +395,14 @@ def _classify_host(# Fail-safe: unresolvable / timeout → treat as public.return _cache_classification(ctx, hostname, False)- # If any resolved IP is private (and not a NAT64 metadata wrap),- # classify as local.+ # A hostname is local only when every resolved address is local. A single+ # public or metadata answer can be selected by the HTTP client, so it must+ # prevent a local classification.+ if not addr_info:+ return _cache_classification(ctx, hostname, False)for entry in addr_info:- ip_str = entry[4][0]try:+ ip_str = entry[4][0]# A hostname that resolves to a cloud-metadata IP must NOT be# treated as local: link-local metadata IPs (169.254.169.254, …)# pass is_private_ip, which would classify the host local and let@@ -340,11 +416,11 @@ def _classify_host(return _cache_classification(ctx, hostname, False)if _is_nat64_wrapped_metadata(ip_str):return _cache_classification(ctx, hostname, False)- if is_private_ip(ip_str):- return _cache_classification(ctx, hostname, True)+ if not is_private_ip(ip_str):+ return _cache_classification(ctx, hostname, False)except Exception: # pragma: no cover - defensive- continue- return _cache_classification(ctx, hostname, False)+ return _cache_classification(ctx, hostname, False)+ return _cache_classification(ctx, hostname, True)def _get_engine_class(engine_name: str):@@ -1331,6 +1407,11 @@ def context_from_snapshot(scope_raw = _get_setting_value(settings_snapshot, "policy.egress_scope", DEFAULT_EGRESS_SCOPE)+ from ...settings.manager import check_env_setting++ env_scope = check_env_setting("policy.egress_scope")+ if env_scope is not None:+ scope_raw = env_scope# `both` is retired (ADR-0007): the blanket-permissive middle scope is# coerced to the protective `adaptive` default so a residual value — an# un-migrated DB, a queued snapshot, or an env-var override that bypasses@@ -1341,8 +1422,10 @@ def context_from_snapshot(if str(scope_raw).strip().lower() == EgressScope.BOTH.value:scope_raw = EgressScope.ADAPTIVE.valuetry:- scope = EgressScope(str(scope_raw).lower())- except ValueError as exc:+ scope = parse_user_egress_scope(+ scope_raw, disabled_unprotected="adaptive"+ )+ except PolicyDeniedError:# An unrecognised scope means the saved setting was corrupted# or tampered with — silently falling back to BOTH (the most# permissive scope) would mask policy violations rather than@@ -1351,18 +1434,31 @@ def context_from_snapshot("refusing to construct EgressContext from unknown scope",value=scope_raw,)- raise PolicyDeniedError(- Decision(False, "unknown_egress_scope"),- target=str(scope_raw),- ) from exc+ raise+ if (+ str(scope_raw).strip().lower() == EgressScope.UNPROTECTED.value+ and scope == EgressScope.ADAPTIVE+ ):+ logger.bind(policy_audit=True).warning(+ "unprotected egress is disabled; coercing scope to adaptive"+ )++ env_require_local_llm = check_env_setting("llm.require_local_endpoint")+ env_require_local_embeddings = check_env_setting("embeddings.require_local")require_local_llm = _coerce_bool(- _get_setting_value(+ env_require_local_llm+ if env_require_local_llm is not None+ else _get_setting_value(settings_snapshot, "llm.require_local_endpoint", False))require_local_embeddings = _coerce_bool(- _get_setting_value(settings_snapshot, "embeddings.require_local", False)+ env_require_local_embeddings+ if env_require_local_embeddings is not None+ else _get_setting_value(+ settings_snapshot, "embeddings.require_local", False+ ))raw_hostnames = _get_setting_value(@@ -1405,10 +1501,12 @@ def context_from_snapshot(require_local_llm = Truerequire_local_embeddings = Trueelif 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+ # The escape hatch lifts user-level locality requirements, but cannot+ # weaken immutable operator environment locks.+ if env_require_local_llm is None:+ require_local_llm = False+ if env_require_local_embeddings is None:+ require_local_embeddings = Falsereturn EgressContext(scope=scope,@@ -1509,6 +1607,31 @@ def resolve_run_primary_engine()+def build_run_egress_context(+ settings_snapshot: Optional[dict],+ search_engine: Optional[str],+ *,+ username: Optional[str] = None,+) -> EgressContext:+ """Resolve the research worker's per-run ``EgressContext``.++ Composes the policy setup ``run_research_process`` runs at startup:+ current operator env policy is reapplied on the snapshot, the primary+ engine is derived, and the ``EgressContext`` is constructed. This is the+ single production seam invoked by the worker; a stale queued snapshot+ carrying an operator-disabled ``unprotected`` scope is coerced to a+ protected scope here (via the read-time backstop in+ ``context_from_snapshot``), not at queue extraction time.+ """+ from ...settings.manager import (+ apply_environment_overrides_to_snapshot,+ )++ effective = apply_environment_overrides_to_snapshot(settings_snapshot or {})+ primary = resolve_run_primary_engine({"search.tool": search_engine})+ return context_from_snapshot(effective, primary, username=username)++def _coerce_bool(value) -> bool:"""Coerce a setting value to bool, defensively.diff --git a/src/local_deep_research/security/egress/validators.py b/src/local_deep_research/security/egress/validators.pyindex 24bc468305..6e34a69b61 100644--- a/src/local_deep_research/security/egress/validators.py+++ b/src/local_deep_research/security/egress/validators.py@@ -13,11 +13,36 @@ but the egress rules themselves live here next to the policy they encode.from .policy import (EgressContext,EgressScope,+ PolicyDeniedError,_classify_host,_resolve_with_timeout,+ parse_user_egress_scope,)+def validate_egress_scope(form_data, _all_db_settings):+ """Validate the scope and enforce the operator-controlled escape hatch."""+ key = "policy.egress_scope"+ if key not in form_data:+ return None+ value = form_data[key]+ if not isinstance(value, str):+ return {"key": key, "error": "Egress scope must be a string"}+ try:+ parse_user_egress_scope(value)+ except PolicyDeniedError as exc:+ if exc.decision.reason == "unprotected_egress_disabled":+ return {+ "key": key,+ "error": "Unprotected egress is disabled by the server operator",+ }+ return {+ "key": key,+ "error": "Unknown egress scope",+ }+ return None++def validate_allowed_local_hostnames(form_data, all_db_settings):"""Reject public hostnames being added to llm.allowed_local_hostnames.@@ -157,6 +182,7 @@ def validate_trusted_search_engines(form_data, all_db_settings):# lockstep edit at each save route; each route only supplies its own response# shaping around ``first_egress_validation_error``.EGRESS_SETTINGS_VALIDATORS = (+ validate_egress_scope,validate_allowed_local_hostnames,validate_trusted_search_engines,)diff --git a/src/local_deep_research/settings/base.py b/src/local_deep_research/settings/base.pyindex d976756995..778e4b0b4e 100644--- a/src/local_deep_research/settings/base.py+++ b/src/local_deep_research/settings/base.py@@ -45,10 +45,20 @@ class ISettingsManager(ABC):pass@abstractmethod- def get_all_settings(self) -> Dict[str, Any]:+ def get_all_settings(+ self,+ bypass_cache: bool = False,+ include_environment_overrides: bool = True,+ strict: bool = False,+ ) -> Dict[str, Any]:"""Get all settings.+ Args:+ bypass_cache: If true, bypass any implementation cache.+ include_environment_overrides: If true, overlay current LDR_* values.+ strict: If true, propagate database and enum query failures.+Returns:Dictionary of all settings with metadata"""@@ -102,10 +112,13 @@ class ISettingsManager(ABC):pass@abstractmethod- def get_settings_snapshot(self) -> Dict[str, Any]:+ def get_settings_snapshot(self, strict: bool = False) -> Dict[str, Any]:"""Get a simplified settings snapshot with just key-value pairs.+ Args:+ strict: If true, propagate database and enum query failures.+Returns:Dictionary with setting keys mapped to their values"""@@ -131,6 +144,7 @@ class ISettingsManager(ABC):commit: bool = True,overwrite: bool = True,delete_extra: bool = False,+ preserve_environment_locked: bool = False,) -> None:"""Import settings from a dictionary.@@ -140,5 +154,8 @@ class ISettingsManager(ABC):commit: Whether to commit the DB after loadingoverwrite: If true, overwrite existing settingsdelete_extra: If true, delete settings not in settings_data+ preserve_environment_locked: If true, preserve the stored value+ for settings with active environment overrides while imported+ metadata may refresh"""passdiff --git a/src/local_deep_research/settings/env_definitions/security.py b/src/local_deep_research/settings/env_definitions/security.pyindex 1f06aeff8f..7d93ac37d9 100644--- a/src/local_deep_research/settings/env_definitions/security.py+++ b/src/local_deep_research/settings/env_definitions/security.py@@ -77,4 +77,14 @@ SECURITY_SETTINGS = [),default=False,),+ BooleanSetting(+ key="policy.allow_unprotected_egress",+ description=(+ "Allow users to select the UNPROTECTED egress scope. Disabled by "+ "default; this is an environment-only operator gate and cannot be "+ "changed through the user-writable settings API. Hard SSRF and "+ "cloud-metadata protections remain active when enabled."+ ),+ default=False,+ ),]diff --git a/src/local_deep_research/settings/manager.py b/src/local_deep_research/settings/manager.pyindex 02d7598a9a..7e6c61080e 100644--- a/src/local_deep_research/settings/manager.py+++ b/src/local_deep_research/settings/manager.py@@ -354,6 +354,51 @@ def check_env_setting(key: str) -> str | None:return None+def apply_environment_overrides_to_snapshot(+ snapshot: Dict[str, Any],+) -> Dict[str, Any]:+ """Return a copied snapshot with current LDR_* overrides reapplied.++ Queued research snapshots can outlive a process restart. Environment values+ are operator policy and retain highest precedence at actual dispatch time.+ """+ if not isinstance(snapshot, dict):+ return snapshot+ effective = dict(snapshot)+ # Old or partial queued snapshots may omit keys added after enqueue. Use+ # the registered defaults as metadata so every active LDR_* override is+ # injected at dispatch, not only overrides for keys already serialized.+ default_metadata = SettingsManager().default_settings+ candidate_keys = set(snapshot) | set(default_metadata)+ for key in candidate_keys:+ if check_env_setting(str(key)) is None:+ continue+ stored = snapshot.get(key, default_metadata.get(key))+ metadata = stored if isinstance(stored, dict) else None+ current = metadata.get("value") if metadata is not None else stored+ if metadata is not None:+ ui_element = str(metadata.get("ui_element", "text"))+ elif isinstance(current, bool):+ ui_element = "checkbox"+ elif isinstance(current, (list, dict)):+ ui_element = "json"+ elif isinstance(current, (int, float)):+ ui_element = "number"+ else:+ ui_element = "text"+ typed = get_typed_setting_value(+ str(key), current, ui_element, default=current, check_env=True+ )+ if metadata is not None:+ updated = dict(metadata)+ updated["value"] = typed+ updated["editable"] = False+ effective[key] = updated+ else:+ effective[key] = typed+ return effective++class SettingsManager(ISettingsManager):"""Manager for handling application settings with database storage and file fallback.@@ -452,6 +497,14 @@ class SettingsManager(ISettingsManager):self.__settings_locked = Falsereturn bool(self.__settings_locked)+ def _is_environment_locked(self, key: str, operation: str) -> bool:+ if check_env_setting(key) is None:+ return False+ logger.bind(policy_audit=True).warning(+ "environment-locked setting rejected at {}", operation, key=key+ )+ return True+@functools.cached_propertydef default_settings(self) -> Dict[str, Any]:"""@@ -755,6 +808,8 @@ class SettingsManager(ISettingsManager):if self.settings_locked:logger.error("Cannot edit setting {} because they are locked.", key)return False+ if self._is_environment_locked(key, "set_setting"):+ return False# Always update database if availabletry:@@ -882,7 +937,12 @@ class SettingsManager(ISettingsManager):self.__dict__.pop("default_settings", None)logger.debug("Settings cache cleared")- def get_all_settings(self, bypass_cache: bool = False) -> Dict[str, Any]:+ def get_all_settings(+ self,+ bypass_cache: bool = False,+ include_environment_overrides: bool = True,+ strict: bool = False,+ ) -> Dict[str, Any]:"""Get all settings, merging defaults with database values.@@ -891,6 +951,9 @@ class SettingsManager(ISettingsManager):Args:bypass_cache: If True, bypass the cache and read directly from database+ include_environment_overrides: If True, overlay current LDR_* values.+ strict: If True, propagate database and enum query failures.+Returns:Dictionary of all settings@@ -912,18 +975,19 @@ class SettingsManager(ISettingsManager):result[key] = dict(default_setting)# Check env var override for defaults not yet in DB- env_value = check_env_setting(key)- if env_value is not None:- ui_element = default_setting.get("ui_element", "text")- typed_value = get_typed_setting_value(- key,- None,- ui_element,- default=env_value,- check_env=True,- )- result[key]["value"] = typed_value- result[key]["editable"] = False+ if include_environment_overrides:+ env_value = check_env_setting(key)+ if env_value is not None:+ ui_element = default_setting.get("ui_element", "text")+ typed_value = get_typed_setting_value(+ key,+ None,+ ui_element,+ default=env_value,+ check_env=True,+ )+ result[key]["value"] = typed_value+ result[key]["editable"] = False# Override with database settingstry:@@ -940,6 +1004,8 @@ class SettingsManager(ISettingsManager):logger.exception("Error querying settings from database in get_all_settings")+ if strict:+ raisedb_settings = []for setting in db_settings:@@ -987,23 +1053,24 @@ class SettingsManager(ISettingsManager):}# Override from the environment variables if needed.- env_value = check_env_setting(str(setting.key))- if env_value is not None:- ui_element = result[str(setting.key)].get(- "ui_element", setting.ui_element- )- typed_value = get_typed_setting_value(- str(setting.key),- None,- ui_element,- default=env_value,- check_env=True,- )- result[str(setting.key)]["value"] = typed_value- # Mark it as non-editable, because changes to the DB- # value have no effect as long as the environment- # variable is set.- result[str(setting.key)]["editable"] = False+ if include_environment_overrides:+ env_value = check_env_setting(str(setting.key))+ if env_value is not None:+ ui_element = result[str(setting.key)].get(+ "ui_element", setting.ui_element+ )+ typed_value = get_typed_setting_value(+ str(setting.key),+ None,+ ui_element,+ default=env_value,+ check_env=True,+ )+ result[str(setting.key)]["value"] = typed_value+ # Mark it as non-editable, because changes to the DB+ # value have no effect as long as the environment+ # variable is set.+ result[str(setting.key)]["editable"] = False# Re-inject search strategy options from code after DB merge,# since the DB stores options=null for this setting.@@ -1017,11 +1084,14 @@ class SettingsManager(ISettingsManager):return result- def get_settings_snapshot(self) -> Dict[str, Any]:+ def get_settings_snapshot(self, strict: bool = False) -> Dict[str, Any]:"""Get a simplified settings snapshot with just key-value pairs.This is useful for passing settings to background threads or storing in metadata.+ Args:+ strict: If True, propagate database and enum query failures.+Returns:Dictionary with setting keys mapped to their values"""@@ -1035,7 +1105,7 @@ class SettingsManager(ISettingsManager):"Create a new instance or call close() only at end of lifecycle.")- all_settings = self.get_all_settings()+ all_settings = self.get_all_settings(strict=strict)settings_snapshot = {}for key, setting in all_settings.items():@@ -1098,6 +1168,11 @@ class SettingsManager(ISettingsManager):else:setting_obj = setting+ if self._is_environment_locked(+ setting_obj.key, "create_or_update_setting"+ ):+ return None+try:# Check if setting existsdb_setting = (@@ -1191,6 +1266,9 @@ class SettingsManager(ISettingsManager):)return False+ if self._is_environment_locked(key, "delete_setting"):+ return False+try:# Remove from databaseresult = (@@ -1244,8 +1322,14 @@ class SettingsManager(ISettingsManager):Returns:True if the version saved in the DB matches the package version.+ Reads the stored ``app.version`` row directly (``check_env=False``)+ rather than going through the env-aware read path. The schema-version+ marker must reflect what is persisted so a stale DB triggers a+ migration even when ``LDR_APP_VERSION`` happens to match the running+ package; reading the env value would mask the staleness and skip+ the migration."""- db_version = self.get_setting("app.version")+ db_version = self.get_setting("app.version", check_env=False)logger.debug(f"App version saved in DB is {db_version}, have package "f"settings from version {package_version}."@@ -1269,7 +1353,27 @@ class SettingsManager(ISettingsManager):"""logger.debug(f"Updating saved DB version to {package_version}.")- self.delete_setting("app.version", commit=False)+ # Internal migration plumbing: this row is the schema-version+ # marker, not a user-facing setting. The env lock applies to+ # ordinary set/delete mutations via the public API; using the+ # env-guarded delete_setting() here would let a stale+ # LDR_APP_VERSION suppress the row replacement and either leave+ # the unique constraint violated (next commit raises) or leave+ # the stale marker in place. The narrowest correct path is to+ # delete the prior row directly and abort the call on failure+ # rather than blindly inserting a duplicate.+ if self.db_session is None:+ raise RuntimeError("Database session is not initialized")+ try:+ self._check_thread_safety()+ self.db_session.query(Setting).filter(+ Setting.key == "app.version"+ ).delete(synchronize_session=False)+ except SQLAlchemyError:+ logger.exception("Error deleting prior app.version row")+ self.db_session.rollback()+ return+version = Setting(key="app.version",value=package_version,@@ -1280,9 +1384,6 @@ class SettingsManager(ISettingsManager):ui_element="text",visible=False,)-- if self.db_session is None:- raise RuntimeError("Database session is not initialized")self.db_session.add(version)if commit:self.db_session.commit()@@ -1293,6 +1394,7 @@ class SettingsManager(ISettingsManager):commit: bool = True,overwrite: bool = True,delete_extra: bool = False,+ preserve_environment_locked: bool = False,) -> None:"""Import settings directly from the export format. This can be used to@@ -1306,64 +1408,105 @@ class SettingsManager(ISettingsManager):delete_extra: If true, it will delete any settings that are inthe database but don't have a corresponding entry in`settings_data`.+ preserve_environment_locked: If true, preserve stored values for+ settings with active environment overrides while imported+ metadata is refreshed."""if self.db_session is None:raise RuntimeError("Database session is not initialized")logger.debug(f"Importing {len(settings_data)} settings")-- # `overwrite=False` is the version-bump reconciliation point: this is- # the ONE place where JSON-defined schema (options, description,- # constraints) refreshes into the DB rows while the user's chosen value- # is preserved. `load_from_defaults_file(overwrite=False)` runs here on- # version mismatch. Because each row is fully recreated from- # `settings_data` below, all schema fields come from the JSON defaults;- # only the existing value is carried over. `get_all_settings()` then- # serves that snapshot verbatim — it does not re-read JSON per call.- # This is why metadata edits surface at version bump, by design; see- # the note at `get_all_settings()` and closed PR #2474.- for key, setting_values in settings_data.items():- # Don't let a corrupted export reintroduce malformed keys- # (e.g. trailing-dot keys); skip them instead of writing verbatim.- if not is_valid_setting_key(key):- logger.warning(- "Skipping import of setting with malformed key {!r}", key+ changed_keys: list[str] = []+ retained_keys: set[str] = set()+ try:+ # `overwrite=False` is the version-bump reconciliation point:+ # refresh JSON-defined schema while preserving the stored value.+ # Environment overrides must not become persisted values.+ for key, raw_setting_values in settings_data.items():+ if not is_valid_setting_key(key):+ logger.warning(+ "Skipping import of setting with malformed key {!r}",+ key,+ )+ continue++ retained_keys.add(key)+ setting_values = dict(raw_setting_values)+ if (+ preserve_environment_locked+ and check_env_setting(key) is not None+ ):+ existing_value = (+ self.db_session.query(Setting.value)+ .filter(Setting.key == key)+ .first()+ )+ if existing_value is not None:+ logger.bind(policy_audit=True).warning(+ "Preserving stored value for environment-locked "+ "setting during import: {}",+ key,+ )+ setting_values["value"] = existing_value[0]+ if not overwrite:+ existing_value = self.get_setting(key, check_env=False)+ if existing_value is not None:+ setting_values["value"] = existing_value++ # Import needs strict failure semantics. The public+ # delete_setting() helper intentionally swallows SQL errors,+ # which would allow this transaction to continue after a+ # rollback and commit only a suffix of the import.+ (+ self.db_session.query(Setting)+ .filter(Setting.key == key)+ .delete(synchronize_session=False))- continue- setting_values = dict(setting_values)- if not overwrite:- existing_value = self.get_setting(key)- if existing_value is not None:- # Preserve the user's value; everything else (schema) is- # taken fresh from `setting_values` (the JSON defaults).- setting_values["value"] = existing_value-- # Delete any existing setting so we can completely overwrite it.- self.delete_setting(key, commit=False)-- # Convert type string to SettingType enum if needed- if "type" in setting_values and isinstance(- setting_values["type"], str- ):- setting_values["type"] = SettingType[setting_values["type"]]- setting = Setting(- key=key, **_filter_setting_columns(setting_values)- )- self.db_session.add(setting)+ if "type" in setting_values and isinstance(+ setting_values["type"], str+ ):+ setting_values["type"] = SettingType[setting_values["type"]]- if commit or delete_extra:- self.db_session.commit()- logger.info(f"Successfully imported {len(settings_data)} settings")- # Emit WebSocket event for all imported settings- self._emit_settings_changed(list(settings_data.keys()))-- if delete_extra:- all_settings = self.get_all_settings()- for key in all_settings:- if key not in settings_data:+ self.db_session.add(+ Setting(key=key, **_filter_setting_columns(setting_values))+ )+ changed_keys.append(key)++ if delete_extra:+ existing_keys = [+ str(row[0])+ for row in self.db_session.query(Setting.key).all()+ ]+ for key in existing_keys:+ if key in retained_keys or (+ preserve_environment_locked+ and check_env_setting(key) is not None+ ):+ continuelogger.debug(f"Deleting extraneous setting: {key}")- self.delete_setting(key, commit=False)+ (+ self.db_session.query(Setting)+ .filter(Setting.key == key)+ .delete(synchronize_session=False)+ )+ changed_keys.append(key)++ if commit:+ self.db_session.commit()+ logger.info(+ f"Successfully imported {len(changed_keys)} settings"+ )+ self._emit_settings_changed(changed_keys)+ except Exception:+ self.db_session.rollback()+ raise++ def emit_settings_changed_after_commit(+ self, changed_keys: List[str]+ ) -> None:+ """Notify the current user's clients after the caller commits settings."""+ self._emit_settings_changed(changed_keys)def _emit_settings_changed(self, changed_keys: Optional[List[Any]] = None):"""diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pyindex 2db44d153f..c17ed280bd 100644--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@ -21,7 +21,11 @@ from local_deep_research.settings.logger import log_settingsfrom ..utilities.log_utils import InterceptHandlerfrom ..security import SecurityHeaders, get_security_default-from ..security.egress.policy import DEFAULT_EGRESS_SCOPE+from ..security.egress.policy import (+ DEFAULT_EGRESS_SCOPE,+ effective_scope_for_display,+ unprotected_egress_allowed,+)from ..security.rate_limiter import limiterfrom ..security.file_upload_validator import FileUploadValidatorfrom ..security.web_middleware import (@@ -578,6 +582,7 @@ def apply_middleware(app):)or DEFAULT_EGRESS_SCOPE)+ scope = effective_scope_for_display(scope)except Exception:logger.debug("Failed to read egress scope for template context",@@ -694,6 +699,7 @@ def register_blueprints(app):def index():"""Root route - redirect to login if not authenticated"""from flask import redirect, session, url_for+ from ..settings.manager import check_env_settingfrom ..constants import get_available_strategiesfrom ..database.session_context import get_user_db_session@@ -710,6 +716,22 @@ def register_blueprints(app):with get_user_db_session(username) as db_session:if db_session:settings_manager = get_settings_manager(db_session, username)+ raw_egress_scope = settings_manager.get_setting(+ "policy.egress_scope", DEFAULT_EGRESS_SCOPE+ )+ effective_egress_scope = effective_scope_for_display(+ raw_egress_scope+ )+ egress_scope_env_locked = (+ check_env_setting("policy.egress_scope") is not None+ )+ llm_local_env_locked = (+ check_env_setting("llm.require_local_endpoint") is not None+ )+ embeddings_local_env_locked = (+ check_env_setting("embeddings.require_local") is not None+ )+settings = {"llm_provider": settings_manager.get_setting("llm.provider", "ollama"@@ -740,9 +762,11 @@ def register_blueprints(app):"search.search_strategy", "source-based"),# Egress policy controls (Stage 1c UI).- "policy_egress_scope": settings_manager.get_setting(- "policy.egress_scope", DEFAULT_EGRESS_SCOPE- ),+ "policy_egress_scope": effective_egress_scope,+ "egress_scope_env_locked": egress_scope_env_locked,+ "allow_unprotected_egress": unprotected_egress_allowed(),+ "llm_local_env_locked": llm_local_env_locked,+ "embeddings_local_env_locked": embeddings_local_env_locked,"llm_require_local_endpoint": settings_manager.get_setting("llm.require_local_endpoint", False),diff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.pyindex e10adf2471..a19e0f2a41 100644--- a/src/local_deep_research/web/queue/processor_v2.py+++ b/src/local_deep_research/web/queue/processor_v2.py@@ -23,7 +23,11 @@ from ...database.models import (from ...database.queue_service import UserQueueServicefrom ...database.session_context import get_user_db_sessionfrom ...database.session_passwords import session_password_store-from ...exceptions import DuplicateResearchError, SystemAtCapacityError+from ...exceptions import (+ DuplicateResearchError,+ InvalidQueuedResearchOverridesError,+ SystemAtCapacityError,+)from ...security.log_sanitizer import redact_secretsfrom ...notifications.queue_helpers import (send_research_completed_notification_from_session,@@ -33,6 +37,7 @@ from .lifecycle_cleanup import (cleanup_queued_research_state,reconcile_research_queue_status,)+from ..routes.research_validation import validate_search_overridesfrom ..services.research_service import (run_research_process,start_research_process,@@ -1097,6 +1102,41 @@ class QueueProcessorV2:)continue+ except InvalidQueuedResearchOverridesError as error:+ logger.warning(+ "Invalid persisted search overrides for queued research "+ f"{research_id}; marking FAILED"+ )+ with self._spawn_retry_counts_lock:+ self._spawn_retry_counts.pop(research_id, None)++ research = (+ db_session.query(ResearchHistory)+ .filter_by(id=research_id)+ .first()+ )+ fresh_queued = (+ db_session.query(QueuedResearch)+ .filter_by(username=username, research_id=research_id)+ .first()+ )+ if research:+ research.status = ResearchStatus.FAILED+ if fresh_queued:+ db_session.delete(fresh_queued)+ self._commit_with_safe_rollback(+ db_session,+ "terminal invalid persisted overrides for research "+ f"{research_id}",+ )+ self.notify_research_failed(+ username=username,+ research_id=research_id,+ error_message=str(error),+ user_password=password,+ )+ continue+except Exception as e:# ``password`` is a parameter of this method — drop the# traceback chain and redact str(e).@@ -1242,11 +1282,6 @@ class QueueProcessorV2:f"(status={research.status})")- # Claim IN_PROGRESS before spawn to close the- # thread-completes-before-parent-commits race.- research.status = ResearchStatus.IN_PROGRESS- db_session.commit()-# Extract settingssettings_snapshot = queued_research.settings_snapshot or {}@@ -1257,6 +1292,30 @@ class QueueProcessorV2:):submission_params = settings_snapshot.get("submission", {})complete_settings = settings_snapshot.get("settings_snapshot", {})+ allowed_override_keys = (+ "model_provider",+ "model",+ "custom_endpoint",+ "search_engine",+ "max_results",+ "time_period",+ "iterations",+ "questions_per_iteration",+ "strategy",+ )+ explicit_override_keys = settings_snapshot.get(+ "submission_overrides"+ )+ override_keys = (+ explicit_override_keys+ if isinstance(explicit_override_keys, list)+ else allowed_override_keys+ )+ runtime_overrides = {+ key: submission_params[key]+ for key in allowed_override_keys+ if key in override_keys and key in submission_params+ }else:submission_params = settings_snapshot# A legacy-flat queued row (enqueued by an older version, pre-@@ -1268,6 +1327,28 @@ class QueueProcessorV2:complete_settings = ({"search.tool": _legacy_engine} if _legacy_engine else {})+ runtime_overrides = {+ "model_provider": submission_params.get("model_provider"),+ "model": submission_params.get("model"),+ "custom_endpoint": submission_params.get("custom_endpoint"),+ "search_engine": submission_params.get("search_engine"),+ "max_results": submission_params.get("max_results"),+ "time_period": submission_params.get("time_period"),+ "iterations": submission_params.get("iterations"),+ "questions_per_iteration": submission_params.get(+ "questions_per_iteration"+ ),+ "strategy": submission_params.get("strategy", "source-based"),+ }++ validation_error = validate_search_overrides(runtime_overrides)+ if validation_error is not None:+ raise InvalidQueuedResearchOverridesError(validation_error)++ # Claim IN_PROGRESS before spawn to close the+ # thread-completes-before-parent-commits race.+ research.status = ResearchStatus.IN_PROGRESS+ db_session.commit()try:research_thread = start_research_process(@@ -1277,18 +1358,8 @@ class QueueProcessorV2:run_research_process,username=username,user_password=password, # Pass password for metrics- model_provider=submission_params.get("model_provider"),- model=submission_params.get("model"),- custom_endpoint=submission_params.get("custom_endpoint"),- search_engine=submission_params.get("search_engine"),- max_results=submission_params.get("max_results"),- time_period=submission_params.get("time_period"),- iterations=submission_params.get("iterations"),- questions_per_iteration=submission_params.get(- "questions_per_iteration"- ),- strategy=submission_params.get("strategy", "source-based"),settings_snapshot=complete_settings,+ **runtime_overrides,)except DuplicateResearchError:# A live thread already exists for this research_id (e.g.diff --git a/src/local_deep_research/web/routes/metrics_routes.py b/src/local_deep_research/web/routes/metrics_routes.pyindex 7bd54cc0d0..7c097e1f68 100644--- a/src/local_deep_research/web/routes/metrics_routes.py+++ b/src/local_deep_research/web/routes/metrics_routes.py@@ -2446,6 +2446,8 @@ def api_journal_data_download():from ...security.egress.policy import (DEFAULT_EGRESS_SCOPE,EgressScope,+ PolicyDeniedError,+ parse_user_egress_scope,)from ...utilities.db_utils import get_settings_manager@@ -2453,9 +2455,17 @@ def api_journal_data_download():scope_raw = get_settings_manager(username=username).get_setting("policy.egress_scope", DEFAULT_EGRESS_SCOPE)+ # Retired "both" reads as the adaptive default, mirroring+ # context_from_snapshot's read-time backstop for un-migrated rows.+ if str(scope_raw).strip().lower() == EgressScope.BOTH.value:+ scope_raw = EgressScope.ADAPTIVE.valuetry:- scope = EgressScope(str(scope_raw).lower())- except ValueError:+ # Stale "unprotected" rows fall back to adaptive when the+ # operator gate is off, matching every other runtime reader.+ scope = parse_user_egress_scope(+ scope_raw, disabled_unprotected="adaptive"+ )+ except PolicyDeniedError:scope = None # corrupt scope -> fail closed belowif scope is None or scope in (EgressScope.PRIVATE_ONLY,diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex b6c9c1d220..e70f5f9002 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -32,6 +32,7 @@ from ...security import (sanitize_filename,strip_settings_snapshot,)+from ...utilities.type_utils import to_boolfrom ...utilities.url_utils import is_safe_custom_llm_endpointfrom ...security.rate_limiter import (_get_api_user_key,@@ -68,6 +69,7 @@ from ..services.research_service import ()from ...security.rate_limiter import limiterfrom ..utils.templates import render_template_with_defaults+from .research_validation import validate_search_overridesfrom .globals import (append_research_log,get_active_research_ids,@@ -251,14 +253,13 @@ def _precheck_engine_policy(settings_manager, params, search_engine, username):# Overlay per-research form overrides so the snapshot reflects# what the user picked for THIS run (per-research overrides, not# a global settings save).- _apply_policy_overrides(policy_snapshot, params)-# Resolve the primary the SAME way the worker does (single source of# truth) so the precheck and the background worker agree on accept vs.# refuse — including the fail-closed missing-primary case, which the# ValueError handler below maps to a 400. (Previously this substituted# searxng and accepted runs the worker then refused.)try:+ _apply_policy_overrides(policy_snapshot, params)primary = resolve_run_primary_engine(policy_snapshot)policy_ctx = context_from_snapshot(policy_snapshot,@@ -406,15 +407,20 @@ def _precheck_engine_policy(settings_manager, params, search_engine, username):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."+ "refused (fail-closed). To override, ask the server "+ "operator to enable the Unprotected escape hatch "+ "(LDR_POLICY_ALLOW_UNPROTECTED_EGRESS), then select the "+ "'Unprotected' scope yourself.")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."+ "local inference, mark the collection public, or — to "+ "override — ask the server operator to enable the "+ "Unprotected escape hatch "+ "(LDR_POLICY_ALLOW_UNPROTECTED_EGRESS), then set Egress "+ "Scope to 'Unprotected' yourself.")return (jsonify(@@ -443,14 +449,31 @@ def _apply_policy_overrides(settings_snapshot, params):"""if not isinstance(settings_snapshot, dict):return- if params.get("policy_egress_scope") is not None:- settings_snapshot["policy.egress_scope"] = params["policy_egress_scope"]- if params.get("llm_require_local_endpoint") is not None:- settings_snapshot["llm.require_local_endpoint"] = bool(+ from ...settings.manager import check_env_setting+ from ...security.egress.policy import (+ parse_user_egress_scope,+ )++ scope_override = params.get("policy_egress_scope")+ if (+ scope_override is not None+ and check_env_setting("policy.egress_scope") is None+ ):+ settings_snapshot["policy.egress_scope"] = parse_user_egress_scope(+ scope_override+ ).value+ if (+ params.get("llm_require_local_endpoint") is not None+ and check_env_setting("llm.require_local_endpoint") is None+ ):+ settings_snapshot["llm.require_local_endpoint"] = to_bool(params["llm_require_local_endpoint"])- if params.get("embeddings_require_local") is not None:- settings_snapshot["embeddings.require_local"] = bool(+ if (+ params.get("embeddings_require_local") is not None+ and check_env_setting("embeddings.require_local") is None+ ):+ settings_snapshot["embeddings.require_local"] = to_bool(params["embeddings_require_local"])# NOTE: the per-run `custom_endpoint` form value is deliberately NOT@@ -561,6 +584,10 @@ def _queue_research(@require_json_body(error_format="status")def start_research():data = request.json+ validation_error = validate_search_overrides(data)+ if validation_error is not None:+ return jsonify({"status": "error", "message": validation_error}), 400+# Debug logging to trace model parameterlogger.debug(f"Request data keys: {list(data.keys())}")@@ -758,19 +785,43 @@ def start_research():research_id = str(uuid.uuid4())# Create organized research metadata with settings snapshot+ submission = {+ "model_provider": model_provider,+ "model": model,+ "custom_endpoint": custom_endpoint,+ "search_engine": search_engine,+ "max_results": max_results,+ "time_period": time_period,+ "iterations": iterations,+ "questions_per_iteration": questions_per_iteration,+ "strategy": strategy,+ }+ submission_overrides = []+ if data.get("model_provider"):+ submission_overrides.append("model_provider")+ if data.get("model"):+ submission_overrides.append("model")+ if data.get("custom_endpoint"):+ submission_overrides.append("custom_endpoint")+ if data.get("search_engine") or data.get("search_tool"):+ submission_overrides.append("search_engine")+ if data.get("max_results") is not None:+ submission_overrides.append("max_results")+ if data.get("time_period") is not None:+ submission_overrides.append("time_period")+ if data.get("iterations") is not None:+ submission_overrides.append("iterations")+ if data.get("questions_per_iteration") is not None:+ submission_overrides.append("questions_per_iteration")+ if data.get("strategy"):+ submission_overrides.append("strategy")+research_settings = {# Direct submission parameters- "submission": {- "model_provider": model_provider,- "model": model,- "custom_endpoint": custom_endpoint,- "search_engine": search_engine,- "max_results": max_results,- "time_period": time_period,- "iterations": iterations,- "questions_per_iteration": questions_per_iteration,- "strategy": strategy,- },+ "submission": submission,+ # Only these request-supplied values remain fixed if queued work is+ # dispatched after operator environment settings change.+ "submission_overrides": submission_overrides,# System information"system": {"timestamp": created_at,@@ -783,7 +834,19 @@ def start_research():# Add any additional metadata from requestadditional_metadata = data.get("metadata", {})if additional_metadata:- research_settings.update(additional_metadata)+ reserved_metadata_keys = {+ "submission",+ "submission_overrides",+ "system",+ "settings_snapshot",+ }+ research_settings.update(+ {+ key: value+ for key, value in additional_metadata.items()+ if key not in reserved_metadata_keys+ }+ )# Get complete settings snapshot for this researchtry:from ...settings import SettingsManager@@ -802,7 +865,10 @@ def start_research():db_session_for_settings, owns_session=False)# Get all current settings as a snapshot (bypass cache to ensure fresh data)- all_settings = settings_manager.get_all_settings(bypass_cache=True)+ all_settings = settings_manager.get_all_settings(+ bypass_cache=True,+ include_environment_overrides=False,+ )# Apply per-research egress policy overrides (form-supplied# values override saved settings JUST FOR THIS RUN; they do# not persist to the user's settings DB).@@ -830,7 +896,8 @@ def start_research():temp_session, owns_session=False)all_settings = settings_manager.get_all_settings(- bypass_cache=True+ bypass_cache=True,+ include_environment_overrides=False,)_apply_policy_overrides(all_settings, params)research_settings["settings_snapshot"] = all_settingsdiff --git a/src/local_deep_research/web/routes/research_validation.py b/src/local_deep_research/web/routes/research_validation.pynew file mode 100644index 0000000000..2b95596ba5--- /dev/null+++ b/src/local_deep_research/web/routes/research_validation.py@@ -0,0 +1,40 @@+"""Validation for user-supplied search overrides.++Shared by the research-start route and the queue dispatcher so an override+is validated identically whether it arrives on a fresh request or is replayed+from a persisted queued row.+"""++from collections.abc import Mapping+from typing import Final, TypeAlias++MAX_RESULTS_MIN: Final = 1+MAX_RESULTS_MAX: Final = 50+ALLOWED_TIME_PERIODS: Final = frozenset({"d", "w", "m", "y", "all"})++JsonScalar: TypeAlias = str | int | float | bool | None+JsonValue: TypeAlias = JsonScalar | list["JsonValue"] | dict[str, "JsonValue"]+++def validate_search_overrides(data: Mapping[str, JsonValue]) -> str | None:+ """Return an error message for an invalid override, or None if valid.++ ``type(x) is not int`` is deliberate rather than ``isinstance``: ``bool``+ is a subclass of ``int``, so ``isinstance(True, int)`` is True and would+ let ``max_results: true`` silently coerce to 1. The exact-type check+ rejects booleans (and floats) instead.+ """+ max_results = data.get("max_results")+ if max_results is not None and (+ type(max_results) is not int+ or not MAX_RESULTS_MIN <= max_results <= MAX_RESULTS_MAX+ ):+ return "max_results must be an integer between 1 and 50"++ time_period = data.get("time_period")+ if time_period is not None and (+ type(time_period) is not str or time_period not in ALLOWED_TIME_PERIODS+ ):+ return "time_period must be one of: d, w, m, y, all"++ return Nonediff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex cb22ebbbcf..cd6a26a17d 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -41,6 +41,7 @@ optimal experience when JavaScript is available.import platformimport timefrom typing import Any, Optional+from types import SimpleNamespacefrom datetime import UTC, datetime, timedelta, timezoneimport requests@@ -66,7 +67,19 @@ from ...database.encrypted_db import db_managerfrom ...utilities.db_utils import get_settings_managerfrom ...utilities.url_utils import normalize_urlfrom ...security.decorators import require_json_body-from ...security.egress.policy import DEFAULT_EGRESS_SCOPE+from ...security.egress.policy import (+ DEFAULT_EGRESS_SCOPE,+ Decision,+ EgressContext,+ EgressScope,+ PolicyDeniedError,+ context_from_snapshot,+ effective_scope_for_display,+ evaluate_llm_endpoint,+ parse_user_egress_scope,+ resolve_run_primary_engine,+ unprotected_egress_allowed,+)from ...security.egress.validators import (first_egress_validation_error,)@@ -74,6 +87,8 @@ from ..auth.decorators import login_requiredfrom ..utils.request_helpers import parse_bool_argfrom ...security.rate_limiter import settings_limitfrom ...settings.manager import (+ SettingsManager,+ check_env_setting,get_typed_setting_value,is_valid_setting_key,parse_boolean,@@ -116,7 +131,7 @@ settings_bp = Blueprint("settings", __name__, url_prefix="/settings")def _filter_editable_settings(form_data: dict, db_session: Session) -> dict:- """Remove non-editable keys from *form_data* in place.+ """Remove operator-locked and non-editable keys in place.Returns a dict of *all* ``{key: Setting}`` records from the databaseso callers can reuse it for further validation (e.g. egress-policy checks).@@ -128,10 +143,14 @@ def _filter_editable_settings(form_data: dict, db_session: Session) -> dict:non_editable_keys = [keyfor key in form_data.keys()- if key in all_db_settings and not all_db_settings[key].editable+ if check_env_setting(key) is not None+ or (key in all_db_settings and not all_db_settings[key].editable)]if non_editable_keys:- logger.warning("Skipping non-editable settings: {}", non_editable_keys)+ logger.bind(policy_audit=True).warning(+ "Skipping operator-locked or non-editable settings: {}",+ non_editable_keys,+ )for key in non_editable_keys:del form_data[key]@@ -242,49 +261,75 @@ def _get_setting_from_session(key: str | None, default=None):return default-def _model_list_local_only() -> bool:- """True when the model-list endpoints must NOT call cloud provider APIs- (doing so sends the API key off-machine).-- The effective local-only posture = the ``llm.require_local_endpoint``- toggle OR a private egress scope (``private_only``, or ``adaptive``- resolving to private). Checking only the raw toggle missed a PRIVATE_ONLY- user who never ticked it — the scope forces local at run time but the- stored toggle is still False. Best-effort: returns False (allow) on error- so a transient settings hiccup doesn't break the model dropdown.- """+def _resolve_model_discovery_policy() -> tuple[EgressContext, dict[str, Any]]:+ """Resolve the current egress policy before model cache or network access."""username = session.get("username")+ settings_snapshot = Nonetry:with get_user_db_session(username) as db_session:- if not db_session:- return False- sm = get_settings_manager(db_session, username)- if bool(sm.get_setting("llm.require_local_endpoint", False)):- return True- scope = str(- sm.get_setting("policy.egress_scope", DEFAULT_EGRESS_SCOPE)- ).lower()- if scope == "private_only":- return True- if scope == "adaptive":- from ...security.egress.policy import context_from_snapshot-- snap = sm.get_settings_snapshot()- if isinstance(snap, dict):- primary = sm.get_setting("search.tool", DEFAULT_SEARCH_TOOL)- return bool(- context_from_snapshot(- snap,- primary or DEFAULT_SEARCH_TOOL,- username=username,- ).require_local_llm- )- return False+ if db_session:+ settings_manager = get_settings_manager(db_session, username)+ settings_snapshot = settings_manager.get_settings_snapshot(+ strict=True+ )+ except PolicyDeniedError:+ raiseexcept Exception:- logger.debug(- "model-list local-only check failed; allowing", exc_info=True+ logger.bind(policy_audit=True).warning(+ "available-model policy settings unavailable"+ )+ raise PolicyDeniedError(+ Decision(False, "settings_unavailable"),+ target="available_models",+ ) from None++ if not isinstance(settings_snapshot, dict):+ raise PolicyDeniedError(+ Decision(False, "settings_unavailable"),+ target="available_models",)- return False++ scope_raw = check_env_setting("policy.egress_scope")+ if scope_raw is None:+ scope_raw = settings_snapshot.get(+ "policy.egress_scope", DEFAULT_EGRESS_SCOPE+ )+ if str(scope_raw).strip().lower() == EgressScope.BOTH.value:+ scope_raw = EgressScope.ADAPTIVE.value+ parse_user_egress_scope(scope_raw)+ primary = resolve_run_primary_engine(+ settings_snapshot, default=DEFAULT_SEARCH_TOOL+ )+ return (+ context_from_snapshot(+ settings_snapshot,+ primary,+ username=username,+ ),+ settings_snapshot,+ )+++def _model_discovery_provider_allowed(+ provider: str,+ policy_context: EgressContext,+ settings_snapshot: dict[str, Any],+) -> bool:+ """Return whether a provider's configured endpoint is allowed to list models."""+ if not policy_context.require_local_llm:+ return True+ decision = evaluate_llm_endpoint(+ normalize_provider(provider),+ policy_context,+ settings_snapshot=settings_snapshot,+ )+ if not decision.allowed:+ logger.bind(policy_audit=True).info(+ "available-model provider denied by egress policy",+ provider=normalize_provider(provider),+ reason=decision.reason,+ )+ return decision.alloweddef coerce_setting_for_write(key: str, value: Any, ui_element: str) -> Any:@@ -307,13 +352,73 @@ def coerce_setting_for_write(key: str, value: Any, ui_element: str) -> Any:# from an environment variable override. check_env=True (the default)# would silently replace the user's value with an env var, which is# incorrect on the write path.- return get_typed_setting_value(+ coerced = get_typed_setting_value(key=key,value=value,ui_element=ui_element,default=None,check_env=False,)+ if key == "policy.egress_scope" and isinstance(coerced, str):+ return coerced.strip().lower()+ return coerced+++def _shape_egress_scope_metadata(settings):+ """Hide the operator-disabled escape hatch from settings API metadata."""+ if not isinstance(settings, dict):+ return settings+ metadata = settings.get("policy.egress_scope")+ if not isinstance(metadata, dict):+ return settings+ shaped = dict(settings)+ scope = dict(metadata)+ env_value = check_env_setting("policy.egress_scope")+ if env_value is not None:+ scope["value"] = env_value+ scope["editable"] = False+ options = scope.get("options")+ if isinstance(options, list) and not unprotected_egress_allowed():+ scope["options"] = [+ option+ for option in options+ if str(option.get("value") if isinstance(option, dict) else option)+ .strip()+ .lower()+ != EgressScope.UNPROTECTED.value+ ]+ scope["value"] = effective_scope_for_display(scope.get("value"))+ shaped["policy.egress_scope"] = scope+ return shaped+++def _shape_effective_setting_metadata(settings):+ """Apply deployment overrides to settings API response metadata."""+ if not isinstance(settings, dict):+ return settings+ shaped = dict(settings)+ for key, metadata in settings.items():+ if not isinstance(metadata, dict):+ continue+ env_value = check_env_setting(key)+ if env_value is None:+ continue+ current = dict(metadata)+ current["value"] = get_typed_setting_value(+ key=key,+ value=current.get("value"),+ ui_element=str(current.get("ui_element", "text")),+ default=current.get("value"),+ check_env=True,+ )+ current["editable"] = False+ shaped[key] = current+ return _shape_egress_scope_metadata(shaped)+++def _shape_single_effective_metadata(key, setting_data):+ shaped = _shape_effective_setting_metadata({key: dict(setting_data)})+ return shaped[key]@settings_bp.route("/", methods=["GET"])@@ -633,6 +738,8 @@ def save_all_settings("step": setting.step,}+ all_settings = _shape_effective_setting_metadata(all_settings)+# Customize the success message based on what changedsuccess_message = ""if len(updated_settings) == 1:@@ -722,7 +829,9 @@ def reset_to_defaults():"""Reset all settings to their default values"""try:- settings_manager.load_from_defaults_file()+ settings_manager.load_from_defaults_file(+ preserve_environment_locked=True+ )logger.info("Successfully imported settings from default files")@@ -914,6 +1023,7 @@ def api_get_all_settings(if key in category_keys}+ settings = _shape_effective_setting_metadata(settings)settings = DataSanitizer.redact_settings_snapshot(settings)return jsonify({"status": "success", "settings": settings})@@ -949,9 +1059,7 @@ def api_get_db_setting(# Return full setting details from DBsetting_data = {"key": db_setting.key,- "value": DataSanitizer.redact_value(- db_setting.key, db_setting.ui_element, db_setting.value- ),+ "value": db_setting.value,"type": db_setting.typeif isinstance(db_setting.type, str)else db_setting.type.value,@@ -966,6 +1074,15 @@ def api_get_db_setting("visible": db_setting.visible,"editable": db_setting.editable,}+ # Shape first (this may overwrite ``value`` with a matching+ # ``LDR_*`` env override so the effective value renders), then+ # redact once — matching the shape-then-redact order used by the+ # bulk GET route. The empty-value rule keeps ``""`` readable and+ # metadata (ui_element, editable, ...) is left untouched.+ setting_data = _shape_single_effective_metadata(key, setting_data)+ setting_data["value"] = DataSanitizer.redact_value(+ key, setting_data.get("ui_element"), setting_data.get("value")+ )return jsonify(setting_data)# Not in DB — check defaults so this endpoint is consistent@@ -975,9 +1092,7 @@ def api_get_db_setting(default_ui = default_meta.get("ui_element", "text")setting_data = {"key": key,- "value": DataSanitizer.redact_value(- key, default_ui, default_meta.get("value")- ),+ "value": default_meta.get("value"),"type": default_meta.get("type", "APP"),"name": default_meta.get("name", key),"description": default_meta.get("description"),@@ -990,6 +1105,11 @@ def api_get_db_setting("visible": default_meta.get("visible", True),"editable": default_meta.get("editable", True),}+ # Same shape-then-redact-once order as the DB branch above.+ setting_data = _shape_single_effective_metadata(key, setting_data)+ setting_data["value"] = DataSanitizer.redact_value(+ key, setting_data.get("ui_element"), setting_data.get("value")+ )return jsonify(setting_data)return jsonify({"error": f"Setting not found: {key}"}), 404@@ -1040,6 +1160,15 @@ def api_update_setting(key, db_session: Optional[Session] = None):elif value is None:return jsonify({"error": "No value provided"}), 400+ if check_env_setting(key) is not None:+ logger.bind(policy_audit=True).warning(+ "environment-locked setting rejected at api_update_setting",+ key=key,+ )+ return jsonify(+ {"error": f"Setting {key} is environment-locked"}+ ), 403+# Check if setting existsdb_setting = (db_session.query(Setting).filter(Setting.key == key).first()@@ -1100,25 +1229,17 @@ def api_update_setting(key, db_session: Optional[Session] = None):# public hostname into llm.allowed_local_hostnames (which the host# classifier then trusts as local), one key at a time. Run the# same validators here for the keys they govern.- if key in (- "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()- }- _err = first_egress_validation_error(- {key: value}, _all_db_settings+ _all_db_settings = {+ s.key: s for s in db_session.query(Setting).all()+ }+ _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"),)- 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+ return jsonify({"error": _err["error"]}), 400# Update setting# Pass the db_session to avoid session lookup issues@@ -1146,33 +1267,60 @@ def api_update_setting(key, db_session: Optional[Session] = None):return jsonify(response_data)return jsonify({"error": f"Failed to update setting {key}"}), 500- # Namespace validation: reject new keys outside allowed prefixes.- if not _is_allowed_new_setting_key(key):- logger.warning(- "Security: Rejected setting outside allowed namespaces: {!r} (user={!r})",- key,- session["username"],- )- return jsonify({"error": _new_key_rejection_reason(key)}), 400-- # Create new setting with default metadata- if is_openai_chunk_size:- setting_dict = {- "key": key,- **registered_metadata,- "type": SettingType.APP.value,- "value": value,- }+ # Registered settings may be absent after DELETE. Recreate them from+ # trusted default metadata so callers cannot replace types, options,+ # bounds, or editability, and apply the same coercion/validation as an+ # ordinary update. Genuinely custom keys keep the namespace contract.+ default_meta = SettingsManager().default_settings.get(key)+ if default_meta is not None:+ if not default_meta.get("editable", True):+ return jsonify({"error": f"Setting {key} is not editable"}), 403+ default_ui = str(default_meta.get("ui_element", "text"))+ if value is not None:+ value = coerce_setting_for_write(+ key=key, value=value, ui_element=default_ui+ )+ validation_setting = SimpleNamespace(+ key=key,+ ui_element=default_ui,+ options=default_meta.get("options"),+ min_value=default_meta.get("min_value"),+ max_value=default_meta.get("max_value"),+ )+ is_valid, error_message = validate_setting(+ validation_setting, value+ )+ if not is_valid:+ logger.warning(+ "Validation failed for recreated setting {}: {}",+ key,+ error_message,+ )+ return jsonify(+ {"error": f"Invalid value for setting {key}"}+ ), 400+ setting_dict = dict(default_meta)+ setting_dict.update({"key": key, "value": value})+ default_type = setting_dict.get("type")+ if (+ isinstance(default_type, str)+ and default_type in SettingType.__members__+ ):+ setting_dict["type"] = SettingType[default_type]else:+ if not _is_allowed_new_setting_key(key):+ logger.warning(+ "Security: Rejected setting outside allowed namespaces: {!r} (user={!r})",+ key,+ session["username"],+ )+ return jsonify({"error": _new_key_rejection_reason(key)}), 400setting_dict = {"key": key,"value": value,"name": key.split(".")[-1].replace("_", " ").title(),"description": f"Setting for {key}",}-- # Add additional metadata if provided.- # 'visible' and 'editable' are system-controlled — not accepted from callers.for field in ["type","name",@@ -1187,6 +1335,18 @@ def api_update_setting(key, db_session: Optional[Session] = None):if field in data:setting_dict[field] = data[field]+ # Apply egress validation to creation as well as updates. Otherwise,+ # DELETE followed by PUT can recreate a governed key without guards.+ _all_db_settings = {s.key: s for s in db_session.query(Setting).all()}+ _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 create",+ key=key,+ reason=_err.get("error"),+ )+ return jsonify({"error": _err["error"]}), 400+# Create settingdb_setting = create_or_update_setting(setting_dict, db_session=db_session@@ -1227,12 +1387,22 @@ def api_update_setting(key, db_session: Optional[Session] = None):@settings_bp.route("/api/<path:key>", methods=["DELETE"])@login_required+@settings_limit@with_user_session()def api_delete_setting(key, db_session: Optional[Session] = None, settings_manager=None):"""Delete a setting"""try:+ if check_env_setting(key) is not None:+ logger.bind(policy_audit=True).warning(+ "environment-locked setting rejected at api_delete_setting",+ key=key,+ )+ return jsonify(+ {"error": f"Setting {key} is environment-locked"}+ ), 403+# Check if setting existsdb_setting = (db_session.query(Setting).filter(Setting.key == key).first()@@ -1264,7 +1434,9 @@ def api_import_settings():"""Import settings from defaults file"""try:- settings_manager.load_from_defaults_file()+ settings_manager.load_from_defaults_file(+ preserve_environment_locked=True+ )invalidate_settings_caches(session["username"])return jsonify({"message": "Settings imported successfully"})@@ -1338,6 +1510,8 @@ def api_get_available_models():# Check if force_refresh is requestedforce_refresh = parse_bool_arg("force_refresh")+ policy_context, policy_snapshot = _resolve_model_discovery_policy()+# Get all auto-discovered providers (show all so users can discover# and configure providers they haven't set up yet)from ...llm.providers import get_discovered_provider_options@@ -1346,6 +1520,14 @@ def api_get_available_models():# it is already included here. The previous hardcoded LLAMACPP append# produced a duplicate entry in the dropdown.provider_options = get_discovered_provider_options()+ if policy_context.require_local_llm:+ provider_options = [+ option+ for option in provider_options+ if _model_discovery_provider_allowed(+ option["value"], policy_context, policy_snapshot+ )+ ]# Available models by providerproviders: dict[str, Any] = {}@@ -1372,6 +1554,13 @@ def api_get_available_models():# Group models by providerfor model in cached_models:+ if (+ policy_context.require_local_llm+ and not _model_discovery_provider_allowed(+ model.provider, policy_context, policy_snapshot+ )+ ):+ continueprovider_key = (f"{normalize_provider(model.provider)}_models")@@ -1399,6 +1588,8 @@ def api_get_available_models():})+ except PolicyDeniedError:+ raiseexcept Exception:logger.warning("Error reading cached models from database")# Continue to fetch fresh data@@ -1407,43 +1598,32 @@ def api_get_available_models():# auto-discovery loop below (their provider classes' list_models_for_api),# which is the single fetch path. The previous hand-rolled per-provider# blocks here were dead in normal mode (overwritten by discovery) and an- # inferior duplicate (no SSRF validation, no auth headers); local-only mode- # now keeps the local providers via the LOCAL_PROVIDERS filter below.+ # inferior duplicate (no SSRF validation, no auth headers).# Fetch models from auto-discovered providersfrom ...llm.providers import discover_providersdiscovered_providers = discover_providers()- # Egress policy: when the effective posture is local-only the user- # has opted into local-only inference, so don't list cloud providers- # (OpenRouter, Google, XAI, IonOS, OpenAI, Anthropic, ...). We still- # list the known-local providers (ollama/llamacpp/lmstudio) via their- # provider classes — which validate the URL (SSRF) and support auth- # headers — by filtering the discovered set to LOCAL_PROVIDERS rather- # than skipping discovery entirely. Use the scope-aware helper so a- # PRIVATE_ONLY / adaptive-private user is covered even if the raw- # toggle is False.- require_local_for_discovered = _model_list_local_only()- if require_local_for_discovered:- from ...llm.providers._helpers import LOCAL_PROVIDERS-- local_only_providers = {+ if policy_context.require_local_llm:+ all_discovered_providers = discovered_providers+ discovered_providers = {key: info- for key, info in discovered_providers.items()- if normalize_provider(key) in LOCAL_PROVIDERS+ for key, info in all_discovered_providers.items()+ if _model_discovery_provider_allowed(+ key, policy_context, policy_snapshot+ )}logger.bind(policy_audit=True).info("local-only egress posture: limiting discovered model lists "- "to local providers",- kept=list(local_only_providers.keys()),+ "to endpoint-approved local providers",+ kept=list(discovered_providers.keys()),skipped=[key- for key in discovered_providers- if key not in local_only_providers+ for key in all_discovered_providers+ if key not in discovered_providers],)- discovered_providers = local_only_providersfor provider_key, provider_info in discovered_providers.items():provider_models = []@@ -1462,14 +1642,21 @@ def api_get_available_models():# Get base URL if provider has configurable URLprovider_base_url: str | None = None- if (- hasattr(provider_class, "url_setting")- and provider_class.url_setting- ):+ url_setting = getattr(provider_class, "url_setting", None)+ if url_setting:provider_base_url = _get_setting_from_session(- provider_class.url_setting, ""+ url_setting, "")+ if policy_context.require_local_llm:+ provider_snapshot = dict(policy_snapshot)+ if url_setting:+ provider_snapshot[url_setting] = provider_base_url+ if not _model_discovery_provider_allowed(+ provider_key, policy_context, provider_snapshot+ ):+ continue+# Use the provider's list_models_for_api methodmodels = provider_class.list_models_for_api(api_key, provider_base_url@@ -1491,6 +1678,8 @@ def api_get_available_models():f"Successfully fetched {len(provider_models)} models from {provider_info.provider_name}")+ except PolicyDeniedError:+ raiseexcept Exception:logger.exception(f"Error getting {provider_info.provider_name} models"@@ -1559,6 +1748,21 @@ def api_get_available_models():{"provider_options": provider_options, "providers": providers})+ except PolicyDeniedError as exc:+ reason = exc.decision.reason+ status_code = 503 if reason == "settings_unavailable" else 400+ logger.bind(policy_audit=True).warning(+ "available-model discovery denied by egress policy", reason=reason+ )+ _log_available_models_duration(+ endpoint_start, cache_hit=False, error=True+ )+ return jsonify(+ {+ "status": "error",+ "message": f"Egress policy refused this request: {reason}",+ }+ ), status_codeexcept Exception:logger.exception("Error getting available models")_log_available_models_duration(diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 8bdfb6b3a2..31042c57bc 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -10,7 +10,10 @@ from loguru import loggerfrom ...exceptions import DuplicateResearchError, ResearchTerminatedExceptionfrom ...config.llm_config import get_llm-from ...settings.manager import SnapshotSettingsContext+from ...settings.manager import (+ SnapshotSettingsContext,+ apply_environment_overrides_to_snapshot,+)# Output directory for research resultsfrom ...config.paths import get_research_outputs_directory@@ -895,9 +898,7 @@ def run_research_process(research_id, query, mode, **kwargs):time_period = kwargs.get("time_period")iterations = kwargs.get("iterations")questions_per_iteration = kwargs.get("questions_per_iteration")- strategy = kwargs.get(- "strategy", "source-based"- ) # Default to source-based+ strategy = kwargs.get("strategy")settings_snapshot = kwargs.get("settings_snapshot", {}) # Complete settings snapshot@@ -925,11 +926,46 @@ def run_research_process(research_id, query, mode, **kwargs):f"custom_endpoint={custom_endpoint}, strategy={strategy}")+ # Reapply current operator environment policy at actual dispatch time.+ # Queued snapshots may predate a restart or configuration change; every+ # downstream consumer must see this same effective copy.+ settings_snapshot = apply_environment_overrides_to_snapshot(+ settings_snapshot+ )+ if max_results is not None:+ settings_snapshot["search.max_results"] = max_results+ if time_period is not None:+ settings_snapshot["search.time_period"] = time_period+# Create a settings context that uses snapshot - no database access in threadssettings_context = SnapshotSettingsContext(settings_snapshot, username=username)+ if "model_provider" not in kwargs:+ model_provider = settings_context.get_setting("llm.provider")+ if "model" not in kwargs:+ model = settings_context.get_setting("llm.model")+ if (+ "custom_endpoint" not in kwargs+ and model_provider == "openai_endpoint"+ ):+ custom_endpoint = settings_context.get_setting(+ "llm.openai_endpoint.url"+ )+ if "search_engine" not in kwargs:+ search_engine = settings_context.get_setting("search.tool")+ if "iterations" not in kwargs:+ iterations = settings_context.get_setting("search.iterations")+ if "questions_per_iteration" not in kwargs:+ questions_per_iteration = settings_context.get_setting(+ "search.questions_per_iteration"+ )+ if "strategy" not in kwargs:+ strategy = settings_context.get_setting(+ "search.search_strategy", "source-based"+ )+# Only log settings if explicitly enabled via LDR_LOG_SETTINGS env varfrom ...settings.logger import log_settings@@ -957,17 +993,14 @@ def run_research_process(research_id, query, mode, **kwargs):from ...security import set_active_context as _set_egress_ctxfrom ...security.egress.policy import (PolicyDeniedError,- context_from_snapshot,- resolve_run_primary_engine,+ build_run_egress_context,)try:- _egress_primary = resolve_run_primary_engine(settings_snapshot)- _egress_ctx = context_from_snapshot(- settings_snapshot,- _egress_primary,- username=username,+ _egress_ctx = build_run_egress_context(+ settings_snapshot, search_engine, username=username)+ _egress_primary = _egress_ctx.primary_engine_set_egress_ctx(_egress_ctx)except (PolicyDeniedError, ValueError) as _ctx_err:# Corrupted scope or invalid policy config. The run-start@@ -997,21 +1030,6 @@ def run_research_process(research_id, query, mode, **kwargs):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,diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.jsindex 3a565aafbd..0bb76d0232 100644--- a/src/local_deep_research/web/static/js/components/research.js+++ b/src/local_deep_research/web/static/js/components/research.js@@ -944,11 +944,31 @@// Privacy & Egress controls — persist to settings DB on change so// the picked scope/local-inference toggles survive the next page load// and the egress-policy warning banner refreshes immediately.+ let policyScopeSaveQueue = Promise.resolve();+ let policyScopeSaveGeneration = 0;const policyScopeSelect = document.getElementById('policy_egress_scope');if (policyScopeSelect) {- policyScopeSelect.addEventListener('change', function() {- saveSearchSetting('policy.egress_scope', this.value);- applyPrivacyPanelScope(this.value);+ policyScopeSelect.dataset.savedValue = policyScopeSelect.value;+ policyScopeSelect.addEventListener("change", function() {+ const selectedValue = this.value;+ const generation = ++policyScopeSaveGeneration;+ applyPrivacyPanelScope(selectedValue);+ policyScopeSaveQueue = policyScopeSaveQueue+ .catch(() => undefined)+ .then(() => saveSearchSetting(+ "policy.egress_scope",+ selectedValue,+ () => {+ if (generation === policyScopeSaveGeneration) {+ refreshPolicyScopeFromServer(this);+ }+ },+ () => {+ if (generation === policyScopeSaveGeneration) {+ this.dataset.savedValue = selectedValue;+ }+ }+ ));});// Apply the initial cue on page load (the data-scope attribute is// already set server-side from settings; this just keeps the icon@@ -956,13 +976,13 @@applyPrivacyPanelScope(policyScopeSelect.value);}const llmRequireLocalInput = document.getElementById('llm_require_local_endpoint');- if (llmRequireLocalInput) {+ if (llmRequireLocalInput && llmRequireLocalInput.dataset.envLocked !== "true") {llmRequireLocalInput.addEventListener('change', function() {saveSearchSetting('llm.require_local_endpoint', this.checked);});}const embRequireLocalInput = document.getElementById('embeddings_require_local');- if (embRequireLocalInput) {+ if (embRequireLocalInput && embRequireLocalInput.dataset.envLocked !== "true") {embRequireLocalInput.addEventListener('change', function() {saveSearchSetting('embeddings.require_local', this.checked);});@@ -2259,7 +2279,13 @@},body: JSON.stringify({ value: modelValue })})- .then(response => response.json())+ .then(async response => {+ const data = await response.json();+ if (!response.ok) {+ throw new Error(data.error || data.message || `HTTP ${response.status}`);+ }+ return data;+ }).then(data => {SafeLogger.log('Model setting saved to database:', data);@@ -2454,26 +2480,32 @@// on the settings page.)const LOCK_TITLE = 'Forced on by the Private-only egress scope — local inference is required so data stays on this machine.';const scopeLocked = normalized === 'private_only';- ['llm_require_local_endpoint', 'embeddings_require_local'].forEach((id) => {+ ["llm_require_local_endpoint", "embeddings_require_local"].forEach((id) => {const cb = document.getElementById(id);if (!cb) return;+ const envLocked = cb.dataset.envLocked === "true";+ const envValue = cb.dataset.envValue === "true";+ const envTitle = cb.dataset.envTitle || "Locked by the server operator";if (scopeLocked) {- // Remember the user's choice once, so we can restore it later.- if (!cb.dataset.userCheckedSaved) {- cb.dataset.userChecked = cb.checked ? '1' : '0';- cb.dataset.userCheckedSaved = '1';+ if (!envLocked && !cb.dataset.userCheckedSaved) {+ cb.dataset.userChecked = cb.checked ? "1" : "0";+ cb.dataset.userCheckedSaved = "1";}cb.checked = true;cb.disabled = true;cb.title = LOCK_TITLE;+ } else if (envLocked) {+ cb.checked = envValue;+ cb.disabled = true;+ cb.title = envTitle;} else {if (cb.dataset.userCheckedSaved) {- cb.checked = cb.dataset.userChecked === '1';+ cb.checked = cb.dataset.userChecked === "1";delete cb.dataset.userChecked;delete cb.dataset.userCheckedSaved;}cb.disabled = false;- cb.title = '';+ cb.title = "";}});@@ -2489,40 +2521,66 @@icon.className = iconClassByScope[normalized] || iconClassByScope.adaptive;}- function saveSearchSetting(settingKey, value) {- // Save to the database using the settings API- fetch(`/settings/api/${settingKey}`, {- method: 'PUT',+ function refreshPolicyScopeFromServer(select) {+ select.disabled = true;+ const settingKey = "policy.egress_scope";+ fetch(`/settings/api/${settingKey}`)+ .then(async response => {+ const data = await response.json();+ if (!response.ok) throw new Error(data.error || "Refresh failed");+ return data;+ })+ .then(data => {+ const effectiveValue = data.value || "adaptive";+ if (select.querySelector(`option[value="${effectiveValue}"]`)) {+ select.value = effectiveValue;+ } else {+ select.value = "adaptive";+ }+ select.dataset.savedValue = select.value;+ select.disabled = data.editable === false;+ applyPrivacyPanelScope(select.value);+ })+ .catch(error => {+ SafeLogger.error("Unable to refresh effective egress scope:", error);+ window.location.reload();+ });+ }++ function saveSearchSetting(settingKey, value, onFailure = null, onSuccess = null) {+ return fetch(`/settings/api/${settingKey}`, {+ method: "PUT",headers: {- 'Content-Type': 'application/json',- 'X-CSRFToken': window.api ? window.api.getCsrfToken() : ''+ "Content-Type": "application/json",+ "X-CSRFToken": window.api ? window.api.getCsrfToken() : ""},body: JSON.stringify({ value })})- .then(response => response.json())+ .then(async response => {+ const data = await response.json();+ if (!response.ok) {+ throw new Error(data.error || `Request failed (${response.status})`);+ }+ return data;+ }).then(data => {SafeLogger.log(`Search setting ${settingKey} saved to database:`, data);-- // If the response includes warnings, display them directly- if (data.warnings && typeof window.displayWarnings === 'function') {+ if (data.warnings && typeof window.displayWarnings === "function") {window.displayWarnings(data.warnings);}-- // Optionally show a notification+ if (typeof onSuccess === "function") onSuccess(data);if (window.ui && window.ui.showMessage) {- window.ui.showMessage(`${settingKey.split('.').pop()} updated to: ${value}`, 'success', 2000);+ window.ui.showMessage(`${settingKey.split(".").pop()} updated to: ${value}`, "success", 2000);}}).catch(error => {SafeLogger.error(`Error saving search setting ${settingKey} to database:`, error);-- // Show error notification if available+ if (typeof onFailure === "function") onFailure(error);if (window.ui && window.ui.showMessage) {- window.ui.showMessage(`Error updating ${settingKey}: ${error.message}`, 'error', 3000);+ window.ui.showMessage(`Error updating ${settingKey}: ${error.message}`, "error", 3000);}});}-// Research form submission handlerfunction handleResearchSubmit(event) {event.preventDefault();@@ -2679,14 +2737,14 @@const questionsPerIteration = questionsInput ? parseInt(questionsInput.value, 10) : 3;// Egress policy form fields (per-research override, not saved- // to settings). Mirror the model/search_engine pattern: the- // server falls back to saved settings when these are unset.- const policyScopeEl = document.getElementById('policy_egress_scope');- const llmLocalEl = document.getElementById('llm_require_local_endpoint');- const embLocalEl = document.getElementById('embeddings_require_local');- const policyEgressScope = policyScopeEl ? policyScopeEl.value : null;- const llmRequireLocalEndpoint = llmLocalEl ? !!llmLocalEl.checked : null;- const embeddingsRequireLocal = embLocalEl ? !!embLocalEl.checked : null;+ // to settings). Omit disabled controls: the server derives operator+ // locks and Private-only locality from the effective scope/environment.+ const policyScopeEl = document.getElementById("policy_egress_scope");+ const llmLocalEl = document.getElementById("llm_require_local_endpoint");+ const embLocalEl = document.getElementById("embeddings_require_local");+ const policyEgressScope = policyScopeEl && !policyScopeEl.disabled ? policyScopeEl.value : null;+ const llmRequireLocalEndpoint = llmLocalEl && !llmLocalEl.disabled ? !!llmLocalEl.checked : null;+ const embeddingsRequireLocal = embLocalEl && !embLocalEl.disabled ? !!embLocalEl.checked : null;// Prepare the data for submissionconst formData = {diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.htmlindex 7423dce8f4..80f013f399 100644--- a/src/local_deep_research/web/templates/pages/research.html+++ b/src/local_deep_research/web/templates/pages/research.html@@ -150,29 +150,31 @@</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 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">+ <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: operator-enabled escape hatch that disables normal egress protection — not recommended (hard SSRF/cloud-metadata blocking still applies).") }}</label>+ <select id="policy_egress_scope" name="policy_egress_scope" class="ldr-form-control"{% if settings.egress_scope_env_locked %} disabled aria-disabled="true" data-env-locked="true" title="Locked by LDR_POLICY_EGRESS_SCOPE"{% endif %}><option value="adaptive" {% if not settings.policy_egress_scope or settings.policy_egress_scope == "adaptive" %}selected{% endif %}>Adaptive (default — follows primary)</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>+ {% if settings.allow_unprotected_egress %}<option value="unprotected" {% if settings.policy_egress_scope == "unprotected" %}selected{% endif %}>Unprotected (no protection — not recommended)</option>{% endif %}</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? ↗</a></span>+ <span class="ldr-input-help" id="policy_egress_scope_help">{% if settings.egress_scope_env_locked %}Locked by the server operator via LDR_POLICY_EGRESS_SCOPE. {% endif %}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? ↗</a></span></div><div class="ldr-form-group ldr-half"><div style="font-weight:normal; opacity:0.85; font-size:0.9rem; margin-bottom:0.35rem;">Local inference</div><label for="llm_require_local_endpoint" style="display:flex; align-items:center; gap:0.4rem; font-weight:normal; margin:0 0 0.35rem 0;">- <input type="checkbox" id="llm_require_local_endpoint" name="llm_require_local_endpoint" value="true" {% if settings.llm_require_local_endpoint %}checked{% endif %}>+ <input type="checkbox" id="llm_require_local_endpoint" name="llm_require_local_endpoint" value="true" {% if settings.llm_require_local_endpoint %}checked{% endif %}{% if settings.llm_local_env_locked %} disabled aria-disabled="true" data-env-locked="true" data-env-value="{{ settings.llm_require_local_endpoint | lower }}" data-env-title="Locked by LDR_LLM_REQUIRE_LOCAL_ENDPOINT" title="Locked by LDR_LLM_REQUIRE_LOCAL_ENDPOINT"{% endif %}>{{ tooltip("Require local LLM endpoint", "When checked, blocks cloud LLM providers (OpenAI, Anthropic, Google, OpenRouter). Local providers (Ollama, LM Studio, llama.cpp) and OpenAI-compatible endpoints pointed at local hosts are allowed.") }}</label>+ {% if settings.llm_local_env_locked %}<span class="ldr-input-help">LLM locality is locked by the server operator.</span>{% endif %}<label for="embeddings_require_local" style="display:flex; align-items:center; gap:0.4rem; font-weight:normal; margin:0;">- <input type="checkbox" id="embeddings_require_local" name="embeddings_require_local" value="true" {% if settings.embeddings_require_local %}checked{% endif %}>+ <input type="checkbox" id="embeddings_require_local" name="embeddings_require_local" value="true" {% if settings.embeddings_require_local %}checked{% endif %}{% if settings.embeddings_local_env_locked %} disabled aria-disabled="true" data-env-locked="true" data-env-value="{{ settings.embeddings_require_local | lower }}" data-env-title="Locked by LDR_EMBEDDINGS_REQUIRE_LOCAL" title="Locked by LDR_EMBEDDINGS_REQUIRE_LOCAL"{% endif %}>{{ tooltip("Require local embeddings", "When checked, indexing with cloud embedding providers (OpenAI) is blocked. Critical for keeping a local corpus from being uploaded chunk-by-chunk during indexing.") }}</label>+ {% if settings.embeddings_local_env_locked %}<span class="ldr-input-help">Embedding locality is locked by the server operator.</span>{% endif %}</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. <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>+ <span class="ldr-input-help" style="display:block; margin-top:0.5rem;">These controls decide what data leaves your machine for this run. Editable controls override the corresponding global settings just for this research; controls marked locked are enforced by the server operator. 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__.pyindex 0ff314535c..b79024df5f 100644--- a/src/local_deep_research/web/warning_checks/__init__.py+++ b/src/local_deep_research/web/warning_checks/__init__.py@@ -238,7 +238,7 @@ def calculate_warnings() -> List[dict]:warnings.append(w)# Loud, non-dismissible banner when protection is turned off.- w = _safe_check(check_unprotected_egress, egress_scope)+ w = _safe_check(check_unprotected_egress, effective_scope)if w:warnings.append(w)diff --git a/tests/api/test_in_memory_settings_environment.py b/tests/api/test_in_memory_settings_environment.pynew file mode 100644index 0000000000..1c5ccd3f62--- /dev/null+++ b/tests/api/test_in_memory_settings_environment.py@@ -0,0 +1,295 @@+from inspect import signature+from typing import Any+from unittest.mock import PropertyMock, patch++import pytest++from local_deep_research.api.settings_utils import InMemorySettingsManager+from local_deep_research.settings.base import ISettingsManager+from local_deep_research.settings.manager import SettingsManager+++def default_settings() -> dict[str, Any]:+ return {+ "app.port": {+ "value": 5000,+ "ui_element": "number",+ "editable": True,+ "description": "Server port",+ },+ "policy.egress_scope": {+ "value": "strict",+ "ui_element": "select",+ "editable": True,+ "description": "Stored egress policy",+ "options": ["adaptive", "strict", "public_only"],+ },+ }+++def make_manager(default_settings: dict[str, Any]) -> InMemorySettingsManager:+ with patch.object(+ SettingsManager,+ "default_settings",+ new_callable=PropertyMock,+ return_value=default_settings,+ ):+ return InMemorySettingsManager()+++def test_get_setting_uses_current_environment_value_after_manager_initialization(+ monkeypatch, default_settings+):+ # Given+ monkeypatch.setenv("LDR_APP_PORT", "8080")+ manager = make_manager(default_settings)+ monkeypatch.setenv("LDR_APP_PORT", "9090")++ # When+ value = manager.get_setting("app.port")++ # Then+ assert value == 9090+ assert manager.get_setting("app.port", check_env=False) == 5000+++def test_get_setting_reveals_canonical_value_after_environment_override_removed(+ monkeypatch, default_settings+):+ # Given+ monkeypatch.setenv("LDR_APP_PORT", "8080")+ manager = make_manager(default_settings)+ monkeypatch.delenv("LDR_APP_PORT")++ # When+ value = manager.get_setting("app.port")++ # Then+ assert value == 5000+++def test_get_all_settings_without_environment_overrides_returns_baseline_metadata(+ monkeypatch, default_settings+):+ # Given+ monkeypatch.setenv("LDR_APP_PORT", "8080")+ manager = make_manager(default_settings)++ # When+ baseline = manager.get_all_settings(include_environment_overrides=False)++ # Then+ assert baseline["app.port"]["value"] == 5000+ assert baseline["app.port"]["editable"] is True+ assert manager._settings["app.port"]["value"] == 5000+++def test_get_all_settings_applies_current_environment_overlay_to_returned_copy(+ monkeypatch, default_settings+):+ # Given+ monkeypatch.setenv("LDR_APP_PORT", "8080")+ manager = make_manager(default_settings)+ monkeypatch.setenv("LDR_APP_PORT", "9090")++ # When+ effective = manager.get_all_settings()++ # Then+ assert effective["app.port"]["value"] == 9090+ assert effective["app.port"]["editable"] is False+ assert manager._settings["app.port"]["value"] == 5000+ assert manager._settings["app.port"]["editable"] is True+++def test_get_settings_snapshot_remains_environment_aware_by_default(+ monkeypatch, default_settings+):+ # Given+ monkeypatch.setenv("LDR_APP_PORT", "8080")+ manager = make_manager(default_settings)++ # When+ snapshot = manager.get_settings_snapshot()++ # Then+ assert snapshot["app.port"] == 8080+++def test_import_preserves_stored_baseline_and_refreshes_locked_metadata(+ monkeypatch, default_settings+):+ # Given+ monkeypatch.setenv("LDR_POLICY_EGRESS_SCOPE", "adaptive")+ manager = make_manager(default_settings)+ imported = {+ "policy.egress_scope": {+ "value": "public_only",+ "ui_element": "select",+ "editable": True,+ "description": "Fresh egress policy",+ "options": ["adaptive", "strict", "public_only"],+ }+ }++ # When+ manager.import_settings(imported, preserve_environment_locked=True)++ # Then+ baseline = manager.get_all_settings(include_environment_overrides=False)+ assert baseline["policy.egress_scope"]["value"] == "strict"+ assert (+ baseline["policy.egress_scope"]["description"] == "Fresh egress policy"+ )+ assert baseline["policy.egress_scope"]["options"] == [+ "adaptive",+ "strict",+ "public_only",+ ]+ assert manager.get_setting("policy.egress_scope") == "adaptive"+++def test_load_defaults_preserves_stored_baseline_and_refreshes_locked_metadata(+ monkeypatch, default_settings+):+ # Given+ monkeypatch.setenv("LDR_POLICY_EGRESS_SCOPE", "adaptive")+ manager = make_manager(default_settings)+ refreshed_defaults = {+ **default_settings,+ "policy.egress_scope": {+ "value": "public_only",+ "ui_element": "select",+ "editable": True,+ "description": "Refreshed egress policy",+ "options": ["adaptive", "strict", "public_only"],+ },+ }++ # When+ with patch.object(+ SettingsManager,+ "default_settings",+ new_callable=PropertyMock,+ return_value=refreshed_defaults,+ ):+ manager.load_from_defaults_file(preserve_environment_locked=True)++ # Then+ baseline = manager.get_all_settings(include_environment_overrides=False)+ assert baseline["policy.egress_scope"]["value"] == "strict"+ assert (+ baseline["policy.egress_scope"]["description"]+ == "Refreshed egress policy"+ )+ assert manager.get_setting("policy.egress_scope") == "adaptive"+++def test_import_uses_canonical_value_for_environment_locked_key_absent_from_storage(+ monkeypatch, default_settings+):+ # Given+ monkeypatch.setenv("LDR_POLICY_NEW_SCOPE", "operator-value")+ manager = make_manager(default_settings)+ imported = {+ "policy.new_scope": {+ "value": "canonical-value",+ "ui_element": "text",+ "editable": True,+ "description": "New policy scope",+ }+ }++ # When+ manager.import_settings(imported, preserve_environment_locked=True)++ # Then+ baseline = manager.get_all_settings(include_environment_overrides=False)+ assert baseline["policy.new_scope"]["value"] == "canonical-value"+ assert manager.get_setting("policy.new_scope") == "operator-value"+++def test_import_of_bare_scalar_keeps_environment_locked_entry_intact(+ monkeypatch, default_settings+):+ # Given a bare-scalar import (a supported settings_data shape) for a+ # key that is stored and environment-locked+ monkeypatch.setenv("LDR_APP_PORT", "8080")+ manager = make_manager(default_settings)++ # When+ manager.import_settings(+ {"app.port": 9999}, preserve_environment_locked=True+ )++ # Then the stored entry survives untouched (no metadata to merge)+ baseline = manager.get_all_settings(include_environment_overrides=False)+ assert baseline["app.port"]["value"] == 5000+ assert baseline["app.port"]["ui_element"] == "number"+ assert manager.get_setting("app.port") == 8080+++def test_import_of_bare_scalar_still_replaces_unlocked_entry(+ monkeypatch, default_settings+):+ # Given no environment lock on the key+ monkeypatch.delenv("LDR_APP_PORT", raising=False)+ manager = make_manager(default_settings)++ # When+ manager.import_settings(+ {"app.port": 9999}, preserve_environment_locked=True+ )++ # Then the scalar import behaves as before the preservation flag+ assert manager.get_all_settings()["app.port"] == 9999+++def test_settings_managers_expose_environment_override_toggle():+ # Given+ methods = (+ ISettingsManager.get_all_settings,+ SettingsManager.get_all_settings,+ InMemorySettingsManager.get_all_settings,+ )++ # When+ parameters = [signature(method).parameters for method in methods]++ # Then+ assert all(+ "include_environment_overrides" in params for params in parameters+ )+ assert all(+ params["include_environment_overrides"].default is True+ for params in parameters+ )+++def test_settings_managers_share_get_all_settings_parameter_order():+ parameter_names = [+ tuple(signature(method).parameters)+ for method in (+ ISettingsManager.get_all_settings,+ SettingsManager.get_all_settings,+ InMemorySettingsManager.get_all_settings,+ )+ ]++ assert parameter_names == [+ ("self", "bypass_cache", "include_environment_overrides", "strict"),+ ("self", "bypass_cache", "include_environment_overrides", "strict"),+ ("self", "bypass_cache", "include_environment_overrides", "strict"),+ ]+++def test_positional_bypass_cache_does_not_disable_in_memory_environment_overlay(+ monkeypatch, default_settings+):+ monkeypatch.setenv("LDR_APP_PORT", "8080")+ manager = make_manager(default_settings)++ effective = manager.get_all_settings(False)++ assert effective["app.port"]["value"] == 8080diff --git a/tests/api/test_settings_utils.py b/tests/api/test_settings_utils.pyindex 90cb2ebd62..4f68736cb3 100644--- a/tests/api/test_settings_utils.py+++ b/tests/api/test_settings_utils.py@@ -1,6 +1,6 @@"""Tests for API settings utilities."""-from unittest.mock import patch+from unittest.mock import PropertyMock, patchfrom local_deep_research.api.settings_utils import (InMemorySettingsManager,@@ -8,6 +8,7 @@ from local_deep_research.api.settings_utils import (create_settings_snapshot,extract_setting_value,)+from local_deep_research.settings.manager import SettingsManagerclass TestInMemorySettingsManager:@@ -130,6 +131,72 @@ class TestInMemorySettingsManager:assert len(settings) == 1assert "only.setting" in settings+ def test_import_preserves_environment_locked_setting_with_delete_extra(+ self, monkeypatch+ ):+ manager = InMemorySettingsManager()+ manager.set_setting("policy.egress_scope", "strict")+ monkeypatch.setenv("LDR_POLICY_EGRESS_SCOPE", "adaptive")+ manager.import_settings(+ {+ "policy.egress_scope": {+ "value": "public_only",+ "ui_element": "select",+ },+ "only.setting": {"value": "only", "ui_element": "text"},+ },+ delete_extra=True,+ preserve_environment_locked=True,+ )+ assert (+ manager.get_setting("policy.egress_scope", check_env=False)+ == "strict"+ )+ assert manager.get_setting("only.setting") == "only"++ def test_import_preserves_locked_value_and_refreshes_metadata(+ self, monkeypatch+ ):+ manager = InMemorySettingsManager()+ key = "policy.egress_scope"+ manager._settings[key] = {+ "value": "strict",+ "description": "Stale description",+ "options": ["legacy"],+ "ui_element": "text",+ "min_value": 1,+ "max_value": 2,+ }+ monkeypatch.setenv("LDR_POLICY_EGRESS_SCOPE", "adaptive")+ canonical = {+ "value": "public_only",+ "description": "Fresh description",+ "options": ["adaptive", "strict", "public_only"],+ "ui_element": "select",+ "min_value": 0,+ "max_value": 10,+ }++ manager.import_settings(+ {key: canonical}, preserve_environment_locked=True+ )++ refreshed = manager.get_all_settings(+ include_environment_overrides=False+ )[key]+ assert refreshed["value"] == "strict"+ assert refreshed["description"] == "Fresh description"+ assert refreshed["options"] == ["adaptive", "strict", "public_only"]+ assert refreshed["ui_element"] == "select"+ assert refreshed["min_value"] == 0+ assert refreshed["max_value"] == 10++ manager.import_settings(+ {key: {**canonical, "value": "adaptive"}},+ preserve_environment_locked=False,+ )+ assert manager.get_all_settings()[key]["value"] == "adaptive"+def test_import_settings_no_overwrite(self):"""Test importing without overwriting existing settings."""manager = InMemorySettingsManager()@@ -189,6 +256,62 @@ class TestInMemorySettingsManager:# Should be back to default# (exact value depends on defaults file)+ def test_load_from_defaults_preserves_locked_value_and_refreshes_metadata(+ self, monkeypatch+ ):+ manager = InMemorySettingsManager()+ manager._settings["policy.egress_scope"] = {+ "value": "strict",+ "description": "Stale description",+ "options": ["legacy"],+ "ui_element": "text",+ "min_value": 1,+ "max_value": 2,+ }+ manager._settings["app.debug"] = {+ "value": "stale unlocked value",+ "description": "Stale unlocked description",+ "ui_element": "text",+ }+ monkeypatch.setenv("LDR_POLICY_EGRESS_SCOPE", "adaptive")+ defaults = {+ "policy.egress_scope": {+ "value": "public_only",+ "description": "Fresh description",+ "options": ["adaptive", "strict", "public_only"],+ "ui_element": "select",+ "min_value": 0,+ "max_value": 10,+ },+ "app.debug": {+ "value": "canonical unlocked value",+ "description": "Fresh unlocked description",+ "ui_element": "text",+ },+ }++ with patch.object(+ SettingsManager,+ "default_settings",+ new_callable=PropertyMock,+ return_value=defaults,+ ):+ manager.load_from_defaults_file(preserve_environment_locked=True)++ locked = manager.get_all_settings(include_environment_overrides=False)[+ "policy.egress_scope"+ ]+ assert locked["value"] == "strict"+ assert locked["description"] == "Fresh description"+ assert locked["options"] == ["adaptive", "strict", "public_only"]+ assert locked["ui_element"] == "select"+ assert locked["min_value"] == 0+ assert locked["max_value"] == 10+ assert (+ manager.get_all_settings()["app.debug"]["value"]+ == "canonical unlocked value"+ )+def test_env_var_override(self, monkeypatch):"""Test that environment variables override defaults."""monkeypatch.setenv("LDR_LLM_PROVIDER", "env_provider")diff --git a/tests/database/test_alembic_migrations.py b/tests/database/test_alembic_migrations.pyindex 6082a91aa0..90eb79c165 100644--- a/tests/database/test_alembic_migrations.py+++ b/tests/database/test_alembic_migrations.py@@ -694,6 +694,9 @@ class TestMigrationChain:"0023_drop_chunk_collection_unique.py","0024_chunk_id_autoincrement.py","0025_split_context_warning_dismissals.py",+ "0026_add_app_logs_export_index.py",+ "0027_disable_legacy_unprotected_egress.py",+ "0028_expand_rag_index_identity.py",]for filename in expected_files:@@ -6068,6 +6071,10 @@ class TestMigrationSafetyGuards:# 0013: restoring 'auto'/'parallel' references would recreate# broken state — those engines no longer exist in the codebase."0013_remove_meta_search_engines.py",+ # 0027: the original value cannot be distinguished from settings that+ # were already adaptive, and restoring unprotected would weaken the+ # new operator-controlled security boundary.+ "0027_disable_legacy_unprotected_egress.py",# 0016: the dropped cache tables were orphaned dead code holding no# data, and their models are removed — nothing to recreate."0016_drop_orphaned_cache_tables.py",diff --git a/tests/database/test_migration_0027_disable_legacy_unprotected.py b/tests/database/test_migration_0027_disable_legacy_unprotected.pynew file mode 100644index 0000000000..b0594a3e81--- /dev/null+++ b/tests/database/test_migration_0027_disable_legacy_unprotected.py@@ -0,0 +1,346 @@+"""Tests for migration 0027: neutralize legacy unprotected selections."""++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+++def _upgrade(engine, revision):+ config = get_alembic_config(engine)+ with engine.begin() as conn:+ config.attributes["connection"] = conn+ command.upgrade(config, revision)+++def migrated_to_0025_engine(tmp_path):+ engine = create_engine(f"sqlite:///{tmp_path / 'test_0027.db'}")+ _upgrade(engine, "0025")+ yield engine+ engine.dispose()+++def _seed(engine, value):+ with engine.begin() as conn:+ conn.execute(+ text(+ "INSERT INTO settings "+ "(key, value, type, name, ui_element, visible, editable) "+ "VALUES ('policy.egress_scope', :value, 'app', "+ "'Egress Scope', 'select', 1, 1)"+ ),+ {"value": json.dumps(value)},+ )+++def _read(engine):+ with engine.begin() as conn:+ raw = conn.execute(+ text("SELECT value FROM settings WHERE key='policy.egress_scope'")+ ).scalar_one()+ return json.loads(raw)+++def _seed_queued(engine, research_id, snapshot):+ with engine.begin() as conn:+ conn.execute(+ text(+ "INSERT INTO queued_researches "+ "(username, research_id, query, mode, settings_snapshot, "+ "position) "+ "VALUES ('tester', :research_id, 'q', 'quick', :snapshot, 1)"+ ),+ {"research_id": research_id, "snapshot": json.dumps(snapshot)},+ )+++def _read_queued(engine, research_id):+ with engine.begin() as conn:+ raw = conn.execute(+ text(+ "SELECT settings_snapshot FROM queued_researches "+ "WHERE research_id = :research_id"+ ),+ {"research_id": research_id},+ ).scalar_one()+ return json.loads(raw)+++ "legacy", ["unprotected", "UNPROTECTED", " unprotected "]+)+def test_unprotected_is_reset_to_adaptive(migrated_to_0025_engine, legacy):+ _seed(migrated_to_0025_engine, legacy)+ _upgrade(migrated_to_0025_engine, "0027")+ assert _read(migrated_to_0025_engine) == "adaptive"+++ "scope", ["adaptive", "public_only", "private_only", "strict"]+)+def test_protected_scopes_are_preserved(migrated_to_0025_engine, scope):+ _seed(migrated_to_0025_engine, scope)+ _upgrade(migrated_to_0025_engine, "0027")+ assert _read(migrated_to_0025_engine) == scope++[email protected]("value", [None, 123, True])+def test_settings_non_string_scope_value_is_left_untouched(+ migrated_to_0025_engine, value+):+ """The settings-table decode guard: a non-string decoded value (a+ corrupted row storing JSON null/number/bool, which SQLite may hand back+ as a raw non-str) is not legacy-unprotected, so the migration leaves the+ row exactly as stored instead of crashing or rewriting it.+ """+ _seed(migrated_to_0025_engine, value)++ def _raw_stored():+ with migrated_to_0025_engine.begin() as conn:+ return conn.execute(+ text(+ "SELECT value FROM settings WHERE key='policy.egress_scope'"+ )+ ).scalar_one()++ before = _raw_stored()+ _upgrade(migrated_to_0025_engine, "0027")+ assert _raw_stored() == before+++ ("research_id", "snapshot", "expected"),+ [+ (+ "wrapped-scalar",+ {+ "submission": {"query": "queued query", "mode": "deep"},+ "settings_snapshot": {+ "policy.egress_scope": " UnPrOtEcTeD ",+ "search.tool": {"value": "searxng", "type": "select"},+ },+ "queue_metadata": {"attempt": 2},+ },+ {+ "submission": {"query": "queued query", "mode": "deep"},+ "settings_snapshot": {+ "policy.egress_scope": "adaptive",+ "search.tool": {"value": "searxng", "type": "select"},+ },+ "queue_metadata": {"attempt": 2},+ },+ ),+ (+ "wrapped-metadata",+ {+ "submission": {"query": "queued query"},+ "settings_snapshot": {+ "policy.egress_scope": {+ "value": "UNPROTECTED",+ "type": "select",+ "label": "Egress Scope",+ },+ "llm.model": {"value": "model-a"},+ },+ "queue_metadata": {"owner": "tester"},+ },+ {+ "submission": {"query": "queued query"},+ "settings_snapshot": {+ "policy.egress_scope": {+ "value": "adaptive",+ "type": "select",+ "label": "Egress Scope",+ },+ "llm.model": {"value": "model-a"},+ },+ "queue_metadata": {"owner": "tester"},+ },+ ),+ (+ "flat-scalar",+ {+ "policy.egress_scope": "unprotected",+ "query": "legacy queued query",+ "metadata": {"request_id": "request-1"},+ },+ {+ "policy.egress_scope": "adaptive",+ "query": "legacy queued query",+ "metadata": {"request_id": "request-1"},+ },+ ),+ (+ "flat-metadata",+ {+ "policy.egress_scope": {+ "value": " unprotected ",+ "type": "select",+ "visible": True,+ },+ "query": "legacy queued query",+ "metadata": {"request_id": "request-2"},+ },+ {+ "policy.egress_scope": {+ "value": "adaptive",+ "type": "select",+ "visible": True,+ },+ "query": "legacy queued query",+ "metadata": {"request_id": "request-2"},+ },+ ),+ ],+)+def test_queued_unprotected_scopes_are_reset_to_adaptive(+ migrated_to_0025_engine, research_id, snapshot, expected+):+ _seed_queued(migrated_to_0025_engine, research_id, snapshot)++ _upgrade(migrated_to_0025_engine, "0027")++ assert _read_queued(migrated_to_0025_engine, research_id) == expected+++def test_queued_protected_scope_is_preserved(migrated_to_0025_engine):+ snapshot = {+ "submission": {"query": "queued query"},+ "settings_snapshot": {+ "policy.egress_scope": {+ "value": "strict",+ "type": "select",+ "label": "Egress Scope",+ },+ "search.tool": "searxng",+ },+ "queue_metadata": {"attempt": 2},+ }+ _seed_queued(migrated_to_0025_engine, "protected", snapshot)++ _upgrade(migrated_to_0025_engine, "0027")++ assert _read_queued(migrated_to_0025_engine, "protected") == snapshot+++ ("research_id", "raw_snapshot"),+ [+ ("malformed-json", "{not valid json"),+ ("non-dict-top-level", json.dumps(["unprotected"])),+ (+ "non-dict-nested-snapshot",+ json.dumps(+ {+ "submission": {"query": "q"},+ "settings_snapshot": None,+ }+ ),+ ),+ ],+)+def test_unrecognized_snapshots_are_left_untouched(+ migrated_to_0025_engine, research_id, raw_snapshot+):+ """Defensive branches: rows the migration cannot safely interpret are+ skipped byte-for-byte, and they do not abort migration of other rows.+ """+ with migrated_to_0025_engine.begin() as conn:+ conn.execute(+ text(+ "INSERT INTO queued_researches "+ "(username, research_id, query, mode, settings_snapshot, "+ "position) "+ "VALUES ('tester', :research_id, 'q', 'quick', :snapshot, 1)"+ ),+ {"research_id": research_id, "snapshot": raw_snapshot},+ )+ _seed_queued(+ migrated_to_0025_engine,+ "still-migrated",+ {"policy.egress_scope": "unprotected", "query": "q"},+ )++ _upgrade(migrated_to_0025_engine, "0027")++ with migrated_to_0025_engine.begin() as conn:+ untouched = conn.execute(+ text(+ "SELECT settings_snapshot FROM queued_researches "+ "WHERE research_id = :research_id"+ ),+ {"research_id": research_id},+ ).scalar_one()+ assert untouched == raw_snapshot+ assert _read_queued(migrated_to_0025_engine, "still-migrated") == {+ "policy.egress_scope": "adaptive",+ "query": "q",+ }+++def test_null_snapshot_is_skipped(migrated_to_0025_engine):+ with migrated_to_0025_engine.begin() as conn:+ conn.execute(+ text(+ "INSERT INTO queued_researches "+ "(username, research_id, query, mode, position) "+ "VALUES ('tester', 'null-snapshot', 'q', 'quick', 1)"+ )+ )++ _upgrade(migrated_to_0025_engine, "0027")++ with migrated_to_0025_engine.begin() as conn:+ raw = conn.execute(+ text(+ "SELECT settings_snapshot FROM queued_researches "+ "WHERE research_id = 'null-snapshot'"+ )+ ).scalar_one()+ assert raw is None+++def test_queued_researches_are_migrated_without_settings_table(+ migrated_to_0025_engine,+):+ snapshot = {"policy.egress_scope": "unprotected", "query": "queued query"}+ _seed_queued(migrated_to_0025_engine, "without-settings", snapshot)+ with migrated_to_0025_engine.begin() as conn:+ conn.execute(text("DROP TABLE settings"))++ _upgrade(migrated_to_0025_engine, "0027")++ assert _read_queued(migrated_to_0025_engine, "without-settings") == {+ "policy.egress_scope": "adaptive",+ "query": "queued query",+ }+++def test_settings_are_migrated_without_queued_researches_table(+ migrated_to_0025_engine,+):+ _seed(migrated_to_0025_engine, "unprotected")+ with migrated_to_0025_engine.begin() as conn:+ conn.execute(text("DROP TABLE queued_researches"))++ _upgrade(migrated_to_0025_engine, "0027")++ assert _read(migrated_to_0025_engine) == "adaptive"+++def test_0027_chains_to_0026():+ 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)+ assert script.get_revision("0027").down_revision == "0026"diff --git a/tests/database/test_migration_0028_expand_rag_index_identity.py b/tests/database/test_migration_0028_expand_rag_index_identity.pynew file mode 100644index 0000000000..10e9d064f4--- /dev/null+++ b/tests/database/test_migration_0028_expand_rag_index_identity.py@@ -0,0 +1,228 @@+from sqlalchemy import create_engine, inspect, text+from sqlalchemy.exc import IntegrityError+from alembic import command+import pytest++from local_deep_research.database.alembic_runner import (+ get_alembic_config,+ get_head_revision,+ get_migrations_dir,+ stamp_database,+)+from local_deep_research.database.models.library import RAGIndex+++_TABLE = "rag_indices"+_CONSTRAINT = "uix_collection_model"+++def _create_rag_indices(engine, *, includes_constraint: bool) -> None:+ constraint = (+ ", CONSTRAINT uix_collection_model UNIQUE "+ "(collection_name, embedding_model, embedding_model_type)"+ if includes_constraint+ else ""+ )+ with engine.begin() as connection:+ connection.execute(+ text(+ "CREATE TABLE rag_indices ("+ "id INTEGER PRIMARY KEY, "+ "collection_name VARCHAR NOT NULL, "+ "embedding_model VARCHAR NOT NULL, "+ "embedding_model_type VARCHAR NOT NULL, "+ "index_hash VARCHAR NOT NULL UNIQUE, "+ "chunk_size INTEGER NOT NULL"+ f"{constraint}"+ ")"+ )+ )+++def _upgrade(engine) -> None:+ config = get_alembic_config(engine)+ with engine.begin() as connection:+ config.attributes["connection"] = connection+ command.upgrade(config, "0028")+++def _downgrade(engine) -> None:+ config = get_alembic_config(engine)+ with engine.begin() as connection:+ config.attributes["connection"] = connection+ command.downgrade(config, "0027")+++def _constraint_names(engine) -> set[str]:+ return {+ constraint["name"]+ for constraint in inspect(engine).get_unique_constraints(_TABLE)+ if constraint["name"]+ }+++def _insert_index(connection, *, index_hash: str, chunk_size: int) -> None:+ connection.execute(+ text(+ "INSERT INTO rag_indices "+ "(collection_name, embedding_model, embedding_model_type, index_hash, "+ "chunk_size) VALUES "+ "('collection-1', 'model', 'sentence_transformers', :index_hash, "+ ":chunk_size)"+ ),+ {"index_hash": index_hash, "chunk_size": chunk_size},+ )+++def _current_revision(engine) -> str:+ with engine.connect() as connection:+ return connection.execute(+ text("SELECT version_num FROM alembic_version")+ ).scalar_one()+++def legacy_engine(tmp_path):+ engine = create_engine(f"sqlite:///{tmp_path / 'rag_identity.db'}")+ _create_rag_indices(engine, includes_constraint=True)+ stamp_database(engine, "0027")+ yield engine+ engine.dispose()+++def test_0028_is_head_and_chains_to_0027():+ from alembic.config import Config+ from alembic.script import ScriptDirectory++ config = Config()+ config.set_main_option("script_location", str(get_migrations_dir()))+ script = ScriptDirectory.from_config(config)++ assert get_head_revision() == "0028"+ assert script.get_revision("0028").down_revision == "0027"+++def test_upgrade_drops_legacy_constraint_and_preserves_rows(legacy_engine):+ # Given+ with legacy_engine.begin() as connection:+ _insert_index(connection, index_hash="before-upgrade", chunk_size=100)++ # When+ _upgrade(legacy_engine)++ # Then+ assert _CONSTRAINT not in _constraint_names(legacy_engine)+ with legacy_engine.connect() as connection:+ assert (+ connection.execute(+ text("SELECT COUNT(*) FROM rag_indices")+ ).scalar_one()+ == 1+ )+++def test_upgrade_allows_distinct_full_configurations(legacy_engine):+ _upgrade(legacy_engine)++ # Given+ with legacy_engine.begin() as connection:+ _insert_index(connection, index_hash="chunk-100", chunk_size=100)++ # When+ _insert_index(connection, index_hash="chunk-200", chunk_size=200)++ # Then+ with legacy_engine.connect() as connection:+ assert (+ connection.execute(+ text("SELECT COUNT(*) FROM rag_indices")+ ).scalar_one()+ == 2+ )+++def test_upgrade_is_idempotent_when_constraint_is_already_absent(legacy_engine):+ # Given+ _upgrade(legacy_engine)++ # When+ _upgrade(legacy_engine)++ # Then+ assert _CONSTRAINT not in _constraint_names(legacy_engine)+++def test_upgrade_skips_missing_rag_indices_table(tmp_path):+ engine = create_engine(f"sqlite:///{tmp_path / 'missing_rag_indices.db'}")+ try:+ stamp_database(engine, "0027")++ # When+ _upgrade(engine)++ # Then+ assert not inspect(engine).has_table(_TABLE)+ assert _current_revision(engine) == "0028"+ finally:+ engine.dispose()+++def test_upgrade_skips_table_without_legacy_constraint(tmp_path):+ engine = create_engine(f"sqlite:///{tmp_path / 'no_legacy_constraint.db'}")+ try:+ _create_rag_indices(engine, includes_constraint=False)+ stamp_database(engine, "0027")++ # When+ _upgrade(engine)++ # Then+ assert _CONSTRAINT not in _constraint_names(engine)+ assert _current_revision(engine) == "0028"+ finally:+ engine.dispose()+++def test_downgrade_recreates_constraint_when_data_is_lossless(legacy_engine):+ _upgrade(legacy_engine)+ with legacy_engine.begin() as connection:+ _insert_index(connection, index_hash="only-config", chunk_size=100)++ # When+ _downgrade(legacy_engine)++ # Then+ assert _CONSTRAINT in _constraint_names(legacy_engine)+ assert _current_revision(legacy_engine) == "0027"+ with pytest.raises(IntegrityError):+ with legacy_engine.begin() as connection:+ _insert_index(connection, index_hash="duplicate", chunk_size=200)+++def test_downgrade_refuses_to_drop_full_configuration_rows(legacy_engine):+ _upgrade(legacy_engine)+ with legacy_engine.begin() as connection:+ _insert_index(connection, index_hash="config-one", chunk_size=100)+ _insert_index(connection, index_hash="config-two", chunk_size=200)++ # When / Then+ with pytest.raises(RuntimeError, match="Cannot downgrade past 0028"):+ _downgrade(legacy_engine)++ assert _current_revision(legacy_engine) == "0028"+ with legacy_engine.connect() as connection:+ assert (+ connection.execute(+ text("SELECT COUNT(*) FROM rag_indices")+ ).scalar_one()+ == 2+ )+++def test_model_metadata_does_not_restore_legacy_constraint(tmp_path):+ engine = create_engine(f"sqlite:///{tmp_path / 'model_metadata.db'}")+ try:+ RAGIndex.__table__.create(engine)+ assert _CONSTRAINT not in _constraint_names(engine)+ finally:+ engine.dispose()diff --git a/tests/js/components/research.test.js b/tests/js/components/research.test.jsindex 83e6a8984a..909194d239 100644--- a/tests/js/components/research.test.js+++ b/tests/js/components/research.test.js@@ -36,6 +36,17 @@ function buildForm() {<div id="research-alert" role="alert" style="display:none"></div><div id="research-error-alert" class="ldr-settings-error-container" style="display:none"></div><textarea id="query" name="query"></textarea>+ <div class="ldr-privacy-panel" data-scope="adaptive">+ <i id="ldr-privacy-panel-icon"></i>+ <select id="policy_egress_scope" name="policy_egress_scope">+ <option value="adaptive" selected>Adaptive</option>+ <option value="public_only">Public only</option>+ <option value="private_only">Private only</option>+ <option value="strict">Primary only</option>+ </select>+ <input type="checkbox" id="llm_require_local_endpoint">+ <input type="checkbox" id="embeddings_require_local">+ </div><label class="ldr-mode-option"><input type="radio" name="research_mode" value="quick" checked></label><label class="ldr-mode-option"><input type="radio" name="research_mode" value="detailed"></label>@@ -61,11 +72,6 @@ function buildForm() {<input id="iterations" value="2"><input id="questions_per_iteration" value="3">- <select id="policy_egress_scope" name="policy_egress_scope">- <option value="adaptive" selected>Adaptive (default)</option>- <option value="public_only">Public only</option>- <option value="private_only">Private only</option>- </select></div><button type="submit" id="start-research-btn"><span></span></button>@@ -124,6 +130,21 @@ beforeAll(async () => {beforeEach(() => {fetchMock.mockClear();+ const policyScope = document.getElementById("policy_egress_scope");+ policyScope.value = "adaptive";+ policyScope.disabled = false;+ policyScope.dataset.savedValue = "adaptive";+ ["llm_require_local_endpoint", "embeddings_require_local"].forEach((id) => {+ const control = document.getElementById(id);+ control.checked = false;+ control.disabled = false;+ control.title = "";+ delete control.dataset.envLocked;+ delete control.dataset.envValue;+ delete control.dataset.envTitle;+ delete control.dataset.userChecked;+ delete control.dataset.userCheckedSaved;+ });// A non-empty query so the query guard (which runs first) always passes and// the model guard is the thing under test. Individual tests override this.document.getElementById('query').value = 'What is quantum computing?';@@ -153,6 +174,26 @@ function callsTo(url) {return fetchMock.mock.calls.filter(([u]) => u === url);}+describe('research form fixture fidelity', () => {+ it('keeps one production egress-scope control in the privacy panel', () => {+ const policyScopes = document.querySelectorAll('#policy_egress_scope');++ expect(policyScopes).toHaveLength(1);++ const policyScope = document.querySelector(+ '.ldr-privacy-panel #policy_egress_scope'+ );+ expect(policyScope.name).toBe('policy_egress_scope');+ expect(policyScope.closest('#advanced-options-panel')).toBeNull();+ expect(Array.from(policyScope.options, ({ value }) => value)).toEqual([+ 'adaptive',+ 'public_only',+ 'private_only',+ 'strict',+ ]);+ });+});+describe('research form — model-required guard', () => {it('blocks submission, shows an inline error, and focuses the model field when no model is selected', () => {document.getElementById('model_hidden').value = '';@@ -561,6 +602,124 @@ describe('research form — model list loading', () => {});});+describe("research form — egress lock truthfulness", () => {+ it("omits disabled operator-controlled fields from the run payload", () => {+ document.getElementById("model_hidden").value = "qwen3:4b";+ document.getElementById("policy_egress_scope").disabled = true;+ document.getElementById("llm_require_local_endpoint").disabled = true;+ document.getElementById("embeddings_require_local").disabled = true;++ submitForm();++ const body = JSON.parse(callsTo(START_RESEARCH)[0][1].body);+ expect(body).not.toHaveProperty("policy_egress_scope");+ expect(body).not.toHaveProperty("llm_require_local_endpoint");+ expect(body).not.toHaveProperty("embeddings_require_local");+ });++ it("includes explicit false locality values when controls are editable", () => {+ document.getElementById("model_hidden").value = "qwen3:4b";++ submitForm();++ const body = JSON.parse(callsTo(START_RESEARCH)[0][1].body);+ expect(body.policy_egress_scope).toBe("adaptive");+ expect(body.llm_require_local_endpoint).toBe(false);+ expect(body.embeddings_require_local).toBe(false);+ });++ it("restores an environment lock after leaving Private only", () => {+ const scope = document.getElementById("policy_egress_scope");+ const llm = document.getElementById("llm_require_local_endpoint");+ llm.dataset.envLocked = "true";+ llm.dataset.envValue = "false";+ llm.dataset.envTitle = "operator lock";+ llm.checked = false;+ llm.disabled = true;++ scope.value = "private_only";+ scope.dispatchEvent(new Event("change"));+ expect(llm.checked).toBe(true);+ expect(llm.disabled).toBe(true);++ scope.value = "adaptive";+ scope.dispatchEvent(new Event("change"));+ expect(llm.checked).toBe(false);+ expect(llm.disabled).toBe(true);+ expect(llm.title).toBe("operator lock");+ });++ it("refreshes rejected scope changes from effective server metadata", async () => {+ const scope = document.getElementById("policy_egress_scope");+ fetchMock+ .mockImplementationOnce(() => Promise.resolve({+ ok: false,+ status: 400,+ json: () => Promise.resolve({ error: "operator rejected" }),+ }))+ .mockImplementationOnce(() => Promise.resolve({+ ok: true,+ status: 200,+ json: () => Promise.resolve({+ value: "adaptive",+ editable: true,+ }),+ }));++ scope.value = "private_only";+ scope.dispatchEvent(new Event("change"));++ await vi.waitFor(() => {+ expect(scope.value).toBe("adaptive");+ expect(scope.disabled).toBe(false);+ });+ expect(scope.dataset.savedValue).toBe("adaptive");+ expect(document.querySelector(".ldr-privacy-panel").dataset.scope).toBe("adaptive");+ expect(document.body.dataset.scope).toBe("adaptive");+ });++ it("serializes rapid scope saves in selection order", async () => {+ const scope = document.getElementById("policy_egress_scope");+ let resolveFirst;+ const successfulResponse = () => ({+ ok: true,+ status: 200,+ json: () => Promise.resolve({}),+ });+ fetchMock+ .mockImplementationOnce(() => new Promise(resolve => {+ resolveFirst = resolve;+ }))+ .mockImplementationOnce(() => Promise.resolve(successfulResponse()));++ scope.value = "private_only";+ scope.dispatchEvent(new Event("change"));+ scope.value = "adaptive";+ scope.dispatchEvent(new Event("change"));++ await vi.waitFor(() => {+ const writes = fetchMock.mock.calls.filter(+ ([url, options]) =>+ url === "/settings/api/policy.egress_scope" &&+ options?.method === "PUT"+ );+ expect(writes).toHaveLength(1);+ });++ resolveFirst(successfulResponse());+ await vi.waitFor(() => {+ const writes = fetchMock.mock.calls.filter(+ ([url, options]) =>+ url === "/settings/api/policy.egress_scope" &&+ options?.method === "PUT"+ );+ expect(writes).toHaveLength(2);+ expect(JSON.parse(writes[0][1].body).value).toBe("private_only");+ expect(JSON.parse(writes[1][1].body).value).toBe("adaptive");+ });+ });+});+describe('research form — submit-owned alert clearing (generic + egress errors)', () => {// Regression: clearEgressError() used to remove only alerts tagged as// egress errors (`data-egress-alert="true"`). Generic submissiondiff --git a/tests/mcp/test_classify_error_contract.py b/tests/mcp/test_classify_error_contract.pynew file mode 100644index 0000000000..45cc09ba95--- /dev/null+++ b/tests/mcp/test_classify_error_contract.py@@ -0,0 +1,60 @@+"""Direct contract test for ``_classify_error`` -- runs without MCP.++``_classify_error`` is a pure substring classifier with no runtime+dependency on the optional ``mcp`` package. The public-tool tests in+``test_policy_denied.py`` / ``test_validation.py`` import the full+``mcp/server.py`` module (which imports ``mcp.server.fastmcp`` at module+level) and are therefore gated behind ``MCP_AVAILABLE``. This file stubs+the optional MCP import so the classifier contract can be verified in any+environment -- in particular, pinning that the non-policy test input+``"connection refused"`` maps to ``connection_error`` and not ``unknown``.++The stub only satisfies the module-level import-time reference to+``FastMCP``; the classifier function itself never touches it.+"""++import sys+from collections.abc import Callable+from unittest.mock import MagicMock++import pytest+from _pytest.fixtures import SubRequest+++def classify_error(request: SubRequest) -> Callable[[str], str]:+ """Load ``_classify_error`` without requiring the real MCP package.++ Stubs ``mcp``, ``mcp.server``, and ``mcp.server.fastmcp`` in+ ``sys.modules`` for the duration of the test, then imports (or re-uses)+ the classifier from ``mcp/server.py``. Stubs are removed in teardown so+ other tests' ``try: import mcp`` detection is unaffected.+ """+ stubs: dict[str, MagicMock] = {}+ for mod in ("mcp", "mcp.server", "mcp.server.fastmcp"):+ if mod not in sys.modules:+ stubs[mod] = MagicMock()+ sys.modules[mod] = stubs[mod]+ try:+ from local_deep_research.mcp.server import _classify_error++ yield _classify_error+ finally:+ for mod in stubs:+ sys.modules.pop(mod, None)+++def test_classify_connection_refused(classify_error):+ """'connection refused' maps to connection_error via the classifier's+ ``"connection" in error_lower`` branch. This pins the input used by+ ``test_non_policy_exception_keeps_existing_classification`` so it does+ not silently fall through to 'unknown'."""+ assert classify_error("connection refused") == "connection_error"+++def test_classify_network_unreachable_is_unknown(classify_error):+ """Negative control: 'network unreachable' does NOT contain the+ classifier's 'connection' substring and therefore maps to 'unknown'.+ This is the latent bug in the original test input -- the classifier+ behaviour is intentional (substring-based), the test input was wrong."""+ assert classify_error("network unreachable") == "unknown"diff --git a/tests/mcp/test_policy_denied.py b/tests/mcp/test_policy_denied.pynew file mode 100644index 0000000000..e7c4393366--- /dev/null+++ b/tests/mcp/test_policy_denied.py@@ -0,0 +1,247 @@+"""Tests for PolicyDeniedError handling in the public MCP tools.++The egress policy PEPs (search-system factory, BaseSearchEngine self-check,+audit-hook net) raise ``PolicyDeniedError`` when a search/research operation+is hard-stopped by the user's declared egress scope. The public MCP tools+must:++* convert that denial into a structured, machine-readable response with the+ stable ``error_type=policy_denied`` and the PDP's short reason code;+* never leak the ``target`` attribute (engine names / URLs may carry user+ content or internal hostnames) or the exception chain;+* preserve fail-closed behaviour -- the underlying engine ``run()`` does NOT+ fire when policy denies;+* preserve resource cleanup (settings context, engine handles) when a denial+ fires mid-run;+* leave non-policy failures on their existing classification path.++The factory PEP is the primary enforcement point (see+``web_search_engines/search_engine_factory.py``); these tests verify the MCP+boundary converts its denials correctly.+"""++from unittest.mock import MagicMock, patch++import pytest++from local_deep_research.security.egress.policy import (+ Decision,+ PolicyDeniedError,+)++# MCP is an optional dependency. Skip the full module when it is absent so+# the suite still collects in minimal environments; the import-only checks+# below still run unconditionally to catch syntax/import regressions.+try:+ import mcp # noqa: F401++ MCP_AVAILABLE = True+except ImportError:+ MCP_AVAILABLE = False++pytestmark = pytest.mark.skipif(+ not MCP_AVAILABLE, reason="MCP package not installed"+)+++def _denied(+ reason: str = "scope_mismatch_private_only",+ target: str = "wikipedia",+) -> PolicyDeniedError:+ """Build a denial carrying a sensitive target the response must NOT leak."""+ return PolicyDeniedError(Decision(False, reason), target=target)+++# -----------------------------------------------------------------------------+# Research tools (quick / detailed / report / documents)+# These all delegate to an ``ldr_*`` function which internally instantiates+# engines through the factory PEP. Patching the ``ldr_*`` boundary exercises+# the public tool's exception handler without depending on the factory's+# runtime environment.+# -----------------------------------------------------------------------------+++def test_quick_research_policy_denied():+ """quick_research surfaces PolicyDeniedError as error_type=policy_denied."""+ from local_deep_research.mcp.server import quick_research++ with patch(+ "local_deep_research.mcp.server.ldr_quick_summary",+ side_effect=_denied(),+ ) as mock_call:+ result = quick_research(query="test query")++ mock_call.assert_called_once()+ assert result["status"] == "error"+ assert result["error_type"] == "policy_denied"+ assert result["reason"] == "scope_mismatch_private_only"+ # The sensitive target must NOT appear anywhere in the client response.+ assert "wikipedia" not in str(result)+++def test_detailed_research_policy_denied():+ from local_deep_research.mcp.server import detailed_research++ with patch(+ "local_deep_research.mcp.server.ldr_detailed_research",+ side_effect=_denied(+ reason="unprotected_egress_disabled",+ target="https://internal.example.com/search?q=secret",+ ),+ ) as mock_call:+ result = detailed_research(query="test query")++ mock_call.assert_called_once()+ assert result["status"] == "error"+ assert result["error_type"] == "policy_denied"+ assert result["reason"] == "unprotected_egress_disabled"+ # Neither the URL target nor its query content may leak.+ assert "internal.example.com" not in str(result)+ assert "secret" not in str(result)+++def test_generate_report_policy_denied():+ from local_deep_research.mcp.server import generate_report++ with patch(+ "local_deep_research.mcp.server.ldr_generate_report",+ side_effect=_denied(),+ ) as mock_call:+ result = generate_report(query="test query")++ mock_call.assert_called_once()+ assert result["status"] == "error"+ assert result["error_type"] == "policy_denied"+ assert result["reason"] == "scope_mismatch_private_only"+++def test_analyze_documents_policy_denied():+ from local_deep_research.mcp.server import analyze_documents++ with patch(+ "local_deep_research.mcp.server.ldr_analyze_documents",+ side_effect=_denied(target="collection_secret"),+ ) as mock_call:+ result = analyze_documents(query="test", collection_name="mycoll")++ mock_call.assert_called_once()+ assert result["status"] == "error"+ assert result["error_type"] == "policy_denied"+ assert "collection_secret" not in str(result)+++# -----------------------------------------------------------------------------+# search() -- the direct-search path. It calls the factory PEP directly via+# _execute_search, then arms the audit-hook net around engine.run(). These+# tests verify both denial points preserve fail-closed + cleanup.+# -----------------------------------------------------------------------------+++def test_search_policy_denied_no_engine_run():+ """When the factory PEP denies engine creation, the public search tool+ returns a structured policy_denied response and the engine's run() is+ never invoked -- fail-closed is preserved at the MCP boundary."""+ from local_deep_research.mcp.server import search++ with (+ patch(+ "local_deep_research.mcp.server.create_settings_snapshot",+ return_value={"search.tool": {"value": "wikipedia"}},+ ),+ patch(+ "local_deep_research.web_search_engines.search_engines_config.search_config",+ return_value={"wikipedia": {"requires_api_key": False}},+ ),+ patch(+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine",+ side_effect=_denied(target="wikipedia"),+ ) as mock_factory,+ patch(+ "local_deep_research.mcp.server._egress_audit_net",+ ) as mock_net,+ ):+ result = search(query="test query", engine="wikipedia")++ # The factory PEP was reached and denied.+ mock_factory.assert_called_once()+ # The audit-hook net is armed inside _execute_search immediately before+ # engine.run(); since the factory denied, _execute_search never got that+ # far -- proving no engine run occurred.+ mock_net.assert_not_called()+ # Structured, leak-safe response.+ assert result["status"] == "error"+ assert result["error_type"] == "policy_denied"+ assert result["reason"] == "scope_mismatch_private_only"+ assert "wikipedia" not in str(result)+++def test_search_policy_denied_mid_run_preserves_cleanup():+ """When PolicyDeniedError fires from engine.run() (e.g. the+ BaseSearchEngine self-check denies), resource cleanup still runs and the+ public tool surfaces a structured policy_denied response."""+ from local_deep_research.mcp.server import search++ fake_engine = MagicMock()+ fake_engine.run.side_effect = _denied(target="wikipedia")++ close_calls: list = []++ def track_close(engine, label=""):+ close_calls.append((engine, label))++ with (+ patch(+ "local_deep_research.mcp.server.create_settings_snapshot",+ return_value={"search.tool": {"value": "wikipedia"}},+ ),+ patch(+ "local_deep_research.web_search_engines.search_engines_config.search_config",+ return_value={"wikipedia": {"requires_api_key": False}},+ ),+ patch(+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine",+ return_value=fake_engine,+ ),+ patch(+ "local_deep_research.utilities.resource_utils.safe_close",+ side_effect=track_close,+ ),+ patch(+ "local_deep_research.mcp.server._egress_audit_net",+ ),+ ):+ result = search(query="test query", engine="wikipedia")++ assert result["status"] == "error"+ assert result["error_type"] == "policy_denied"+ assert result["reason"] == "scope_mismatch_private_only"+ # Cleanup preserved: safe_close ran even though policy denied mid-run.+ assert len(close_calls) == 1+ assert close_calls[0][0] is fake_engine+++# -----------------------------------------------------------------------------+# Non-policy failures must keep their existing classification -- the new+# PolicyDeniedError branch must not swallow them.+# -----------------------------------------------------------------------------+++def test_non_policy_exception_keeps_existing_classification():+ """A connection failure is still classified as connection_error -- the+ new PolicyDeniedError handler does not broaden to non-policy failures.++ The input 'connection refused' is pinned by+ test_classify_error_contract.test_classify_connection_refused, which+ verifies the classifier mapping directly (without MCP) so this+ assertion is not built on a message that silently maps to 'unknown'.+ """+ from local_deep_research.mcp.server import quick_research++ with patch(+ "local_deep_research.mcp.server.ldr_quick_summary",+ side_effect=ConnectionError("connection refused"),+ ):+ result = quick_research(query="test query")++ assert result["status"] == "error"+ assert result["error_type"] == "connection_error"diff --git a/tests/news/subscription_manager/test_scheduler_coverage.py b/tests/news/subscription_manager/test_scheduler_coverage.pyindex 8600192bc7..755587b426 100644--- a/tests/news/subscription_manager/test_scheduler_coverage.py+++ b/tests/news/subscription_manager/test_scheduler_coverage.py@@ -60,6 +60,16 @@ DATE_STRING = "local_deep_research.news.core.utils.get_local_date_string"SCHED_MOD = "local_deep_research.scheduler.background"+def _settings_mgr_mock():+ """SettingsManager mock whose strict snapshot satisfies the scheduler's+ fail-closed egress backstop, which now aborts processing unless+ get_settings_snapshot returns a real dict with a resolvable primary+ engine."""+ mgr = MagicMock()+ mgr.get_settings_snapshot.return_value = {"search.tool": "searxng"}+ return mgr++# ---------------------------------------------------------------------------# Fixtures# ---------------------------------------------------------------------------@@ -568,7 +578,7 @@ class TestProcessUserDocumentsFull:return_value=self._dss(download_pdfs=True),),patch(DB_SESSION, return_value=mock_db),- patch(SETTINGS_MGR, return_value=MagicMock()),+ patch(SETTINGS_MGR, return_value=_settings_mgr_mock()),):sched._process_user_documents("u")@@ -589,7 +599,7 @@ class TestProcessUserDocumentsFull:return_value=self._dss(download_pdfs=True),),patch(DB_SESSION, return_value=mock_db),- patch(SETTINGS_MGR, return_value=MagicMock()),+ patch(SETTINGS_MGR, return_value=_settings_mgr_mock()),patch(DOWNLOAD_SVC, return_value=mock_ds),):sched._process_user_documents("u")@@ -608,7 +618,7 @@ class TestProcessUserDocumentsFull:return_value=self._dss(download_pdfs=True),),patch(DB_SESSION, return_value=mock_db),- patch(SETTINGS_MGR, return_value=MagicMock()),+ patch(SETTINGS_MGR, return_value=_settings_mgr_mock()),patch(DOWNLOAD_SVC, side_effect=RuntimeError("fail")),):sched._process_user_documents("u")@@ -650,7 +660,7 @@ class TestProcessUserDocumentsFull:return_value=self._dss(extract_text=True),),patch(DB_SESSION, return_value=mock_db),- patch(SETTINGS_MGR, return_value=MagicMock()),+ patch(SETTINGS_MGR, return_value=_settings_mgr_mock()),patch(DOWNLOAD_SVC, return_value=mock_ds),patch(IS_DOWNLOADABLE, return_value=True),):@@ -686,7 +696,7 @@ class TestProcessUserDocumentsFull:return_value=self._dss(extract_text=True),),patch(DB_SESSION, return_value=mock_db),- patch(SETTINGS_MGR, return_value=MagicMock()),+ patch(SETTINGS_MGR, return_value=_settings_mgr_mock()),patch(DOWNLOAD_SVC, return_value=mock_ds),patch(IS_DOWNLOADABLE, return_value=True),):@@ -705,7 +715,7 @@ class TestProcessUserDocumentsFull:return_value=self._dss(extract_text=True),),patch(DB_SESSION, return_value=mock_db),- patch(SETTINGS_MGR, return_value=MagicMock()),+ patch(SETTINGS_MGR, return_value=_settings_mgr_mock()),patch(DOWNLOAD_SVC, side_effect=RuntimeError("import fail")),):sched._process_user_documents("u")@@ -726,7 +736,7 @@ class TestProcessUserDocumentsFull:return_value=self._dss(generate_rag=True),),patch(DB_SESSION, return_value=mock_db) as mock_session,- patch(SETTINGS_MGR, return_value=MagicMock()),+ patch(SETTINGS_MGR, return_value=_settings_mgr_mock()),):sched._process_user_documents("u")@@ -749,7 +759,7 @@ class TestProcessUserDocumentsFull:return_value=self._dss(download_pdfs=True),),patch(DB_SESSION, return_value=mock_db),- patch(SETTINGS_MGR, return_value=MagicMock()),+ patch(SETTINGS_MGR, return_value=_settings_mgr_mock()),patch(DOWNLOAD_SVC, return_value=mock_ds),):sched._process_user_documents("u")@@ -771,7 +781,7 @@ class TestProcessUserDocumentsFull:return_value=self._dss(download_pdfs=True),),patch(DB_SESSION, return_value=mock_db),- patch(SETTINGS_MGR, return_value=MagicMock()),+ patch(SETTINGS_MGR, return_value=_settings_mgr_mock()),patch(DOWNLOAD_SVC, return_value=mock_ds),):sched._process_user_documents("u")@@ -790,7 +800,7 @@ class TestProcessUserDocumentsFull:),),patch(DB_SESSION, return_value=mock_db),- patch(SETTINGS_MGR, return_value=MagicMock()),+ patch(SETTINGS_MGR, return_value=_settings_mgr_mock()),):sched._process_user_documents("u")@@ -821,7 +831,7 @@ class TestProcessUserDocumentsFull:return_value=self._dss(download_pdfs=True),),patch(DB_SESSION, return_value=mock_db),- patch(SETTINGS_MGR, return_value=MagicMock()),+ patch(SETTINGS_MGR, return_value=_settings_mgr_mock()),patch(DOWNLOAD_SVC, return_value=mock_ds),):sched._process_user_documents("u")@@ -839,7 +849,7 @@ class TestProcessUserDocumentsFull:return_value=self._dss(download_pdfs=True),),patch(DB_SESSION, return_value=mock_db),- patch(SETTINGS_MGR, return_value=MagicMock()),+ patch(SETTINGS_MGR, return_value=_settings_mgr_mock()),patch(DOWNLOAD_SVC, side_effect=RuntimeError("fail")),):sched._process_user_documents("u")diff --git a/tests/news/test_library_sweep.py b/tests/news/test_library_sweep.pyindex 716816b2ad..0c21b5b62c 100644--- a/tests/news/test_library_sweep.py+++ b/tests/news/test_library_sweep.py@@ -163,7 +163,7 @@ def _patched_session(db):patch.object(BackgroundJobScheduler,"_arm_egress_backstop",- lambda *a, **kw: None,+ lambda *a, **kw: True,),patch(DEFAULT_LIB, return_value="default-lib"),):@@ -1350,6 +1350,7 @@ def test_reconciler_arms_egress_backstop_in_body():BackgroundJobScheduler,"_arm_egress_backstop",autospec=True,+ return_value=True,) as arm_spy,patch(DEFAULT_LIB, return_value="default-lib"),patch(FACTORY) as mock_factory,diff --git a/tests/news/test_scheduler.py b/tests/news/test_scheduler.pyindex 68240d4b7a..98416350e9 100644--- a/tests/news/test_scheduler.py+++ b/tests/news/test_scheduler.py@@ -508,6 +508,36 @@ class TestProcessUserDocuments:instance = BackgroundJobScheduler()yield instance+ from local_deep_research.config.thread_settings import (+ clear_settings_context,+ )+ from local_deep_research.database.session_context import (+ get_user_db_session,+ )+ from local_deep_research.database.thread_local_session import (+ cleanup_current_thread,+ )+ from local_deep_research.research_library.zotero import sync_service+ from local_deep_research.security.egress.audit_hook import (+ clear_active_context,+ )+ from local_deep_research.settings.manager import SettingsManager+ from local_deep_research.utilities.thread_context import (+ clear_search_context,+ )++ for username in tuple(instance.user_sessions):+ instance._credential_store.clear(username)+ instance.user_sessions.clear()+ instance.scheduler.reset_mock()+ cleanup_current_thread()+ clear_settings_context()+ clear_search_context()+ clear_active_context()+ sync_service.SettingsManager = SettingsManager+ sync_service.get_user_db_session = get_user_db_session+ BackgroundJobScheduler._instance = None+def test_process_user_documents_batch_processing(self, scheduler):"""_process_user_documents processes in batches."""# Verify batch size config exists@@ -518,6 +548,208 @@ class TestProcessUserDocuments:assert "max_concurrent_jobs" in scheduler.configassert scheduler.config["max_concurrent_jobs"] == 10+ @pytest.mark.parametrize(+ "snapshot_failure",+ [RuntimeError("snapshot unavailable"), []],+ ids=["exception", "invalid_snapshot"],+ )+ def test_process_user_documents_stops_when_snapshot_build_fails(+ self, scheduler, snapshot_failure+ ):+ from local_deep_research.scheduler.background import (+ DocumentSchedulerSettings,+ )++ settings_manager = MagicMock()+ settings_manager.get_settings_snapshot.side_effect = [+ {"policy.egress_scope": "adaptive", "search.tool": "library"},+ snapshot_failure,+ ]+ settings_manager.get_setting.return_value = "library"+ scheduler.user_sessions["alice"] = {"scheduled_jobs": set()}+ scheduler._credential_store.store("alice", "password")++ with (+ patch.object(+ scheduler,+ "_get_document_scheduler_settings",+ return_value=DocumentSchedulerSettings(+ download_pdfs=True,+ extract_text=True,+ ),+ ),+ patch(+ "local_deep_research.database.session_context.get_user_db_session"+ ) as db_session,+ patch(+ "local_deep_research.settings.manager.SettingsManager",+ return_value=settings_manager,+ ),+ patch(+ "local_deep_research.research_library.services.download_service.DownloadService"+ ) as download_service,+ ):+ db_session.return_value.__enter__.return_value = MagicMock()+ db_session.return_value.__exit__.return_value = False++ scheduler._process_user_documents("alice")++ download_service.assert_not_called()++ def test_process_user_documents_stops_when_policy_is_denied(+ self, scheduler+ ):+ from local_deep_research.scheduler.background import (+ DocumentSchedulerSettings,+ )+ from local_deep_research.security.egress.policy import (+ Decision,+ PolicyDeniedError,+ )++ settings_manager = MagicMock()+ settings_manager.get_settings_snapshot.return_value = {+ "policy.egress_scope": "adaptive",+ "search.tool": "library",+ }+ settings_manager.get_setting.return_value = "library"+ scheduler.user_sessions["alice"] = {"scheduled_jobs": set()}+ scheduler._credential_store.store("alice", "password")++ with (+ patch.object(+ scheduler,+ "_get_document_scheduler_settings",+ return_value=DocumentSchedulerSettings(+ download_pdfs=True,+ extract_text=True,+ ),+ ),+ patch(+ "local_deep_research.database.session_context.get_user_db_session"+ ) as db_session,+ patch(+ "local_deep_research.settings.manager.SettingsManager",+ return_value=settings_manager,+ ),+ patch(+ "local_deep_research.security.egress.policy.context_from_snapshot",+ side_effect=PolicyDeniedError(+ Decision(False, "scope_mismatch"), target="private"+ ),+ ),+ patch(+ "local_deep_research.research_library.services.download_service.DownloadService"+ ) as download_service,+ ):+ db_session.return_value.__enter__.return_value = MagicMock()+ db_session.return_value.__exit__.return_value = False++ scheduler._process_user_documents("alice")++ download_service.assert_not_called()+++class TestReconcilerPolicySetup:+ @pytest.fixture+ def scheduler(self):+ from local_deep_research.scheduler.background import (+ BackgroundJobScheduler,+ )++ BackgroundJobScheduler._instance = None+ with patch(+ "local_deep_research.scheduler.background.BackgroundScheduler"+ ) as mock_scheduler:+ mock_scheduler.return_value = MagicMock()+ instance = BackgroundJobScheduler()+ yield instance++ from local_deep_research.config.thread_settings import (+ clear_settings_context,+ )+ from local_deep_research.database.session_context import (+ get_user_db_session,+ )+ from local_deep_research.database.thread_local_session import (+ cleanup_current_thread,+ )+ from local_deep_research.research_library.zotero import sync_service+ from local_deep_research.security.egress.audit_hook import (+ clear_active_context,+ )+ from local_deep_research.settings.manager import SettingsManager+ from local_deep_research.utilities.thread_context import (+ clear_search_context,+ )++ for username in tuple(instance.user_sessions):+ instance._credential_store.clear(username)+ instance.user_sessions.clear()+ instance.scheduler.reset_mock()+ cleanup_current_thread()+ clear_settings_context()+ clear_search_context()+ clear_active_context()+ sync_service.SettingsManager = SettingsManager+ sync_service.get_user_db_session = get_user_db_session+ BackgroundJobScheduler._instance = None++ @pytest.mark.parametrize(+ "snapshot_failure",+ [RuntimeError("snapshot unavailable"), []],+ ids=["exception", "invalid_snapshot"],+ )+ def test_reconciler_stops_before_rag_when_snapshot_setup_fails(+ self, scheduler, snapshot_failure+ ):+ from local_deep_research.scheduler.background import (+ DocumentSchedulerSettings,+ )++ settings_manager = MagicMock()+ if isinstance(snapshot_failure, BaseException):+ settings_manager.get_settings_snapshot.side_effect = (+ snapshot_failure+ )+ else:+ settings_manager.get_settings_snapshot.return_value = (+ snapshot_failure+ )+ scheduler.user_sessions["alice"] = {"scheduled_jobs": set()}+ scheduler._credential_store.store("alice", "password")++ with (+ patch.object(+ scheduler,+ "_get_document_scheduler_settings",+ return_value=DocumentSchedulerSettings(+ enabled=True,+ generate_rag=True,+ ),+ ),+ patch(+ "local_deep_research.database.session_context.get_user_db_session"+ ) as db_session,+ patch(+ "local_deep_research.settings.manager.SettingsManager",+ return_value=settings_manager,+ ),+ patch(+ "local_deep_research.research_library.services.rag_service_factory.get_rag_service"+ ) as rag_service,+ patch(+ "local_deep_research.research_library.services.download_service.DownloadService"+ ) as download_service,+ ):+ db_session.return_value.__enter__.return_value = MagicMock()+ db_session.return_value.__exit__.return_value = False++ scheduler._reconcile_unindexed_documents("alice")++ rag_service.assert_not_called()+ download_service.assert_not_called()+class TestStoreResearchResult:"""Tests for _store_research_result method."""@@ -2455,3 +2687,34 @@ class TestSchedulerEgressBackstop:fake_sm.get_settings_snapshot.side_effect = RuntimeError("no db")# Must swallow the error (best-effort backstop).sched._arm_egress_backstop(fake_sm, "alice")++ def test_arm_egress_backstop_fails_closed_when_snapshot_lacks_primary(self):+ """V2-R1-2: the primary engine must be derived from the SAME strict+ snapshot rather than a second non-strict ``get_setting('search.tool',+ DEFAULT_SEARCH_TOOL)`` call. A snapshot that succeeds but lacks a usable+ ``search.tool`` must STOP scheduled work — the previous non-strict+ fallback would substitute the public ``DEFAULT_SEARCH_TOOL`` and+ silently widen an adaptive run's scope to PUBLIC_ONLY.+ """+ from local_deep_research.scheduler.background import (+ BackgroundJobScheduler,+ )++ sched = BackgroundJobScheduler()+ fake_sm = MagicMock()+ # Snapshot succeeds but carries no usable primary engine.+ fake_sm.get_settings_snapshot.return_value = {+ "policy.egress_scope": "adaptive",+ }+ # If the production code regresses to a non-strict get_setting+ # fallback, this is the value that would wrongly be used as the+ # primary — proving the regression would arm a context (return True).+ fake_sm.get_setting.return_value = "searxng"++ result = sched._arm_egress_backstop(fake_sm, "alice")+ assert result is False, (+ "snapshot without search.tool must fail-closed; a regressed "+ "non-strict get_setting fallback would have armed a context"+ )+ # And the non-strict read path must not even be consulted.+ fake_sm.get_setting.assert_not_called()diff --git a/tests/news/test_scheduler_credential_lifecycle.py b/tests/news/test_scheduler_credential_lifecycle.pyindex 6688f35e60..a5eeda6424 100644--- a/tests/news/test_scheduler_credential_lifecycle.py+++ b/tests/news/test_scheduler_credential_lifecycle.py@@ -385,6 +385,11 @@ class TestDocSchedulerCredentialLifecycle:),):mock_sm_cls.return_value.set_setting.side_effect = fake_set_setting+ # The egress backstop now aborts unless the strict snapshot is a+ # real dict with a resolvable primary engine.+ mock_sm_cls.return_value.get_settings_snapshot.return_value = {+ "search.tool": "searxng"+ }scheduler._process_user_documents("alice")assert "document_scheduler.last_run" in set_setting_calls, (@@ -422,7 +427,9 @@ class TestDocSchedulerCredentialLifecycle:research_id="r-123"),),- patch("local_deep_research.settings.manager.SettingsManager"),+ patch(+ "local_deep_research.settings.manager.SettingsManager"+ ) as mock_sm_cls,patch("local_deep_research.utilities.thread_context.set_search_context") as mock_set_ctx,@@ -432,6 +439,11 @@ class TestDocSchedulerCredentialLifecycle:"local_deep_research.research_library.services.download_service.DownloadService"),):+ # The egress backstop now aborts unless the strict snapshot is a+ # real dict with a resolvable primary engine.+ mock_sm_cls.return_value.get_settings_snapshot.return_value = {+ "search.tool": "searxng"+ }scheduler._process_user_documents("alice")assert mock_set_ctx.called, (diff --git a/tests/notifications/test_manager.py b/tests/notifications/test_manager.pyindex 398fe15072..f298c1f53a 100644--- a/tests/notifications/test_manager.py+++ b/tests/notifications/test_manager.py@@ -1055,15 +1055,26 @@ class TestEgressPolicyURLFilter:assert "slack://t" in outassert "http://127.0.0.1/h" not in out- def test_unprotected_scope_passes_all_urls(self):+ def test_unprotected_scope_passes_all_urls(self, monkeypatch):# 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).+ # the hard SSRF/metadata block still applies to metadata IPs). The+ # operator must explicitly enable this dangerous mode.+ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")mgr = self._mgr("unprotected")out = mgr._filter_urls_by_egress_policy("slack://t http://127.0.0.1/h")assert "slack://t" in outassert "http://127.0.0.1/h" in out+ def test_unprotected_scope_is_protective_when_gate_disabled(+ self, monkeypatch+ ):+ monkeypatch.delenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", raising=False)+ 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" not in out+def test_public_only_blocks_private_http_keeps_public(self):mgr = self._mgr("public_only", tool="searxng")out = mgr._filter_urls_by_egress_policy(diff --git a/tests/research_library/routes/_route_helpers_rag.py b/tests/research_library/routes/_route_helpers_rag.pyindex dcbb55afdc..be858f11d8 100644--- a/tests/research_library/routes/_route_helpers_rag.py+++ b/tests/research_library/routes/_route_helpers_rag.py@@ -153,7 +153,8 @@ def _make_settings_mock(overrides=None):defaults.get(k, d))mock_sm.get_all_settings.return_value = {}- mock_sm.set_setting = Mock()+ mock_sm.settings_locked = False+ mock_sm.set_setting = Mock(return_value=True)mock_sm.get_settings_snapshot.return_value = {}return mock_smdiff --git a/tests/research_library/routes/test_rag_configure_atomicity.py b/tests/research_library/routes/test_rag_configure_atomicity.pynew file mode 100644index 0000000000..fc2099f660--- /dev/null+++ b/tests/research_library/routes/test_rag_configure_atomicity.py@@ -0,0 +1,212 @@+# allow: no-sut-import -- exercises the /library/api/rag/configure route via the Flask test client through _auth_client; patches local_deep_research.research_library.routes.rag_routes symbols+from unittest.mock import MagicMock, patch++import pytest++from ._route_helpers_rag import _ROUTES, _auth_client, _create_app+++_REQUESTED_SETTING_KEYS = [+ "local_search_embedding_model",+ "local_search_embedding_provider",+ "local_search_chunk_size",+ "local_search_chunk_overlap",+ "local_search_splitter_type",+ "local_search_text_separators",+ "local_search_distance_metric",+ "local_search_normalize_vectors",+ "local_search_index_type",+]+++def app():+ return _create_app()+++def _configuration_payload(**overrides):+ payload = {+ "embedding_model": "test-model",+ "embedding_provider": "sentence_transformers",+ "chunk_size": 500,+ "chunk_overlap": 100,+ "collection_id": "collection-1",+ }+ payload.update(overrides)+ return payload+++def _rag_service(index_hash: str = "index-hash") -> MagicMock:+ service = MagicMock()+ service.__enter__.return_value = service+ service.__exit__.return_value = False+ service._get_or_create_rag_index.return_value.index_hash = index_hash+ return service+++class TestConfigureRagAtomicity:+ def test_commits_staged_settings_and_borrowed_index_once_on_success(+ self, app+ ):+ rag_service = _rag_service()++ with _auth_client(+ app,+ extra_patches=[+ patch(f"{_ROUTES}.LibraryRAGService", return_value=rag_service)+ ],+ ) as (client, context):+ # Given+ settings = context["settings"]+ db_session = settings.db_session++ def assert_committed(keys):+ assert db_session.commit.call_count == 1+ assert keys == _REQUESTED_SETTING_KEYS++ settings.emit_settings_changed_after_commit.side_effect = (+ assert_committed+ )++ # When+ response = client.post(+ "/library/api/rag/configure",+ json=_configuration_payload(),+ )++ # Then+ assert response.status_code == 200+ rag_service._get_or_create_rag_index.assert_called_once_with(+ "collection-1", db_session=db_session, commit=False+ )+ db_session.commit.assert_called_once_with()+ db_session.rollback.assert_not_called()+ settings.emit_settings_changed_after_commit.assert_called_once_with(+ _REQUESTED_SETTING_KEYS+ )++ def test_emits_once_after_default_settings_commit(self, app):+ with _auth_client(app) as (client, context):+ # Given+ settings = context["settings"]+ db_session = settings.db_session++ # When+ response = client.post(+ "/library/api/rag/configure",+ json=_configuration_payload(collection_id=None),+ )++ # Then+ assert response.status_code == 200+ db_session.commit.assert_called_once_with()+ settings.emit_settings_changed_after_commit.assert_called_once_with(+ _REQUESTED_SETTING_KEYS+ )++ def test_rolls_back_staged_settings_when_index_creation_fails(self, app):+ rag_service = _rag_service()+ rag_service._get_or_create_rag_index.side_effect = RuntimeError(+ "index creation failed"+ )++ with _auth_client(+ app,+ extra_patches=[+ patch(f"{_ROUTES}.LibraryRAGService", return_value=rag_service)+ ],+ ) as (client, context):+ # Given+ settings = context["settings"]+ db_session = settings.db_session++ # When+ response = client.post(+ "/library/api/rag/configure",+ json=_configuration_payload(),+ )++ # Then+ assert response.status_code == 500+ db_session.commit.assert_not_called()+ db_session.rollback.assert_called_once_with()+ settings.emit_settings_changed_after_commit.assert_not_called()++ def test_rolls_back_everything_when_terminal_commit_fails(self, app):+ rag_service = _rag_service()++ with _auth_client(+ app,+ extra_patches=[+ patch(f"{_ROUTES}.LibraryRAGService", return_value=rag_service)+ ],+ ) as (client, context):+ # Given+ settings = context["settings"]+ db_session = settings.db_session+ db_session.commit.side_effect = RuntimeError("commit failed")++ # When+ response = client.post(+ "/library/api/rag/configure",+ json=_configuration_payload(),+ )++ # Then+ assert response.status_code == 500+ rag_service._get_or_create_rag_index.assert_called_once_with(+ "collection-1", db_session=db_session, commit=False+ )+ db_session.commit.assert_called_once_with()+ db_session.rollback.assert_called_once_with()+ settings.emit_settings_changed_after_commit.assert_not_called()++ def test_emits_nothing_when_staged_setting_write_fails(self, app):+ rag_service = _rag_service()++ with _auth_client(+ app,+ extra_patches=[+ patch(f"{_ROUTES}.LibraryRAGService", return_value=rag_service)+ ],+ ) as (client, context):+ # Given+ settings = context["settings"]+ settings.set_setting.return_value = False++ # When+ response = client.post(+ "/library/api/rag/configure",+ json=_configuration_payload(),+ )++ # Then+ assert response.status_code == 500+ settings.emit_settings_changed_after_commit.assert_not_called()+ rag_service._get_or_create_rag_index.assert_not_called()++ @pytest.mark.parametrize(+ "text_separators",+ ["not valid json", '{"separator": "\\n"}', ["\\n", 2]],+ )+ def test_rejects_malformed_text_separators_at_request_boundary(+ self, app, text_separators+ ):+ with _auth_client(app) as (client, context):+ # Given+ db_session = context["settings"].db_session+ settings = context["settings"]++ # When+ response = client.post(+ "/library/api/rag/configure",+ json=_configuration_payload(+ collection_id=None, text_separators=text_separators+ ),+ )++ # Then+ assert response.status_code == 400+ settings.set_setting.assert_not_called()+ db_session.commit.assert_not_called()+ db_session.rollback.assert_not_called()diff --git a/tests/research_library/routes/test_rag_routes.py b/tests/research_library/routes/test_rag_routes.pyindex 4f88dd1b8b..bd0099626d 100644--- a/tests/research_library/routes/test_rag_routes.py+++ b/tests/research_library/routes/test_rag_routes.py@@ -83,12 +83,11 @@ class TestGetRagService:"""Create mock settings manager."""mock = Mock()mock.get_setting.side_effect = lambda key, default=None: {- # 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. "unprotected" disables egress- # protection for the run ("both" is retired per ADR-0007).- "policy.egress_scope": "unprotected",+ # These tests exercise settings plumbing with fake provider names.+ # STRICT limits search to the library primary without imposing the+ # locality requirement that ADAPTIVE would derive from that private+ # engine, and avoids enabling the unprotected escape hatch.+ "policy.egress_scope": "strict","local_search_embedding_model": "test-model","local_search_embedding_provider": "sentence_transformers","local_search_chunk_size": "1000",diff --git a/tests/research_library/routes/test_rag_routes_gaps_coverage.py b/tests/research_library/routes/test_rag_routes_gaps_coverage.pyindex 4aa9c69d70..99bec8e91e 100644--- a/tests/research_library/routes/test_rag_routes_gaps_coverage.py+++ b/tests/research_library/routes/test_rag_routes_gaps_coverage.py@@ -237,9 +237,163 @@ class TestConfigureRag:assert data["success"] is Trueassert data["index_hash"] == "abc123"+ def test_rejects_app_locked_settings_before_writes(self, app):+ service_constructor = MagicMock()+ service_constructor.return_value.__enter__.return_value._get_or_create_rag_index.return_value.index_hash = "abc123"++ with _auth_client(+ app,+ extra_patches=[+ patch(f"{_ROUTES}.LibraryRAGService", service_constructor)+ ],+ ) as (client, ctx):+ # Given+ settings = ctx["settings"]+ settings.settings_locked = True++ # When+ response = client.post(+ "/library/api/rag/configure",+ json={+ "embedding_model": "test-model",+ "embedding_provider": "sentence_transformers",+ "chunk_size": 500,+ "chunk_overlap": 100,+ "collection_id": "coll-1",+ },+ content_type="application/json",+ )++ # Then+ assert response.status_code == 403+ assert response.get_json()["success"] is False+ settings.set_setting.assert_not_called()+ settings.db_session.commit.assert_not_called()+ service_constructor.assert_not_called()++ def test_rejects_environment_locked_settings_before_writes(+ self, app, monkeypatch+ ):+ service_constructor = MagicMock()+ service_constructor.return_value.__enter__.return_value._get_or_create_rag_index.return_value.index_hash = "abc123"+ monkeypatch.setenv("LDR_LOCAL_SEARCH_EMBEDDING_MODEL", "operator-model")++ with _auth_client(+ app,+ extra_patches=[+ patch(f"{_ROUTES}.LibraryRAGService", service_constructor)+ ],+ ) as (client, ctx):+ # Given+ settings = ctx["settings"]++ # When+ response = client.post(+ "/library/api/rag/configure",+ json={+ "embedding_model": "test-model",+ "embedding_provider": "sentence_transformers",+ "chunk_size": 500,+ "chunk_overlap": 100,+ "collection_id": "coll-1",+ },+ content_type="application/json",+ )++ # Then+ assert response.status_code == 403+ response_data = response.get_json()+ assert response_data["success"] is False+ assert "environment-locked" in response_data["error"]+ settings.set_setting.assert_not_called()+ settings.db_session.commit.assert_not_called()+ service_constructor.assert_not_called()++ def test_rolls_back_when_a_staged_setting_write_fails(self, app):+ service_constructor = MagicMock()+ service_constructor.return_value.__enter__.return_value._get_or_create_rag_index.return_value.index_hash = "abc123"++ with _auth_client(+ app,+ extra_patches=[+ patch(f"{_ROUTES}.LibraryRAGService", service_constructor)+ ],+ ) as (client, ctx):+ # Given+ settings = ctx["settings"]+ settings.set_setting.side_effect = [True, True, False]++ # When+ response = client.post(+ "/library/api/rag/configure",+ json={+ "embedding_model": "test-model",+ "embedding_provider": "sentence_transformers",+ "chunk_size": 500,+ "chunk_overlap": 100,+ "collection_id": "coll-1",+ },+ content_type="application/json",+ )++ # Then+ assert response.status_code == 500+ assert response.get_json()["success"] is False+ assert settings.set_setting.call_count == 3+ assert all(+ call.kwargs["commit"] is False+ for call in settings.set_setting.call_args_list+ )+ settings.db_session.rollback.assert_called_once_with()+ settings.db_session.commit.assert_not_called()+ service_constructor.assert_not_called()++ def test_commits_once_after_constructing_collection_service(self, app):+ mock_rag = MagicMock()+ mock_rag.__enter__ = Mock(return_value=mock_rag)+ mock_rag.__exit__ = Mock(return_value=False)+ mock_rag._get_or_create_rag_index.return_value.index_hash = "abc123"++ with _auth_client(app) as (client, ctx):+ # Given+ settings = ctx["settings"]++ def construct_service(*args, **kwargs):+ assert settings.db_session.commit.call_count == 0+ return mock_rag++ service_constructor = Mock(side_effect=construct_service)++ # When+ with patch(f"{_ROUTES}.LibraryRAGService", service_constructor):+ response = client.post(+ "/library/api/rag/configure",+ json={+ "embedding_model": "test-model",+ "embedding_provider": "sentence_transformers",+ "chunk_size": 500,+ "chunk_overlap": 100,+ "collection_id": "coll-1",+ },+ content_type="application/json",+ )++ # Then+ assert response.status_code == 200+ assert response.get_json()["success"] is True+ assert all(+ call.kwargs["commit"] is False+ for call in settings.set_setting.call_args_list+ )+ settings.db_session.commit.assert_called_once_with()+ settings.db_session.rollback.assert_not_called()+ service_constructor.assert_called_once()+def test_exception_returns_500(self, app):"""Exception during configure returns error."""broken_sm = Mock()+ broken_sm.settings_locked = False+ broken_sm.db_session = Mock()broken_sm.set_setting.side_effect = RuntimeError("DB error")with _auth_client(app) as (client, ctx):diff --git a/tests/research_library/routes/test_rag_routes_strict_snapshot.py b/tests/research_library/routes/test_rag_routes_strict_snapshot.pynew file mode 100644index 0000000000..55dc466a42--- /dev/null+++ b/tests/research_library/routes/test_rag_routes_strict_snapshot.py@@ -0,0 +1,168 @@+"""Regression tests for V2-R1-3 strict-snapshot coverage at the+``/api/rag/models`` (``get_available_models``) route.++A non-strict ``get_all_settings`` silently falls back to JSON defaults+when the underlying settings query fails (SQLAlchemyError / stale enum+row). A defaults-only snapshot can lack the operator-selected scope and+provider classification inputs, and thereby admit a cloud embedder's+model-list probe under a local-only posture. The route must therefore+read settings with ``strict=True`` and convert any query failure into+``PolicyDeniedError("settings_unavailable")`` BEFORE any provider+discovery, credential read, or network probe.+"""++from unittest.mock import MagicMock, patch++import pytest+from sqlalchemy.exc import SQLAlchemyError++from local_deep_research.security.egress.policy import (+ Decision,+ PolicyDeniedError,+)+from local_deep_research.settings.manager import SettingsManager++from ._route_helpers_rag import _create_app+++def _settings_manager_with_query_failure(query_error):+ """Build a real ``SettingsManager`` whose settings-enumeration query+ raises.++ Mirrors the production read sequence: an initialization-count query+ (1) followed by the settings-enumeration query (2) which we fail.+ """+ database_session = MagicMock()+ initialization_query = MagicMock()+ initialization_query.count.return_value = 1+ settings_query = MagicMock()+ settings_query.all.side_effect = query_error+ database_session.query.side_effect = [initialization_query, settings_query]+ return SettingsManager(database_session), database_session+++def app():+ return _create_app()+++ "query_error",+ [+ SQLAlchemyError("connection lost"),+ LookupError("unknown setting type"),+ ],+ ids=["sqlalchemy_error", "stale_enum_row"],+)+def test_get_available_models_refuses_before_any_probe_when_settings_query_fails(+ app, query_error+):+ """``/api/rag/models`` must refuse with ``settings_unavailable`` BEFORE+ importing provider classes, reading credentials, or opening any+ network probe when the underlying settings query fails.++ Regression for V2-R1-3: a non-strict snapshot fell back to JSON+ defaults, then handed the permissive snapshot to provider discovery+ — opening the door to a cloud embedder probe the operator had not+ authorized.+ """+ manager, database_session = _settings_manager_with_query_failure(+ query_error+ )++ # Provider discovery surface — none of these may run when the+ # settings snapshot is unevaluable. We patch them at the source+ # modules so function-local imports inside the route are caught.+ extra_patches = [+ patch(+ "local_deep_research.embeddings.embeddings_config._get_provider_classes"+ ),+ patch("local_deep_research.security.egress.policy.evaluate_embeddings"),+ patch(+ "local_deep_research.security.egress.policy.context_from_snapshot"+ ),+ # Override the helper-injected mock_sm with a real failing+ # SettingsManager. Stacks after the base patch and overrides it.+ patch(+ "local_deep_research.research_library.routes.rag_routes.get_settings_manager",+ return_value=manager,+ ),+ # Override the helper-injected mock db session so the real+ # SettingsManager's queries land on our failing mock.+ patch(+ "local_deep_research.database.session_context.get_user_db_session",+ side_effect=lambda *a, **k: _ctx_yielding(database_session),+ ),+ ]++ from ._route_helpers_rag import _auth_client++ with _auth_client(app, extra_patches=extra_patches) as (client, _ctx):+ response = client.get("/library/api/rag/models")++ # Then: a 503 with no provider construction, no policy evaluation,+ # no network probe — the refusal happens at the snapshot gate.+ assert response.status_code == 503+ body = response.get_json()+ assert body["success"] is False+ assert "unavailable" in body["error"].lower()+ # The settings-enumeration query was issued once (proving strict=True+ # ran); no further DB reads occurred downstream.+ assert database_session.query.call_count == 2+++def test_get_available_models_400_for_non_settings_policy_denial(app):+ """A non-``settings_unavailable`` ``PolicyDeniedError`` (e.g. a real+ scope-mismatch raised after the snapshot was successfully read) must+ surface as 400, distinct from the 503 used for ``settings_unavailable``+ and the 500 used for unrelated server crashes.++ Locks the route's exception-handler contract so a future refactor+ cannot collapse these branches back to the generic 500 path.+ """+ good_session = MagicMock()+ initialization_query = MagicMock()+ initialization_query.count.return_value = 1+ settings_query = MagicMock()+ settings_query.all.return_value = []+ good_session.query.side_effect = [initialization_query, settings_query]+ good_manager = SettingsManager(good_session)++ non_settings_denial = PolicyDeniedError(+ Decision(False, "scope_mismatch_private_only"),+ target="available_rag_models",+ )++ extra_patches = [+ patch(+ "local_deep_research.embeddings.embeddings_config._get_provider_classes",+ side_effect=non_settings_denial,+ ),+ patch(+ "local_deep_research.research_library.routes.rag_routes.get_settings_manager",+ return_value=good_manager,+ ),+ patch(+ "local_deep_research.database.session_context.get_user_db_session",+ side_effect=lambda *a, **k: _ctx_yielding(good_session),+ ),+ ]++ from ._route_helpers_rag import _auth_client++ with _auth_client(app, extra_patches=extra_patches) as (client, _ctx):+ response = client.get("/library/api/rag/models")++ assert response.status_code == 400+ body = response.get_json()+ assert body["success"] is False+++def _ctx_yielding(session):+ from contextlib import contextmanager++ @contextmanager+ def _ctx():+ yield session++ return _ctx()diff --git a/tests/research_library/services/test_download_service_3827_fix.py b/tests/research_library/services/test_download_service_3827_fix.pyindex 2603e29a05..800ef02c30 100644--- a/tests/research_library/services/test_download_service_3827_fix.py+++ b/tests/research_library/services/test_download_service_3827_fix.py@@ -809,6 +809,12 @@ def test_process_user_documents_rolls_back_on_resource_error():]settings_manager = MagicMock()+ # The egress backstop aborts unless the strict snapshot is a real dict+ # with a resolvable primary engine; supply one so processing reaches the+ # per-resource rollback path this test exercises.+ settings_manager.get_settings_snapshot.return_value = {+ "search.tool": "searxng"+ }with (patch.object(@@ -911,6 +917,13 @@ def test_process_user_documents_rolls_back_on_text_extraction_wrapper_error():download_service.__enter__ = MagicMock(return_value=download_service)download_service.__exit__ = MagicMock(return_value=False)+ settings_manager = MagicMock()+ # The egress backstop aborts unless the strict snapshot is a real dict+ # with a resolvable primary engine.+ settings_manager.get_settings_snapshot.return_value = {+ "search.tool": "searxng"+ }+with (patch.object(scheduler,@@ -923,7 +936,7 @@ def test_process_user_documents_rolls_back_on_text_extraction_wrapper_error():),patch("local_deep_research.settings.manager.SettingsManager",- return_value=MagicMock(),+ return_value=settings_manager,),patch("local_deep_research.research_library.services.download_service.DownloadService",diff --git a/tests/research_library/services/test_library_rag_service_coverage.py b/tests/research_library/services/test_library_rag_service_coverage.pyindex 9db825549f..e9763266f2 100644--- a/tests/research_library/services/test_library_rag_service_coverage.py+++ b/tests/research_library/services/test_library_rag_service_coverage.py@@ -10,6 +10,7 @@ Focuses on logic paths not exercised by the existing test_library_rag_service.py"""import hashlib+import jsonimport threadingimport timefrom pathlib import Path@@ -77,7 +78,26 @@ class TestGetIndexHash:def test_hash_is_sha256_hex(self):svc = _make_service()h = svc._get_index_hash("c", "m", "p")- expected = hashlib.sha256("c:m:p".encode()).hexdigest()+ identity = {+ "chunk_overlap": 200,+ "chunk_size": 1000,+ "collection_name": "c",+ "distance_metric": "cosine",+ "embedding_model": "m",+ "embedding_provider": "p",+ "index_type": "flat",+ "normalize_vectors": True,+ "splitter_type": "recursive",+ "text_separators": ["\n\n", "\n", ". ", " ", ""],+ }+ expected = hashlib.sha256(+ json.dumps(+ identity,+ ensure_ascii=False,+ separators=(",", ":"),+ sort_keys=True,+ ).encode()+ ).hexdigest()assert h == expecteddef test_hash_length_is_64_chars(self):diff --git a/tests/research_library/services/test_library_rag_service_strict_snapshot.py b/tests/research_library/services/test_library_rag_service_strict_snapshot.pynew file mode 100644index 0000000000..1a4d321353--- /dev/null+++ b/tests/research_library/services/test_library_rag_service_strict_snapshot.py@@ -0,0 +1,202 @@+"""Regression tests for V2-R1-3 strict-snapshot coverage at+``LibraryRAGService.__init__``.++A non-strict ``get_settings_snapshot`` silently falls back to JSON defaults+when the underlying settings query fails (SQLAlchemyError / stale enum+row). Those defaults can lack an operator-selected cloud embedding+provider's classification inputs and admit a cloud embedder under a+local-only posture. The constructor must therefore read the snapshot with+``strict=True`` and convert any query failure into+``PolicyDeniedError("settings_unavailable")`` BEFORE constructing a+``LocalEmbeddingManager``, performing provider discovery, or reading any+credential.+"""++from contextlib import contextmanager+from unittest.mock import MagicMock, patch++import pytest+from sqlalchemy.exc import SQLAlchemyError++from local_deep_research.security.egress.policy import (+ Decision,+ PolicyDeniedError,+)++_MOD = "local_deep_research.research_library.services.library_rag_service"+++@contextmanager+def _ctx_yielding(session):+ yield session+++def _build_session_raising_on_settings_query(query_error):+ """Build a mock DB session whose second ``query()`` (the settings+ enumeration query) raises, mirroring the production sequence:++ 1. ``SettingsManager.__init__`` issues an initialization-count query.+ 2. ``get_settings_snapshot(strict=True)`` issues the settings-enumeration+ query that we want to fail.+ """+ session = MagicMock()+ initialization_query = MagicMock()+ initialization_query.count.return_value = 1+ settings_query = MagicMock()+ settings_query.all.side_effect = query_error+ session.query.side_effect = [initialization_query, settings_query]+ return session+++ "query_error",+ [+ SQLAlchemyError("connection lost"),+ LookupError("unknown setting type"),+ ],+ ids=["sqlalchemy_error", "stale_enum_row"],+)+def test_construction_refuses_before_embedding_manager_when_settings_query_fails(+ query_error,+):+ """When the settings query fails, ``LibraryRAGService.__init__`` must+ raise ``PolicyDeniedError("settings_unavailable")`` BEFORE constructing+ a ``LocalEmbeddingManager`` or performing provider discovery / network+ access.++ Regression for V2-R1-3: the previous non-strict read silently+ fell back to JSON defaults, which could admit an operator-selected+ cloud embedding provider under a local-only posture.+ """+ session = _build_session_raising_on_settings_query(query_error)++ # Patch every external collaborator that must NOT be touched when the+ # snapshot read fails. ``LocalEmbeddingManager`` is the cloud-egress+ # surface we are protecting; the credential-store, egress PDP and the+ # text splitter are downstream collaborators that should also never+ # run.+ with (+ patch(f"{_MOD}.LocalEmbeddingManager") as lem_cls,+ patch(+ f"{_MOD}.get_user_db_session",+ side_effect=lambda *a, **k: _ctx_yielding(session),+ ),+ patch(f"{_MOD}.FileIntegrityManager") as fim_cls,+ patch(f"{_MOD}.get_text_splitter") as gts,+ patch(+ "local_deep_research.security.egress.policy.evaluate_embeddings"+ ) as eval_emb,+ ):+ from local_deep_research.research_library.services.library_rag_service import (+ LibraryRAGService,+ )++ with pytest.raises(PolicyDeniedError) as exc_info:+ LibraryRAGService(+ username="alice",+ embedding_provider="ollama",+ embedding_model="dummy",+ db_password="pw",+ )++ # Then: a single, decision-bearing PolicyDeniedError — never a bare+ # SQLAlchemyError / LookupError leak — and never a fallback that+ # proceeds to construct the manager.+ assert exc_info.value.decision.reason == "settings_unavailable"+ assert exc_info.value.target == "ollama"+ # No cloud-egress surface touched.+ lem_cls.assert_not_called()+ fim_cls.assert_not_called()+ gts.assert_not_called()+ eval_emb.assert_not_called()+ # The settings-enumeration query was issued (proving strict=True path),+ # but no further DB reads occurred downstream.+ assert session.query.call_count == 2+++def test_construction_succeeds_under_normal_strict_read():+ """Sanity guard: a healthy strict snapshot still constructs the+ service exactly as before. Ensures the strict gate does not regress+ the happy path while turning defaults-only failures into hard refusals.+ """+ session = MagicMock()+ initialization_query = MagicMock()+ initialization_query.count.return_value = 1+ settings_query = MagicMock()+ settings_query.all.return_value = []+ session.query.side_effect = [initialization_query, settings_query]++ with (+ patch(f"{_MOD}.LocalEmbeddingManager") as lem_cls,+ patch(+ f"{_MOD}.get_user_db_session",+ side_effect=lambda *a, **k: _ctx_yielding(session),+ ),+ patch(f"{_MOD}.FileIntegrityManager"),+ patch(f"{_MOD}.get_text_splitter"),+ ):+ lem_cls.return_value.embeddings = MagicMock()++ from local_deep_research.research_library.services.library_rag_service import (+ LibraryRAGService,+ )++ svc = LibraryRAGService(+ username="alice",+ embedding_provider="sentence_transformers",+ embedding_model="all-MiniLM-L6-v2",+ db_password="pw",+ )++ # Sanity: the manager WAS constructed on the happy path.+ lem_cls.assert_called_once()+ assert svc.embedding_provider == "sentence_transformers"+ assert svc.embedding_model == "all-MiniLM-L6-v2"+++def test_construction_propagates_policy_denied_from_egress_evaluation():+ """If ``context_from_snapshot`` itself raises ``PolicyDeniedError``+ (e.g. invalid scope), the constructor must propagate it verbatim+ rather than wrap it in a ``settings_unavailable`` decision — the+ decision reason is the actual policy refusal, not settings being+ unavailable.+ """+ session = MagicMock()+ initialization_query = MagicMock()+ initialization_query.count.return_value = 1+ settings_query = MagicMock()+ settings_query.all.return_value = []+ session.query.side_effect = [initialization_query, settings_query]++ inner_denial = PolicyDeniedError(+ Decision(False, "invalid_policy_config"), target="ollama"+ )++ with (+ patch(f"{_MOD}.LocalEmbeddingManager") as lem_cls,+ patch(+ f"{_MOD}.get_user_db_session",+ side_effect=lambda *a, **k: _ctx_yielding(session),+ ),+ patch(f"{_MOD}.FileIntegrityManager"),+ patch(f"{_MOD}.get_text_splitter"),+ patch(+ "local_deep_research.security.egress.policy.context_from_snapshot",+ side_effect=inner_denial,+ ),+ ):+ from local_deep_research.research_library.services.library_rag_service import (+ LibraryRAGService,+ )++ with pytest.raises(PolicyDeniedError) as exc_info:+ LibraryRAGService(+ username="alice",+ embedding_provider="ollama",+ embedding_model="dummy",+ db_password="pw",+ )++ # Propagated verbatim — NOT re-wrapped as settings_unavailable.+ assert exc_info.value.decision.reason == "invalid_policy_config"+ lem_cls.assert_not_called()diff --git a/tests/research_library/services/test_rag_index_identity.py b/tests/research_library/services/test_rag_index_identity.pynew file mode 100644index 0000000000..46380e61b3--- /dev/null+++ b/tests/research_library/services/test_rag_index_identity.py@@ -0,0 +1,147 @@+import hashlib+from contextlib import contextmanager+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest++from local_deep_research.database.models.library import EmbeddingProvider+++_MODULE = "local_deep_research.research_library.services.library_rag_service"+++def _make_service(**overrides):+ with (+ patch(f"{_MODULE}.LocalEmbeddingManager") as embedding_manager,+ patch(f"{_MODULE}.get_user_db_session"),+ patch(f"{_MODULE}.FileIntegrityManager"),+ patch(f"{_MODULE}.get_text_splitter"),+ ):+ embedding_manager.return_value.embeddings = MagicMock()+ from local_deep_research.research_library.services.library_rag_service import (+ LibraryRAGService,+ )++ config = {"username": "testuser", "db_password": "password"}+ config.update(overrides)+ return LibraryRAGService(**config)+++ "overrides",+ [+ {"chunk_size": 501},+ {"chunk_overlap": 101},+ {"splitter_type": "token"},+ {"text_separators": ["\n", " "]},+ {"distance_metric": "l2"},+ {"normalize_vectors": False},+ {"index_type": "hnsw"},+ ],+)+def test_index_hash_changes_for_each_index_affecting_configuration(overrides):+ # Given+ baseline = _make_service()+ changed = _make_service(**overrides)++ # When+ baseline_hash = baseline._get_index_hash(+ "collection-1", "model", "sentence_transformers"+ )+ changed_hash = changed._get_index_hash(+ "collection-1", "model", "sentence_transformers"+ )++ # Then+ assert changed_hash != baseline_hash+++def test_reuses_legacy_row_only_when_its_full_configuration_matches():+ service = _make_service(embedding_model="model")+ collection_name = "collection-1"+ legacy_hash = hashlib.sha256(+ f"{collection_name}:model:sentence_transformers".encode()+ ).hexdigest()+ legacy = SimpleNamespace(+ id=1,+ index_hash=legacy_hash,+ collection_name=collection_name,+ embedding_model="model",+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,+ chunk_size=service.chunk_size,+ chunk_overlap=service.chunk_overlap,+ splitter_type=service.splitter_type,+ text_separators=service.text_separators,+ distance_metric=service.distance_metric,+ normalize_vectors=service.normalize_vectors,+ index_type=service.index_type,+ is_current=True,+ )+ new_hash = service._get_index_hash(+ collection_name, "model", "sentence_transformers"+ )+ hash_query = MagicMock()+ hash_query.filter_by.return_value.first.return_value = None+ exact_match_query = MagicMock()+ exact_match_query.filter_by.return_value.all.return_value = [legacy]+ db_session = MagicMock()+ db_session.query.side_effect = [hash_query, exact_match_query]++ # Given+ assert legacy_hash != new_hash++ # When+ result = service._get_or_create_rag_index(+ "1", db_session=db_session, commit=False+ )++ # Then+ assert result is legacy+ db_session.add.assert_not_called()+ db_session.commit.assert_not_called()+++def test_concurrent_index_creation_rolls_back_only_the_savepoint(tmp_path):+ service = _make_service(embedding_model="model")+ service.embedding_manager.embeddings.embed_query.return_value = [0.0, 0.0]+ collection_name = "collection-1"+ index_hash = service._get_index_hash(+ collection_name, "model", "sentence_transformers"+ )+ concurrent = SimpleNamespace(id=2, index_hash=index_hash, is_current=True)+ missing_query = MagicMock()+ missing_query.filter_by.return_value.first.return_value = None+ candidates_query = MagicMock()+ candidates_query.filter_by.return_value.all.return_value = []+ concurrent_query = MagicMock()+ concurrent_query.filter_by.return_value.first.return_value = concurrent+ db_session = MagicMock()+ db_session.query.side_effect = [+ missing_query,+ candidates_query,+ concurrent_query,+ ]++ @contextmanager+ def raced_savepoint():+ yield+ from sqlalchemy.exc import IntegrityError++ raise IntegrityError("INSERT", {}, RuntimeError("duplicate"))++ db_session.begin_nested.side_effect = raced_savepoint++ # Given+ service._get_index_path = MagicMock(return_value=tmp_path / "index.faiss")++ # When+ result = service._get_or_create_rag_index(+ "1", db_session=db_session, commit=False+ )++ # Then+ assert result is concurrent+ db_session.begin_nested.assert_called_once_with()+ db_session.commit.assert_not_called()+ db_session.rollback.assert_not_called()diff --git a/tests/security/test_egress_policy.py b/tests/security/test_egress_policy.pyindex 05b47e9681..6979d1810e 100644--- a/tests/security/test_egress_policy.py+++ b/tests/security/test_egress_policy.py@@ -71,6 +71,27 @@ def test_default_scope_constant_matches_registry():assert EgressScope(DEFAULT_EGRESS_SCOPE)+def test_default_scope_options_match_user_selectable_policy_scopes():+ import json++ from local_deep_research.defaults import DEFAULTS_DIR+ from local_deep_research.security.egress.policy import (+ USER_SELECTABLE_PROTECTED_SCOPES,+ )++ path = DEFAULTS_DIR / "default_settings.json"+ with open(path, encoding="utf-8-sig") as f:+ registry = json.load(f)+ option_values = {+ option["value"] for option in registry["policy.egress_scope"]["options"]+ }+ expected = {scope.value for scope in USER_SELECTABLE_PROTECTED_SCOPES} | {+ EgressScope.UNPROTECTED.value+ }+ assert option_values == expected+ assert EgressScope.BOTH.value not in option_values++def test_context_from_snapshot_defaults_to_adaptive():"""A missing policy.egress_scope falls back to the REGISTERED default(adaptive), matching what users with a settings DB already get: a@@ -1439,6 +1460,97 @@ def test_t3_classify_host_uses_dns_when_not_an_ip():assert _classify_host("example.lab", ctx) is True+def test_classify_host_mixed_private_and_public_dns_answer_is_public():+ from local_deep_research.security.egress.policy import _classify_host++ # Given a hostname with both private and public DNS answers.+ ctx = make_ctx(scope=EgressScope.PRIVATE_ONLY)+ answers = [+ (None, None, None, None, ("10.0.0.42", 0)),+ (None, None, None, None, ("8.8.8.8", 0)),+ ]+ with patch(+ "local_deep_research.security.egress.policy._resolve_with_timeout",+ return_value=answers,+ ):+ # When the endpoint hostname is classified.+ classification = _classify_host("mixed.inference.example", ctx)++ # Then a public answer wins rather than admitting the endpoint as local.+ assert classification is False+ assert ctx._dns_cache["mixed.inference.example"] is False+++def test_classify_host_mixed_metadata_and_private_dns_answer_is_public():+ from local_deep_research.security.egress.policy import _classify_host++ # Given a hostname with a private address followed by cloud metadata.+ ctx = make_ctx(scope=EgressScope.PRIVATE_ONLY)+ answers = [+ (None, None, None, None, ("10.0.0.42", 0)),+ (None, None, None, None, ("169.254.169.254", 0)),+ ]+ with patch(+ "local_deep_research.security.egress.policy._resolve_with_timeout",+ return_value=answers,+ ):+ # When the endpoint hostname is classified.+ classification = _classify_host("mixed-metadata.inference.example", ctx)++ # Then metadata keeps the hostname out of the local-only allowlist.+ assert classification is False+ assert ctx._dns_cache["mixed-metadata.inference.example"] is False+++def test_classify_host_all_private_ipv4_and_ipv6_dns_answers_are_local():+ from local_deep_research.security.egress.policy import _classify_host++ # Given a hostname with private IPv4 and IPv6 answers.+ ctx = make_ctx(scope=EgressScope.PRIVATE_ONLY)+ answers = [+ (None, None, None, None, ("10.0.0.42", 0)),+ (None, None, None, None, ("fd12::42", 0, 0, 0)),+ ]+ with patch(+ "local_deep_research.security.egress.policy._resolve_with_timeout",+ return_value=answers,+ ):+ # When the endpoint hostname is classified.+ classification = _classify_host("inference.internal", ctx)++ # Then the all-local hostname remains eligible.+ assert classification is True+ assert ctx._dns_cache["inference.internal"] is True+++def test_llm_endpoint_mixed_dns_answer_is_denied_and_cached():+ # Given a local-only provider URL with mixed DNS answers.+ ctx = make_ctx(scope=EgressScope.PRIVATE_ONLY, require_local_llm=True)+ snapshot = {"llm.lmstudio.url": "http://mixed.inference.example/v1"}+ answers = [+ (None, None, None, None, ("10.0.0.42", 0)),+ (None, None, None, None, ("8.8.8.8", 0)),+ ]+ with patch(+ "local_deep_research.security.egress.policy._resolve_with_timeout",+ return_value=answers,+ ) as resolve:+ # When model discovery checks the provider twice.+ first = evaluate_llm_endpoint(+ "lmstudio", ctx, settings_snapshot=snapshot+ )+ second = evaluate_llm_endpoint(+ "lmstudio", ctx, settings_snapshot=snapshot+ )++ # Then it never treats the endpoint as local and only resolves once.+ assert not first.allowed+ assert first.reason == "provider_remote"+ assert second == first+ resolve.assert_called_once_with("mixed.inference.example")+ assert ctx._dns_cache["mixed.inference.example"] is False++def test_t4_ipv6_literal_url_classifies():"""T4: IPv6-literal URLs (with square brackets) classifycorrectly. Catches regressions in the bracket-strip logic.diff --git a/tests/security/test_egress_unprotected.py b/tests/security/test_egress_unprotected.pyindex 491c49a9b6..dd093e9304 100644--- a/tests/security/test_egress_unprotected.py+++ b/tests/security/test_egress_unprotected.py@@ -7,14 +7,21 @@ local-inference requirements.from __future__ import annotations+import pytest+from local_deep_research.security.egress.policy import (+ DEFAULT_EGRESS_SCOPE,EgressContext,EgressScope,+ PolicyDeniedError,+ USER_SELECTABLE_PROTECTED_SCOPES,context_from_snapshot,+ effective_scope_for_display,evaluate_engine,evaluate_llm_endpoint,evaluate_retriever,evaluate_url,+ parse_user_egress_scope,)@@ -27,6 +34,65 @@ def unprot_ctx(primary: str = "arxiv") -> EgressContext:)+def test_user_selectable_protected_scopes_exclude_internal_and_escape_hatch():+ assert USER_SELECTABLE_PROTECTED_SCOPES == {+ EgressScope.ADAPTIVE,+ EgressScope.PUBLIC_ONLY,+ EgressScope.PRIVATE_ONLY,+ EgressScope.STRICT,+ }+ assert EgressScope.BOTH not in USER_SELECTABLE_PROTECTED_SCOPES+ assert EgressScope.UNPROTECTED not in USER_SELECTABLE_PROTECTED_SCOPES+++ ("raw", "expected"),+ [+ (" adaptive ", EgressScope.ADAPTIVE),+ ("PUBLIC_ONLY", EgressScope.PUBLIC_ONLY),+ ("private_only", EgressScope.PRIVATE_ONLY),+ ("strict", EgressScope.STRICT),+ ],+)+def test_parse_user_egress_scope_canonicalizes_protected_values(raw, expected):+ assert parse_user_egress_scope(raw) is expected++[email protected]("raw", ["both", "unknown", "", None, 1])+def test_parse_user_egress_scope_rejects_non_user_values(raw):+ with pytest.raises(PolicyDeniedError) as exc_info:+ parse_user_egress_scope(raw)+ assert exc_info.value.decision.reason == "unknown_egress_scope"+++def test_parse_user_egress_scope_enforces_gate_and_runtime_fallback(+ monkeypatch,+):+ monkeypatch.delenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", raising=False)+ with pytest.raises(PolicyDeniedError) as exc_info:+ parse_user_egress_scope("unprotected")+ assert exc_info.value.decision.reason == "unprotected_egress_disabled"+ assert (+ parse_user_egress_scope("unprotected", disabled_unprotected="adaptive")+ is EgressScope.ADAPTIVE+ )++ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")+ assert parse_user_egress_scope(" UNPROTECTED ") is EgressScope.UNPROTECTED++[email protected]("raw", ["both", "unknown", "", None, 1])+def test_effective_scope_for_display_falls_back_safely(raw):+ assert effective_scope_for_display(raw) == DEFAULT_EGRESS_SCOPE+++def test_effective_scope_for_display_respects_unprotected_gate(monkeypatch):+ monkeypatch.delenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", raising=False)+ assert effective_scope_for_display("unprotected") == DEFAULT_EGRESS_SCOPE+ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")+ assert effective_scope_for_display(" UNPROTECTED ") == "unprotected"++def test_engine_any_allowed_under_unprotected():# A normally-unclassified/unknown engine is permitted by the escape hatch.d = evaluate_engine(@@ -57,7 +123,64 @@ def test_cloud_llm_allowed_under_unprotected():).allowed-def test_context_unprotected_lifts_local_requirements():+def test_context_unprotected_coerces_to_adaptive_by_default():+ ctx = context_from_snapshot(+ {"policy.egress_scope": "unprotected", "search.tool": "arxiv"},+ "arxiv",+ )+ assert ctx.scope is EgressScope.PUBLIC_ONLY+++def test_context_reapplies_current_environment_scope_to_stale_snapshot(+ monkeypatch,+):+ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")+ monkeypatch.setenv("LDR_POLICY_EGRESS_SCOPE", "private_only")+ ctx = context_from_snapshot(+ {"policy.egress_scope": "unprotected", "search.tool": "arxiv"},+ "arxiv",+ )+ assert ctx.scope is EgressScope.PRIVATE_ONLY+ assert ctx.require_local_llm is True+ assert ctx.require_local_embeddings is True+++def test_unprotected_cannot_clear_environment_locality_locks(monkeypatch):+ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")+ monkeypatch.setenv("LDR_LLM_REQUIRE_LOCAL_ENDPOINT", "true")+ monkeypatch.setenv("LDR_EMBEDDINGS_REQUIRE_LOCAL", "true")+ ctx = context_from_snapshot(+ {+ "policy.egress_scope": "unprotected",+ "llm.require_local_endpoint": False,+ "embeddings.require_local": False,+ "search.tool": "arxiv",+ },+ "arxiv",+ )+ assert ctx.scope is EgressScope.UNPROTECTED+ assert ctx.require_local_llm is True+ assert ctx.require_local_embeddings is True+++def test_context_reapplies_current_environment_locality_flags(monkeypatch):+ monkeypatch.setenv("LDR_LLM_REQUIRE_LOCAL_ENDPOINT", "true")+ monkeypatch.setenv("LDR_EMBEDDINGS_REQUIRE_LOCAL", "true")+ ctx = context_from_snapshot(+ {+ "policy.egress_scope": "public_only",+ "llm.require_local_endpoint": False,+ "embeddings.require_local": False,+ "search.tool": "arxiv",+ },+ "arxiv",+ )+ assert ctx.require_local_llm is True+ assert ctx.require_local_embeddings is True+++def test_context_unprotected_lifts_local_requirements(monkeypatch):+ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")# Even with the require-local flags saved on, UNPROTECTED lifts them.snap = {"policy.egress_scope": "unprotected",@@ -99,6 +222,52 @@ def test_trusted_destinations_warning():assert w2 is not None and "openai" in w2["message"]+def test_effective_dispatch_snapshot_reapplies_all_environment_overrides(+ monkeypatch,+):+ from local_deep_research.settings.manager import (+ apply_environment_overrides_to_snapshot,+ )++ monkeypatch.setenv("LDR_POLICY_TRUSTED_SEARCH_ENGINES", "[]")+ monkeypatch.setenv("LDR_LLM_ALLOWED_LOCAL_HOSTNAMES", '["localhost"]')+ snapshot = {+ "policy.trusted_search_engines": {+ "value": ["stale-engine"],+ "ui_element": "json",+ "editable": True,+ },+ "llm.allowed_local_hostnames": ["stale.internal"],+ }+ effective = apply_environment_overrides_to_snapshot(snapshot)+ assert effective["policy.trusted_search_engines"]["value"] == []+ assert effective["policy.trusted_search_engines"]["editable"] is False+ assert effective["llm.allowed_local_hostnames"] == ["localhost"]+ assert snapshot["policy.trusted_search_engines"]["value"] == [+ "stale-engine"+ ]+ partial = apply_environment_overrides_to_snapshot({})+ assert partial["policy.trusted_search_engines"]["value"] == []+ assert partial["policy.trusted_search_engines"]["editable"] is False+ assert partial["llm.allowed_local_hostnames"]["value"] == ["localhost"]+ assert partial["llm.allowed_local_hostnames"]["editable"] is False+++def test_validate_unprotected_scope_respects_operator_gate(monkeypatch):+ from local_deep_research.security.egress.validators import (+ validate_egress_scope,+ )++ form = {"policy.egress_scope": "unprotected"}+ assert validate_egress_scope(form, {}) is not None+ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")+ assert validate_egress_scope(form, {}) is None+ assert (+ validate_egress_scope({"policy.egress_scope": "invalid"}, {})+ is not None+ )++def test_validate_trusted_search_engines_rejects_public():from local_deep_research.security.egress.validators import (validate_trusted_search_engines,diff --git a/tests/security/test_password_leakage.py b/tests/security/test_password_leakage.pyindex a4b862a885..2578910af5 100644--- a/tests/security/test_password_leakage.py+++ b/tests/security/test_password_leakage.py@@ -797,7 +797,7 @@ class TestSchedulerBackgroundPasswordLeakage:last_run=None,)scheduler._get_document_scheduler_settings = lambda u: doc_settings- scheduler._arm_egress_backstop = lambda sm, u: None+ scheduler._arm_egress_backstop = lambda sm, u: True# One fake completed research session so the snapshot block is# reached (empty result returns before it).@@ -829,4 +829,7 @@ class TestSchedulerBackgroundPasswordLeakage:_LEAKED_PASSWORD,"_process_user_documents snapshot handler",)- assert "Could not build settings snapshot" in loguru_caplog_full.text+ assert (+ "doc scheduler: egress policy setup failed; skipping scheduled work"+ in loguru_caplog_full.text+ )diff --git a/tests/security/test_strict_policy_settings_snapshots.py b/tests/security/test_strict_policy_settings_snapshots.pynew file mode 100644index 0000000000..50b75c3726--- /dev/null+++ b/tests/security/test_strict_policy_settings_snapshots.py@@ -0,0 +1,242 @@+from contextlib import contextmanager+from datetime import UTC, datetime+from unittest.mock import MagicMock, PropertyMock, patch++import pytest+from sqlalchemy.exc import SQLAlchemyError++from local_deep_research.scheduler.background import (+ BackgroundJobScheduler,+ DocumentSchedulerSettings,+)+from local_deep_research.settings.manager import SettingsManager+++def _settings_manager_with_query_failure(error):+ database_session = MagicMock()+ initialization_query = MagicMock()+ initialization_query.count.return_value = 1+ settings_query = MagicMock()+ settings_query.all.side_effect = error+ database_session.query.side_effect = [initialization_query, settings_query]+ return SettingsManager(database_session), database_session+++@contextmanager+def _database_session(database_session):+ yield database_session+++def scheduler():+ BackgroundJobScheduler._instance = None+ with patch("local_deep_research.scheduler.background.BackgroundScheduler"):+ yield BackgroundJobScheduler()+ BackgroundJobScheduler._instance = None+++ "query_error",+ [SQLAlchemyError("connection lost"), LookupError("unknown setting type")],+)+def test_strict_snapshot_propagates_query_error(query_error):+ # Given+ manager, _ = _settings_manager_with_query_failure(query_error)++ # When / Then+ with pytest.raises(type(query_error)):+ manager.get_settings_snapshot(strict=True)+++def test_default_snapshot_returns_defaults_when_query_fails():+ # Given+ manager, _ = _settings_manager_with_query_failure(+ SQLAlchemyError("offline")+ )++ # When+ with patch.object(+ SettingsManager,+ "default_settings",+ new_callable=PropertyMock,+ return_value={"policy.egress_scope": {"value": "adaptive"}},+ ):+ snapshot = manager.get_settings_snapshot()++ # Then+ assert snapshot == {"policy.egress_scope": "adaptive"}+++def test_strict_snapshot_applies_current_environment_override(monkeypatch):+ # Given+ database_session = MagicMock()+ database_session.query.return_value.count.return_value = 1+ database_session.query.return_value.all.return_value = []+ manager = SettingsManager(database_session)+ monkeypatch.setenv("LDR_POLICY_EGRESS_SCOPE", "private_only")++ # When+ with patch.object(+ SettingsManager,+ "default_settings",+ new_callable=PropertyMock,+ return_value={+ "policy.egress_scope": {+ "value": "adaptive",+ "ui_element": "select",+ }+ },+ ):+ snapshot = manager.get_settings_snapshot(strict=True)++ # Then+ assert snapshot["policy.egress_scope"] == "private_only"+++def test_model_discovery_rejects_query_failure_before_cache_provider_or_credential(+ authenticated_client,+):+ # Given+ database_session = MagicMock()+ initialization_query = MagicMock()+ initialization_query.count.return_value = 1+ settings_query = MagicMock()+ settings_query.all.side_effect = SQLAlchemyError("connection lost")+ database_session.query.side_effect = [initialization_query, settings_query]++ # When+ with (+ patch(+ "local_deep_research.web.routes.settings_routes.get_user_db_session",+ side_effect=lambda *args, **kwargs: _database_session(+ database_session+ ),+ ),+ patch(+ "local_deep_research.web.routes.settings_routes.get_settings_manager",+ side_effect=lambda database, *args: SettingsManager(database),+ ),+ patch(+ "local_deep_research.llm.providers.get_discovered_provider_options"+ ) as provider_options,+ patch(+ "local_deep_research.llm.providers.discover_providers"+ ) as providers,+ patch(+ "local_deep_research.web.routes.settings_routes._get_setting_from_session"+ ) as credential,+ ):+ response = authenticated_client.get("/settings/api/available-models")++ # Then+ assert response.status_code == 503+ assert database_session.query.call_count == 2+ provider_options.assert_not_called()+ providers.assert_not_called()+ credential.assert_not_called()+++def test_egress_backstop_stops_when_real_settings_query_fails(scheduler):+ # Given+ manager, _ = _settings_manager_with_query_failure(+ SQLAlchemyError("offline")+ )++ # When+ with patch(+ "local_deep_research.security.egress.audit_hook.set_active_context"+ ) as set_active_context:+ armed = scheduler._arm_egress_backstop(manager, "alice")++ # Then+ assert armed is False+ set_active_context.assert_not_called()+++def test_document_scheduler_skips_download_when_strict_snapshot_query_fails(+ scheduler,+):+ # Given+ database_session = MagicMock()+ initialization_query = MagicMock()+ initialization_query.count.return_value = 1+ research_query = MagicMock()+ research_query.filter.return_value = research_query+ research_query.order_by.return_value = research_query+ research_query.limit.return_value = research_query+ research_query.all.return_value = [+ MagicMock(+ id="research-1", title="Research", completed_at=datetime.now(UTC)+ )+ ]+ settings_query = MagicMock()+ settings_query.all.side_effect = SQLAlchemyError("settings unavailable")+ database_session.query.side_effect = [+ initialization_query,+ research_query,+ settings_query,+ ]+ scheduler.user_sessions["alice"] = {"scheduled_jobs": set()}+ scheduler._credential_store.store("alice", "password")++ # When+ with (+ patch.object(+ scheduler,+ "_get_document_scheduler_settings",+ return_value=DocumentSchedulerSettings(download_pdfs=True),+ ),+ patch(+ "local_deep_research.database.session_context.get_user_db_session",+ side_effect=lambda *args, **kwargs: _database_session(+ database_session+ ),+ ),+ patch.object(scheduler, "_arm_egress_backstop", return_value=True),+ patch(+ "local_deep_research.research_library.services.download_service.DownloadService"+ ) as download_service,+ ):+ scheduler._process_user_documents("alice")++ # Then+ assert database_session.query.call_count == 3+ download_service.assert_not_called()+++def test_reconciler_skips_rag_when_real_settings_query_fails(scheduler):+ # Given+ database_session = MagicMock()+ initialization_query = MagicMock()+ initialization_query.count.return_value = 1+ settings_query = MagicMock()+ settings_query.all.side_effect = LookupError("unknown setting type")+ database_session.query.side_effect = [initialization_query, settings_query]+ scheduler.user_sessions["alice"] = {"scheduled_jobs": set()}+ scheduler._credential_store.store("alice", "password")++ # When+ with (+ patch.object(+ scheduler,+ "_get_document_scheduler_settings",+ return_value=DocumentSchedulerSettings(+ enabled=True,+ generate_rag=True,+ ),+ ),+ patch(+ "local_deep_research.database.session_context.get_user_db_session",+ side_effect=lambda *args, **kwargs: _database_session(+ database_session+ ),+ ),+ patch(+ "local_deep_research.research_library.services.rag_service_factory.get_rag_service"+ ) as rag_service,+ ):+ scheduler._reconcile_unindexed_documents("alice")++ # Then+ assert database_session.query.call_count == 2+ rag_service.assert_not_called()diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.jsonindex 33342162c8..8dac51cc5b 100644--- a/tests/settings/golden_master_settings.json+++ b/tests/settings/golden_master_settings.json@@ -2271,7 +2271,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.); UNPROTECTED = escape hatch that disables egress protection entirely (not recommended; hard SSRF/cloud-metadata blocking still applies).",+ "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 = operator-enabled escape hatch that disables egress protection entirely (not recommended; requires LDR_POLICY_ALLOW_UNPROTECTED_EGRESS=true; hard SSRF/cloud-metadata blocking still applies).","editable": true,"max_value": null,"min_value": null,diff --git a/tests/settings/test_settings_manager.py b/tests/settings/test_settings_manager.pyindex 9ddca2f475..8fc19bf925 100644--- a/tests/settings/test_settings_manager.py+++ b/tests/settings/test_settings_manager.py@@ -18,6 +18,7 @@ from unittest.mock import MagicMock, patch, PropertyMockfrom local_deep_research.settings.manager import (SettingsManager,+ apply_environment_overrides_to_snapshot,get_typed_setting_value,check_env_setting,is_valid_setting_key,@@ -440,6 +441,30 @@ class TestSettingsManagerSetSetting:assert result is Trueassert mock_setting.value == "updated_value"+ def test_set_setting_refuses_environment_locked_key_without_mutation(+ self, monkeypatch+ ):+ mock_session = MagicMock()+ mock_session.query.return_value.count.return_value = 1+ mock_setting = MagicMock()+ mock_setting.value = "stored_value"+ mock_setting.editable = True+ mock_session.query.return_value.filter.return_value.first.return_value = mock_setting+ manager = SettingsManager(db_session=mock_session)+ manager._SettingsManager__settings_locked = False+ mock_session.reset_mock()+ monkeypatch.setenv("LDR_APP_DEBUG", "true")++ with patch.object(manager, "_emit_settings_changed") as mock_emit:+ result = manager.set_setting("app.debug", "new_value")++ assert result is False+ assert mock_setting.value == "stored_value"+ mock_session.query.assert_not_called()+ mock_session.add.assert_not_called()+ mock_session.commit.assert_not_called()+ mock_emit.assert_not_called()+def test_set_setting_preserves_type(self):"""Test that set_setting preserves the type of the value."""mock_session = MagicMock()@@ -597,36 +622,126 @@ class TestSettingsManagerImportExport:mock_session.add.assert_called()def test_import_settings_with_delete_extra_true(self):- """Test that import_settings deletes extra settings when delete_extra=True."""- mock_session = MagicMock()- mock_session.query.return_value.count.return_value = 1+ """Delete-extra removes imported rows and extras before commit."""+ from local_deep_research.database.models import Setting+ mock_session = MagicMock()+ mutation_query = MagicMock()+ mutation_query.filter.return_value.delete.return_value = 1+ key_query = MagicMock()+ key_query.all.return_value = [("test.key",), ("extra.key",)]+ mock_session.query.side_effect = lambda model: (+ key_query if model is Setting.key else mutation_query+ )manager = SettingsManager(db_session=mock_session)- # Mock get_all_settings to return extra key- extra_settings = {- "test.key": {"value": "v1"},- "extra.key": {"value": "v2"},- }+ with patch.object(manager, "_emit_settings_changed"):+ manager.import_settings(+ {"test.key": {"value": "v1", "type": "APP"}},+ delete_extra=True,+ )- with patch.object(manager, "get_setting", return_value=None):- with patch.object(manager, "delete_setting") as mock_delete:- with patch.object(- manager, "get_all_settings", return_value=extra_settings- ):- with patch.object(manager, "_emit_settings_changed"):- manager.import_settings(- {"test.key": {"value": "v1", "type": "APP"}},- delete_extra=True,- )-- # Should delete the extra.key- delete_calls = [- call- for call in mock_delete.call_args_list- if call[0][0] == "extra.key"- ]- assert len(delete_calls) > 0+ assert mutation_query.filter.return_value.delete.call_count == 2+ mock_session.commit.assert_called_once()++ def test_import_preserves_locked_value_and_refreshes_metadata(+ self, monkeypatch+ ):+ from sqlalchemy import create_engine+ from sqlalchemy.orm import sessionmaker++ from local_deep_research.database.models import Base, Setting++ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()+ try:+ session.add(+ Setting(+ key="policy.egress_scope",+ value="strict",+ type="APP",+ name="Stale egress scope",+ description="Stale description",+ category="legacy",+ ui_element="text",+ options=["legacy"],+ min_value=1,+ max_value=2,+ step=0.5,+ visible=False,+ editable=False,+ )+ )+ session.commit()+ manager = SettingsManager(db_session=session)+ monkeypatch.setenv("LDR_POLICY_EGRESS_SCOPE", "public_only")+ monkeypatch.setenv("LDR_POLICY_NEW_SCOPE", "operator absent value")++ manager.import_settings(+ {+ "policy.egress_scope": {+ "value": "adaptive",+ "type": "APP",+ "name": "Fresh egress scope",+ "description": "Fresh description",+ "category": "policy",+ "ui_element": "select",+ "options": ["adaptive", "strict", "public_only"],+ "min_value": 0,+ "max_value": 10,+ "step": 1,+ "visible": True,+ "editable": True,+ },+ "policy.new_scope": {+ "value": "canonical absent value",+ "type": "APP",+ "name": "New scope",+ "description": "New metadata",+ "category": "policy",+ "ui_element": "text",+ "visible": True,+ "editable": True,+ },+ },+ preserve_environment_locked=True,+ )++ assert (+ manager.get_setting("policy.egress_scope", check_env=False)+ == "strict"+ )+ locked = manager.get_all_settings()["policy.egress_scope"]+ assert locked["name"] == "Fresh egress scope"+ assert locked["description"] == "Fresh description"+ assert locked["category"] == "policy"+ assert locked["ui_element"] == "select"+ assert locked["options"] == ["adaptive", "strict", "public_only"]+ assert locked["min_value"] == 0+ assert locked["max_value"] == 10+ assert locked["step"] == 1+ assert locked["visible"] is True++ assert (+ manager.get_setting("policy.new_scope", check_env=False)+ == "canonical absent value"+ )+ assert (+ manager.get_all_settings()["policy.new_scope"]["description"]+ == "New metadata"+ )++ assert manager.get_setting("policy.egress_scope") == "public_only"+ monkeypatch.delenv("LDR_POLICY_EGRESS_SCOPE")+ assert manager.get_setting("policy.egress_scope") == "strict"+ assert (+ manager.get_all_settings()["policy.egress_scope"]["editable"]+ is True+ )+ finally:+ session.close()+ engine.dispose()def test_import_settings_type_detection_from_key(self):"""Test that import_settings detects type from key prefix."""@@ -845,6 +960,104 @@ class TestSettingsManagerVersioning:mock_session.add.assert_called_once()mock_session.commit.assert_not_called()+ def test_db_version_matches_package_ignores_env_override(self):+ """LDR_APP_VERSION must not fool db_version_matches_package into+ reporting a match.++ The schema-version marker has to reflect what is *stored in the DB*+ — if the env var matches the running package but the DB row is+ stale, the migration must still run. Routing the read through the+ env-aware get_setting() path would short-circuit the comparison+ against the env value and falsely report equality.+ """+ mock_session = MagicMock()+ mock_session.query.return_value.count.return_value = 1++ manager = SettingsManager(db_session=mock_session)++ from local_deep_research.__version__ import __version__ as pkg_version++ os.environ["LDR_APP_VERSION"] = pkg_version++ # Stored DB version is stale — env var must not mask that.+ with patch.object(+ manager, "get_setting", wraps=manager.get_setting+ ) as spy:+ result = manager.db_version_matches_package()++ assert result is False, (+ "LDR_APP_VERSION must not make a stale DB row appear to match"+ )+ spy.assert_called_once_with("app.version", check_env=False)++ def test_update_db_version_bypasses_env_lock_on_internal_delete(+ self, monkeypatch+ ):+ """update_db_version must replace the prior app.version row even when+ LDR_APP_VERSION is set.++ The version marker is internal migration plumbing: the env lock+ applies to ordinary user mutations (set/delete via the public API),+ not to this write. If the prior row is left in place, the new+ insert would either raise a UNIQUE violation or silently duplicate+ the marker — either way the migration is corrupted.+ """+ from local_deep_research.database.models import Setting++ mock_session = MagicMock()+ mock_session.query.return_value.count.return_value = 1+ # Internal delete returns a rowcount.+ mock_session.query.return_value.filter.return_value.delete.return_value = 1++ manager = SettingsManager(db_session=mock_session)+ monkeypatch.setenv("LDR_APP_VERSION", "9.9.9")++ with patch.object(manager, "delete_setting") as public_delete:+ manager.update_db_version()++ # The public, env-guarded delete_setting must NOT be used for the+ # internal migration write.+ public_delete.assert_not_called()++ # The internal SQL delete must have run against app.version.+ added = mock_session.add.call_args.args+ assert len(added) == 1+ assert isinstance(added[0], Setting)+ assert added[0].key == "app.version"++ from local_deep_research.__version__ import __version__ as pkg_version++ assert added[0].value == pkg_version+ mock_session.commit.assert_called_once()++ def test_update_db_version_with_env_lock_writes_package_value_not_env_value(+ self, monkeypatch+ ):+ """The stored app.version after update_db_version must equal the+ *package* version, not whatever happens to be in LDR_APP_VERSION.+ """+ from local_deep_research.__version__ import __version__ as pkg_version++ # Pin a clearly-wrong env value to prove it is ignored end-to-end.+ if pkg_version == "0.0.0-wrong":+ monkeypatch.setenv("LDR_APP_VERSION", "0.0.0-other-wrong")+ else:+ monkeypatch.setenv("LDR_APP_VERSION", "0.0.0-wrong")++ mock_session = MagicMock()+ mock_session.query.return_value.count.return_value = 1+ mock_session.query.return_value.filter.return_value.delete.return_value = 1++ manager = SettingsManager(db_session=mock_session)+ manager.update_db_version(commit=False)++ added = mock_session.add.call_args.args+ assert added[0].key == "app.version"+ assert added[0].value == pkg_version, (+ "update_db_version must store the package version, not the "+ "LDR_APP_VERSION env value"+ )+class TestSettingsManagerStaticMethods:"""Tests for static helper methods."""@@ -1045,6 +1258,24 @@ class TestDeleteSetting:assert result is False+ def test_delete_setting_refuses_environment_locked_key_without_mutation(+ self, monkeypatch+ ):+ mock_session = MagicMock()+ mock_session.query.return_value.count.return_value = 1+ manager = SettingsManager(db_session=mock_session)+ mock_session.reset_mock()+ monkeypatch.setenv("LDR_APP_DEBUG", "true")++ with patch.object(manager, "_emit_settings_changed") as mock_emit:+ result = manager.delete_setting("app.debug")++ assert result is False+ mock_session.query.assert_not_called()+ mock_session.add.assert_not_called()+ mock_session.commit.assert_not_called()+ mock_emit.assert_not_called()+def test_delete_setting_rollback_on_error(self):"""Test that delete_setting rolls back on error."""from sqlalchemy.exc import SQLAlchemyError@@ -1278,6 +1509,107 @@ class TestGetAllSettingsEnvTypeConversion:assert result["app.host"]["editable"] is False+class TestSnapshotEnvironmentOverrides:+ @pytest.fixture(autouse=True)+ def clean_env(self):+ original_env = {+ key: value+ for key, value in os.environ.items()+ if key.startswith("LDR_")+ }+ for key in list(os.environ):+ if key.startswith("LDR_"):+ os.environ.pop(key)+ yield+ for key in list(os.environ):+ if key.startswith("LDR_"):+ os.environ.pop(key)+ os.environ.update(original_env)++ def test_snapshot_omits_default_only_environment_override(+ self, monkeypatch+ ):+ defaults = {+ "app.port": {+ "value": 5000,+ "ui_element": "number",+ "editable": True,+ "description": "Server port",+ }+ }+ mock_session = MagicMock()+ mock_session.query.return_value.count.return_value = 1+ mock_session.query.return_value.all.return_value = []+ manager = SettingsManager(db_session=mock_session)+ monkeypatch.setenv("LDR_APP_PORT", "8080")++ with patch.object(+ SettingsManager,+ "default_settings",+ new_callable=PropertyMock,+ return_value=defaults,+ ):+ baseline = manager.get_all_settings(+ include_environment_overrides=False+ )+ effective = manager.get_all_settings()++ assert baseline["app.port"] == defaults["app.port"]+ assert effective["app.port"]["value"] == 8080+ assert effective["app.port"]["editable"] is False++ def test_snapshot_omits_db_environment_override_and_dispatch_reapplies_it(+ self, monkeypatch+ ):+ mock_setting = MagicMock()+ mock_setting.key = "app.port"+ mock_setting.value = 5000+ mock_setting.type = "APP"+ mock_setting.name = "Port"+ mock_setting.description = "Server port"+ mock_setting.category = "app"+ mock_setting.ui_element = "number"+ mock_setting.options = None+ mock_setting.min_value = 1+ mock_setting.max_value = 65535+ mock_setting.step = 1+ mock_setting.visible = True+ mock_setting.editable = True++ mock_session = MagicMock()+ mock_session.query.return_value.count.return_value = 1+ mock_session.query.return_value.all.return_value = [mock_setting]+ manager = SettingsManager(db_session=mock_session)+ manager._SettingsManager__settings_locked = False+ monkeypatch.setenv("LDR_APP_PORT", "8080")++ with patch.object(+ SettingsManager,+ "default_settings",+ new_callable=PropertyMock,+ return_value={},+ ):+ baseline = manager.get_all_settings(+ include_environment_overrides=False+ )+ effective = manager.get_all_settings()++ assert baseline["app.port"]["value"] == 5000+ assert baseline["app.port"]["editable"] is True+ assert baseline["app.port"]["name"] == "Port"+ assert effective["app.port"]["value"] == 8080+ assert effective["app.port"]["editable"] is False++ monkeypatch.setenv("LDR_APP_PORT", "9090")+ changed_override = apply_environment_overrides_to_snapshot(baseline)+ assert changed_override["app.port"]["value"] == 9090+ assert changed_override["app.port"]["editable"] is False++ monkeypatch.delenv("LDR_APP_PORT")+ restored = apply_environment_overrides_to_snapshot(baseline)+ assert restored == baseline++class TestGetBoolSettingMethod:"""Tests for get_bool_setting() method on the unified SettingsManager."""@@ -1402,6 +1734,27 @@ class TestCreateOrUpdateSetting:# Should NOT call session.add for update (only for create)mock_session.add.assert_not_called()+ def test_create_or_update_refuses_environment_locked_key_without_mutation(+ self, monkeypatch+ ):+ mock_session = MagicMock()+ mock_session.query.return_value.count.return_value = 1+ manager = SettingsManager(db_session=mock_session)+ manager._SettingsManager__settings_locked = False+ mock_session.reset_mock()+ monkeypatch.setenv("LDR_APP_DEBUG", "true")++ with patch.object(manager, "_emit_settings_changed") as mock_emit:+ result = manager.create_or_update_setting(+ {"key": "app.debug", "value": "new_value", "name": "Debug"}+ )++ assert result is None+ mock_session.query.assert_not_called()+ mock_session.add.assert_not_called()+ mock_session.commit.assert_not_called()+ mock_emit.assert_not_called()+def test_update_non_editable_returns_none(self):"""Bug 3 fix: create_or_update_setting returns None for non-editable settings."""mock_session = MagicMock()diff --git a/tests/settings/test_settings_manager_post_commit_events.py b/tests/settings/test_settings_manager_post_commit_events.pynew file mode 100644index 0000000000..4347f9519b--- /dev/null+++ b/tests/settings/test_settings_manager_post_commit_events.py@@ -0,0 +1,13 @@+from unittest.mock import Mock, patch++from local_deep_research.settings.manager import SettingsManager+++def test_post_commit_settings_event_delegates_to_scoped_emitter():+ manager = SettingsManager(db_session=Mock())+ keys = ["local_search_embedding_model", "local_search_chunk_size"]++ with patch.object(manager, "_emit_settings_changed") as emit:+ manager.emit_settings_changed_after_commit(keys)++ emit.assert_called_once_with(keys)diff --git a/tests/test_api_key_configuration.py b/tests/test_api_key_configuration.pyindex f68c0cdd5b..cce3065319 100644--- a/tests/test_api_key_configuration.py+++ b/tests/test_api_key_configuration.py@@ -126,13 +126,12 @@ class TestAPIKeyConfiguration:# from this minimal snapshot (searxng et al. need an instance# URL), and the research path does create the engine. But# "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 "unprotected" (the escape- # hatch; "both" is retired per ADR-0007) so the test stays- # about LLM-provider config, not egress.+ # egress scope it would resolve to PRIVATE_ONLY and force a+ # local LLM. STRICT limits search to that selected engine but+ # does not impose locality, keeping this test about provider+ # configuration without enabling the unprotected escape hatch."search.tool": "library",- "policy.egress_scope": "unprotected",+ "policy.egress_scope": "strict","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.pyindex 6375bd715b..5b073b6f53 100644--- a/tests/test_llm_provider_integration.py+++ b/tests/test_llm_provider_integration.py@@ -125,12 +125,11 @@ 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 "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.+ # PRIVATE, so use STRICT: it limits search to that selected engine+ # without forcing local inference. This keeps the test about the+ # OpenRouter provider without enabling the unprotected escape hatch.settings_snapshot["search.tool"]["value"] = "library"- settings_snapshot["policy.egress_scope"] = {"value": "unprotected"}+ settings_snapshot["policy.egress_scope"] = {"value": "strict"}# Verify settings are correct - get_all_settings returns nested dictsassert (diff --git a/tests/vector_stores/test_full_migration_lifecycle.py b/tests/vector_stores/test_full_migration_lifecycle.pyindex 450b0574f3..6c1565bde2 100644--- a/tests/vector_stores/test_full_migration_lifecycle.py+++ b/tests/vector_stores/test_full_migration_lifecycle.py@@ -326,6 +326,11 @@ class TestFullMigrationLifecycle:db_password=db_password,embedding_model=embedding_model,embedding_provider=embedding_provider,+ # Match the seeded rag_index row's build config. The expanded+ # index identity (migration 0028) now includes chunk_size/overlap,+ # so a mismatch here would resolve to a different, empty index.+ chunk_size=500,+ chunk_overlap=50,distance_metric="cosine",normalize_vectors=False,index_type="flat",diff --git a/tests/web/queue/test_persisted_search_override_validation.py b/tests/web/queue/test_persisted_search_override_validation.pynew file mode 100644index 0000000000..17d6476673--- /dev/null+++ b/tests/web/queue/test_persisted_search_override_validation.py@@ -0,0 +1,298 @@+from contextlib import nullcontext+from unittest.mock import Mock, patch++import pytest+from sqlalchemy import create_engine+from sqlalchemy.orm import Session, sessionmaker++from local_deep_research.constants import ResearchStatus+from local_deep_research.database.models.active_research import (+ UserActiveResearch,+)+from local_deep_research.database.models.queue import QueueStatus, TaskMetadata+from local_deep_research.database.models.queued_research import QueuedResearch+from local_deep_research.database.models.research import ResearchHistory+from local_deep_research.database.queue_service import UserQueueService+from local_deep_research.exceptions import DuplicateResearchError+from local_deep_research.web.queue.processor_v2 import QueueProcessorV2+++MODULE = "local_deep_research.web.queue.processor_v2"+++def db_session() -> Session:+ engine = create_engine("sqlite:///:memory:")+ QueuedResearch.__table__.create(engine)+ QueueStatus.__table__.create(engine)+ TaskMetadata.__table__.create(engine)+ ResearchHistory.__table__.create(engine)+ UserActiveResearch.__table__.create(engine)+ session = sessionmaker(bind=engine)()++ yield session++ session.close()+ engine.dispose()+++def _persist_queued_research(+ db_session: Session,+ research_id: str,+ settings_snapshot,+) -> QueuedResearch:+ queued = QueuedResearch(+ username="alice",+ research_id=research_id,+ query="persisted override validation",+ mode="quick",+ position=1,+ settings_snapshot=settings_snapshot,+ )+ db_session.add_all(+ [+ queued,+ ResearchHistory(+ id=research_id,+ query=queued.query,+ mode=queued.mode,+ status=ResearchStatus.QUEUED,+ created_at="2026-07-31T00:00:00+00:00",+ ),+ ]+ )+ db_session.commit()+ return queued+++INVALID_PERSISTED_OVERRIDES = (+ pytest.param(+ {+ "submission": {"max_results": 0},+ "submission_overrides": ["max_results"],+ "settings_snapshot": {},+ },+ id="wrapped-max-results",+ ),+ pytest.param(+ {+ "submission": {"time_period": "week"},+ "submission_overrides": ["time_period"],+ "settings_snapshot": {},+ },+ id="wrapped-time-period",+ ),+ pytest.param({"max_results": 51}, id="legacy-flat-max-results"),+ pytest.param({"time_period": "week"}, id="legacy-flat-time-period"),+)++[email protected]("settings_snapshot", INVALID_PERSISTED_OVERRIDES)+def test_invalid_persisted_overrides_are_rejected_before_claim_and_spawn(+ db_session: Session, settings_snapshot+) -> None:+ # Given: a queued record persisted by an older or malformed submission.+ from local_deep_research import exceptions++ research_id = "invalid-persisted"+ queued = _persist_queued_research(+ db_session, research_id, settings_snapshot+ )+ processor = QueueProcessorV2()++ # When: direct queue dispatch reconstructs its runtime overrides.+ with patch(+ f"{MODULE}.start_research_process", return_value=Mock(ident=1)+ ) as start:+ with pytest.raises(+ getattr(+ exceptions, "InvalidQueuedResearchOverridesError", ValueError+ )+ ):+ processor._start_research(db_session, "alice", "password", queued)++ # Then: no IN_PROGRESS claim or process can have been created.+ assert (+ db_session.get(ResearchHistory, research_id).status+ == ResearchStatus.QUEUED+ )+ start.assert_not_called()+ assert (+ db_session.query(UserActiveResearch)+ .filter_by(research_id=research_id)+ .first()+ is None+ )+++ ("max_results", "time_period"),+ ((1, "d"), (50, "all")),+ ids=("minimum-day", "maximum-all-time"),+)+def test_valid_persisted_override_boundaries_reach_the_process(+ db_session: Session, max_results: int, time_period: str+) -> None:+ # Given: a wrapped record with explicit canonical boundary overrides.+ queued = _persist_queued_research(+ db_session,+ f"valid-{max_results}-{time_period}",+ {+ "submission": {+ "max_results": max_results,+ "time_period": time_period,+ },+ "submission_overrides": ["max_results", "time_period"],+ "settings_snapshot": {},+ },+ )++ # When: the persisted record starts.+ with patch(+ f"{MODULE}.start_research_process", return_value=Mock(ident=2)+ ) as start:+ QueueProcessorV2()._start_research(+ db_session, "alice", "password", queued+ )++ # Then: validation permits and preserves both boundary values.+ assert start.call_args.kwargs["max_results"] == max_results+ assert start.call_args.kwargs["time_period"] == time_period+++def test_wrapped_non_effective_invalid_values_remain_deferred(+ db_session: Session,+) -> None:+ # Given: values that look invalid but were not submitted as overrides.+ queued = _persist_queued_research(+ db_session,+ "deferred-values",+ {+ "submission": {+ "model": "queued-model",+ "max_results": 0,+ "time_period": "week",+ },+ "submission_overrides": ["model"],+ "settings_snapshot": {},+ },+ )++ # When: queue dispatch reconstructs only effective submission overrides.+ with patch(+ f"{MODULE}.start_research_process", return_value=Mock(ident=3)+ ) as start:+ QueueProcessorV2()._start_research(+ db_session, "alice", "password", queued+ )++ # Then: deferred snapshot values neither reject nor override runtime defaults.+ call_kwargs = start.call_args.kwargs+ assert call_kwargs["model"] == "queued-model"+ assert "max_results" not in call_kwargs+ assert "time_period" not in call_kwargs+++def test_duplicate_status_precedes_persisted_override_validation(+ db_session: Session,+) -> None:+ # Given: an already-started record with otherwise invalid persisted data.+ queued = _persist_queued_research(+ db_session,+ "duplicate-precedence",+ {+ "submission": {"max_results": 0},+ "submission_overrides": ["max_results"],+ "settings_snapshot": {},+ },+ )+ db_session.get(+ ResearchHistory, "duplicate-precedence"+ ).status = ResearchStatus.IN_PROGRESS+ db_session.commit()+ processor = QueueProcessorV2()++ # When: the queue processor re-enters dispatch for the stale row.+ with patch(f"{MODULE}.start_research_process") as start:+ with pytest.raises(DuplicateResearchError):+ processor._start_research(db_session, "alice", "password", queued)++ # Then: duplicate cleanup retains its existing precedence and never spawns.+ assert (+ db_session.get(ResearchHistory, "duplicate-precedence").status+ == ResearchStatus.IN_PROGRESS+ )+ start.assert_not_called()+++def test_invalid_persisted_row_is_terminal_without_a_retry_or_spawn(+ db_session: Session,+) -> None:+ # Given: a queued task with a stale retry count and an invalid effective override.+ research_id = "invalid-terminal"+ _persist_queued_research(+ db_session,+ research_id,+ {+ "submission": {"max_results": 0},+ "submission_overrides": ["max_results"],+ "settings_snapshot": {},+ },+ )+ db_session.add_all(+ [+ TaskMetadata(+ task_id=research_id, status="queued", task_type="research"+ ),+ QueueStatus(active_tasks=0, queued_tasks=1),+ ]+ )+ db_session.commit()+ processor = QueueProcessorV2()+ processor._spawn_retry_counts[research_id] = 2++ # When: normal queue dispatch reaches the invalid persisted row.+ with (+ patch(+ f"{MODULE}.start_research_process",+ side_effect=AssertionError(+ "invalid persisted overrides must not spawn"+ ),+ ) as start,+ patch(+ f"{MODULE}.get_user_db_session",+ return_value=nullcontext(db_session),+ ),+ patch(+ f"{MODULE}.send_research_failed_notification_from_session"+ ) as send_failed,+ patch.object(+ processor,+ "notify_research_failed",+ wraps=processor.notify_research_failed,+ ) as notify_failed,+ patch.object(+ processor,+ "_bump_spawn_retry_count",+ wraps=processor._bump_spawn_retry_count,+ ) as bump_retry,+ ):+ processor._start_queued_researches(+ db_session, UserQueueService(db_session), "alice", "password", 1+ )++ # Then: invalid data is terminal, while generic retry/capacity behavior stays untouched.+ assert start.call_count == bump_retry.call_count == 0+ assert research_id not in processor._spawn_retry_counts+ research = db_session.get(ResearchHistory, research_id)+ metadata = db_session.get(TaskMetadata, research_id)+ queued_row = (+ db_session.query(QueuedResearch)+ .filter_by(research_id=research_id)+ .first()+ )+ assert (research.status, metadata.status) == 2 * (ResearchStatus.FAILED,)+ assert queued_row is None+ notify_failed.assert_called_once()+ assert notify_failed.call_args.kwargs["research_id"] == research_id+ send_failed.assert_called_once()diff --git a/tests/web/queue/test_processor_v2_real.py b/tests/web/queue/test_processor_v2_real.pyindex c229ddc9c5..4063afdfef 100644--- a/tests/web/queue/test_processor_v2_real.py+++ b/tests/web/queue/test_processor_v2_real.py@@ -600,6 +600,97 @@ class TestStartResearch:assert call_kwargs["strategy"] == "graph-based"assert call_kwargs["settings_snapshot"] == {"setting_a": "value_a"}+ @patch(f"{MODULE}.start_research_process")+ def test_new_format_omitted_settings_are_not_forwarded_as_overrides(+ self, mock_start_research+ ):+ # Given: a queued row whose request supplied only request-scoped limits.+ from local_deep_research.constants import ResearchStatus++ processor = _make_processor()+ mock_start_research.return_value = Mock(ident=12345)+ mock_session = MagicMock()+ mock_research = Mock(status=ResearchStatus.QUEUED)+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research+ queued = Mock(+ research_id="r-deferred",+ query="test query",+ mode="quick",+ settings_snapshot={+ "submission": {+ "model_provider": "enqueue-provider",+ "model": "enqueue-model",+ "search_engine": "enqueue-engine",+ "max_results": 12,+ "time_period": "w",+ "iterations": 3,+ "questions_per_iteration": 2,+ "strategy": "enqueue-strategy",+ },+ "submission_overrides": ["max_results", "time_period"],+ "settings_snapshot": {"search.tool": "snapshot-engine"},+ },+ )++ # When: the queue processor dispatches the row.+ with patch(f"{MODULE}.UserActiveResearch"):+ processor._start_research(mock_session, "alice", "pw", queued)++ # Then: absent configuration keys do not become explicit None/defaults.+ call_kwargs = mock_start_research.call_args.kwargs+ deferred_keys = {+ "model_provider",+ "model",+ "custom_endpoint",+ "search_engine",+ "iterations",+ "questions_per_iteration",+ "strategy",+ }+ assert deferred_keys.isdisjoint(call_kwargs)+ assert call_kwargs["max_results"] == 12+ assert call_kwargs["time_period"] == "w"++ @patch(f"{MODULE}.start_research_process")+ def test_new_format_non_list_submission_overrides_falls_back(+ self, mock_start_research+ ):+ """A malformed (non-list) submission_overrides must not trip the+ substring-membership footgun (`key in "somestring"`). The isinstance+ guard falls back to treating all present submission keys as overrides,+ so a value containing none of the key names still forwards them.+ """+ from local_deep_research.constants import ResearchStatus++ processor = _make_processor()+ mock_start_research.return_value = Mock(ident=12345)+ mock_session = MagicMock()+ mock_research = Mock(status=ResearchStatus.QUEUED)+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research+ queued = Mock(+ research_id="r-malformed-overrides",+ query="test query",+ mode="quick",+ settings_snapshot={+ "submission": {+ "model": "enqueue-model",+ "iterations": 4,+ },+ # Not a list — a corrupted value containing no key names.+ # Without the isinstance guard, `"model" in "xyz"` is False+ # and every key would be dropped instead.+ "submission_overrides": "xyz",+ "settings_snapshot": {"search.tool": "snapshot-engine"},+ },+ )++ with patch(f"{MODULE}.UserActiveResearch"):+ processor._start_research(mock_session, "alice", "pw", queued)++ call_kwargs = mock_start_research.call_args.kwargs+ assert call_kwargs["model"] == "enqueue-model"+ assert call_kwargs["iterations"] == 4+@patch(f"{MODULE}.start_research_process")def test_legacy_format_uses_flat_dict(self, mock_start_research):"""Legacy format: flat dict used as submission_params."""@@ -931,6 +1022,138 @@ class TestStartResearch:assert "r-uar-fail" not in processor._spawn_retry_counts+# ---------------------------------------------------------------------------+# Queue extraction — what `_start_research` forwards to the worker+# ---------------------------------------------------------------------------+++class TestStartResearchExtraction:+ """Queue-to-worker extraction seam: what `_start_research` forwards.++ Policy coercion is the WORKER's job — exercised below via+ `build_run_egress_context`, not reimplemented here.+ """++ @patch(f"{MODULE}.start_research_process")+ def test_wrapped_snapshot_subdict_forwarded_verbatim(self, mock_start):+ # Wrapped: the inner subdict is forwarded verbatim, including any+ # stale policy.egress_scope — coercion is the worker's job.+ from local_deep_research.constants import ResearchStatus++ processor = _make_processor()+ mock_start.return_value = Mock(ident=1)+ session = MagicMock()+ research = Mock(status=ResearchStatus.QUEUED)+ session.query.return_value.filter_by.return_value.first.return_value = (+ research+ )+ queued = Mock(+ research_id="r-wrapped",+ query="q",+ mode="quick",+ settings_snapshot={+ "submission": {+ "model_provider": "ollama",+ "model": "llama3",+ "search_engine": "pubmed",+ },+ "settings_snapshot": {+ "policy.egress_scope": "unprotected",+ "search.tool": "pubmed",+ },+ },+ )++ with patch(f"{MODULE}.UserActiveResearch"):+ processor._start_research(session, "alice", "pw", queued)++ dispatched = mock_start.call_args.kwargs["settings_snapshot"]+ assert dispatched.get("policy.egress_scope") == "unprotected"+ assert dispatched.get("search.tool") == "pubmed"++ @patch(f"{MODULE}.start_research_process")+ def test_legacy_flat_drops_policy_egress_scope(self, mock_start):+ # Legacy flat: only search.tool is seeded; the top-level+ # policy.egress_scope is dropped at extraction.+ from local_deep_research.constants import ResearchStatus++ processor = _make_processor()+ mock_start.return_value = Mock(ident=1)+ session = MagicMock()+ research = Mock(status=ResearchStatus.QUEUED)+ session.query.return_value.filter_by.return_value.first.return_value = (+ research+ )+ queued = Mock(+ research_id="r-flat",+ query="q",+ mode="quick",+ settings_snapshot={+ "policy.egress_scope": "unprotected",+ "search_engine": "pubmed",+ "model_provider": "ollama",+ "model": "llama3",+ },+ )++ with patch(f"{MODULE}.UserActiveResearch"):+ processor._start_research(session, "alice", "pw", queued)++ dispatched = mock_start.call_args.kwargs["settings_snapshot"]+ assert "policy.egress_scope" not in dispatched+ assert dispatched == {"search.tool": "pubmed"}+++# ---------------------------------------------------------------------------+# Worker policy setup — `build_run_egress_context` (the production seam+# `run_research_process` invokes at startup)+# ---------------------------------------------------------------------------+++class TestWorkerBuildRunEgressContext:+ """Worker policy seam: `build_run_egress_context` is the helper+ `run_research_process` calls at startup to overlay current operator+ env policy and construct the per-run EgressContext. The read-time+ backstop in `context_from_snapshot` coerces a stale operator-disabled+ ``unprotected`` scope HERE — these tests fail if the helper is weakened+ or the backstop is removed.+ """++ def test_wrapped_stale_unprotected_coerced_when_gate_off(self, monkeypatch):+ # Gate OFF (default): stale unprotected must not survive.+ from local_deep_research.security.egress import (+ EgressScope,+ build_run_egress_context,+ )++ monkeypatch.delenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", raising=False)+ monkeypatch.delenv("LDR_POLICY_EGRESS_SCOPE", raising=False)++ snapshot = {+ "policy.egress_scope": "unprotected",+ "search.tool": "pubmed",+ }+ ctx = build_run_egress_context(snapshot, "pubmed", username="alice")+ assert ctx.scope is not EgressScope.UNPROTECTED++ def test_legacy_partial_snapshot_resolves_to_protected_default(+ self, monkeypatch+ ):+ # Gate OFF: a near-empty legacy snapshot resolves via the+ # registry-default adaptive scope — never UNPROTECTED.+ from local_deep_research.security.egress import (+ EgressScope,+ build_run_egress_context,+ )++ monkeypatch.delenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", raising=False)+ monkeypatch.delenv("LDR_POLICY_EGRESS_SCOPE", raising=False)++ snapshot = {"search.tool": "pubmed"} # legacy extraction output+ ctx = build_run_egress_context(snapshot, "pubmed", username="alice")+ assert ctx.scope is not EgressScope.UNPROTECTED++# ---------------------------------------------------------------------------# process_pending_operations_for_user — progress/error updates, rollback# ---------------------------------------------------------------------------diff --git a/tests/web/routes/test_metrics_routes.py b/tests/web/routes/test_metrics_routes.pyindex e10798e67d..a390da1a47 100644--- a/tests/web/routes/test_metrics_routes.py+++ b/tests/web/routes/test_metrics_routes.py@@ -1377,6 +1377,13 @@ class TestApiJournalDataDownload:rate-limited, CSRF-protected, multi-GB rebuild trigger."""+ @pytest.fixture+ def journal_download_client(self, authenticated_client, monkeypatch):+ from local_deep_research.security.rate_limiter import limiter++ monkeypatch.setattr(limiter, "enabled", False)+ return authenticated_client+def test_requires_authentication(self, client):response = client.post(f"{METRICS_PREFIX}/api/journal-data/download",@@ -1453,20 +1460,83 @@ class TestApiJournalDataDownload:assert "42" in data["message"]def test_refused_under_private_only_egress_scope(- self, authenticated_client+ self, journal_download_client):"""Under an offline-for-public scope (PRIVATE_ONLY) the manualjournal-data download must be refused (403) BEFORE any public HTTP- fetch — the user opted out of public egress. The downloader is- intentionally NOT mocked: if the gate works it is never reached.+ fetch — the user opted out of public egress."""mgr = MagicMock()mgr.get_setting.side_effect = lambda key, default=None: ("private_only" if key == "policy.egress_scope" else default)- with patch(- "local_deep_research.utilities.db_utils.get_settings_manager",- return_value=mgr,+ with (+ patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mgr,+ ),+ patch(+ "local_deep_research.journal_quality.downloader.download_journal_data"+ ) as download,+ ):+ response = journal_download_client.post(+ f"{METRICS_PREFIX}/api/journal-data/download",+ json={"force": False},+ )+ assert response.status_code == 403, response.status_code+ assert response.get_json()["success"] is False+ download.assert_not_called()++ def test_refused_under_strict_egress_scope(self, journal_download_client):+ """STRICT is likewise an offline-for-public scope here."""+ mgr = MagicMock()+ mgr.get_setting.side_effect = lambda key, default=None: (+ "strict" if key == "policy.egress_scope" else default+ )+ with (+ patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mgr,+ ),+ patch(+ "local_deep_research.journal_quality.downloader.download_journal_data"+ ) as download,+ ):+ response = journal_download_client.post(+ f"{METRICS_PREFIX}/api/journal-data/download",+ json={"force": False},+ )+ assert response.status_code == 403, response.status_code+ download.assert_not_called()++ def test_stale_unprotected_scope_with_gate_off_is_treated_as_adaptive(+ self, authenticated_client, monkeypatch+ ):+ """A stored "unprotected" row left over from when the operator gate+ was enabled must read as the coerced adaptive scope once the gate is+ off — the same fallback every other runtime reader applies via+ parse_user_egress_scope. Adaptive is not offline-for-public here, so+ the (mocked) download proceeds rather than being refused or honored+ as raw UNPROTECTED.+ """+ monkeypatch.delenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", raising=False)+ mgr = MagicMock()+ mgr.get_setting.side_effect = lambda key, default=None: (+ "unprotected" if key == "policy.egress_scope" else default+ )+ with (+ patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mgr,+ ),+ patch(+ "local_deep_research.journal_quality.downloader.download_journal_data",+ return_value=(True, "Journal data is already up to date"),+ ),+ patch(+ "local_deep_research.journal_quality.downloader.get_download_state",+ return_value={"counts": None},+ ),):response = authenticated_client.post(f"{METRICS_PREFIX}/api/journal-data/download",@@ -1476,18 +1546,55 @@ class TestApiJournalDataDownload:pytest.skip(f"Route gated by CSRF/rate-limit (status={response.status_code})")+ assert response.status_code == 200, response.status_code++ def test_refused_under_corrupt_egress_scope(self, journal_download_client):+ """An unparseable stored scope fails closed (403)."""+ mgr = MagicMock()+ mgr.get_setting.side_effect = lambda key, default=None: (+ "no-such-scope" if key == "policy.egress_scope" else default+ )+ with (+ patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mgr,+ ),+ patch(+ "local_deep_research.journal_quality.downloader.download_journal_data"+ ) as download,+ ):+ response = journal_download_client.post(+ f"{METRICS_PREFIX}/api/journal-data/download",+ json={"force": False},+ )assert response.status_code == 403, response.status_code- assert response.get_json()["success"] is False+ download.assert_not_called()- def test_refused_under_strict_egress_scope(self, authenticated_client):- """STRICT is likewise an offline-for-public scope here."""+ def test_retired_both_scope_is_treated_as_adaptive(+ self, authenticated_client+ ):+ """A residual "both" value (un-migrated row or env override) reads+ as the adaptive default — the same read-time backstop+ context_from_snapshot applies — so the download proceeds instead of+ failing closed as an unknown scope.+ """mgr = MagicMock()mgr.get_setting.side_effect = lambda key, default=None: (- "strict" if key == "policy.egress_scope" else default+ "both" if key == "policy.egress_scope" else default)- with patch(- "local_deep_research.utilities.db_utils.get_settings_manager",- return_value=mgr,+ with (+ patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mgr,+ ),+ patch(+ "local_deep_research.journal_quality.downloader.download_journal_data",+ return_value=(True, "Journal data is already up to date"),+ ),+ patch(+ "local_deep_research.journal_quality.downloader.get_download_state",+ return_value={"counts": None},+ ),):response = authenticated_client.post(f"{METRICS_PREFIX}/api/journal-data/download",@@ -1497,7 +1604,43 @@ class TestApiJournalDataDownload:pytest.skip(f"Route gated by CSRF/rate-limit (status={response.status_code})")- assert response.status_code == 403, response.status_code+ assert response.status_code == 200, response.status_code++ def test_whitespace_padded_scope_parses_via_shared_helper(+ self, authenticated_client+ ):+ """ " PUBLIC_ONLY " (padding/case noise) must normalize and allow the+ download. The previous raw EgressScope(...) construction did not+ strip, so it spuriously refused such values as corrupt — this pins+ the switch to parse_user_egress_scope.+ """+ mgr = MagicMock()+ mgr.get_setting.side_effect = lambda key, default=None: (+ " PUBLIC_ONLY " if key == "policy.egress_scope" else default+ )+ with (+ patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mgr,+ ),+ patch(+ "local_deep_research.journal_quality.downloader.download_journal_data",+ return_value=(True, "Journal data is already up to date"),+ ),+ patch(+ "local_deep_research.journal_quality.downloader.get_download_state",+ return_value={"counts": None},+ ),+ ):+ response = authenticated_client.post(+ f"{METRICS_PREFIX}/api/journal-data/download",+ json={"force": False},+ )+ if response.status_code in (302, 400, 429):+ pytest.skip(+ f"Route gated by CSRF/rate-limit (status={response.status_code})"+ )+ assert response.status_code == 200, response.status_codedef test_response_up_to_date_message_when_counts_none(self, authenticated_clientdiff --git a/tests/web/routes/test_research_routes_extracted_helpers.py b/tests/web/routes/test_research_routes_extracted_helpers.pyindex 70fb644bab..0cb328a077 100644--- a/tests/web/routes/test_research_routes_extracted_helpers.py+++ b/tests/web/routes/test_research_routes_extracted_helpers.py@@ -894,7 +894,7 @@ class TestStartResearchHappyPath:"model": "llama3","search_engine": "tavily","max_results": 15,- "time_period": "30d",+ "time_period": "m","iterations": 3,"questions_per_iteration": 2,"strategy": "comprehensive",@@ -911,7 +911,7 @@ class TestStartResearchHappyPath:assert kwargs["model"] == "llama3"assert kwargs["search_engine"] == "tavily"assert kwargs["max_results"] == 15- assert kwargs["time_period"] == "30d"+ assert kwargs["time_period"] == "m"assert kwargs["iterations"] == 3assert kwargs["questions_per_iteration"] == 2assert kwargs["strategy"] == "comprehensive"@@ -946,6 +946,64 @@ class TestStartResearchHappyPath:create_kwargs = mock_rh.call_args[1]assert create_kwargs["status"] == ResearchStatus.QUEUED+ def test_queued_submission_omits_resolved_setting_defaults(+ self, client, app+ ):+ # Given: defaults resolved during enqueue differ from the persisted snapshot.+ ms = _mock_db_session(active_count=5)+ sm = _make_settings_manager(+ {+ "llm.provider": "enqueue-provider",+ "llm.model": "enqueue-model",+ "search.tool": "enqueue-engine",+ "search.iterations": 7,+ "search.questions_per_iteration": 8,+ "search.search_strategy": "enqueue-strategy",+ }+ )++ @app.before_request+ def _inject_g():+ g.db_session = ms++ # When: the client queues a request without configuration overrides.+ with (+ patch(_GET_USER_DB, side_effect=_ctx_factory(ms)),+ patch(_SM_MANAGER, return_value=sm),+ patch(_SM_SETTINGS, return_value=sm),+ patch(f"{MODULE}.ResearchHistory"),+ patch(f"{MODULE}.QueuedResearch") as mock_queued,+ patch(_QP),+ ):+ response = client.post(+ "/api/start_research",+ json={+ "query": "queued topic",+ "metadata": {+ "submission": {"search_engine": "attacker-engine"},+ "submission_overrides": ["search_engine"],+ "system": {"user": "attacker"},+ "client_tag": "retained",+ },+ },+ content_type="application/json",+ )++ # Then: resolved values remain available as provenance, but none are+ # treated as fixed per-run overrides.+ assert response.status_code == 200+ queued_snapshot = mock_queued.call_args.kwargs["settings_snapshot"]+ submission = queued_snapshot["submission"]+ assert submission["model_provider"] == "enqueue-provider"+ assert submission["model"] == "enqueue-model"+ assert submission["search_engine"] == "enqueue-engine"+ assert submission["iterations"] == 7+ assert submission["questions_per_iteration"] == 8+ assert submission["strategy"] == "enqueue-strategy"+ assert queued_snapshot["submission_overrides"] == []+ assert queued_snapshot["system"]["user"] == "testuser"+ assert queued_snapshot["client_tag"] == "retained"+def test_non_queued_research_has_in_progress_status(self, client, app):"""When should_queue=False, ResearchHistory is created with IN_PROGRESS status."""ms = _mock_db_session(active_count=0)diff --git a/tests/web/routes/test_research_routes_policy.py b/tests/web/routes/test_research_routes_policy.pyindex 7c786c47eb..b7abbd943a 100644--- a/tests/web/routes/test_research_routes_policy.py+++ b/tests/web/routes/test_research_routes_policy.py@@ -14,6 +14,7 @@ from unittest.mock import Mockimport pytestfrom flask import Flask+from local_deep_research.security.egress.policy import PolicyDeniedErrorfrom local_deep_research.web.routes.research_routes import (_apply_policy_overrides,_precheck_engine_policy,@@ -31,6 +32,26 @@ class TestApplyPolicyOverrides:_apply_policy_overrides(snap, {"policy_egress_scope": "private_only"})assert snap["policy.egress_scope"] == "private_only"+ def test_unprotected_override_disabled_by_default(self):+ with pytest.raises(PolicyDeniedError) as exc_info:+ _apply_policy_overrides(+ {"policy.egress_scope": "adaptive"},+ {"policy_egress_scope": "unprotected"},+ )+ assert exc_info.value.decision.reason == "unprotected_egress_disabled"++ def test_unprotected_override_requires_operator_opt_in(self, monkeypatch):+ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")+ snap = {"policy.egress_scope": "adaptive"}+ _apply_policy_overrides(snap, {"policy_egress_scope": "unprotected"})+ assert snap["policy.egress_scope"] == "unprotected"++ def test_environment_scope_cannot_be_overridden(self, monkeypatch):+ monkeypatch.setenv("LDR_POLICY_EGRESS_SCOPE", "private_only")+ snap = {"policy.egress_scope": "private_only"}+ _apply_policy_overrides(snap, {"policy_egress_scope": "public_only"})+ assert snap["policy.egress_scope"] == "private_only"+def test_bool_overrides_coerced(self):snap = {}_apply_policy_overrides(@@ -44,6 +65,41 @@ class TestApplyPolicyOverrides:# Empty string is falsy => coerced to False.assert snap["embeddings.require_local"] is False+ @pytest.mark.parametrize(+ ("env_key", "snapshot_key", "param_key"),+ [+ (+ "LDR_LLM_REQUIRE_LOCAL_ENDPOINT",+ "llm.require_local_endpoint",+ "llm_require_local_endpoint",+ ),+ (+ "LDR_EMBEDDINGS_REQUIRE_LOCAL",+ "embeddings.require_local",+ "embeddings_require_local",+ ),+ ],+ )+ def test_environment_locality_flags_cannot_be_weakened(+ self, monkeypatch, env_key, snapshot_key, param_key+ ):+ monkeypatch.setenv(env_key, "true")+ snap = {snapshot_key: True}+ _apply_policy_overrides(snap, {param_key: False})+ assert snap[snapshot_key] is True++ def test_string_false_boolean_override_is_false(self):+ snap = {}+ _apply_policy_overrides(+ snap,+ {+ "llm_require_local_endpoint": "false",+ "embeddings_require_local": "0",+ },+ )+ assert snap["llm.require_local_endpoint"] is False+ assert snap["embeddings.require_local"] is False+def test_absent_params_leave_snapshot_untouched(self):snap = {"policy.egress_scope": "both"}_apply_policy_overrides(snap, {})@@ -89,6 +145,18 @@ class TestPrecheckEnginePolicy:result = _precheck_engine_policy(mgr, {}, "arxiv", "user")assert result is None+ def test_disabled_unprotected_override_returns_400(self, app_ctx):+ mgr = _mgr({"policy.egress_scope": "private_only"})+ result = _precheck_engine_policy(+ mgr, {"policy_egress_scope": "unprotected"}, "pubmed", "user"+ )+ assert result is not None+ response, status = result+ assert status == 400+ assert response.get_json()["message"].endswith(+ "unprotected_egress_disabled"+ )+def test_forbidden_engine_response_flags_egress_scope_field(self, app_ctx):# The 400 must tell the frontend WHICH field to highlight so the error# can be shown inline on the Egress Scope dropdown (not just as a@@ -262,7 +330,8 @@ class TestPrecheckEnginePolicy:)assert result is None- def test_unprotected_scope_bypasses_two_axis(self, app_ctx):+ def test_unprotected_scope_bypasses_two_axis(self, app_ctx, monkeypatch):+ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")# The escape hatch: the otherwise-denied combo is permitted under# UNPROTECTED (audit_run evaluates permissive), so no 400.mgr = _mgr(diff --git a/tests/web/routes/test_research_routes_start_research_coverage.py b/tests/web/routes/test_research_routes_start_research_coverage.pyindex 18df0d1d5c..b1b7b73889 100644--- a/tests/web/routes/test_research_routes_start_research_coverage.py+++ b/tests/web/routes/test_research_routes_start_research_coverage.py@@ -259,6 +259,10 @@ class TestStartResearchSettingsFromDb:data = resp.get_json()assert data["status"] == "success"assert "research_id" in data+ sm.get_all_settings.assert_called_once_with(+ bypass_cache=True,+ include_environment_overrides=False,+ )class TestStartResearchMissingQuery:@@ -625,6 +629,10 @@ class TestStartResearchNoGDbSession:assert resp.status_code == 200data = resp.get_json()assert data["status"] == "success"+ sm.get_all_settings.assert_called_once_with(+ bypass_cache=True,+ include_environment_overrides=False,+ )class TestStartResearchSnapshotFailure:diff --git a/tests/web/routes/test_settings_routes.py b/tests/web/routes/test_settings_routes.pyindex e5955d3c1b..bff41572a6 100644--- a/tests/web/routes/test_settings_routes.py+++ b/tests/web/routes/test_settings_routes.py@@ -166,6 +166,186 @@ class TestSettingsBlueprintImport:assert settings_bp.name == "settings"+class TestEgressScopeMetadataShaping:+ def test_disabled_gate_hides_unprotected_and_normalizes_legacy_value(self):+ from local_deep_research.web.routes.settings_routes import (+ _shape_egress_scope_metadata,+ )++ settings = {+ "policy.egress_scope": {+ "value": "unprotected",+ "options": [+ {"value": "adaptive", "label": "Adaptive"},+ {"value": "unprotected", "label": "Unprotected"},+ ],+ }+ }+ shaped = _shape_egress_scope_metadata(settings)+ assert shaped["policy.egress_scope"]["value"] == "adaptive"+ assert [+ option["value"]+ for option in shaped["policy.egress_scope"]["options"]+ ] == ["adaptive"]++ def test_enabled_gate_keeps_unprotected(self, monkeypatch):+ from local_deep_research.web.routes.settings_routes import (+ _shape_egress_scope_metadata,+ )++ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")+ settings = {+ "policy.egress_scope": {+ "value": "unprotected",+ "options": [{"value": "unprotected", "label": "Unprotected"}],+ }+ }+ assert _shape_egress_scope_metadata(settings) == settings++ def test_scope_write_is_canonicalized(self):+ from local_deep_research.web.routes.settings_routes import (+ coerce_setting_for_write,+ )++ assert (+ coerce_setting_for_write(+ "policy.egress_scope", " STRICT ", "select"+ )+ == "strict"+ )++ def test_scope_metadata_uses_environment_effective_value(self, monkeypatch):+ from local_deep_research.web.routes.settings_routes import (+ _shape_egress_scope_metadata,+ )++ monkeypatch.setenv("LDR_POLICY_EGRESS_SCOPE", "strict")+ shaped = _shape_egress_scope_metadata(+ {"policy.egress_scope": {"value": "adaptive", "editable": True}}+ )+ assert shaped["policy.egress_scope"] == {+ "value": "strict",+ "editable": False,+ }++ def test_effective_metadata_shapes_locality_environment_lock(+ self, monkeypatch+ ):+ from local_deep_research.web.routes.settings_routes import (+ _shape_effective_setting_metadata,+ )++ monkeypatch.setenv("LDR_LLM_REQUIRE_LOCAL_ENDPOINT", "true")+ shaped = _shape_effective_setting_metadata(+ {+ "llm.require_local_endpoint": {+ "value": False,+ "editable": True,+ "ui_element": "checkbox",+ }+ }+ )+ assert shaped["llm.require_local_endpoint"]["value"] is True+ assert shaped["llm.require_local_endpoint"]["editable"] is False++ def test_effective_metadata_falls_back_on_malformed_typed_env(+ self, monkeypatch+ ):+ from local_deep_research.web.routes.settings_routes import (+ _shape_effective_setting_metadata,+ )++ monkeypatch.setenv("LDR_SEARCH_ITERATIONS", "not-a-number")+ shaped = _shape_effective_setting_metadata(+ {+ "search.iterations": {+ "value": 4,+ "editable": True,+ "ui_element": "number",+ }+ }+ )+ assert shaped["search.iterations"]["value"] == 4+ assert shaped["search.iterations"]["editable"] is False+++class TestModelDiscoveryPolicy:+ MODULE = "local_deep_research.web.routes.settings_routes"++ @staticmethod+ def _make_sm(scope="unprotected", primary="library", require_local=False):+ sm = MagicMock()+ values = {+ "llm.require_local_endpoint": require_local,+ "policy.egress_scope": scope,+ "search.tool": primary,+ }+ sm.get_setting.side_effect = lambda key, default=None: values.get(+ key, default+ )+ sm.get_settings_snapshot.return_value = dict(values)+ return sm++ def _run(self, sm):+ from contextlib import contextmanager+ from local_deep_research.web.routes import settings_routes++ @contextmanager+ def _fake_db(*a, **kw):+ yield True++ with (+ patch(f"{self.MODULE}.session", {"username": "alice"}),+ patch(f"{self.MODULE}.get_user_db_session", side_effect=_fake_db),+ patch(f"{self.MODULE}.get_settings_manager", return_value=sm),+ ):+ return settings_routes._resolve_model_discovery_policy()[+ 0+ ].require_local_llm++ def test_disabled_gate_unprotected_with_private_primary_is_local(+ self, monkeypatch+ ):+ from local_deep_research.security.egress.policy import PolicyDeniedError++ monkeypatch.delenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", raising=False)+ sm = self._make_sm(scope="unprotected", primary="library")+ with pytest.raises(PolicyDeniedError) as exc_info:+ self._run(sm)+ assert exc_info.value.decision.reason == "unprotected_egress_disabled"++ def test_enabled_gate_unprotected_stays_permissive(self, monkeypatch):+ """Control: with the operator gate enabled, raw ``unprotected`` stays+ ``unprotected`` (permissive) — discovery is NOT local-only."""+ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")+ sm = self._make_sm(scope="unprotected", primary="library")+ assert self._run(sm) is False++ def test_explicit_private_only_is_local(self):+ """Existing behaviour: explicit ``private_only`` → local-only."""+ sm = self._make_sm(scope="private_only", primary="library")+ assert self._run(sm) is True++ def test_explicit_adaptive_with_private_primary_is_local(self):+ """Existing behaviour: explicit ``adaptive`` + ``library`` primary →+ resolves PRIVATE_ONLY → local-only."""+ sm = self._make_sm(scope="adaptive", primary="library")+ assert self._run(sm) is True++ def test_public_only_is_not_local(self):+ """Existing behaviour: ``public_only`` → not local-only."""+ sm = self._make_sm(scope="public_only", primary="searxng")+ assert self._run(sm) is False++ def test_require_local_endpoint_toggle_forces_local(self):+ """Existing behaviour: the ``llm.require_local_endpoint`` toggle+ forces local-only regardless of scope."""+ sm = self._make_sm(+ scope="public_only", primary="searxng", require_local=True+ )+ assert self._run(sm) is True++class TestSettingsPageRoutes:"""Tests for settings page routes."""@@ -1091,3 +1271,453 @@ class TestApiUpdateSettingTypeConversion:json={"value": original["value"]},content_type="application/json",)+++class TestApiRecreateEgressSettingValidation:+ """Deleted governed settings must not bypass validation on recreation."""++ def test_delete_then_put_rejects_disabled_unprotected(+ self, authenticated_client, monkeypatch+ ):+ monkeypatch.delenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", raising=False)+ key = "policy.egress_scope"+ assert (+ authenticated_client.delete(+ f"{SETTINGS_PREFIX}/api/{key}"+ ).status_code+ == 200+ )++ response = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/{key}",+ json={"value": "unprotected", "ui_element": "text"},+ )++ assert response.status_code == 400+ assert "disabled" in response.get_json()["error"].lower()++ def test_delete_then_put_rejects_public_local_hostname(+ self, authenticated_client+ ):+ key = "llm.allowed_local_hostnames"+ assert (+ authenticated_client.delete(+ f"{SETTINGS_PREFIX}/api/{key}"+ ).status_code+ == 200+ )++ with (+ patch(+ "local_deep_research.security.egress.validators._resolve_with_timeout",+ return_value=[object()],+ ),+ patch(+ "local_deep_research.security.egress.validators._classify_host",+ return_value=False,+ ),+ ):+ response = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/{key}",+ json={"value": ["example.com"], "ui_element": "json"},+ )++ assert response.status_code == 400+ assert "public" in response.get_json()["error"].lower()++ def test_delete_then_put_rejects_public_trusted_engine(+ self, authenticated_client+ ):+ key = "policy.trusted_search_engines"+ assert (+ authenticated_client.delete(+ f"{SETTINGS_PREFIX}/api/{key}"+ ).status_code+ == 200+ )++ response = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/{key}",+ json={"value": ["searxng"], "ui_element": "json"},+ )++ assert response.status_code == 400+ assert "public" in response.get_json()["error"].lower()++ def test_registered_json_value_is_coerced_and_metadata_is_trusted(+ self, authenticated_client+ ):+ key = "llm.allowed_local_hostnames"+ assert (+ authenticated_client.delete(+ f"{SETTINGS_PREFIX}/api/{key}"+ ).status_code+ == 200+ )+ with (+ patch(+ "local_deep_research.security.egress.validators._resolve_with_timeout",+ return_value=[object()],+ ),+ patch(+ "local_deep_research.security.egress.validators._classify_host",+ return_value=True,+ ),+ ):+ response = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/{key}",+ json={+ "value": '["localhost"]',+ "ui_element": "text",+ "editable": False,+ },+ )+ assert response.status_code == 201+ assert response.get_json()["setting"]["value"] == ["localhost"]+ detail = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/{key}"+ ).get_json()+ assert detail["ui_element"] == "json"+ assert detail["editable"] is True+ assert detail["type"] == "llm"++ def test_registered_checkbox_is_coerced(self, authenticated_client):+ key = "llm.require_local_endpoint"+ assert (+ authenticated_client.delete(+ f"{SETTINGS_PREFIX}/api/{key}"+ ).status_code+ == 200+ )+ response = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/{key}",+ json={"value": "false", "ui_element": "number"},+ )+ assert response.status_code == 201+ assert response.get_json()["setting"]["value"] is False+ detail = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/{key}"+ ).get_json()+ assert detail["ui_element"] == "checkbox"+ assert detail["type"] == "llm"++ def test_registered_numeric_bounds_are_enforced(self, authenticated_client):+ key = "search.iterations"+ assert (+ authenticated_client.delete(+ f"{SETTINGS_PREFIX}/api/{key}"+ ).status_code+ == 200+ )+ response = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/{key}",+ json={"value": 0, "ui_element": "text", "min_value": -100},+ )+ assert response.status_code == 400++ def test_registered_policy_setting_can_be_safely_recreated(+ self, authenticated_client+ ):+ key = "policy.egress_scope"+ assert (+ authenticated_client.delete(+ f"{SETTINGS_PREFIX}/api/{key}"+ ).status_code+ == 200+ )+ response = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/{key}",+ json={+ "value": "adaptive",+ "type": "APP",+ "ui_element": "text",+ "options": [],+ },+ )+ assert response.status_code == 201+ detail = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/{key}"+ ).get_json()+ assert detail["value"] == "adaptive"+ assert detail["type"] == "search"+ assert detail["ui_element"] == "select"+ assert detail["options"]+++class TestEgressScopeWriteRouteIntegration:+ """Every persisted write route must enforce the operator gate."""++ def test_put_rejects_unprotected_when_gate_disabled(+ self, authenticated_client, monkeypatch+ ):+ monkeypatch.delenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", raising=False)+ response = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/policy.egress_scope",+ json={"value": "unprotected"},+ )+ assert response.status_code == 400+ stored = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/policy.egress_scope"+ ).get_json()["value"]+ assert stored != "unprotected"++ def test_save_all_rejects_unprotected_when_gate_disabled(+ self, authenticated_client, monkeypatch+ ):+ monkeypatch.delenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", raising=False)+ response = authenticated_client.post(+ f"{SETTINGS_PREFIX}/save_all_settings",+ json={"policy.egress_scope": "unprotected"},+ )+ assert response.status_code == 400+ stored = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/policy.egress_scope"+ ).get_json()["value"]+ assert stored != "unprotected"++ def test_save_all_persists_unprotected_when_gate_enabled(+ self, authenticated_client, monkeypatch+ ):+ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")+ response = authenticated_client.post(+ f"{SETTINGS_PREFIX}/save_all_settings",+ json={"policy.egress_scope": "unprotected"},+ )+ assert response.status_code == 200+ stored = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/policy.egress_scope"+ ).get_json()["value"]+ assert stored == "unprotected"++ def test_form_save_rejects_unprotected_when_gate_disabled(+ self, authenticated_client, monkeypatch+ ):+ monkeypatch.delenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", raising=False)+ response = authenticated_client.post(+ f"{SETTINGS_PREFIX}/save_settings",+ data={"policy.egress_scope": "unprotected"},+ follow_redirects=True,+ )+ assert response.status_code == 200+ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")+ stored = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/policy.egress_scope"+ ).get_json()["value"]+ assert stored != "unprotected"++ def test_put_persists_unprotected_when_gate_enabled(+ self, authenticated_client, monkeypatch+ ):+ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")+ response = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/policy.egress_scope",+ json={"value": "unprotected"},+ )+ assert response.status_code == 200+ stored = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/policy.egress_scope"+ ).get_json()["value"]+ assert stored == "unprotected"++ @pytest.mark.parametrize(+ ("key", "env_key", "env_value"),+ [+ ("policy.egress_scope", "LDR_POLICY_EGRESS_SCOPE", "strict"),+ (+ "llm.require_local_endpoint",+ "LDR_LLM_REQUIRE_LOCAL_ENDPOINT",+ "true",+ ),+ (+ "embeddings.require_local",+ "LDR_EMBEDDINGS_REQUIRE_LOCAL",+ "true",+ ),+ ],+ )+ def test_single_setting_mutations_reject_environment_locks(+ self, authenticated_client, monkeypatch, key, env_key, env_value+ ):+ monkeypatch.setenv(env_key, env_value)+ put_response = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/{key}", json={"value": "adaptive"}+ )+ delete_response = authenticated_client.delete(+ f"{SETTINGS_PREFIX}/api/{key}"+ )+ assert put_response.status_code == 403+ assert delete_response.status_code == 403++ @pytest.mark.parametrize(+ ("key", "env_key", "env_value"),+ [+ ("policy.egress_scope", "LDR_POLICY_EGRESS_SCOPE", "strict"),+ (+ "llm.require_local_endpoint",+ "LDR_LLM_REQUIRE_LOCAL_ENDPOINT",+ "true",+ ),+ (+ "embeddings.require_local",+ "LDR_EMBEDDINGS_REQUIRE_LOCAL",+ "true",+ ),+ ],+ )+ @pytest.mark.parametrize("route_kind", ["json", "form"])+ def test_bulk_writes_preserve_environment_locked_database_value(+ self,+ authenticated_client,+ monkeypatch,+ key,+ env_key,+ env_value,+ route_kind,+ ):+ before = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/{key}"+ ).get_json()["value"]+ if key == "policy.egress_scope":+ attempted = "strict" if before != "strict" else "adaptive"+ else:+ attempted = not bool(before)++ monkeypatch.setenv(env_key, env_value)+ if route_kind == "json":+ response = authenticated_client.post(+ f"{SETTINGS_PREFIX}/save_all_settings",+ json={key: attempted},+ )+ assert response.status_code == 200+ else:+ response = authenticated_client.post(+ f"{SETTINGS_PREFIX}/save_settings",+ data={key: str(attempted).lower()},+ )+ assert response.status_code == 302++ monkeypatch.delenv(env_key)+ after = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/{key}"+ ).get_json()["value"]+ assert after == before++ @pytest.mark.parametrize(+ ("key", "env_key", "env_value", "persisted_value"),+ [+ (+ "policy.egress_scope",+ "LDR_POLICY_EGRESS_SCOPE",+ "adaptive",+ "strict",+ ),+ (+ "llm.require_local_endpoint",+ "LDR_LLM_REQUIRE_LOCAL_ENDPOINT",+ "false",+ True,+ ),+ (+ "embeddings.require_local",+ "LDR_EMBEDDINGS_REQUIRE_LOCAL",+ "false",+ True,+ ),+ ],+ )+ @pytest.mark.parametrize("endpoint", ["/reset_to_defaults", "/api/import"])+ def test_defaults_import_preserves_environment_locked_database_value(+ self,+ authenticated_client,+ monkeypatch,+ key,+ env_key,+ env_value,+ persisted_value,+ endpoint,+ ):+ setup_response = authenticated_client.put(+ f"{SETTINGS_PREFIX}/api/{key}",+ json={"value": persisted_value},+ )+ assert setup_response.status_code == 200++ monkeypatch.setenv(env_key, env_value)+ response = authenticated_client.post(f"{SETTINGS_PREFIX}{endpoint}")+ assert response.status_code == 200++ monkeypatch.delenv(env_key)+ stored = authenticated_client.get(+ f"{SETTINGS_PREFIX}/api/{key}"+ ).get_json()["value"]+ assert stored == persisted_value+++class TestResearchPageEgressEnvironmentLock:+ def test_env_locked_scope_is_normalized_and_disabled(+ self, authenticated_client, monkeypatch+ ):+ monkeypatch.setenv("LDR_POLICY_EGRESS_SCOPE", " UNPROTECTED ")+ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")++ response = authenticated_client.get("/")++ assert response.status_code == 200+ html = response.get_data(as_text=True)+ assert "data-env-locked" in html+ assert "Locked by LDR_POLICY_EGRESS_SCOPE" in html+ assert "unprotected" in html++ @pytest.mark.parametrize(+ ("env_key", "control_id", "raw_value", "expected_checked"),+ [+ (+ "LDR_LLM_REQUIRE_LOCAL_ENDPOINT",+ "llm_require_local_endpoint",+ "true",+ True,+ ),+ (+ "LDR_LLM_REQUIRE_LOCAL_ENDPOINT",+ "llm_require_local_endpoint",+ "false",+ False,+ ),+ (+ "LDR_EMBEDDINGS_REQUIRE_LOCAL",+ "embeddings_require_local",+ "true",+ True,+ ),+ (+ "LDR_EMBEDDINGS_REQUIRE_LOCAL",+ "embeddings_require_local",+ "false",+ False,+ ),+ ],+ )+ def test_locality_env_lock_renders_effective_disabled_control(+ self,+ authenticated_client,+ monkeypatch,+ env_key,+ control_id,+ raw_value,+ expected_checked,+ ):+ from bs4 import BeautifulSoup++ monkeypatch.setenv(env_key, raw_value)+ response = authenticated_client.get("/")++ assert response.status_code == 200+ control = BeautifulSoup(+ response.get_data(as_text=True), "html.parser"+ ).find(id=control_id)+ assert control is not None+ assert control.has_attr("disabled")+ assert control.get("aria-disabled") == "true"+ assert control.get("data-env-locked") == "true"+ assert control.get("data-env-value") == raw_value+ assert control.has_attr("checked") is expected_checkeddiff --git a/tests/web/routes/test_settings_routes_coverage.py b/tests/web/routes/test_settings_routes_coverage.pyindex 9139e2d07b..cf5ef65a89 100644--- a/tests/web/routes/test_settings_routes_coverage.py+++ b/tests/web/routes/test_settings_routes_coverage.py@@ -746,11 +746,11 @@ class TestSaveAllSettings:assert "warnings" in data@pytest.mark.parametrize(- "egress_key",+ ("egress_key", "updated_value"),[- "policy.egress_scope",- "llm.require_local_endpoint",- "embeddings.require_local",+ ("policy.egress_scope", "strict"),+ ("llm.require_local_endpoint", True),+ ("embeddings.require_local", True),],)@patch(@@ -763,7 +763,14 @@ class TestSaveAllSettings:)@patch(f"{ROUTES_MODULE}.validate_setting", return_value=(True, None))def test_egress_keys_trigger_warnings_in_bulk_path(- self, mock_v, mock_c, mock_s, mock_w, egress_key, authenticated_client+ self,+ mock_v,+ mock_c,+ mock_s,+ mock_w,+ egress_key,+ updated_value,+ authenticated_client,):"""Regression test for #4463: the bulk ``save_all_settings`` path mustrecalculate warnings when an egress-policy key changes.@@ -789,7 +796,7 @@ class TestSaveAllSettings:mock_ctx.return_value.__exit__ = MagicMock(return_value=False)resp = authenticated_client.post(f"{SETTINGS_PREFIX}/save_all_settings",- json={egress_key: "true"},+ json={egress_key: updated_value},)assert resp.status_code == 200diff --git a/tests/web/routes/test_settings_routes_deep_coverage2.py b/tests/web/routes/test_settings_routes_deep_coverage2.pyindex 48afe4bc97..17c35d157b 100644--- a/tests/web/routes/test_settings_routes_deep_coverage2.py+++ b/tests/web/routes/test_settings_routes_deep_coverage2.py@@ -973,7 +973,10 @@ class TestApiGetAvailableModelsAnthropic:f"{MODULE}._get_setting_from_session",side_effect=_setting_side_effect,),- patch(f"{MODULE}._model_list_local_only", return_value=False),+ patch(+ f"{MODULE}._resolve_model_discovery_policy",+ return_value=(MagicMock(require_local_llm=False), {}),+ ),patch(f"{MODULE}.safe_get") as mock_safe_get,patch("local_deep_research.llm.providers.discover_providers",@@ -1316,6 +1319,11 @@ class TestApiGetAvailableModelsApiKeySettingNone:mock_sm = MagicMock()mock_sm.get_setting.side_effect = _sm_get_setting+ mock_sm.get_settings_snapshot.return_value = {+ "policy.egress_scope": "public_only",+ "search.tool": "searxng",+ "llm.lmstudio.url": "http://localhost:1234/v1",+ }with _authenticated_client(app) as (client, mock_session):mock_session.query.return_value = mock_cache_querydiff --git a/tests/web/routes/test_settings_routes_gaps_coverage.py b/tests/web/routes/test_settings_routes_gaps_coverage.pyindex 41eaf57323..44cf7b1758 100644--- a/tests/web/routes/test_settings_routes_gaps_coverage.py+++ b/tests/web/routes/test_settings_routes_gaps_coverage.py@@ -320,6 +320,94 @@ class TestApiGetDbSettingRedaction:body = resp.get_json()assert body["value"] == ""+ def test_password_value_is_redacted_when_env_overrides_db(+ self, monkeypatch+ ):+ """An ``LDR_*`` env override supplying the effective value must+ not bypass the redaction.++ ``_shape_single_effective_metadata`` overwrites ``value`` from the+ matching environment variable AFTER the route's initial redaction.+ Without a second redaction pass on the shaped metadata, the+ env-supplied secret ships in plaintext. This regression pins the+ second pass while preserving the env-lock metadata.+ """+ monkeypatch.setenv("LDR_LLM_OPENAI_API_KEY", "env-secret-proof")+ app = _create_test_app()+ existing = _make_password_db_setting(value="db-still-secret")++ with _client_with_db(app, existing) as (client, _db):+ resp = client.get("/settings/api/llm.openai.api_key")++ assert resp.status_code == 200+ body = resp.get_json()+ assert body["value"] == "[REDACTED]"+ # Env-lock metadata survives the second redaction pass.+ assert body["ui_element"] == "password"+ assert body["editable"] is False+ # Belt-and-braces: neither the env override nor the stored value+ # appears anywhere in the serialized payload.+ assert "env-secret-proof" not in resp.get_data(as_text=True)+ assert "db-still-secret" not in resp.get_data(as_text=True)++ def test_non_secret_env_override_stays_readable(self, monkeypatch):+ """The second redaction pass must only touch sensitive settings:+ a non-secret env-overridden value ships readable (with the+ env-lock metadata), not as [REDACTED]."""+ monkeypatch.setenv("LDR_SEARCH_FETCH_MODE", "full_page")+ app = _create_test_app()+ plain = _make_password_db_setting(+ key="search.fetch.mode", value="summary_focus_query"+ )+ plain.ui_element = "select"++ with _client_with_db(app, plain) as (client, _db):+ resp = client.get("/settings/api/search.fetch.mode")++ assert resp.status_code == 200+ body = resp.get_json()+ assert body["value"] == "full_page"+ assert body["editable"] is False++ def test_password_value_is_redacted_when_env_overrides_default(+ self, monkeypatch+ ):+ """Same regression on the default-branch: no DB row, default_meta+ provides the password ui_element, and the ``LDR_*`` env override+ supplies the effective value. The shaped value must still be+ redacted and ``editable`` locked to False."""+ monkeypatch.setenv("LDR_LLM_OPENAI_API_KEY", "env-secret-proof")+ app = _create_test_app()+ mock_sm = MagicMock()+ mock_sm.default_settings.get.return_value = {+ "value": None,+ "ui_element": "password",+ "type": "LLM",+ "name": "llm.openai.api_key",+ "description": None,+ "category": "llm_general",+ "options": None,+ "min_value": None,+ "max_value": None,+ "step": None,+ "visible": True,+ "editable": True,+ }++ with _client_with_db(app, None) as (client, _db):+ with patch(+ f"{DECORATOR_MODULE}.SettingsManager",+ return_value=mock_sm,+ ):+ resp = client.get("/settings/api/llm.openai.api_key")++ assert resp.status_code == 200+ body = resp.get_json()+ assert body["value"] == "[REDACTED]"+ assert body["ui_element"] == "password"+ assert body["editable"] is False+ assert "env-secret-proof" not in resp.get_data(as_text=True)+# ===========================================================================# get_bulk_settings (GET /settings/api/bulk) — caller-controlled keys[]@@ -787,6 +875,11 @@ class TestApiGetAvailableModels:return infodef _run_models(self, local_only):+ from local_deep_research.security.egress.policy import (+ EgressContext,+ EgressScope,+ )+app = _create_test_app()@contextmanager@@ -801,6 +894,18 @@ class TestApiGetAvailableModels:"OpenAI", [{"value": "gpt-4", "label": "GPT-4 (OpenAI)"}]),}+ policy_context = EgressContext(+ scope=(+ EgressScope.PRIVATE_ONLY+ if local_only+ else EgressScope.PUBLIC_ONLY+ ),+ primary_engine="library",+ require_local_llm=local_only,+ require_local_embeddings=False,+ local_hostnames=(),+ username="testuser",+ )with _authenticated_client(app) as client:with (@@ -816,7 +921,8 @@ class TestApiGetAvailableModels:return_value=discovered,),patch(- f"{MODULE}._model_list_local_only", return_value=local_only+ f"{MODULE}._resolve_model_discovery_policy",+ return_value=(policy_context, {}),),patch(f"{MODULE}._get_setting_from_session", return_value=""),):@@ -855,3 +961,328 @@ class TestApiGetAvailableModels:]# Cloud provider filtered out entirely (key absent, not just empty).assert "openai_models" not in providers+++class TestApiGetAvailableModelsEgressPolicy:+ @staticmethod+ def _settings_manager(snapshot):+ manager = MagicMock()+ manager.get_settings_snapshot.return_value = snapshot+ manager.get_setting.side_effect = lambda key, default=None: (+ snapshot.get(key, default)+ )+ return manager++ @staticmethod+ def _cached_model(provider, key):+ model = MagicMock()+ model.provider = provider+ model.model_key = key+ model.model_label = key+ return model++ def test_cache_hit_filters_cloud_models_and_options_under_private_only(+ self,+ ):+ # Given a private-only policy and mixed cache.+ app = _create_test_app()+ snapshot = {+ "policy.egress_scope": "private_only",+ "search.tool": "library",+ }+ settings_manager = self._settings_manager(snapshot)+ database_session = MagicMock()+ database_session.query.return_value.filter.return_value.all.return_value = [+ self._cached_model("OLLAMA", "llama3"),+ self._cached_model("OPENAI", "gpt-4"),+ ]++ @contextmanager+ def _session(*args, **kwargs):+ yield database_session++ provider_options = [+ {"value": "OLLAMA", "label": "Ollama", "is_cloud": False},+ {"value": "OPENAI", "label": "OpenAI", "is_cloud": True},+ ]++ with _authenticated_client(app) as client:+ with (+ patch(f"{MODULE}.get_user_db_session", side_effect=_session),+ patch(+ f"{MODULE}.get_settings_manager",+ return_value=settings_manager,+ ),+ patch(+ "local_deep_research.llm.providers.get_discovered_provider_options",+ return_value=provider_options,+ ),+ patch(+ "local_deep_research.llm.providers.discover_providers",+ return_value={},+ ),+ ):+ # When the cache is read.+ response = client.get("/settings/api/available-models")++ # Then only local provider data is returned.+ assert response.status_code == 200+ payload = response.get_json()+ assert payload["provider_options"] == [provider_options[0]]+ assert payload["providers"] == {+ "ollama_models": [+ {"value": "llama3", "label": "llama3", "provider": "OLLAMA"}+ ]+ }++ def test_fresh_discovery_skips_local_provider_with_remote_url(self):+ # Given private-only egress and a remote LM Studio URL.+ app = _create_test_app()+ snapshot = {+ "policy.egress_scope": "private_only",+ "search.tool": "library",+ "llm.lmstudio.url": "https://8.8.8.8/v1",+ }+ settings_manager = self._settings_manager(snapshot)+ database_session = MagicMock()+ provider_class = MagicMock()+ provider_class.api_key_setting = "llm.lmstudio.api_key"+ provider_class.url_setting = "llm.lmstudio.url"+ provider_info = MagicMock()+ provider_info.provider_name = "LM Studio"+ provider_info.provider_class = provider_class+ provider_options = [+ {"value": "LMSTUDIO", "label": "LM Studio", "is_cloud": False},+ {"value": "OPENAI", "label": "OpenAI", "is_cloud": True},+ ]++ @contextmanager+ def _session(*args, **kwargs):+ yield database_session++ with _authenticated_client(app) as client:+ with (+ patch(f"{MODULE}.get_user_db_session", side_effect=_session),+ patch(+ f"{MODULE}.get_settings_manager",+ return_value=settings_manager,+ ),+ patch(+ "local_deep_research.llm.providers.get_discovered_provider_options",+ return_value=provider_options,+ ),+ patch(+ "local_deep_research.llm.providers.discover_providers",+ return_value={"LMSTUDIO": provider_info},+ ),+ ):+ # When models are refreshed.+ response = client.get(+ "/settings/api/available-models?force_refresh=true"+ )++ # Then that endpoint is never called or returned.+ assert response.status_code == 200+ payload = response.get_json()+ assert payload["provider_options"] == []+ assert payload["providers"] == {}+ provider_class.list_models_for_api.assert_not_called()++ def test_fresh_discovery_mixed_dns_never_reads_key_or_calls_provider(self):+ # Given a local-only provider URL with private and public DNS answers.+ app = _create_test_app()+ snapshot = {+ "policy.egress_scope": "private_only",+ "search.tool": "library",+ "llm.lmstudio.url": "http://mixed.inference.example/v1",+ }+ settings_manager = self._settings_manager(snapshot)+ database_session = MagicMock()+ provider_class = MagicMock()+ provider_class.api_key_setting = "llm.lmstudio.api_key"+ provider_class.url_setting = "llm.lmstudio.url"+ provider_class.list_models_for_api.return_value = []+ provider_info = MagicMock()+ provider_info.provider_name = "LM Studio"+ provider_info.provider_class = provider_class++ @contextmanager+ def _session(*args, **kwargs):+ yield database_session++ with _authenticated_client(app) as client:+ with (+ patch(f"{MODULE}.get_user_db_session", side_effect=_session),+ patch(+ f"{MODULE}.get_settings_manager",+ return_value=settings_manager,+ ),+ patch(+ "local_deep_research.llm.providers.get_discovered_provider_options",+ return_value=[],+ ),+ patch(+ "local_deep_research.llm.providers.discover_providers",+ return_value={"LMSTUDIO": provider_info},+ ),+ patch(+ "local_deep_research.security.egress.policy._resolve_with_timeout",+ return_value=[+ (None, None, None, None, ("10.0.0.42", 0)),+ (None, None, None, None, ("8.8.8.8", 0)),+ ],+ ),+ patch(+ f"{MODULE}._get_setting_from_session",+ side_effect=lambda key, default=None: (+ "provider-credential"+ if key == "llm.lmstudio.api_key"+ else snapshot.get(key, default)+ ),+ ) as get_setting,+ ):+ # When fresh model discovery runs.+ response = client.get(+ "/settings/api/available-models?force_refresh=true"+ )++ # Then it denies before retrieving credentials or invoking the provider.+ assert response.status_code == 200+ assert response.get_json()["providers"] == {}+ get_setting.assert_not_called()+ provider_class.list_models_for_api.assert_not_called()++ def test_cache_filters_provider_with_mixed_dns_answers(self):+ # Given a cached local-provider model whose endpoint has a public answer.+ app = _create_test_app()+ snapshot = {+ "policy.egress_scope": "private_only",+ "search.tool": "library",+ "llm.lmstudio.url": "http://mixed.inference.example/v1",+ }+ settings_manager = self._settings_manager(snapshot)+ database_session = MagicMock()+ database_session.query.return_value.filter.return_value.all.return_value = [+ self._cached_model("LMSTUDIO", "local-model")+ ]++ @contextmanager+ def _session(*args, **kwargs):+ yield database_session++ provider_options = [+ {"value": "LMSTUDIO", "label": "LM Studio", "is_cloud": False}+ ]+ with _authenticated_client(app) as client:+ with (+ patch(f"{MODULE}.get_user_db_session", side_effect=_session),+ patch(+ f"{MODULE}.get_settings_manager",+ return_value=settings_manager,+ ),+ patch(+ "local_deep_research.llm.providers.get_discovered_provider_options",+ return_value=provider_options,+ ),+ patch(+ "local_deep_research.llm.providers.discover_providers",+ return_value={"LMSTUDIO": MagicMock()},+ ),+ patch(+ "local_deep_research.security.egress.policy._resolve_with_timeout",+ return_value=[+ (None, None, None, None, ("10.0.0.42", 0)),+ (None, None, None, None, ("8.8.8.8", 0)),+ ],+ ) as resolve,+ ):+ # When model discovery reads the cache.+ response = client.get("/settings/api/available-models")++ # Then both the provider option and its stale cached model are filtered.+ resolve.assert_called_once_with("mixed.inference.example")+ assert response.status_code == 200+ assert response.get_json() == {"provider_options": [], "providers": {}}++ def test_disabled_unprotected_scope_rejects_before_cache_return(+ self, monkeypatch+ ):+ # Given a residual disabled unprotected scope and cached models.+ monkeypatch.delenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", raising=False)+ app = _create_test_app()+ settings_manager = self._settings_manager(+ {+ "policy.egress_scope": "unprotected",+ "search.tool": "library",+ }+ )+ database_session = MagicMock()+ database_session.query.return_value.filter.return_value.all.return_value = [+ self._cached_model("OPENAI", "gpt-4")+ ]++ @contextmanager+ def _session(*args, **kwargs):+ yield database_session++ with _authenticated_client(app) as client:+ with (+ patch(f"{MODULE}.get_user_db_session", side_effect=_session),+ patch(+ f"{MODULE}.get_settings_manager",+ return_value=settings_manager,+ ),+ patch(+ "local_deep_research.llm.providers.get_discovered_provider_options",+ return_value=[],+ ) as provider_options,+ ):+ # When available models are requested.+ response = client.get("/settings/api/available-models")++ # Then the route returns its stable policy-denied response.+ assert response.status_code == 400+ assert response.get_json() == {+ "status": "error",+ "message": "Egress policy refused this request: unprotected_egress_disabled",+ }+ provider_options.assert_not_called()++ def test_settings_snapshot_failure_refuses_before_cache_return(self):+ # Given settings cannot be loaded and cached cloud models exist.+ app = _create_test_app()+ settings_manager = MagicMock()+ settings_manager.get_settings_snapshot.side_effect = RuntimeError(+ "db error"+ )+ database_session = MagicMock()+ database_session.query.return_value.filter.return_value.all.return_value = [+ self._cached_model("OPENAI", "gpt-4")+ ]++ @contextmanager+ def _session(*args, **kwargs):+ yield database_session++ with _authenticated_client(app) as client:+ with (+ patch(f"{MODULE}.get_user_db_session", side_effect=_session),+ patch(+ f"{MODULE}.get_settings_manager",+ return_value=settings_manager,+ ),+ patch(+ "local_deep_research.llm.providers.get_discovered_provider_options",+ return_value=[],+ ) as provider_options,+ ):+ # When available models are requested.+ response = client.get("/settings/api/available-models")++ # Then discovery is denied rather than returning cached data.+ assert response.status_code == 503+ assert response.get_json() == {+ "status": "error",+ "message": "Egress policy refused this request: settings_unavailable",+ }+ provider_options.assert_not_called()diff --git a/tests/web/routes/test_start_research_search_override_validation.py b/tests/web/routes/test_start_research_search_override_validation.pynew file mode 100644index 0000000000..7b8491fdc9--- /dev/null+++ b/tests/web/routes/test_start_research_search_override_validation.py@@ -0,0 +1,217 @@+# allow: no-sut-import - black-box HTTP test; drives the real research route+from unittest.mock import MagicMock, patch++import pytest+from flask import g, session++from tests.web.routes import test_research_routes_extracted_helpers as helpers+from tests.web.routes.test_research_routes_extracted_helpers import (+ app as _app_fixture,+)+from tests.web.routes.test_research_routes_extracted_helpers import (+ client as _client_fixture,+)++app = _app_fixture+client = _client_fixture+++INVALID_OVERRIDES = (+ ("max_results", 0),+ ("max_results", 51),+ ("max_results", True),+ ("max_results", False),+ ("max_results", 1.0),+ ("max_results", "50"),+ ("time_period", ""),+ ("time_period", "7d"),+ ("time_period", "30d"),+ ("time_period", "day"),+ ("time_period", "Y"),+ ("time_period", 1),+)+INVALID_CASES = tuple(+ (active_count, override)+ for active_count in (0, 5)+ for override in INVALID_OVERRIDES+)+VALID_DIRECT_OVERRIDES = tuple(+ (max_results, time_period)+ for max_results in (1, 50)+ for time_period in ("d", "w", "m", "y", "all")+)++[email protected](autouse=True)+def _authenticated_session(app):+ @app.before_request+ def _set_session():+ session["username"] = "testuser"+ session["session_id"] = "sid-1"+++def _prepare_request(app, active_count):+ db_session = helpers._mock_db_session(active_count=active_count)++ @app.before_request+ def _inject_db_session():+ g.db_session = db_session++ return db_session+++class TestStartResearchSearchOverrideValidation:+ @pytest.mark.parametrize(+ "case",+ INVALID_CASES,+ ids=[+ f"active-{active_count}-{field}-{value!r}"+ for active_count, (field, value) in INVALID_CASES+ ],+ )+ def test_invalid_search_override_returns_400_before_dispatch(+ self, case, client, app+ ):+ # Given: an authenticated request with an explicit invalid override.+ active_count, (field, value) = case+ db_session = _prepare_request(app, active_count)+ settings_manager = helpers._make_settings_manager()+ fake_thread = MagicMock()+ fake_thread.ident = 42+ patches = helpers._happy_path_patches(+ db_session, settings_manager, fake_thread+ )++ # When: the request reaches the start-research HTTP endpoint.+ with (+ patches[0],+ patches[1],+ patches[2],+ patches[3],+ patches[4] as start_research_process,+ patches[5],+ patches[6],+ patches[7] as research_history,+ patches[8],+ patch(helpers._QP) as queue_processor,+ ):+ response = client.post(+ "/api/start_research",+ json={+ "query": "override validation",+ "model": "llama3",+ field: value,+ },+ )++ # Then: invalid input is rejected before either execution path mutates state.+ assert response.status_code == 400+ body = response.get_json()+ assert body["status"] == "error"+ assert field in body["message"].lower()+ start_research_process.assert_not_called()+ queue_processor.notify_research_queued.assert_not_called()+ research_history.assert_not_called()++ @pytest.mark.parametrize(+ "override",+ VALID_DIRECT_OVERRIDES,+ ids=[+ f"max-{max_results}-period-{time_period}"+ for max_results, time_period in VALID_DIRECT_OVERRIDES+ ],+ )+ def test_valid_search_override_boundaries_dispatch_directly(+ self, override, client, app+ ):+ # Given: a direct-dispatch request with canonical boundary values.+ max_results, time_period = override+ db_session = _prepare_request(app, active_count=0)+ settings_manager = helpers._make_settings_manager()+ fake_thread = MagicMock()+ fake_thread.ident = 42+ patches = helpers._happy_path_patches(+ db_session, settings_manager, fake_thread+ )++ # When: the client submits the explicit search overrides.+ with (+ patches[0],+ patches[1],+ patches[2],+ patches[3],+ patches[4] as start_research_process,+ patches[5],+ patches[6],+ patches[7],+ patches[8],+ patch(helpers._QP) as queue_processor,+ ):+ response = client.post(+ "/api/start_research",+ json={+ "query": "valid override",+ "model": "llama3",+ "max_results": max_results,+ "time_period": time_period,+ },+ )++ # Then: the request starts exactly once with its explicit values.+ assert response.status_code == 200+ assert response.get_json()["status"] == "success"+ start_research_process.assert_called_once()+ assert (+ start_research_process.call_args.kwargs["max_results"]+ == max_results+ )+ assert (+ start_research_process.call_args.kwargs["time_period"]+ == time_period+ )+ queue_processor.notify_research_queued.assert_not_called()++ def test_valid_search_overrides_retain_queue_provenance(self, client, app):+ # Given: a queue-bound request with both explicit valid overrides.+ db_session = _prepare_request(app, active_count=5)+ settings_manager = helpers._make_settings_manager()+ fake_thread = MagicMock()+ fake_thread.ident = 42+ patches = helpers._happy_path_patches(+ db_session, settings_manager, fake_thread+ )++ # When: the client submits values while the active-research limit is reached.+ with (+ patches[0],+ patches[1],+ patches[2],+ patches[3],+ patches[4] as start_research_process,+ patches[5],+ patches[6],+ patches[7],+ patches[8],+ patch(helpers._QP) as queue_processor,+ ):+ response = client.post(+ "/api/start_research",+ json={+ "query": "queued override",+ "max_results": 50,+ "time_period": "all",+ },+ )++ # Then: the request queues, retaining exactly both override names.+ assert response.status_code == 200+ assert response.get_json()["status"] == "queued"+ start_research_process.assert_not_called()+ queue_processor.notify_research_queued.assert_called_once()+ snapshot = queue_processor.notify_research_queued.call_args.kwargs[+ "settings_snapshot"+ ]+ assert snapshot["submission_overrides"] == [+ "max_results",+ "time_period",+ ]diff --git a/tests/web/services/test_research_service_coverage_gaps.py b/tests/web/services/test_research_service_coverage_gaps.pyindex 154102b87e..c975791d59 100644--- a/tests/web/services/test_research_service_coverage_gaps.py+++ b/tests/web/services/test_research_service_coverage_gaps.py@@ -17,6 +17,7 @@ Targets specific uncovered lines:from contextlib import contextmanagerfrom unittest.mock import MagicMock, patch+import pytestfrom loguru import logger# Register MILESTONE log level used by progress_callback@@ -34,6 +35,18 @@ QUEUE_PROC_MOD = "local_deep_research.web.queue.processor_v2"ENV_REGISTRY_MOD = "local_deep_research.settings.env_registry"[email protected](autouse=True)+def _clear_raw_worker_egress_context():+ """Raw-worker tests bypass the production thread-cleanup decorator."""+ from local_deep_research.security.egress.audit_hook import (+ clear_active_context,+ )++ clear_active_context()+ yield+ clear_active_context()++# ---------------------------------------------------------------------------# Helpers# ---------------------------------------------------------------------------@@ -255,6 +268,216 @@ class TestSettingsContextInnerClass:assert ctx.get_setting("nonexistent.key", "fallback") == "fallback"assert ctx.get_setting("nonexistent.key") is None+ def test_dispatch_refresh_reaches_all_worker_consumers(self):+ func = _get_raw_run_research_process()+ stale = {"search.tool": "stale", "policy.egress_scope": "strict"}+ effective = {+ "search.tool": "searxng",+ "policy.egress_scope": "public_only",+ "policy.trusted_search_engines": {+ "value": [],+ "editable": False,+ },+ }+ refresh = MagicMock(return_value=effective)+ captured_contexts = []+ system = MagicMock()+ system.analyze_topic.return_value = {+ "findings": "test",+ "formatted_findings": "result",+ }+ system_cls = MagicMock(return_value=system)++ patches = _base_run_patches()+ patches[f"{MODULE}.apply_environment_overrides_to_snapshot"] = refresh+ patches[f"{MODULE}.get_search"] = MagicMock()+ patches[f"{MODULE}.AdvancedSearchSystem"] = system_cls+ patches[f"{THREAD_SETTINGS_MOD}.set_settings_context"] = lambda ctx: (+ captured_contexts.append(ctx)+ )++ stack = []+ for target, mock_obj in patches.items():+ p = patch(target, mock_obj)+ stack.append(p)+ p.start()+ try:+ func(+ 1,+ "test",+ "quick",+ username="user1",+ settings_snapshot=stale,+ )+ finally:+ for p in reversed(stack):+ p.stop()++ refresh.assert_called_once_with(stale)+ assert captured_contexts[0].get_setting("search.tool") == "searxng"+ assert (+ captured_contexts[0].get_setting("policy.trusted_search_engines")+ == []+ )+ assert system_cls.call_args.kwargs["settings_snapshot"] is effective+ search_context_calls = patches[+ f"{MODULE}.set_search_context"+ ].call_args_list+ assert any(+ call.args and call.args[0].get("settings_snapshot") is effective+ for call in search_context_calls+ )++ def test_dispatch_resolves_omitted_overrides_from_refreshed_snapshot(self):+ # Given: a queue snapshot and a changed environment-refreshed snapshot.+ func = _get_raw_run_research_process()+ stale = {+ "llm.provider": "enqueue-provider",+ "llm.model": "enqueue-model",+ "llm.openai_endpoint.url": "http://enqueue.invalid/v1",+ "search.tool": "enqueue-engine",+ "search.iterations": 1,+ "search.questions_per_iteration": 1,+ "search.search_strategy": "enqueue-strategy",+ }+ effective = {+ "llm.provider": "openai_endpoint",+ "llm.model": "dispatch-model",+ "llm.openai_endpoint.url": "http://dispatch.example/v1",+ "search.tool": "dispatch-engine",+ "search.iterations": 4,+ "search.questions_per_iteration": 3,+ "search.search_strategy": "dispatch-strategy",+ }+ system = MagicMock()+ system.analyze_topic.return_value = {+ "findings": "test",+ "formatted_findings": "result",+ }+ get_llm = MagicMock()+ get_search = MagicMock()+ patches = _base_run_patches()+ patches[f"{MODULE}.apply_environment_overrides_to_snapshot"] = (+ MagicMock(return_value=effective)+ )+ patches[f"{MODULE}.get_llm"] = get_llm+ patches[f"{MODULE}.get_search"] = get_search+ patches[f"{MODULE}.AdvancedSearchSystem"] = MagicMock(+ return_value=system+ )++ # When: the worker runs without any per-run configuration kwargs.+ with (+ patch(+ "local_deep_research.security.egress.policy.context_from_snapshot",+ return_value=MagicMock(),+ ),+ patch(+ "local_deep_research.security.egress.run_classification.audit_run_from_snapshot",+ return_value=MagicMock(allowed=True),+ ),+ ):+ stack = []+ for target, mock_obj in patches.items():+ patcher = patch(target, mock_obj)+ stack.append(patcher)+ patcher.start()+ try:+ func(+ 1,+ "test",+ "quick",+ username="user1",+ settings_snapshot=stale,+ )+ finally:+ for patcher in reversed(stack):+ patcher.stop()++ # Then: execution derives every settings-backed value after refresh.+ assert get_llm.call_args.kwargs["provider"] == "openai_endpoint"+ assert get_llm.call_args.kwargs["model_name"] == "dispatch-model"+ assert (+ get_llm.call_args.kwargs["openai_endpoint_url"]+ == "http://dispatch.example/v1"+ )+ assert get_search.call_args.kwargs["search_tool"] == "dispatch-engine"+ system_kwargs = patches[+ f"{MODULE}.AdvancedSearchSystem"+ ].call_args.kwargs+ assert system_kwargs["strategy_name"] == "dispatch-strategy"+ assert system_kwargs["max_iterations"] == 4+ assert system_kwargs["questions_per_iteration"] == 3++ def test_worker_audits_the_explicit_engine_it_executes(self):+ # Given: an explicit request engine that differs from the snapshot primary.+ func = _get_raw_run_research_process()+ effective = {"search.tool": "snapshot-engine"}+ system = MagicMock()+ system.analyze_topic.return_value = {+ "findings": "test",+ "formatted_findings": "result",+ }+ get_search = MagicMock()+ get_llm = MagicMock()+ egress_context = MagicMock(primary_engine="request-engine")+ audit_decision = MagicMock(allowed=True)+ patches = _base_run_patches()+ patches[f"{MODULE}.apply_environment_overrides_to_snapshot"] = (+ MagicMock(return_value=effective)+ )+ patches[f"{MODULE}.get_search"] = get_search+ patches[f"{MODULE}.get_llm"] = get_llm+ patches[f"{MODULE}.AdvancedSearchSystem"] = MagicMock(+ return_value=system+ )++ # When: dispatch executes the request-scoped search engine.+ with (+ patch(+ "local_deep_research.security.egress.policy.context_from_snapshot",+ return_value=egress_context,+ ) as context_from_snapshot,+ patch(+ "local_deep_research.security.egress.run_classification.audit_run_from_snapshot",+ return_value=audit_decision,+ ) as audit_run,+ # build_run_egress_context re-imports this from settings.manager,+ # so the {MODULE} patch above doesn't cover its second application;+ # pin the source too or a stray LDR_* env var pollutes the snapshot.+ patch(+ "local_deep_research.settings.manager.apply_environment_overrides_to_snapshot",+ return_value=effective,+ ),+ ):+ stack = []+ for target, mock_obj in patches.items():+ patcher = patch(target, mock_obj)+ stack.append(patcher)+ patcher.start()+ try:+ func(+ 1,+ "test",+ "quick",+ username="user1",+ model_provider="request-provider",+ model="request-model",+ search_engine="request-engine",+ settings_snapshot=effective,+ )+ finally:+ for patcher in reversed(stack):+ patcher.stop()++ # Then: the audit context, audit primary, and factory all agree.+ context_from_snapshot.assert_any_call(+ effective, "request-engine", username="user1"+ )+ assert audit_run.call_args.args[2] == "request-engine"+ assert get_llm.call_args.kwargs["provider"] == "request-provider"+ assert get_search.call_args.kwargs["search_tool"] == "request-engine"+# ---------------------------------------------------------------------------# 2b. Worker fails closed when the run has no configured primary engine@@ -553,6 +776,7 @@ class TestSearchErrorClassification:mock_system.analyze_topic.side_effect = Exception(error_msg)patches = _base_run_patches()+ patches[f"{MODULE}.get_search"] = MagicMock()patches[f"{MODULE}.AdvancedSearchSystem"] = MagicMock(return_value=mock_system)diff --git a/tests/web/services/test_research_service_progress_integration.py b/tests/web/services/test_research_service_progress_integration.pyindex 45ff7405e0..2c9f71be22 100644--- a/tests/web/services/test_research_service_progress_integration.py+++ b/tests/web/services/test_research_service_progress_integration.py@@ -157,6 +157,12 @@ def captured_progress_callback(mode, flask_app, run_kwargs=None, extras=None):patch("local_deep_research.web.services.research_service.handle_termination"),+ patch(+ "local_deep_research.web.services.research_service.get_llm",+ ),+ patch(+ "local_deep_research.web.services.research_service.get_search",+ ),):call_kwargs = dict(research_id=1,diff --git a/tests/web/services/test_research_service_search_limit_precedence.py b/tests/web/services/test_research_service_search_limit_precedence.pynew file mode 100644index 0000000000..dbbd23c4ad--- /dev/null+++ b/tests/web/services/test_research_service_search_limit_precedence.py@@ -0,0 +1,139 @@+from contextlib import ExitStack+from dataclasses import dataclass+from unittest.mock import MagicMock, patch++import pytest++from tests.web.services.test_research_service_coverage_gaps import (+ MODULE,+ _base_run_patches,+ _get_raw_run_research_process,+)+++@dataclass(frozen=True, slots=True)+class _WorkerSearchLimits:+ max_results: int | None+ time_period: str | None++[email protected](autouse=True)+def _clear_raw_worker_egress_context():+ from local_deep_research.security.egress.audit_hook import (+ clear_active_context,+ )++ clear_active_context()+ yield+ clear_active_context()+++def _dispatch_search_limits(+ limits: _WorkerSearchLimits | None,+) -> tuple[MagicMock, MagicMock]:+ persisted = {+ "llm.provider": "openai_endpoint",+ "llm.model": "persisted-model",+ "llm.openai_endpoint.url": "http://persisted.invalid/v1",+ "search.tool": "searxng",+ "search.max_results": 7,+ "search.time_period": "y",+ }+ effective = {+ "llm.provider": "openai_endpoint",+ "llm.model": "effective-model",+ "llm.openai_endpoint.url": "http://effective.example/v1",+ "search.tool": "searxng",+ "search.max_results": 13,+ "search.time_period": "m",+ }+ search_factory = MagicMock(return_value=MagicMock())+ system = MagicMock()+ system.analyze_topic.return_value = {+ "findings": "test",+ "formatted_findings": "result",+ }+ system_cls = MagicMock(return_value=system)+ patches = _base_run_patches()+ patches[f"{MODULE}.apply_environment_overrides_to_snapshot"] = MagicMock(+ return_value=effective+ )+ patches[f"{MODULE}.get_llm"] = MagicMock(return_value=MagicMock())+ patches[f"{MODULE}.AdvancedSearchSystem"] = system_cls+ worker_kwargs = {"username": "user1", "settings_snapshot": persisted}+ if limits is not None:+ worker_kwargs["max_results"] = limits.max_results+ worker_kwargs["time_period"] = limits.time_period++ with ExitStack() as stack:+ stack.enter_context(+ patch(+ "local_deep_research.config.search_config.factory_get_search",+ search_factory,+ )+ )+ stack.enter_context(+ patch(+ "local_deep_research.security.egress.policy.context_from_snapshot",+ return_value=MagicMock(),+ )+ )+ stack.enter_context(+ patch(+ "local_deep_research.security.egress.run_classification.audit_run_from_snapshot",+ return_value=MagicMock(allowed=True),+ )+ )+ for target, mock_obj in patches.items():+ stack.enter_context(patch(target, mock_obj))+ _get_raw_run_research_process()(1, "test", "quick", **worker_kwargs)++ return search_factory, system_cls+++def test_explicit_search_limits_override_effective_snapshot_at_consumer():+ # Given: explicit limits distinct from persisted and effective snapshots.+ limits = _WorkerSearchLimits(max_results=19, time_period="w")++ # When: the worker dispatches the run with explicit limits.+ search_factory, system_cls = _dispatch_search_limits(limits)++ # Then: the real search consumer and system snapshot use explicit limits.+ search_factory.assert_called_once()+ assert search_factory.call_args.kwargs["max_results"] == 19+ assert search_factory.call_args.kwargs["time_period"] == "w"+ system_snapshot = system_cls.call_args.kwargs["settings_snapshot"]+ assert system_snapshot["search.max_results"] == 19+ assert system_snapshot["search.time_period"] == "w"+++def test_omitted_search_limits_preserve_effective_snapshot():+ # Given: no worker search-limit overrides.+ limits = None++ # When: the worker dispatches the run.+ search_factory, system_cls = _dispatch_search_limits(limits)++ # Then: the real search consumer and system snapshot use 13 and "m".+ search_factory.assert_called_once()+ assert search_factory.call_args.kwargs["max_results"] == 13+ assert search_factory.call_args.kwargs["time_period"] == "m"+ system_snapshot = system_cls.call_args.kwargs["settings_snapshot"]+ assert system_snapshot["search.max_results"] == 13+ assert system_snapshot["search.time_period"] == "m"+++def test_none_search_limits_preserve_effective_snapshot():+ # Given: legacy explicit None search-limit overrides.+ limits = _WorkerSearchLimits(max_results=None, time_period=None)++ # When: the worker dispatches the run.+ search_factory, system_cls = _dispatch_search_limits(limits)++ # Then: the real search consumer and system snapshot use 13 and "m".+ search_factory.assert_called_once()+ assert search_factory.call_args.kwargs["max_results"] == 13+ assert search_factory.call_args.kwargs["time_period"] == "m"+ system_snapshot = system_cls.call_args.kwargs["settings_snapshot"]+ assert system_snapshot["search.max_results"] == 13+ assert system_snapshot["search.time_period"] == "m"diff --git a/tests/web/services/test_settings_manager_extended.py b/tests/web/services/test_settings_manager_extended.pyindex 634f3a9fec..7eab6f173b 100644--- a/tests/web/services/test_settings_manager_extended.py+++ b/tests/web/services/test_settings_manager_extended.py@@ -15,6 +15,7 @@ Tests cover additional functionality not in the main test file:import osimport json+import pytestfrom unittest.mock import Mock, MagicMock, patch@@ -584,6 +585,7 @@ class TestImportExportSettings:manager.import_settings(settings_data, overwrite=False)# Check that existing value was preserved+ manager.get_setting.assert_called_once_with("app.key", check_env=False)added_setting = mock_session.add.call_args[0][0]assert added_setting.value == "existing_value"@@ -593,22 +595,23 @@ class TestImportExportSettings:SettingsManager,)+ from local_deep_research.database.models import Setting+mock_session = Mock()- mock_query = Mock()- mock_query.filter.return_value.delete.return_value = 1- mock_session.query.return_value = mock_query+ mutation_query = Mock()+ events = []+ mutation_query.filter.return_value.delete.side_effect = (+ lambda **kwargs: events.append("delete") or 1+ )+ key_query = Mock()+ key_query.all.return_value = [("app.keep",), ("app.extra",)]+ mock_session.query.side_effect = lambda model: (+ key_query if model is Setting.key else mutation_query+ )+ mock_session.commit.side_effect = lambda: events.append("commit")manager = SettingsManager(db_session=mock_session)- # Mock get_all_settings to return extra setting- manager.get_all_settings = Mock(- return_value={- "app.keep": {"value": True},- "app.extra": {"value": False},- }- )- manager.delete_setting = Mock(return_value=True)-settings_data = {"app.keep": {"value": True,@@ -621,8 +624,33 @@ class TestImportExportSettings:with patch.object(manager, "_emit_settings_changed"):manager.import_settings(settings_data, delete_extra=True)- # Should have deleted the extra setting- manager.delete_setting.assert_any_call("app.extra", commit=False)+ # Imported-row replacement and extra deletion both happen before commit.+ assert events.count("delete") == 2+ assert events[-1] == "commit"++ def test_import_rolls_back_when_strict_delete_fails(self):+ from local_deep_research.settings.manager import SettingsManager++ mock_session = Mock()+ mutation_query = Mock()+ mutation_query.filter.return_value.delete.side_effect = RuntimeError(+ "delete failed"+ )+ mock_session.query.return_value = mutation_query+ manager = SettingsManager(db_session=mock_session)++ with pytest.raises(RuntimeError, match="delete failed"):+ manager.import_settings(+ {+ "app.debug": {+ "value": True,+ "type": "APP",+ }+ }+ )++ mock_session.rollback.assert_called_once()+ mock_session.commit.assert_not_called()class TestLoadFromDefaultsFile:diff --git a/tests/web/warning_checks/test_orchestrator.py b/tests/web/warning_checks/test_orchestrator.pyindex 725bb29ca8..1d9765a490 100644--- a/tests/web/warning_checks/test_orchestrator.py+++ b/tests/web/warning_checks/test_orchestrator.py@@ -607,3 +607,47 @@ class TestCalculateWarningsBackupGlobHardening:# fires and no "backup_info" (which would carry the link target size).assert "no_backups" in typesassert "backup_info" not in types+++class TestCalculateWarningsUnprotectedBannerUsesEffectiveScope:+ """The loud "protection disabled" banner must be driven by the RESOLVED+ effective scope, not the raw stored value. A stale ``unprotected`` row+ left over from before the operator gate existed must NOT light the banner+ once the gate is off (context_from_snapshot coerces it to adaptive) — and+ the banner must still fire when the operator has enabled the gate.++ Pins the effective_scope wiring in calculate_warnings(): reverting it to+ feed the raw egress_scope would fail the gate-off case here.+ """++ def _manager_with_stale_unprotected(self):+ mgr = _make_settings_manager(+ {+ "policy.egress_scope": "unprotected",+ "search.tool": "wikipedia",+ }+ )+ # context_from_snapshot resolves the effective posture from this.+ mgr.get_settings_snapshot.return_value = {+ "policy.egress_scope": "unprotected",+ "search.tool": "wikipedia",+ }+ return mgr++ def test_no_banner_for_stale_unprotected_when_gate_off(self, monkeypatch):+ from local_deep_research.web.warning_checks import calculate_warnings++ monkeypatch.delenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", raising=False)+ with _patch_orchestrator(self._manager_with_stale_unprotected()):+ warnings = calculate_warnings()++ assert "egress_unprotected" not in {w["type"] for w in warnings}++ def test_banner_fires_when_gate_enabled(self, monkeypatch):+ from local_deep_research.web.warning_checks import calculate_warnings++ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")+ with _patch_orchestrator(self._manager_with_stale_unprotected()):+ warnings = calculate_warnings()++ assert "egress_unprotected" in {w["type"] for w in warnings}