~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): redact remaining GET endpoints + extend empty-password guard to /save_settings (#3988)
LearningCircuit5d9b12ed8717
diff --git a/changelog.d/+settings-remaining-leaks.security.md b/changelog.d/+settings-remaining-leaks.security.mdnew file mode 100644index 0000000000..4761591369--- /dev/null+++ b/changelog.d/+settings-remaining-leaks.security.md@@ -0,0 +1 @@+**Closed three remaining password-leak paths in the settings module.** `GET /settings/api/<key>` and `GET /settings/api/bulk` now redact password-typed values to `[REDACTED]` (matching the bulk `/settings/api` endpoint redacted in the previous release). `POST /save_settings` (the JS-disabled form-encoded fallback) now treats an empty value for a password setting as a no-op, so no submission path can wipe a stored API key with empty string.diff --git a/src/local_deep_research/security/data_sanitizer.py b/src/local_deep_research/security/data_sanitizer.pyindex 1c02417fea..8abfa13871 100644--- a/src/local_deep_research/security/data_sanitizer.py+++ b/src/local_deep_research/security/data_sanitizer.py@@ -63,6 +63,33 @@ class DataSanitizer:}return key.rsplit(".", 1)[-1].lower() in sens+ @staticmethod+ def redact_value(+ key: str,+ ui_element: str | None = None,+ value: Any = None,+ sensitive_keys: Set[str] | None = None,+ redaction_text: str = REDACTION_TEXT,+ ) -> Any:+ """Redact a single setting's value when it holds a set secret.++ The single-value counterpart of ``redact_settings_snapshot``: it+ applies the SAME ``is_sensitive_setting`` predicate and the SAME+ empty-value rule, so every read path that ships a setting to the+ browser (the bulk GET, the singular GET, the run-time snapshot)+ masks identically. Returns ``redaction_text`` for a non-empty+ sensitive value, otherwise ``value`` unchanged.++ Empty values (``None``, ``""``, ``[]``, ``{}``) are left readable so+ the UI can tell "configured" from "not configured" without leaking+ that a secret is set.+ """+ if DataSanitizer.is_sensitive_setting(+ key, ui_element, sensitive_keys+ ) and value not in (None, "", [], {}):+ return redaction_text+ return value+@staticmethoddef sanitize(data: Any, sensitive_keys: Set[str] | None = None) -> Any:"""@@ -209,13 +236,15 @@ class DataSanitizer:out[key] = entrycontinuenew_entry = dict(entry) # shallow copy preserves metadata- is_secret = DataSanitizer.is_sensitive_setting(- key, entry.get("ui_element"), sensitive_keys+ # Delegate the per-value rule to redact_value so the snapshot,+ # the singular GET and the bulk GET can never mask differently.+ new_entry["value"] = DataSanitizer.redact_value(+ key,+ entry.get("ui_element"),+ entry.get("value"),+ sensitive_keys,+ redaction_text,)- value = entry.get("value")- # Only redact non-empty values — leave empty fields readable.- if is_secret and value not in (None, "", [], {}):- new_entry["value"] = redaction_textout[key] = new_entryreturn outdiff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex e0d9c95bcb..c745bb0a7d 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -964,7 +964,17 @@ def api_get_all_settings(def api_get_db_setting(key, db_session: Optional[Session] = None, settings_manager=None):- """Get a specific setting by key from DB, falling back to defaults."""+ """Get a specific setting by key from DB, falling back to defaults.++ Password-typed values are redacted in the response so this endpoint+ matches the redaction contract enforced on ``/settings/api`` (the bulk+ GET) and ``/settings/api/bulk``. The same threat applies: any+ authenticated caller could otherwise grab a plaintext API key with+ a single GET. Metadata fields (``ui_element``, ``type``, ...) stay+ intact so the front-end can still render the correct input control.+ """+ from ...security.data_sanitizer import DataSanitizer+try:# Get setting from database using the same sessiondb_setting = (@@ -975,7 +985,9 @@ def api_get_db_setting(# Return full setting details from DBsetting_data = {"key": db_setting.key,- "value": db_setting.value,+ "value": DataSanitizer.redact_value(+ db_setting.key, db_setting.ui_element, db_setting.value+ ),"type": db_setting.typeif isinstance(db_setting.type, str)else db_setting.type.value,@@ -996,14 +1008,17 @@ def api_get_db_setting(# with GET /settings/api which includes default settingsdefault_meta = settings_manager.default_settings.get(key)if default_meta:+ default_ui = default_meta.get("ui_element", "text")setting_data = {"key": key,- "value": default_meta.get("value"),+ "value": DataSanitizer.redact_value(+ key, default_ui, default_meta.get("value")+ ),"type": default_meta.get("type", "APP"),"name": default_meta.get("name", key),"description": default_meta.get("description"),"category": default_meta.get("category"),- "ui_element": default_meta.get("ui_element", "text"),+ "ui_element": default_ui,"options": default_meta.get("options"),"min_value": default_meta.get("min_value"),"max_value": default_meta.get("max_value"),@@ -2569,8 +2584,23 @@ def api_cleanup_rate_limiting():@settings_bp.route("/api/bulk", methods=["GET"])@login_requireddef get_bulk_settings():- """Get multiple settings at once for performance."""+ """Get multiple settings at once for performance.++ The caller-supplied ``keys[]`` is unrestricted, so this endpoint is a+ candidate channel to exfiltrate password-typed settings — any+ authenticated client can request ``keys[]=llm.openai.api_key`` and+ would otherwise receive the plaintext value. Redact password fields+ by checking the leaf segment of the dotted key against+ ``DataSanitizer.DEFAULT_SENSITIVE_KEYS`` (e.g. ``api_key``,+ ``password``, ``access_token``, …). Same defense-in-depth predicate+ used in ``redact_settings_snapshot``; here we use the suffix-only+ check because the response shape is ``{value, exists}`` — no+ ``ui_element`` is fetched. ``exists`` is preserved so callers can+ still tell whether the key is configured.+ """try:+ from ...security.data_sanitizer import DataSanitizer+# Get requested settings from query parametersrequested = request.args.getlist("keys[]")if not requested:@@ -2593,7 +2623,11 @@ def get_bulk_settings():for key in requested:try:value = _get_setting_from_session(key)- result[key] = {"value": value, "exists": value is not None}+ exists = value is not None+ # No ui_element metadata in the bulk path, so redact_value+ # falls back to the suffix-only arm of the shared predicate.+ value = DataSanitizer.redact_value(key, None, value)+ result[key] = {"value": value, "exists": exists}except Exception:logger.warning(f"Error getting setting {key}")result[key] = {diff --git a/tests/security/test_redact_settings_snapshot.py b/tests/security/test_redact_settings_snapshot.pyindex 4c8889c04f..a396a8ffa1 100644--- a/tests/security/test_redact_settings_snapshot.py+++ b/tests/security/test_redact_settings_snapshot.py@@ -140,3 +140,51 @@ def test_redactor_and_predicate_agree():assert out[key]["value"] == DataSanitizer.REDACTION_TEXTelse:assert out[key]["value"] == entry["value"]+++# ---------------------------------------------------------------------------+# redact_value — the single-value primitive that the singular GET, the bulk+# GET and redact_settings_snapshot all delegate to.+# ---------------------------------------------------------------------------+++def test_redact_value_masks_password_ui_element():+ """A set secret on a password-typed setting returns the sentinel."""+ assert (+ DataSanitizer.redact_value("llm.openai.api_key", "password", "sk-real")+ == DataSanitizer.REDACTION_TEXT+ )+++def test_redact_value_masks_by_suffix_when_no_ui_element():+ """The bulk GET has no ui_element, so redact_value falls back to the+ suffix arm of the predicate (key ends in a sensitive name)."""+ assert (+ DataSanitizer.redact_value("llm.openai.api_key", None, "sk-real")+ == DataSanitizer.REDACTION_TEXT+ )+++def test_redact_value_passes_through_non_secret():+ """A non-sensitive setting is returned unchanged."""+ assert DataSanitizer.redact_value("llm.model", "text", "gpt") == "gpt"+++def test_redact_value_leaves_empty_values_readable():+ """Empty values are never masked — the UI must tell 'unset' from 'set'+ without the sentinel implying a secret exists."""+ for empty in (None, "", [], {}):+ assert (+ DataSanitizer.redact_value("llm.openai.api_key", "password", empty)+ == empty+ )+++def test_redact_value_respects_custom_redaction_text():+ """Callers can override the sentinel."""+ assert (+ DataSanitizer.redact_value(+ "x.password", None, "pw", redaction_text="***"+ )+ == "***"+ )diff --git a/tests/web/routes/test_settings_routes_gaps_coverage.py b/tests/web/routes/test_settings_routes_gaps_coverage.pyindex 9455f2a034..48c35eddb3 100644--- a/tests/web/routes/test_settings_routes_gaps_coverage.py+++ b/tests/web/routes/test_settings_routes_gaps_coverage.py@@ -11,6 +11,7 @@ Covers:from contextlib import contextmanagerfrom unittest.mock import MagicMock, Mock, patch+import pytestfrom flask import Flask, jsonifyfrom local_deep_research.web.auth.routes import auth_bp@@ -169,13 +170,25 @@ class TestApiGetAllSettingsRedaction:def _make_password_db_setting(key="llm.openai.api_key", value="sk-existing"):- """A mock Setting model row with ui_element='password'."""+ """A mock Setting model row with ui_element='password'.++ All JSON-serialisable fields get concrete values so ``jsonify`` in the+ GET routes doesn't choke on auto-created MagicMock attributes.+ """s = MagicMock()s.key = keys.value = values.ui_element = "password"s.editable = True+ s.visible = Trues.type = MagicMock(value="LLM")+ s.name = key+ s.description = ""+ s.category = "llm_general"+ s.options = None+ s.min_value = None+ s.max_value = None+ s.step = Nonereturn s@@ -298,6 +311,196 @@ class TestApiUpdateSettingEmptyPasswordNoop:assert "unchanged" not in (body.get("message") or "").lower()+# ===========================================================================+# api_get_db_setting (GET /settings/api/<key>) — singular endpoint redaction+#+# The bulk endpoint at /settings/api was redacted in PR #3947, but the+# singular companion was deliberately deferred. With the form template no+# longer pre-filling password values (PR #3954) the singular endpoint's+# only remaining role is diagnostic / single-key API access — same threat+# model as the bulk GET, same redaction needed.+# ===========================================================================+++class TestApiGetDbSettingRedaction:+ SECRET = "sk-real-leaked"++ def test_password_value_is_redacted_db_branch(self):+ """When the setting exists in the DB and is password-typed, the+ response must replace `value` with [REDACTED]."""+ app = _create_test_app()+ existing = _make_password_db_setting(value=self.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]"+ # Metadata still passes through so the front-end can render+ # the right input control.+ assert body["ui_element"] == "password"+ # Belt-and-braces: the secret is nowhere in the serialised payload.+ assert self.SECRET not in resp.get_data(as_text=True)++ def test_non_password_value_passes_through_db_branch(self):+ """Non-password settings stay readable — only `password` is special."""+ app = _create_test_app()+ plain = _make_password_db_setting(+ key="search.fetch.mode", value="summary_focus_query"+ )+ plain.ui_element = "select" # override the helper's default++ with _client_with_db(app, plain) as (client, _db):+ resp = client.get("/settings/api/search.fetch.mode")++ body = resp.get_json()+ assert body["value"] == "summary_focus_query"++ def test_empty_password_value_stays_empty(self):+ """Empty/None values are not the secret — leave them readable+ so the front-end can tell 'not configured' from 'configured'."""+ app = _create_test_app()+ existing = _make_password_db_setting(value="")++ with _client_with_db(app, existing) as (client, _db):+ resp = client.get("/settings/api/llm.openai.api_key")++ body = resp.get_json()+ assert body["value"] == ""+++# ===========================================================================+# get_bulk_settings (GET /settings/api/bulk) — caller-controlled keys[]+#+# Anyone authenticated can ask for arbitrary keys including password-typed+# ones. Default-key list excludes them but a caller can request+# `keys[]=llm.openai.api_key` directly. Apply the same suffix-based+# defense-in-depth used by `redact_settings_snapshot`.+# ===========================================================================+++class TestGetBulkSettingsRedaction:+ SECRET = "sk-real-bulk-leak"++ def test_password_key_is_redacted_when_explicitly_requested(self):+ app = _create_test_app()+ with _authenticated_client(app) as client:+ with patch(+ f"{MODULE}._get_setting_from_session",+ return_value=self.SECRET,+ ):+ resp = client.get(+ "/settings/api/bulk?keys[]=llm.openai.api_key"+ )++ assert resp.status_code == 200+ body = resp.get_json()+ entry = body["settings"]["llm.openai.api_key"]+ assert entry["value"] == "[REDACTED]"+ # `exists` must still be true so callers can tell the key is set+ # — only the value is masked.+ assert entry["exists"] is True+ assert self.SECRET not in resp.get_data(as_text=True)++ def test_non_sensitive_key_passes_through(self):+ """Suffix outside DEFAULT_SENSITIVE_KEYS keeps its real value."""+ app = _create_test_app()+ with _authenticated_client(app) as client:+ with patch(+ f"{MODULE}._get_setting_from_session",+ return_value="searxng",+ ):+ resp = client.get("/settings/api/bulk?keys[]=search.tool")++ body = resp.get_json()+ assert body["settings"]["search.tool"]["value"] == "searxng"++ def test_empty_password_value_stays_empty(self):+ app = _create_test_app()+ with _authenticated_client(app) as client:+ with patch(f"{MODULE}._get_setting_from_session", return_value=""):+ resp = client.get(+ "/settings/api/bulk?keys[]=llm.lmstudio.api_key"+ )++ body = resp.get_json()+ # Empty value is not the secret — stays empty so the front-end+ # can tell "not configured".+ assert body["settings"]["llm.lmstudio.api_key"]["value"] == ""+++# ===========================================================================+# save_settings (POST /save_settings) — JS-disabled form-encoded fallback+#+# PR #3954 added the empty-password no-op guard to save_all_settings+# (JSON path) and api_update_setting. The form-encoded fallback at+# /save_settings was missed. Same guard, same rationale.+# ===========================================================================+++class TestSaveSettingsEmptyPasswordNoop:+ def test_empty_password_form_submit_is_noop(self):+ """POST /save_settings with empty form value must NOT call+ settings_manager.set_setting for password-typed settings."""+ app = _create_test_app()+ existing = _make_password_db_setting(value="sk-keep-me")+ # save_settings also fetches all_db_settings into a {key: row}+ # dict, so the mock query must support `.all()` returning [existing].+ sm = MagicMock()+ sm.set_setting.return_value = True++ with _authenticated_client(app) as client:+ with (+ patch(f"{DECORATOR_MODULE}.SettingsManager", return_value=sm),+ patch(+ f"{MODULE}.coerce_setting_for_write",+ side_effect=lambda key, value, **kw: value,+ ),+ patch(+ "local_deep_research.web.auth.decorators.db_manager",+ Mock(connections={"testuser": True}, has_encryption=False),+ ),+ ):+ # Override the fixture's MagicMock session so query()...all()+ # returns our existing password row.+ with patch(+ f"{DECORATOR_MODULE}.get_user_db_session"+ ) as get_session:+ from contextlib import contextmanager++ @contextmanager+ def _fake_session(*a, **kw):+ db = MagicMock()+ db.query.return_value.all.return_value = [existing]+ yield db++ get_session.side_effect = _fake_session++ # We don't assert on the HTTP response (the form-POST+ # response varies — flash + redirect on success, or a+ # 500 if downstream machinery isn't fully mocked). The+ # invariant we're proving is that set_setting was+ # never called for the empty password key — see the+ # call_args_list check below.+ client.post(+ "/save_settings",+ data={"llm.openai.api_key": ""},+ )++ # Form-POST returns 302 (redirect with flash) on success in this+ # codebase, but what we actually care about is that set_setting+ # was never called for the empty password key.+ for call in sm.set_setting.call_args_list:+ args, kwargs = call+ # set_setting(key, value, commit=False) — first positional is key+ if args and args[0] == "llm.openai.api_key":+ pytest.fail(+ "save_settings called set_setting for an empty "+ "password value; the no-op guard did not fire."+ )++# ===========================================================================# get_bulk_settings# ===========================================================================