~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(settings): make library storage path operator-only (#7152)
LearningCircuit53f9e8017f72
diff --git a/changelog.d/+operator-only-library-path.security.md b/changelog.d/+operator-only-library-path.security.mdnew file mode 100644index 0000000000..cf6f767418--- /dev/null+++ b/changelog.d/+operator-only-library-path.security.md@@ -0,0 +1 @@+Make the research-library storage path operator-only, preventing authenticated accounts from redirecting library reads or writes through settings edits while preserving existing library locations.diff --git a/changelog.d/+settings-reconcile-keeps-own-value.bugfix.md b/changelog.d/+settings-reconcile-keeps-own-value.bugfix.mdnew file mode 100644index 0000000000..6a69d4f360--- /dev/null+++ b/changelog.d/+settings-reconcile-keeps-own-value.bugfix.md@@ -0,0 +1 @@+Stop the settings import that runs on a version bump from writing a setting's child values back into the setting itself, which nested some search-engine settings into themselves on every upgrade. Settings already nested this way are left as they are.diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex 71895d0d3e..0ab8957c15 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -1,7 +1,7 @@# Configuration ReferenceThis document is automatically generated from the application's default settings.-All settings can be configured via the Web UI (Settings page), or overridden via Environment Variables.+Most settings can be configured via the Web UI (Settings page), or overridden via Environment Variables.## Environment Variables@@ -11,6 +11,8 @@ 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. 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.+`research_library.storage_path` is operator-only. Set `LDR_RESEARCH_LIBRARY_STORAGE_PATH` to change it; existing saved paths stay in use if no override is set, including locations outside `LDR_DATA_DIR`. Audit saved paths when upgrading a multi-user installation. User settings save, delete, import, and reset cannot change this path.+## Pre-Database (Env-Only) SettingsThese settings are **required before database initialization** and can only be set via environment variables.@@ -42,8 +44,8 @@ They are not available in the Web UI because they are needed to start the applic| `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_RESEARCH_LIBRARY_ALLOW_FILESYSTEM_PDF_STORAGE` | Boolean | `False` | No | | Allow users to select the UNENCRYPTED 'filesystem' PDF storage mode for library-downloaded PDFs. Disabled by default; this is an environment-only operator gate and cannot be changed through the user-writable settings API. Filesystem mode writes fetched third-party PDFs as PLAINTEXT to a shared library directory (cleartext storage of sensitive information, CWE-312). When off, the 'filesystem' option is withheld from the settings UI and any stored or environment value of 'filesystem' is coerced to the encrypted 'database' mode at write time. Previously-written plaintext files remain readable. Enable only when the library directory lives on an operator-controlled encrypted volume. | Security | |-| `LDR_RESEARCH_LIBRARY_ALLOW_LEGACY_READ_FALLBACK` | Boolean | `False` | No | | SECURITY RISK — leave DISABLED (default) on any multi-user or untrusted deployment. When ENABLED, library PDF reads that miss in the caller's own per-user directory fall back to a shared root derived from the user-editable 'research_library.storage_path' setting. On a multi-user instance this re-opens a CROSS-TENANT READ: a user can edit their own storage_path to point at another user's library directory, and because per-user autoincrement resource ids collide by construction (e.g. 'pdfs/5.pdf'), a read of their own document id then resolves — via this fallback — to the OTHER user's PDF and returns its contents. The safe state is OFF: with the gate off, reads resolve strictly within the requesting user's own per-user root and the fallback never fires. This is an environment-only operator gate and cannot be enabled through the user-writable settings API. Enable ONLY on a single-user or fully-trusted deployment that needs PDFs downloaded before per-user isolation (issue #5521) to keep loading from the legacy shared location. | Security | |-| `LDR_RESEARCH_LIBRARY_ALLOW_SHARED_LIBRARY` | Boolean | `False` | No | | Allow shared-library mode, which drops the per-user library directory boundary so all users' downloaded PDFs live in one shared directory. Disabled by default; this is an environment-only operator gate and cannot be enabled through the user-writable settings API. Because both the shared_library flag and the storage_path are otherwise user-editable, leaving shared mode user-toggleable would let a multi-tenant user point their own storage_path at another user's directory and read/overwrite their PDFs. When off, the per-user subdirectory is always enforced regardless of the user's shared_library setting. Enable only on single-tenant or mutually-trusted deployments. | Security | |+| `LDR_RESEARCH_LIBRARY_ALLOW_LEGACY_READ_FALLBACK` | Boolean | `False` | No | | SECURITY RISK — leave DISABLED (default) on any multi-user or untrusted deployment. When ENABLED, library PDF reads that miss in the caller's own per-user directory fall back to a shared root derived from the operator-only 'research_library.storage_path' setting. Legacy saved paths remain in place, and per-user resource ids collide by design (e.g. 'pdfs/5.pdf'), so this fallback can still expose another user's PDF on a multi-user instance. The safe state is OFF: with the gate off, reads resolve strictly within the requesting user's own per-user root and the fallback never fires. This is an environment-only operator gate and cannot be enabled through the user-writable settings API. Enable ONLY on a single-user or fully-trusted deployment that needs PDFs downloaded before per-user isolation (issue #5521) to keep loading from the legacy shared location. | Security | |+| `LDR_RESEARCH_LIBRARY_ALLOW_SHARED_LIBRARY` | Boolean | `False` | No | | Allow shared-library mode, which drops the per-user library directory boundary so all users' downloaded PDFs live in one shared directory. Disabled by default; this is an environment-only operator gate and cannot be enabled through the user-writable settings API. The shared_library flag is otherwise user-editable; leaving shared mode user-toggleable would let an account drop its per-user directory boundary. The storage_path is now operator-only, but legacy saved paths remain in place. When off, the per-user subdirectory is always enforced regardless of the user's shared_library setting. Enable only on single-tenant or mutually-trusted deployments. | Security | || `LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS` | Boolean | `False` | No | | Allow user-editable PUBLIC search-engine URLs (e.g. the SearXNG instance_url) to point at private / loopback / link-local addresses. Environment-only operator gate so it cannot be flipped through the user-writable settings API. Disabled by default: a public-nature engine (its data source is the public internet) pointed at an internal host lets any authenticated user turn a research run into an internal port scan / service probe, breaking the PUBLIC_ONLY egress promise. Enable only when you self-host SearXNG on localhost/LAN and accept that engine fetches may reach your private network. To approve only specific origins instead of all private addresses, use the finer-grained LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST. Docker deployments instead pin the URL directly via LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL, which is trusted as operator-provisioned. Cloud-metadata endpoints (ALWAYS_BLOCKED_METADATA_IPS) stay blocked regardless of this flag. | Security | || `LDR_SEARCH_ALLOW_PRIVATE_RESULT_FETCH` | Boolean | `False` | No | | Allow full-content fetching (search.snippets_only off) to follow the RESULT URLs a PUBLIC search engine returns into private / loopback addresses, e.g. an internal wiki that a self-hosted SearXNG instance indexes. Distinct from, and required in addition to, the instance-URL approval (LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS, LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST or an env-locked instance URL): that approval only covers reaching the engine itself, and because a public engine proxies the public web, extending it to the URLs the engine returns would let a poisoned index turn result fetching into a scan of the LDR host's private network. Environment-only operator gate so it cannot be flipped through the user-writable settings API. Disabled by default and not set by the bundled docker-compose.yml. Link-local addresses (169.254.0.0/16, fe80::/10) and the cloud-metadata endpoints in ALWAYS_BLOCKED_METADATA_IPS stay blocked regardless of this flag. | Security | || `LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST` | String | `None` | No | | Comma-separated list of exact URL origins (scheme://host[:port]) that user-editable PUBLIC search-engine URLs (e.g. the SearXNG instance_url) may use even though they are private / loopback / link-local — e.g. 'http://localhost:8080,http://192.168.1.5:8888'. Finer-grained alternative to LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS=true: private egress is enabled for an engine only when its configured URL matches a listed origin (the engine's request chain, including redirects, then runs with private access — like the blanket flag, but conditional on the match), rather than for any private URL. Matching is exact scheme + host + port (default ports 80/443 implied, host case-insensitive, path/query ignored); no wildcards or CIDR ranges. Entries that fail to parse are ignored. Environment-only operator setting so it cannot be edited through the user-writable settings API. Cloud-metadata endpoints (ALWAYS_BLOCKED_METADATA_IPS) and non-http(s) schemes stay blocked even if listed. | Security | |@@ -226,7 +228,7 @@ They are not available in the Web UI because they are needed to start the applic| `research_library.max_pdf_size_mb` | `LDR_RESEARCH_LIBRARY_MAX_PDF_SIZE_MB` | `3072` | Maximum allowed PDF file size in megabytes for the research library. PDFs larger than this will not be stored. Uploads are also gated by the per-file upload cap (LDR_SECURITY_UPLOAD_MAX_FILE_SIZE_MB, default 3072 MB / 3 GB) — raising this value above that cap has no effect because uploads are rejected before they reach storage. | APP || `research_library.pdf_storage_mode` | `RESEARCH_LIBRARY_PDF_STORAGE_MODE` | `database` | Choose how PDFs are stored. Each user has their own encrypted database. Database mode stores PDFs encrypted within it (secure, portable, isolated per-user). Filesystem mode stores unencrypted files on disk (faster for large files). None stores only extracted text (smallest footprint). | APP || `research_library.shared_library` | `RESEARCH_LIBRARY_SHARED_LIBRARY` | `false` | ⚠️ WARNING: When enabled, all users share the same library directory. Documents from all users will be visible to each other. Only enable in trusted environments. | APP |-| `research_library.storage_path` | `RESEARCH_LIBRARY_STORAGE_PATH` | `~/Documents/LocalDeepResearch/Library` | Base path for storing research library documents. Each user will have their own subdirectory unless shared library is enabled. | APP |+| `research_library.storage_path` | `RESEARCH_LIBRARY_STORAGE_PATH` | `~/Documents/LocalDeepResearch/Library` | Operator-controlled base path for research library documents. Existing saved locations remain in use; set LDR_RESEARCH_LIBRARY_STORAGE_PATH to change the path. Each user has a subdirectory unless shared library is enabled. | APP || `research_library.upload_pdf_storage` | `RESEARCH_LIBRARY_UPLOAD_PDF_STORAGE` | `none` | Choose how user-uploaded PDFs are stored. Database mode stores PDFs encrypted in your personal database (increases database size but allows viewing/downloading later). Text Only extracts and stores only the text content (smallest footprint). Note: Filesystem storage is not available for uploads for security reasons. | APP || `search.cross_engine_max_context_items` | `LDR_SEARCH_CROSS_ENGINE_MAX_CONTEXT_ITEMS` | `30` | Maximum number of search result previews sent to the LLM for relevance ranking during cross-engine filtering. Higher values let the model evaluate more candidates, improving recall at the cost of increased prompt size and latency. | SEARCH || `search.cross_engine_max_results` | `LDR_SEARCH_CROSS_ENGINE_MAX_RESULTS` | `100` | Maximum number of search results to keep after cross-engine filtering in pipeline/source-based strategies. When results from multiple search engines are combined, this limits how many total results are displayed. Higher values show more comprehensive results. Note: Autonomous agent strategies (like langgraph-agent) manage context autonomously and do not apply this filter. | SEARCH |diff --git a/scripts/generate_config_docs.py b/scripts/generate_config_docs.pyindex 5a9dc11396..5f87439987 100755--- a/scripts/generate_config_docs.py+++ b/scripts/generate_config_docs.py@@ -237,7 +237,7 @@ def generate_docs_content(root_dir: Optional[Path] = None) -> str:"# Configuration Reference","","This document is automatically generated from the application's default settings.",- "All settings can be configured via the Web UI (Settings page), or overridden via Environment Variables.",+ "Most settings can be configured via the Web UI (Settings page), or overridden via Environment Variables.","","## Environment Variables","",@@ -247,6 +247,8 @@ def generate_docs_content(root_dir: Optional[Path] = None) -> str:"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. 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.","",+ "`research_library.storage_path` is operator-only. Set `LDR_RESEARCH_LIBRARY_STORAGE_PATH` to change it; existing saved paths stay in use if no override is set, including locations outside `LDR_DATA_DIR`. Audit saved paths when upgrading a multi-user installation. User settings save, delete, import, and reset cannot change this path.",+ "",]# Env-only section with expanded columnsdiff --git a/src/local_deep_research/defaults/research_library/library_settings.json b/src/local_deep_research/defaults/research_library/library_settings.jsonindex 2067bed43a..a37856e390 100644--- a/src/local_deep_research/defaults/research_library/library_settings.json+++ b/src/local_deep_research/defaults/research_library/library_settings.json@@ -1,8 +1,8 @@{"research_library.storage_path": {"category": "research_library",- "description": "Base path for storing research library documents. Each user will have their own subdirectory unless shared library is enabled.",- "editable": true,+ "description": "Operator-controlled base path for research library documents. Existing saved locations remain in use; set LDR_RESEARCH_LIBRARY_STORAGE_PATH to change the path. Each user has a subdirectory unless shared library is enabled.",+ "editable": false,"max_value": null,"min_value": null,"name": "Library Storage Path",diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex da2b92448a..1ae6c2138d 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -491,7 +491,7 @@ class DownloadService:# self.settings so storage_path/shared_library are read from# this user's captured manager — the ambient one is db-less in# background/scheduler threads and would resolve the default- # root, missing a user's UI-customized storage_path. Use+ # root, missing a user's previously saved storage_path. Use# getattr: __init__ always sets self.settings in production# (incl. scheduler threads), but test doubles that construct# a DownloadService via __new__/partial mocks may not — fall@@ -2218,7 +2218,7 @@ class DownloadService:# self.settings so storage_path/shared_library come from this user's# captured manager — the ambient one is db-less in background/scheduler# threads (this runs under the document scheduler) and would resolve- # the default root, missing a user's UI-customized storage_path. Use+ # the default root, missing a user's previously saved storage_path. Use# getattr: __init__ always sets self.settings in production (incl.# scheduler threads), but test doubles that construct a# DownloadService via __new__/partial mocks may not — fall back todiff --git a/src/local_deep_research/research_library/services/pdf_storage_manager.py b/src/local_deep_research/research_library/services/pdf_storage_manager.pyindex bbee81146e..71913902ca 100644--- a/src/local_deep_research/research_library/services/pdf_storage_manager.py+++ b/src/local_deep_research/research_library/services/pdf_storage_manager.py@@ -183,7 +183,7 @@ class PDFStorageManager:Even for read-only callers the legacy shared-root fallback iscross-tenant read primitive on a multi-tenant instance (the shared- root is derived from the user-editable ``research_library.storage_path``+ root is derived from the operator-only ``research_library.storage_path``and per-user resource ids collide by construction), so it only fireswhen the operator opted into it via``research_library.allow_legacy_read_fallback`` — OFF by default.diff --git a/src/local_deep_research/research_library/utils/__init__.py b/src/local_deep_research/research_library/utils/__init__.pyindex a92a9d8109..005e85dfea 100644--- a/src/local_deep_research/research_library/utils/__init__.py+++ b/src/local_deep_research/research_library/utils/__init__.py@@ -506,13 +506,10 @@ def apply_user_subdir(# containing an env-var token resolved to a different, non-existent path on# read than on write (files became unfindable, tracker state corrupted).base = Path(os.path.expandvars(str(base_path))).expanduser().resolve()- # ``shared_library`` removes the per-user directory boundary. Because both- # ``research_library.shared_library`` and ``research_library.storage_path``- # are user-editable, a multi-tenant attacker could otherwise set their own- # shared_library=true and point storage_path at a victim's directory to- # read/overwrite their library PDFs. So shared mode only takes effect when- # an operator has explicitly enabled it via the environment; otherwise the- # per-user subdirectory is always enforced.+ # ``shared_library`` removes the per-user directory boundary. Its flag is+ # user-editable, so shared mode only takes effect when an operator has+ # explicitly enabled it via the environment. The storage path itself is+ # operator-only; a path saved before that policy remains in place.if (shared_library and _shared_library_allowed()) or not username:return base_reject_unsafe_username_component(username)@@ -538,11 +535,11 @@ def _legacy_read_fallback_allowed() -> bool:Environment-only, mirroring ``_shared_library_allowed`` /``filesystem_pdf_storage_allowed``. The legacy fallback resolves a- per-user read miss against the shared root derived from the user-editable- ``research_library.storage_path``. Because a user could point their own- ``storage_path`` at another user's directory, and per-user autoincrement- resource ids collide by construction, that fallback is a cross-tenant- read primitive on a multi-tenant instance. It is therefore OFF by default+ per-user read miss against the shared root derived from+ ``research_library.storage_path``. Legacy saved paths remain in place, and+ per-user autoincrement resource ids collide by construction, so the fallback+ can still be a cross-tenant read primitive on a multi-tenant instance. It+ is therefore OFF by defaultand can only be enabled by the operator via``LDR_RESEARCH_LIBRARY_ALLOW_LEGACY_READ_FALLBACK=true`` — never throughthe user-writable settings API. When off, reads resolve strictly within@@ -719,7 +716,7 @@ def get_absolute_path_from_settings(settings manager instead of the ambient ``get_settings_manager()``. Thismatters in background/scheduler threads with no Flask request context:there the ambient manager resolves to a *db-less* manager that reads only- env vars and the defaults file, so a user's UI-customized+ env vars and the defaults file, so a user's previously saved``research_library.storage_path`` / ``research_library.shared_library``(stored only in their per-user encrypted DB) is invisible and the pathsilently resolves against the default library location — the wrong root.@@ -754,10 +751,10 @@ def get_absolute_path_from_settings(Even for read-only callers the legacy shared-root fallback is across-tenant read primitive on a multi-tenant instance: the shared root is- derived from the user-editable ``research_library.storage_path``, so a user- can point their own ``storage_path`` at another user's directory and — via- the colliding-id fallback — read that user's PDFs. The read fallback is- therefore gated behind the operator-only+ derived from ``research_library.storage_path``. Legacy account-chosen+ paths remain in place, so a pre-existing path that points at another+ user's directory can still expose PDFs through colliding ids. The fallback+ is therefore gated behind the operator-only``research_library.allow_legacy_read_fallback`` env setting and is OFF bydefault; when off, reads resolve strictly within the caller's own per-userroot.@@ -827,7 +824,7 @@ def get_absolute_path_from_settings(# allow_legacy_fallback=False so they never unlink a colliding file that# belongs to another tenant; (2) the operator must have opted into the# shared-root read fallback, since it is a cross-tenant read primitive- # when a user points storage_path at another user's directory; (3) the+ # when a legacy storage_path points at another user's directory; (3) the# per-user root must actually differ from the shared root.if (allow_legacy_fallbackdiff --git a/src/local_deep_research/settings/env_definitions/security.py b/src/local_deep_research/settings/env_definitions/security.pyindex 0ae83fb317..4129b28a67 100644--- a/src/local_deep_research/settings/env_definitions/security.py+++ b/src/local_deep_research/settings/env_definitions/security.py@@ -185,11 +185,11 @@ SECURITY_SETTINGS = ["directory boundary so all users' downloaded PDFs live in one ""shared directory. Disabled by default; this is an ""environment-only operator gate and cannot be enabled through the "- "user-writable settings API. Because both the shared_library flag "- "and the storage_path are otherwise user-editable, leaving shared "- "mode user-toggleable would let a multi-tenant user point their "- "own storage_path at another user's directory and read/overwrite "- "their PDFs. When off, the per-user subdirectory is always "+ "user-writable settings API. The shared_library flag is otherwise "+ "user-editable; leaving shared mode user-toggleable would let an "+ "account drop its per-user directory boundary. The storage_path "+ "is now operator-only, but legacy saved paths remain in place. "+ "When off, the per-user subdirectory is always ""enforced regardless of the user's shared_library setting. Enable ""only on single-tenant or mutually-trusted deployments."),@@ -205,14 +205,11 @@ SECURITY_SETTINGS = ["SECURITY RISK — leave DISABLED (default) on any multi-user or ""untrusted deployment. When ENABLED, library PDF reads that miss ""in the caller's own per-user directory fall back to a shared "- "root derived from the user-editable "- "'research_library.storage_path' setting. On a multi-user "- "instance this re-opens a CROSS-TENANT READ: a user can edit "- "their own storage_path to point at another user's library "- "directory, and because per-user autoincrement resource ids "- "collide by construction (e.g. 'pdfs/5.pdf'), a read of their own "- "document id then resolves — via this fallback — to the OTHER "- "user's PDF and returns its contents. The safe state is OFF: with "+ "root derived from the operator-only "+ "'research_library.storage_path' setting. Legacy saved paths "+ "remain in place, and per-user resource ids collide by design "+ "(e.g. 'pdfs/5.pdf'), so this fallback can still expose another "+ "user's PDF on a multi-user instance. The safe state is OFF: with ""the gate off, reads resolve strictly within the requesting ""user's own per-user root and the fallback never fires. This is ""an environment-only operator gate and cannot be enabled through "diff --git a/src/local_deep_research/settings/manager.py b/src/local_deep_research/settings/manager.pyindex e023d4fbe3..5e42be8856 100644--- a/src/local_deep_research/settings/manager.py+++ b/src/local_deep_research/settings/manager.py@@ -1,6 +1,7 @@import functoolsimport jsonimport os+import stringimport threadingimport timefrom pathlib import Path@@ -28,6 +29,30 @@ from .base import ISettingsManagerfrom .env_registry import registry as env_registry+# Existing saved values remain in place, but accounts cannot redirect library+# reads or writes through their settings after this release.+OPERATOR_ONLY_SETTINGS = frozenset({"research_library.storage_path"})++# SQLite's LIKE ignores case for ASCII letters only. get_setting() finds child+# rows with LIKE, so "RESEARCH_LIBRARY.STORAGE_PATH.x" is a child of+# "research_library.storage_path" there.+_ASCII_CASE_FOLD = str.maketrans(string.ascii_uppercase, string.ascii_lowercase)+++def is_operator_only_setting(key: str) -> bool:+ """Whether only trusted defaults or an LDR_* environment override may set key.++ Matches each operator-only key and its dotted child keys, ignoring ASCII+ case the same way SQLite's LIKE does in the child-row lookup.+ """+ folded = key.translate(_ASCII_CASE_FOLD)+ for root in OPERATOR_ONLY_SETTINGS:+ folded_root = root.translate(_ASCII_CASE_FOLD)+ if folded == folded_root or folded.startswith(f"{folded_root}."):+ return True+ return False++def parse_boolean(value: Any) -> bool:"""Convert various representations to boolean using HTML checkbox semantics.@@ -950,10 +975,18 @@ class SettingsManager(ISettingsManager):# otherwise turn a leaf read into a `{".": v}`-style wrapper dict# rendered as `[object Object]` (#4840). The exact-match row is# always kept so a direct read of a malformed key still works.+ #+ # An operator-only key is never read as a namespace. Its child+ # rows, whether saved before the policy or matched by LIKE as an+ # ASCII case variant, are dropped, so the read returns the exact+ # row's value, the LDR_* override or the default, never a+ # mapping.+ exact_row_only = is_operator_only_setting(key)settings = [sfor s in settings- if str(s.key) == key or is_valid_setting_key(str(s.key))+ if str(s.key) == key+ or (not exact_row_only and is_valid_setting_key(str(s.key)))]if len(settings) == 1 and str(settings[0].key) == key:# Only an exact row is a bottom-level key. A lone child row@@ -1046,6 +1079,11 @@ class SettingsManager(ISettingsManager):"Cannot edit setting {} because no DB was provided.", key)return False+ if is_operator_only_setting(key):+ logger.bind(policy_audit=True).warning(+ "operator-only setting rejected at set_setting", key=key+ )+ return Falseif self.settings_locked:logger.error("Cannot edit setting {} because they are locked.", key)return False@@ -1306,7 +1344,10 @@ class SettingsManager(ISettingsManager):"max_value": setting.max_value,"step": setting.step,"visible": setting.visible,- "editable": False if self.settings_locked else setting.editable,+ "editable": False+ if self.settings_locked+ or is_operator_only_setting(str(setting.key))+ else setting.editable,}# Override from the environment variables if needed.@@ -1425,6 +1466,12 @@ class SettingsManager(ISettingsManager):else:setting_obj = setting+ if is_operator_only_setting(setting_obj.key):+ logger.bind(policy_audit=True).warning(+ "operator-only setting rejected at create_or_update_setting",+ key=setting_obj.key,+ )+ return Noneif self._is_environment_locked(setting_obj.key, "create_or_update_setting"):@@ -1526,6 +1573,11 @@ class SettingsManager(ISettingsManager):)return False+ if is_operator_only_setting(key):+ logger.bind(policy_audit=True).warning(+ "operator-only setting rejected at delete_setting", key=key+ )+ return Falseif self._is_environment_locked(key, "delete_setting"):return False@@ -1691,7 +1743,9 @@ class SettingsManager(ISettingsManager):settings_data: The raw settings data to import.commit: Whether to commit the DB after loading the settings.overwrite: If true, it will overwrite the value of settings that- are already in the database.+ are already in the database. If false, each key keeps the+ value of its own stored row; the values of its child keys+ are never folded into it.delete_extra: If true, it will delete any settings that are inthe database but don't have a corresponding entry in`settings_data`.@@ -1732,6 +1786,18 @@ class SettingsManager(ISettingsManager):continueretained_keys.add(key)+ if is_operator_only_setting(key) and not (+ override_locked and settings_data is self.default_settings+ ):+ # User-driven import/reset must not replace or delete a+ # legacy path. Upgrade/bootstrap imports use the exact+ # trusted defaults mapping and reconcile its metadata+ # with overwrite=False, retaining the stored location.+ logger.bind(policy_audit=True).warning(+ "operator-only setting rejected at import_settings",+ key=key,+ )+ continuesetting_values = dict(raw_setting_values)value_replaced_from_db = Falseif (@@ -1753,6 +1819,24 @@ class SettingsManager(ISettingsManager):value_replaced_from_db = Trueif not overwrite:existing_value = self.get_setting(key, check_env=False)+ if isinstance(existing_value, dict):+ # get_setting() folds child rows, including ASCII+ # case variants its LIKE lookup matches, into a+ # mapping. Writing that mapping back would replace+ # this row's own value, so re-read the row stored+ # under exactly this key.+ stored_row = (+ self.db_session.query(Setting)+ .filter(Setting.key == key)+ .first()+ )+ existing_value = (+ None+ if stored_row is None+ else self.__get_typed_setting_value(+ stored_row, None, check_env=False+ )+ )if existing_value is not None:setting_values["value"] = existing_valuevalue_replaced_from_db = True@@ -1813,9 +1897,13 @@ class SettingsManager(ISettingsManager):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+ if (+ key in retained_keys+ or is_operator_only_setting(key)+ or (+ preserve_environment_locked+ and check_env_setting(key) is not None+ )):continuelogger.debug(f"Deleting extraneous setting: {key}")diff --git a/src/local_deep_research/web/routers/settings.py b/src/local_deep_research/web/routers/settings.pyindex 7f3eb3a357..6043ec8d6c 100644--- a/src/local_deep_research/web/routers/settings.py+++ b/src/local_deep_research/web/routers/settings.py@@ -98,6 +98,7 @@ from ...utilities.url_utils import normalize_urlfrom ...settings.manager import (check_env_setting,get_typed_setting_value,+ is_operator_only_setting,is_valid_setting_key,parse_boolean,)@@ -289,7 +290,8 @@ def _filter_editable_settings(form_data: dict, db_session: Session) -> dict:non_editable_keys = [keyfor key in form_data.keys()- if check_env_setting(key) is not None+ if is_operator_only_setting(key)+ or check_env_setting(key) is not Noneor (key in all_db_settings and not all_db_settings[key].editable)]if non_editable_keys:@@ -2196,6 +2198,8 @@ def _save_all_settings_sync(form_data: dict, username: str):# page reload (#5978). Port of main's# _shape_effective_setting_metadata.for _echo_key, _echo_meta in all_settings.items():+ if is_operator_only_setting(_echo_key):+ _echo_meta["editable"] = Falseif check_env_setting(_echo_key) is None:continue_echo_meta["value"] = get_typed_setting_value(@@ -4877,6 +4881,11 @@ def _api_update_setting_sync(data, key, username):# 403 naming the lock. Lost diagnostic + wrong status code, not# a data-exposure bug (main's contract restored here).settings_manager = get_settings_manager(db_session, username)+ if is_operator_only_setting(key):+ return JSONResponse(+ {"error": f"Setting {key} is operator-only"},+ status_code=403,+ )if settings_manager.settings_locked:return JSONResponse({"error": "Settings are locked"}, status_code=403@@ -5326,6 +5335,11 @@ def api_delete_setting(try:with get_user_db_session(username) as db_session:settings_manager = get_settings_manager(db_session, username)+ if is_operator_only_setting(key):+ return JSONResponse(+ {"error": f"Setting {key} is operator-only"},+ status_code=403,+ )# Settings lock (app.lock_settings) -- ported from main's# api_delete_setting (#5659, "enforce the settings lock on delete,diff --git a/tests/security/test_operator_only_library_path.py b/tests/security/test_operator_only_library_path.pynew file mode 100644index 0000000000..7de56e9a53--- /dev/null+++ b/tests/security/test_operator_only_library_path.py@@ -0,0 +1,327 @@+"""A legacy library path stays in use but cannot be redirected by its owner."""++from contextlib import nullcontext++import pytest+from sqlalchemy import create_engine+from sqlalchemy.orm import sessionmaker++from local_deep_research.database.models import Base, Setting, SettingType+from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ get_library_storage_path,+)+from local_deep_research.settings.manager import (+ SettingsManager,+ is_operator_only_setting,+)+from local_deep_research.web.routers import settings as settings_routes+++KEY = "research_library.storage_path"+# SQLite's LIKE ignores ASCII case, so get_setting(KEY) finds these child rows.+CASE_VARIANT_CHILDREN = (+ "Research_Library.storage_path.x",+ "RESEARCH_LIBRARY.STORAGE_PATH.x",+)+CASE_VARIANT_KEYS = (+ *CASE_VARIANT_CHILDREN,+ "Research_Library.Storage_Path",+ KEY.upper(),+)+++def _add_raw_row(session, key, value):+ """Store a row directly, the way a database written before the policy has it."""+ session.add(+ Setting(+ key=key,+ value=value,+ type=SettingType.APP,+ name="Legacy row",+ ui_element="text",+ )+ )+ session.commit()+++def _stored_path(session):+ """Read the stored path column fresh from the database."""+ return session.query(Setting.value).filter(Setting.key == KEY).scalar()+++def legacy_path_manager(tmp_path, monkeypatch):+ """Model a pre-upgrade account with a custom, still-editable path row."""+ monkeypatch.delenv("LDR_RESEARCH_LIBRARY_STORAGE_PATH", raising=False)+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path / "data"))+ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()+ manager = SettingsManager(session)+ custom_root = tmp_path / "existing-documents" / "Library"+ row = session.query(Setting).filter(Setting.key == KEY).one()+ row.value = str(custom_root)+ row.editable = True+ session.commit()+ try:+ yield manager, session, custom_root+ finally:+ session.close()+ engine.dispose()+++def test_legacy_location_survives_upgrade_and_operator_override(+ legacy_path_manager, monkeypatch+):+ manager, session, custom_root = legacy_path_manager+ monkeypatch.setattr(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ lambda: manager,+ )++ # The shipped default and old custom roots may be outside LDR_DATA_DIR.+ # Preserve their files in place while changing who can edit the setting.+ user_root = get_library_storage_path("alice")+ assert user_root == custom_root / "alice"+ stored_pdf = user_root / "pdfs" / "5.pdf"+ stored_pdf.parent.mkdir(parents=True)+ stored_pdf.write_bytes(b"existing pdf")+ assert (+ get_absolute_path_from_settings(+ "pdfs/5.pdf",+ "alice",+ allow_legacy_fallback=False,+ settings_manager=manager,+ )+ == stored_pdf+ )++ manager.import_settings(+ manager.default_settings, overwrite=False, override_locked=True+ )+ row = session.query(Setting).filter(Setting.key == KEY).one()+ assert row.value == str(custom_root)+ assert row.editable is False+ assert stored_pdf.read_bytes() == b"existing pdf"++ operator_root = custom_root.parent / "operator-selected"+ monkeypatch.setenv("LDR_RESEARCH_LIBRARY_STORAGE_PATH", str(operator_root))+ assert manager.get_setting(KEY) == str(operator_root)+ assert manager.get_all_settings()[KEY]["editable"] is False+ assert _stored_path(session) == str(custom_root)+++def test_legacy_editable_row_rejects_direct_and_imported_changes(+ legacy_path_manager, tmp_path+):+ manager, session, custom_root = legacy_path_manager+ redirected = str(tmp_path / "other-users-files")+ assert manager.get_all_settings()[KEY]["editable"] is False+ assert manager.set_setting(KEY, redirected) is False+ assert manager.set_setting(f"{KEY}.child", redirected) is False+ assert (+ manager.create_or_update_setting(+ {"key": KEY, "name": "Library Storage Path", "value": redirected}+ )+ is None+ )+ assert manager.delete_setting(KEY) is False++ supplied = dict(manager.default_settings[KEY])+ supplied.update(value=redirected, editable=True)+ manager.import_settings({KEY: supplied}, delete_extra=True)+ assert manager.get_setting(KEY) == str(custom_root)+ manager.import_settings({KEY: supplied}, override_locked=True)+ assert manager.get_setting(KEY) == str(custom_root)+ manager.import_settings({}, delete_extra=True)+ assert manager.get_setting(KEY) == str(custom_root)++ # The authenticated import/reset routes use this wrapper. It must not+ # reset a pre-existing library location to the bundled default.+ manager.load_from_defaults_file()+ row = session.query(Setting).filter(Setting.key == KEY).one()+ assert row.value == str(custom_root)+++def test_http_write_helpers_reject_stale_editable_rows(+ legacy_path_manager, monkeypatch, tmp_path+):+ manager, session, custom_root = legacy_path_manager+ monkeypatch.setattr(+ settings_routes,+ "get_user_db_session",+ lambda _username: nullcontext(session),+ )+ monkeypatch.setattr(+ settings_routes,+ "get_settings_manager",+ lambda *_args, **_kwargs: manager,+ )++ response = settings_routes._api_update_setting_sync(+ {"value": str(tmp_path / "new-root")}, KEY, "alice"+ )+ assert response.status_code == 403+ assert manager.get_setting(KEY) == str(custom_root)++ form_data = {+ KEY: str(tmp_path / "new-root"),+ "research_library.confirm_deletions": False,+ }+ settings_routes._filter_editable_settings(form_data, session)+ assert KEY not in form_data+ assert form_data == {"research_library.confirm_deletions": False}+++def test_bulk_save_echo_masks_legacy_editability(+ legacy_path_manager, monkeypatch+):+ manager, session, custom_root = legacy_path_manager+ monkeypatch.setattr(+ settings_routes,+ "get_user_db_session",+ lambda _username: nullcontext(session),+ )+ monkeypatch.setattr(+ settings_routes,+ "get_settings_manager",+ lambda *_args, **_kwargs: manager,+ )+ monkeypatch.setattr(+ settings_routes, "invalidate_settings_caches", lambda _: None+ )+ monkeypatch.setattr(+ settings_routes, "reschedule_document_jobs_if_needed", lambda *_: None+ )+ monkeypatch.setattr(+ settings_routes, "reschedule_zotero_jobs_if_needed", lambda *_: None+ )++ result = settings_routes._save_all_settings_sync(+ {"research_library.confirm_deletions": False}, "alice"+ )+ assert result["status"] == "success"+ assert result["settings"][KEY]["value"] == str(custom_root)+ assert result["settings"][KEY]["editable"] is False+++def test_operator_only_match_covers_every_child_row_the_lookup_returns(+ legacy_path_manager,+):+ manager, session, _custom_root = legacy_path_manager+ candidates = {+ f"{KEY[:i]}{KEY[i].upper()}{KEY[i + 1 :]}.x"+ for i in range(len(KEY))+ if KEY[i].isalpha()+ }+ candidates |= {f"{KEY.upper()}.X", f"{KEY.title()}.x", f"{KEY}.x"}+ # SQLite does not fold these lookalikes, so the lookup must skip them.+ candidates |= {+ f"{KEY.replace('s', chr(0x017F), 1)}.x",+ f"{KEY.replace('i', chr(0x0131), 1)}.x",+ f"{KEY.replace('a', chr(0x0430), 1)}.x",+ }+ for key in sorted(candidates):+ _add_raw_row(session, key, "/redirected")++ # get_setting() finds child rows with this lookup, so every row it+ # returns for KEY must be refused as operator-only.+ returned = {+ str(row.key) for row in manager._SettingsManager__query_settings(KEY)+ }+ assert {key for key in candidates if key.isascii()} <= returned+ assert not {key for key in candidates if not key.isascii()} & returned+ assert all(is_operator_only_setting(key) for key in returned)++[email protected]("variant", CASE_VARIANT_KEYS)+def test_case_variant_keys_are_refused_by_every_manager_write(+ legacy_path_manager, tmp_path, variant+):+ manager, session, custom_root = legacy_path_manager+ redirected = str(tmp_path / "other-users-files")++ assert manager.set_setting(variant, redirected) is False+ assert (+ manager.create_or_update_setting(+ {+ "key": variant,+ "name": "Library Storage Path",+ "value": redirected,+ }+ )+ is None+ )+ supplied = dict(manager.default_settings[KEY])+ supplied.update(value=redirected, editable=True)+ manager.import_settings({variant: supplied})++ assert session.query(Setting).filter(Setting.key == variant).count() == 0+ assert manager.get_setting(KEY) == str(custom_root)+ assert manager.get_all_settings()[KEY]["editable"] is False+++def test_legacy_child_rows_never_replace_the_path_on_read(+ legacy_path_manager, monkeypatch, tmp_path+):+ manager, session, custom_root = legacy_path_manager+ for child in (f"{KEY}.x", *CASE_VARIANT_CHILDREN):+ _add_raw_row(session, child, str(tmp_path / "redirected"))++ assert manager.get_setting(KEY) == str(custom_root)+ assert manager.get_setting(KEY, check_env=False) == str(custom_root)+ for child in CASE_VARIANT_CHILDREN:+ assert manager.get_all_settings()[child]["editable"] is False++ operator_root = tmp_path / "operator-selected"+ monkeypatch.setenv("LDR_RESEARCH_LIBRARY_STORAGE_PATH", str(operator_root))+ assert manager.get_setting(KEY) == str(operator_root)+++def test_version_bump_import_keeps_the_path_with_legacy_child_rows(+ legacy_path_manager, tmp_path+):+ manager, session, custom_root = legacy_path_manager+ for child in (f"{KEY}.x", *CASE_VARIANT_CHILDREN):+ _add_raw_row(session, child, str(tmp_path / "redirected"))++ manager.import_settings(+ manager.default_settings, overwrite=False, override_locked=True+ )++ assert _stored_path(session) == str(custom_root)+ assert manager.get_setting(KEY) == str(custom_root)+++def test_http_write_helpers_reject_case_variant_keys(+ legacy_path_manager, monkeypatch, tmp_path+):+ manager, session, custom_root = legacy_path_manager+ monkeypatch.setattr(+ settings_routes,+ "get_user_db_session",+ lambda _username: nullcontext(session),+ )+ monkeypatch.setattr(+ settings_routes,+ "get_settings_manager",+ lambda *_args, **_kwargs: manager,+ )++ for variant in CASE_VARIANT_KEYS:+ response = settings_routes._api_update_setting_sync(+ {"value": str(tmp_path / "new-root")}, variant, "alice"+ )+ assert response.status_code == 403, variant+ assert (+ session.query(Setting).filter(Setting.key == variant).count() == 0+ )++ form_data = {+ variant: str(tmp_path / "new-root") for variant in CASE_VARIANT_KEYS+ }+ form_data["research_library.confirm_deletions"] = False+ settings_routes._filter_editable_settings(form_data, session)+ assert form_data == {"research_library.confirm_deletions": False}+ assert manager.get_setting(KEY) == str(custom_root)diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.jsonindex 575f2f15cb..31263308ca 100644--- a/tests/settings/golden_master_settings.json+++ b/tests/settings/golden_master_settings.json@@ -2802,8 +2802,8 @@},"research_library.storage_path": {"category": "research_library",- "description": "Base path for storing research library documents. Each user will have their own subdirectory unless shared library is enabled.",- "editable": true,+ "description": "Operator-controlled base path for research library documents. Existing saved locations remain in use; set LDR_RESEARCH_LIBRARY_STORAGE_PATH to change the path. Each user has a subdirectory unless shared library is enabled.",+ "editable": false,"env_var": "RESEARCH_LIBRARY_STORAGE_PATH","max_value": null,"min_value": null,diff --git a/tests/settings/test_import_settings_validation.py b/tests/settings/test_import_settings_validation.pyindex 06f7a93f9d..77be6355b5 100644--- a/tests/settings/test_import_settings_validation.py+++ b/tests/settings/test_import_settings_validation.py@@ -263,6 +263,105 @@ class TestSettingsManagerImportValidation:assert setting.value == "legacy_stored"assert setting.options == ["d", "w", "m", "y", "all"]+ def test_reconciliation_keeps_a_scalar_row_with_child_rows(self, session):+ """Child rows never replace a stored value during reconciliation.++ get_setting() folds child rows into a mapping, and its LIKE lookup+ also matches ASCII case variants of the key. The version-bump+ import must keep the row's own value instead of that mapping.+ """+ from local_deep_research.database.models import Setting, SettingType+ from local_deep_research.settings.manager import SettingsManager++ manager = SettingsManager(db_session=session)+ stored = (+ session.query(Setting).filter(Setting.key == "llm.provider").one()+ )+ stored.value = "openai"+ for child in ("llm.provider.extra", "LLM.PROVIDER.extra"):+ session.add(+ Setting(+ key=child,+ value="x",+ type=SettingType.LLM,+ name="Extra",+ ui_element="text",+ )+ )+ session.commit()+ assert isinstance(manager.get_setting("llm.provider"), dict)++ manager.import_settings(+ manager.default_settings, overwrite=False, override_locked=True+ )++ stored_value = (+ session.query(Setting.value)+ .filter(Setting.key == "llm.provider")+ .scalar()+ )+ assert stored_value == "openai"++ def test_reconciliation_restores_a_missing_row_with_child_rows(+ self, session+ ):+ """A missing row is re-seeded from its default, not its children."""+ from local_deep_research.database.models import Setting, SettingType+ from local_deep_research.settings.manager import SettingsManager++ manager = SettingsManager(db_session=session)+ key = "search.iterations"+ default_value = manager.default_settings[key]["value"]+ session.query(Setting).filter(Setting.key == key).delete()+ session.add(+ Setting(+ key=f"{key}.extra",+ value="x",+ type=SettingType.SEARCH,+ name="Extra",+ ui_element="text",+ )+ )+ session.commit()++ manager.import_settings(+ manager.default_settings, overwrite=False, override_locked=True+ )++ stored_value = (+ session.query(Setting.value).filter(Setting.key == key).scalar()+ )+ assert stored_value == default_value++ def test_reconciliation_keeps_a_dict_row_next_to_its_child_keys(+ self, session+ ):+ """A dict-valued row keeps its own value beside its shipped children."""+ from local_deep_research.database.models import Setting+ from local_deep_research.settings.manager import SettingsManager++ manager = SettingsManager(db_session=session)+ key = "search.engine.web.gutenberg"+ stored = (+ session.query(Setting.value).filter(Setting.key == key).scalar()+ )+ child_keys = [+ row[0]+ for row in session.query(Setting.key).all()+ if row[0].startswith(f"{key}.")+ ]+ assert isinstance(stored, dict)+ assert child_keys++ manager.import_settings(+ manager.default_settings, overwrite=False, override_locked=True+ )++ stored_after = (+ session.query(Setting.value).filter(Setting.key == key).scalar()+ )+ assert stored_after == stored+def test_fresh_install_seeds_every_default(self, session):"""Every current default imports cleanly through the validated path.diff --git a/tests/web/routers/test_settings_api.py b/tests/web/routers/test_settings_api.pyindex 084772e272..c6dac5d01e 100644--- a/tests/web/routers/test_settings_api.py+++ b/tests/web/routers/test_settings_api.py@@ -465,3 +465,38 @@ def test_manual_corruption_repair_endpoint_is_removed(auth_client):"""Migration 0031 replaces the authenticated manual repair operation."""response = auth_client.post("/settings/fix_corrupted_settings")assert response.status_code == 404+++def test_library_storage_path_is_operator_only_over_http(auth_client):+ key = "research_library.storage_path"+ before = auth_client.get(f"/settings/api/{key}")+ assert before.status_code == 200+ assert before.json()["editable"] is False+ # The bulk read goes through get_setting(), which folds child rows.+ bulk_url = f"/settings/api/bulk?keys[]={key}"+ bulk_before = auth_client.get(bulk_url).json()["settings"][key]["value"]+ assert isinstance(bulk_before, str)++ # SQLite's LIKE finds child rows regardless of ASCII case, so case+ # variants of the key and of its children are refused as well.+ case_variants = (+ "Research_Library.storage_path.x",+ "RESEARCH_LIBRARY.STORAGE_PATH.x",+ "Research_Library.Storage_Path",+ )+ for attempted_key in (key, f"{key}.child", *case_variants):+ response = auth_client.put(+ f"/settings/api/{attempted_key}", json={"value": "/tmp/redirected"}+ )+ assert response.status_code == 403, attempted_key+ for attempted_key in (key, *case_variants):+ response = auth_client.delete(f"/settings/api/{attempted_key}")+ assert response.status_code == 403, attempted_key+ for attempted_key in case_variants:+ response = auth_client.get(f"/settings/api/{attempted_key}")+ assert response.status_code == 404, attempted_key++ after = auth_client.get(f"/settings/api/{key}")+ assert after.json()["value"] == before.json()["value"]+ bulk_after = auth_client.get(bulk_url).json()["settings"][key]["value"]+ assert bulk_after == bulk_before