~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
security: close settings-key injection bypass on form-POST route and harden namespace gates (#3528)
LearningCircuit6430dd4156b6
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex 3725c63fa8..6f8983684a 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -90,6 +90,60 @@ settings_bp = Blueprint("settings", __name__, url_prefix="/settings")# Settings with dynamically populated options (excluded from validation)DYNAMIC_SETTINGS = ["llm.provider", "llm.model", "search.tool"]+# Namespace validation for new setting creation via the web API.+# Keys starting with any ALLOWED prefix may be created; any prefix in+# BLOCKED takes precedence and is rejected even if it also matches an+# allowed prefix. Existing keys (updates) bypass this check — it only+# applies to creation of new DB rows through the three write routes.+ALLOWED_SETTING_PREFIXES = frozenset(+ {+ "app.",+ "backup.",+ "benchmark.",+ "database.",+ "document_scheduler.",+ "embeddings.",+ "focused_iteration.",+ "general.",+ "langgraph_agent.",+ "llm.",+ "mcp.",+ "news.",+ "notifications.",+ "rag.",+ "rate_limiting.",+ "report.",+ "research_library.",+ "search.",+ "ui.",+ "web.",+ }+)+BLOCKED_SETTING_PREFIXES = frozenset(+ {+ "auth.",+ "bootstrap.",+ "db_config.",+ "security.",+ "server.",+ "testing.",+ }+)+++def _is_allowed_new_setting_key(key: str) -> bool:+ """Return True if *key* is permitted to be created via the web API."""+ if not isinstance(key, str) or not key or ".." in key:+ return False+ key = key.lower()+ for prefix in BLOCKED_SETTING_PREFIXES:+ if key.startswith(prefix):+ return False+ for prefix in ALLOWED_SETTING_PREFIXES:+ if key.startswith(prefix):+ return True+ return False+def _get_setting_from_session(key: str, default=None):"""Helper to get a setting using the current session context."""@@ -375,6 +429,22 @@ def save_all_settings(db_session=None, settings_manager=None):})else:+ # 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"],+ )+ validation_errors.append(+ {+ "key": key,+ "name": key,+ "error": "Creating settings under this namespace is not allowed.",+ }+ )+ continue+# Create a new settingnew_setting = {"key": key,@@ -577,6 +647,7 @@ def save_settings(db_session=None, settings_manager=None):updated_count = 0failed_count = 0+ rejected_count = 0# Fetch all settings once to avoid N+1 query problemall_db_settings = {@@ -602,6 +673,18 @@ def save_settings(db_session=None, settings_manager=None):# Get the setting from pre-fetched dictdb_setting = all_db_settings.get(key)+ # Namespace validation: reject new keys outside allowed prefixes.+ # Existing keys (updates) bypass this check — it only applies+ # to creation of brand-new rows through this form-POST route.+ if db_setting is None and not _is_allowed_new_setting_key(key):+ logger.warning(+ "Security: Rejected setting outside allowed namespaces: {!r} (user={!r})",+ key,+ session["username"],+ )+ rejected_count += 1+ continue+# Coerce form POST string to correct Python type.if db_setting:value = coerce_setting_for_write(@@ -634,6 +717,12 @@ def save_settings(db_session=None, settings_manager=None):f"Warning: {failed_count} settings failed to save.","warning",)+ if rejected_count > 0:+ flash(+ f"Rejected {rejected_count} settings (unknown namespace). "+ "This may indicate a bug or an attempted injection.",+ "error",+ )invalidate_settings_caches(session["username"])except Exception:@@ -744,6 +833,7 @@ def api_get_db_setting(key, db_session=None, settings_manager=None):@settings_bp.route("/api/<path:key>", methods=["PUT"])@login_required+@settings_limit@require_json_body(error_message="No data provided")@with_user_session(include_settings_manager=False)def api_update_setting(key, db_session=None):@@ -814,6 +904,20 @@ def api_update_setting(key, db_session=None):invalidate_settings_caches(session["username"])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": f"Creating settings under this namespace is not allowed: {key}"+ }+ ), 400+# Create new setting with default metadatasetting_dict = {"key": key,@@ -822,7 +926,8 @@ def api_update_setting(key, db_session=None):"description": f"Setting for {key}",}- # Add additional metadata if provided+ # Add additional metadata if provided.+ # 'visible' and 'editable' are system-controlled — not accepted from callers.for field in ["type","name",@@ -833,8 +938,6 @@ def api_update_setting(key, db_session=None):"min_value","max_value","step",- "visible",- "editable",]:if field in data:setting_dict[field] = data[field]diff --git a/tests/api_tests/test_all_endpoints.py b/tests/api_tests/test_all_endpoints.pyindex 168f21b78e..0307252f15 100644--- a/tests/api_tests/test_all_endpoints.py+++ b/tests/api_tests/test_all_endpoints.py@@ -69,8 +69,9 @@ class TestAllEndpoints:)assert response.status_code == 200, f"Bulk get failed: {response.data}"- # Test setting CRUD- test_key = "test.endpoint.value"+ # Test setting CRUD (use an allow-listed prefix so the+ # namespace gate permits creation of this throwaway key).+ test_key = "llm.endpoint_test_value"test_value = {"value": "test_endpoint_123", "editable": True}# Create/Updatediff --git a/tests/api_tests/test_comprehensive_apis.py b/tests/api_tests/test_comprehensive_apis.pyindex 6b77255b1b..e1495072e6 100644--- a/tests/api_tests/test_comprehensive_apis.py+++ b/tests/api_tests/test_comprehensive_apis.py@@ -70,8 +70,9 @@ class TestComprehensiveAPIs:data = json.loads(response.data)assert "engines" in data or "engine_options" in data- # Test setting CRUD- test_key = "test.setting"+ # Test setting CRUD (use an allow-listed prefix so the+ # namespace gate permits creation of this throwaway key).+ test_key = "llm.test_setting"test_value = {"value": "test_value_123"}# Create/Update settingdiff --git a/tests/web/routes/test_settings_routes_corrupted_coverage.py b/tests/web/routes/test_settings_routes_corrupted_coverage.pyindex 3c4a7968ad..f9549d2d7d 100644--- a/tests/web/routes/test_settings_routes_corrupted_coverage.py+++ b/tests/web/routes/test_settings_routes_corrupted_coverage.py@@ -448,7 +448,7 @@ class TestApiUpdateSettingCreatesNew:def test_create_new_setting_via_put(self):"""PUT to a non-existent key creates a new setting and returns 201."""- mock_new = _make_setting(key="custom.new_param", value="hello")+ mock_new = _make_setting(key="llm.new_param", value="hello")mock_new.type = MagicMock()mock_new.type.value = "app"@@ -468,14 +468,14 @@ class TestApiUpdateSettingCreatesNew:return_value=mock_new,):resp = client.put(- f"{SETTINGS_PREFIX}/api/custom.new_param",+ f"{SETTINGS_PREFIX}/api/llm.new_param",json={"value": "hello", "type": "app"},)assert resp.status_code == 201data = resp.get_json()assert "created successfully" in data["message"]- assert data["setting"]["key"] == "custom.new_param"+ assert data["setting"]["key"] == "llm.new_param"def test_create_new_setting_failure_returns_500(self):"""PUT to a non-existent key returns 500 when creation fails."""@@ -494,7 +494,7 @@ class TestApiUpdateSettingCreatesNew:return_value=None,):resp = client.put(- f"{SETTINGS_PREFIX}/api/custom.new_param",+ f"{SETTINGS_PREFIX}/api/llm.new_param",json={"value": "hello"},)diff --git a/tests/web/routes/test_settings_routes_coverage.py b/tests/web/routes/test_settings_routes_coverage.pyindex ef8bdf4f8c..e2d2c2167d 100644--- a/tests/web/routes/test_settings_routes_coverage.py+++ b/tests/web/routes/test_settings_routes_coverage.py@@ -389,7 +389,7 @@ class TestApiUpdateSetting:self, mock_create, authenticated_client):"""PUT creates a new setting when key doesn't exist."""- mock_new = _make_setting(key="new.setting", value="v")+ mock_new = _make_setting(key="llm.new_setting", value="v")mock_new.type = MagicMock()mock_new.type.value = "app"mock_create.return_value = mock_new@@ -402,7 +402,7 @@ class TestApiUpdateSetting:)mock_ctx.return_value.__exit__ = MagicMock(return_value=False)resp = authenticated_client.put(- f"{SETTINGS_PREFIX}/api/new.setting",+ f"{SETTINGS_PREFIX}/api/llm.new_setting",json={"value": "hello", "type": "app"},)assert resp.status_code == 201@@ -417,7 +417,7 @@ class TestApiUpdateSetting:)mock_ctx.return_value.__exit__ = MagicMock(return_value=False)resp = authenticated_client.put(- f"{SETTINGS_PREFIX}/api/new.fail",+ f"{SETTINGS_PREFIX}/api/llm.new_fail",json={"value": "hello"},)assert resp.status_code == 500diff --git a/tests/web/routes/test_settings_routes_deep_coverage.py b/tests/web/routes/test_settings_routes_deep_coverage.pyindex b7736b019c..a5002498df 100644--- a/tests/web/routes/test_settings_routes_deep_coverage.py+++ b/tests/web/routes/test_settings_routes_deep_coverage.py@@ -242,8 +242,8 @@ class TestSaveAllSettingsNewSettingUIDetection:assert call_args["ui_element"] == "textarea"@patch(f"{MODULE}.create_or_update_setting")- def test_unknown_prefix_handled_gracefully(self, mock_create):- """Unknown prefix is handled gracefully without crashing."""+ def test_unknown_prefix_rejected_with_validation_error(self, mock_create):+ """Unknown prefix is rejected by the namespace gate with 400."""app = _create_test_app()with _authenticated_client(app) as client:with patch(f"{DECORATOR_MODULE}.get_user_db_session") as mock_ctx:@@ -257,7 +257,14 @@ class TestSaveAllSettingsNewSettingUIDetection:f"{SETTINGS_PREFIX}/save_all_settings",json={"custom.param": "value"},)- assert resp.status_code == 200+ # Namespace gate rejects the key; response has status=error with 400+ assert resp.status_code == 400+ data = resp.get_json()+ assert any(+ e["key"] == "custom.param" and "not allowed" in e["error"]+ for e in data["errors"]+ )+ mock_create.assert_not_called()class TestSaveAllSettingsSkipInvalidKeys:diff --git a/tests/web/routes/test_settings_routes_deep_coverage2.py b/tests/web/routes/test_settings_routes_deep_coverage2.pyindex 7f26d243f4..4355762d2b 100644--- a/tests/web/routes/test_settings_routes_deep_coverage2.py+++ b/tests/web/routes/test_settings_routes_deep_coverage2.py@@ -293,7 +293,7 @@ class TestApiUpdateSettingCreateFails:mock_session.query.return_value.filter.return_value.first.return_value = Nonewith patch(f"{MODULE}.create_or_update_setting", return_value=None):resp = client.put(- f"{SETTINGS_PREFIX}/api/new.setting",+ f"{SETTINGS_PREFIX}/api/llm.new_setting",json={"value": "val"},content_type="application/json",)diff --git a/tests/web/routes/test_settings_routes_security.py b/tests/web/routes/test_settings_routes_security.pyindex 0fd9fcfa70..d8107338b4 100644--- a/tests/web/routes/test_settings_routes_security.py+++ b/tests/web/routes/test_settings_routes_security.py@@ -112,3 +112,214 @@ class TestSaveAllSettingsValidation:data = resp.get_json()assert data["status"] == "error"assert "No settings data" in data["message"]+++# ---------------------------------------------------------------------------+# Namespace validation gate (new-key creation)+# ---------------------------------------------------------------------------+++class TestNewSettingNamespaceGate:+ """The three write routes must reject new keys outside allowed namespaces."""++ def test_put_api_rejects_blocked_prefix_with_400(self):+ """PUT to a new key under a blocked prefix returns 400, not 403/201."""+ app = _create_test_app()+ with _authenticated_client(app) as (client, _):+ resp = client.put(+ "/settings/api/security.evil",+ json={"value": "bad"},+ content_type="application/json",+ )+ assert resp.status_code == 400+ data = resp.get_json()+ assert "not allowed" in data["error"].lower()++ def test_put_api_rejects_unknown_prefix_with_400(self):+ """Unknown prefixes (neither allow nor block) also return 400."""+ app = _create_test_app()+ with _authenticated_client(app) as (client, _):+ resp = client.put(+ "/settings/api/custom.foo",+ json={"value": "x"},+ content_type="application/json",+ )+ assert resp.status_code == 400++ def test_save_all_settings_rejects_blocked_prefix(self):+ """save_all_settings rejects new keys in blocked namespaces via validation_errors."""+ app = _create_test_app()+ # Empty DB so the key is a create attempt, not an update.+ with _authenticated_client(app, mock_settings=[]) as (client, _):+ resp = client.post(+ "/settings/save_all_settings",+ json={"security.admin_override": True},+ content_type="application/json",+ )+ assert resp.status_code == 400+ data = resp.get_json()+ assert data["status"] == "error"+ assert any(+ e["key"] == "security.admin_override"+ and "not allowed" in e["error"]+ for e in data["errors"]+ )++ def test_save_all_settings_rejects_unknown_prefix(self):+ """save_all_settings rejects new keys with unknown prefixes."""+ app = _create_test_app()+ with _authenticated_client(app, mock_settings=[]) as (client, _):+ resp = client.post(+ "/settings/save_all_settings",+ json={"custom.injected": 1},+ content_type="application/json",+ )+ assert resp.status_code == 400+ data = resp.get_json()+ assert any(e["key"] == "custom.injected" for e in data["errors"])++ def test_save_settings_form_post_rejects_blocked_prefix(self):+ """save_settings (non-JS form-POST fallback) rejects blocked namespaces.++ This is the bypass path the original PR #3088 left unguarded — an+ attacker switching from AJAX to form POST must not be able to inject+ `security.*` / `auth.*` / `bootstrap.*` keys. settings_manager.set_setting+ must not be called for rejected keys.+ """+ app = _create_test_app()+ # The @with_user_session decorator constructs SettingsManager(db_session)+ # directly; patch the SettingsManager class at the decorator's import site.+ mock_sm_instance = Mock()+ mock_sm_instance.set_setting.return_value = True+ # Empty DB so the key is genuinely a create attempt, not an update.+ with _authenticated_client(app, mock_settings=[]) as (client, _):+ with patch(+ "local_deep_research.web.utils.route_decorators.SettingsManager",+ return_value=mock_sm_instance,+ ):+ resp = client.post(+ "/settings/save_settings",+ data={"security.admin_override": "true"},+ )+ # The route redirects; the rejection itself is signalled via flash.+ assert resp.status_code == 302+ # The rejected key must NOT have reached set_setting.+ for call in mock_sm_instance.set_setting.call_args_list:+ assert call.args[0] != "security.admin_override", (+ f"Blocked key reached set_setting: {call}"+ )++ def test_save_settings_form_post_rejects_unknown_prefix(self):+ """save_settings rejects unknown (non-allow-listed) prefixes too."""+ app = _create_test_app()+ mock_sm_instance = Mock()+ mock_sm_instance.set_setting.return_value = True+ with _authenticated_client(app, mock_settings=[]) as (client, _):+ with patch(+ "local_deep_research.web.utils.route_decorators.SettingsManager",+ return_value=mock_sm_instance,+ ):+ resp = client.post(+ "/settings/save_settings",+ data={"custom.injected": "x"},+ )+ assert resp.status_code == 302+ for call in mock_sm_instance.set_setting.call_args_list:+ assert call.args[0] != "custom.injected", (+ f"Unknown-prefix key reached set_setting: {call}"+ )++ def test_save_settings_form_post_allows_known_prefix(self):+ """save_settings still writes legitimate keys in the allow-list."""+ app = _create_test_app()+ mock_sm_instance = Mock()+ mock_sm_instance.set_setting.return_value = True+ with _authenticated_client(app, mock_settings=[]) as (client, _):+ with patch(+ "local_deep_research.web.utils.route_decorators.SettingsManager",+ return_value=mock_sm_instance,+ ):+ resp = client.post(+ "/settings/save_settings",+ data={"llm.new_temperature": "0.5"},+ )+ assert resp.status_code == 302+ # Legitimate key DID reach set_setting.+ assert any(+ call.args[0] == "llm.new_temperature"+ for call in mock_sm_instance.set_setting.call_args_list+ ), "Legitimate allow-listed key did not reach set_setting"+++# ---------------------------------------------------------------------------+# Unit tests for _is_allowed_new_setting_key guards+# ---------------------------------------------------------------------------+++class TestIsAllowedNewSettingKey:+ """Helper guards: type, empty-string, double-dot, block-then-allow ordering."""++ def test_rejects_non_string(self):+ from local_deep_research.web.routes.settings_routes import (+ _is_allowed_new_setting_key,+ )++ assert _is_allowed_new_setting_key(None) is False+ assert _is_allowed_new_setting_key(42) is False+ assert _is_allowed_new_setting_key(["llm.model"]) is False++ def test_rejects_empty_and_whitespace_only(self):+ from local_deep_research.web.routes.settings_routes import (+ _is_allowed_new_setting_key,+ )++ assert _is_allowed_new_setting_key("") is False+ # Whitespace-only doesn't match any allowed prefix.+ assert _is_allowed_new_setting_key(" ") is False++ def test_rejects_double_dot(self):+ from local_deep_research.web.routes.settings_routes import (+ _is_allowed_new_setting_key,+ )++ # Even with a valid leading prefix, double-dot is malformed.+ assert _is_allowed_new_setting_key("llm..foo") is False+ assert _is_allowed_new_setting_key("search.engine..x") is False++ def test_block_list_wins_over_allow_list(self):+ from local_deep_research.web.routes.settings_routes import (+ _is_allowed_new_setting_key,+ )++ # Even if a future allow-list contained "security.", the block-list+ # would still reject; check the current lists too.+ assert _is_allowed_new_setting_key("security.foo") is False+ assert _is_allowed_new_setting_key("auth.token") is False+ assert _is_allowed_new_setting_key("bootstrap.x") is False+ assert _is_allowed_new_setting_key("db_config.kdf_iterations") is False+ assert _is_allowed_new_setting_key("server.max_concurrent") is False+ assert _is_allowed_new_setting_key("testing.test_mode") is False++ def test_case_insensitive_prefix_match(self):+ """Uppercase keys are lowercased before prefix comparison."""+ from local_deep_research.web.routes.settings_routes import (+ _is_allowed_new_setting_key,+ )++ assert _is_allowed_new_setting_key("SECURITY.injected") is False+ assert _is_allowed_new_setting_key("LLM.custom_key") is True++ def test_allows_known_prefixes(self):+ from local_deep_research.web.routes.settings_routes import (+ _is_allowed_new_setting_key,+ )++ for key in (+ "app.flag",+ "backup.destination",+ "llm.model",+ "search.tool",+ "rag.chunk_size",+ "embeddings.ollama.url",+ ):+ assert _is_allowed_new_setting_key(key) is True, key