~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): close password-input HTML leak + protect against [REDACTED] write-back (#3954)
LearningCircuitef3fd3bfdea6
diff --git a/.gitleaksignore b/.gitleaksignoreindex bc52641820..e24889a568 100644--- a/.gitleaksignore+++ b/.gitleaksignore@@ -580,3 +580,9 @@ src/local_deep_research/web_search_engines/search_engines_config.py:generic-secr# Placeholder API key for local servers without auth (e.g. llama.cpp)7c84e267390264c58c3857881c70f9b80677d76b:src/local_deep_research/config/llm_config.py:generic-secret:516++# data_sanitizer.py — `is_secret = DataSanitizer.is_sensitive_setting(...)` reads+# as `secret = <token>` to the generic-secret rule. It is a boolean variable+# assignment in redact_settings_snapshot, not a credential (false positive).+src/local_deep_research/security/data_sanitizer.py:generic-secret:212+282bb0c3d9e9d65ae67fa0acc18cd92e7ad447bc:src/local_deep_research/security/data_sanitizer.py:generic-secret:212diff --git a/changelog.d/3954.bugfix.md b/changelog.d/3954.bugfix.mdnew file mode 100644index 0000000000..ea1d37e259--- /dev/null+++ b/changelog.d/3954.bugfix.md@@ -0,0 +1 @@+**Submitting an empty value for a password-typed setting is now a no-op** — previously could overwrite the stored secret with `""`. Belt-and-braces fix for the same `[REDACTED]` sentinel issue: a stale browser tab can no longer corrupt API keys by triggering a save. To clear a password setting, clear the source env var or use settings import.diff --git a/changelog.d/3954.security.md b/changelog.d/3954.security.mdnew file mode 100644index 0000000000..0b4ea86e65--- /dev/null+++ b/changelog.d/3954.security.md@@ -0,0 +1 @@+**Settings form no longer pre-fills password inputs with the stored value**, eliminating an authenticated View-Source disclosure of API keys / OAuth tokens. Password fields render empty with a placeholder indicating configuration state and `autocomplete="new-password"` to prevent browser caching.diff --git a/src/local_deep_research/security/data_sanitizer.py b/src/local_deep_research/security/data_sanitizer.pyindex 073f228764..1c02417fea 100644--- a/src/local_deep_research/security/data_sanitizer.py+++ b/src/local_deep_research/security/data_sanitizer.py@@ -12,9 +12,19 @@ import jsonfrom typing import Any, Set+# The placeholder a redacted value is replaced with. Single source of truth+# so that write-back guards (which must treat this sentinel as a no-op to+# avoid persisting it over a real secret on a redacted GET round-trip)+# cannot drift from what the redactor actually emits.+REDACTION_TEXT = "[REDACTED]"++class DataSanitizer:"""Utility class for removing sensitive information from data structures."""+ # Public alias of the module-level sentinel (see REDACTION_TEXT above).+ REDACTION_TEXT: str = REDACTION_TEXT+# Default set of sensitive key names to redactDEFAULT_SENSITIVE_KEYS: Set[str] = {"api_key",@@ -29,6 +39,30 @@ class DataSanitizer:"csrf_token",}+ @staticmethod+ def is_sensitive_setting(+ key: str,+ ui_element: str | None = None,+ sensitive_keys: Set[str] | None = None,+ ) -> bool:+ """True when a setting holds a secret: it is ``ui_element ==+ "password"`` OR the last dotted segment of its key is a sensitive+ name (``llm.openai.api_key`` -> ``api_key``).++ Single source of truth for "is this a secret" so the GET redactor+ and the write-back no-op guards apply the SAME predicate — a value+ the redactor masks to the sentinel must also be one the guards+ refuse to overwrite, or a redacted GET could round-trip the+ sentinel back over the real secret.+ """+ if ui_element == "password":+ return True+ sens = {+ k.lower()+ for k in (sensitive_keys or DataSanitizer.DEFAULT_SENSITIVE_KEYS)+ }+ return key.rsplit(".", 1)[-1].lower() in sens+@staticmethoddef sanitize(data: Any, sensitive_keys: Set[str] | None = None) -> Any:"""@@ -75,7 +109,7 @@ class DataSanitizer:def redact(data: Any,sensitive_keys: Set[str] | None = None,- redaction_text: str = "[REDACTED]",+ redaction_text: str = REDACTION_TEXT,) -> Any:"""Recursively redact (replace with placeholder) sensitive values in data structures.@@ -125,7 +159,7 @@ class DataSanitizer:def redact_settings_snapshot(snapshot: Any,sensitive_keys: Set[str] | None = None,- redaction_text: str = "[REDACTED]",+ redaction_text: str = REDACTION_TEXT,) -> Any:"""Redact secret values in a settings snapshot while preserving metadata.@@ -169,20 +203,14 @@ class DataSanitizer:if not isinstance(snapshot, dict):return snapshot- sensitive_lower = {- k.lower()- for k in (sensitive_keys or DataSanitizer.DEFAULT_SENSITIVE_KEYS)- }out: dict = {}for key, entry in snapshot.items():if not isinstance(entry, dict) or "value" not in entry:out[key] = entrycontinuenew_entry = dict(entry) # shallow copy preserves metadata- suffix = key.rsplit(".", 1)[-1].lower()- is_secret = (- entry.get("ui_element") == "password"- or suffix in sensitive_lower+ is_secret = DataSanitizer.is_sensitive_setting(+ key, entry.get("ui_element"), sensitive_keys)value = entry.get("value")# Only redact non-empty values — leave empty fields readable.@@ -212,7 +240,7 @@ def sanitize_data(data: Any, sensitive_keys: Set[str] | None = None) -> Any:def redact_data(data: Any,sensitive_keys: Set[str] | None = None,- redaction_text: str = "[REDACTED]",+ redaction_text: str = REDACTION_TEXT,) -> Any:"""Redact (replace) sensitive values in data structures.diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex 4011ee937b..2838cd992f 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -370,6 +370,8 @@ def settings_page():def save_all_settings(db_session=None, settings_manager=None):"""Handle saving all settings at once from the unified settings page"""try:+ from ...security.data_sanitizer import DataSanitizer+# Process JSON dataform_data = request.get_json()if not form_data:@@ -423,6 +425,33 @@ def save_all_settings(db_session=None, settings_manager=None):# Get the setting metadata from pre-fetched dictcurrent_setting = all_db_settings.get(key)+ # SAFETY NET: an empty string OR the redaction sentinel for a+ # password-typed setting is a no-op, never a "clear the value"+ # request. Reasons:+ # 1. The form templates (Jinja2 + JS-rendered) deliberately+ # render password inputs empty so the saved value never+ # enters the HTML source. A user who blurs the field+ # without typing must not wipe their stored API key.+ # 2. /settings/api redacts password values to the redaction+ # sentinel ("[REDACTED]"). A stale browser tab could submit+ # either "" or the sentinel — both must be idempotent on+ # the DB, or the round-trip would persist the literal+ # sentinel over the real secret.+ # 3. Defense-in-depth against direct cURL or automation+ # mistakes that POST an empty/sentinel value.+ # To unset a password setting, clear the source env var or+ # use settings import.+ if (+ current_setting+ and DataSanitizer.is_sensitive_setting(+ key, current_setting.ui_element+ )+ and isinstance(value, str)+ and value in ("", DataSanitizer.REDACTION_TEXT)+ ):+ logger.debug(f"Skipping empty secret write for {key} (no-op)")+ continue+# EARLY VALIDATION: Convert checkbox values BEFORE any other processing# This prevents incorrect triggering of corrupted value detectionif current_setting and current_setting.ui_element == "checkbox":@@ -673,13 +702,16 @@ def save_all_settings(db_session=None, settings_manager=None):# Multiple settings or generic messagesuccess_message = f"Settings saved successfully ({len(updated_settings)} updated, {len(created_settings)} created)"- # Check if any warning-affecting settings were changed and include warnings+ # Check if any warning-affecting settings were changed and include warnings.+ # Redact secret values in the echoed settings so a POST response never+ # ships plaintext API keys back to the browser — matching the+ # redaction the GET /settings/api endpoint already applies.response_data = {"status": "success","message": success_message,"updated": updated_settings,"created": created_settings,- "settings": all_settings,+ "settings": DataSanitizer.redact_settings_snapshot(all_settings),}warning_affecting_keys = WARNING_AFFECTING_KEYS@@ -747,6 +779,8 @@ def reset_to_defaults(db_session=None, settings_manager=None):def save_settings(db_session=None, settings_manager=None):"""Save all settings from the form using POST method - fallback when JavaScript is disabled"""try:+ from ...security.data_sanitizer import DataSanitizer+# Get form dataform_data = request.form.to_dict()@@ -790,6 +824,26 @@ def save_settings(db_session=None, settings_manager=None):rejected_count += 1continue+ # SAFETY NET: empty string OR the redaction sentinel for a+ # password-typed setting is a no-op — never "clear my key".+ # The no-JS form renders password inputs empty (and GET+ # redacts them to the sentinel), so a plain form submit+ # must not wipe the stored secret. Matches the guards in+ # save_all_settings + api_update_setting.+ if (+ db_setting+ and DataSanitizer.is_sensitive_setting(+ key, db_setting.ui_element+ )+ and isinstance(value, str)+ and value in ("", DataSanitizer.REDACTION_TEXT)+ ):+ logger.debug(+ f"Skipping empty secret write for {key} via "+ "save_settings (no-op)"+ )+ continue+# Coerce form POST string to correct Python type.if db_setting:value = coerce_setting_for_write(@@ -964,6 +1018,8 @@ def api_get_db_setting(key, db_session=None, settings_manager=None):def api_update_setting(key, db_session=None):"""Update a setting"""try:+ from ...security.data_sanitizer import DataSanitizer+# Get request datadata = request.get_json()value = data.get("value")@@ -980,6 +1036,29 @@ def api_update_setting(key, db_session=None):if not db_setting.editable:return jsonify({"error": f"Setting {key} is not editable"}), 403+ # SAFETY NET: an empty string OR the redaction sentinel on a+ # password-typed setting is a no-op (never "clear my key").+ # Companion guard to the same check in save_all_settings — see+ # the longer rationale there. Returning 200 with a message keeps+ # the endpoint idempotent so client-side save indicators don't+ # error.+ if (+ DataSanitizer.is_sensitive_setting(key, db_setting.ui_element)+ and isinstance(value, str)+ and value in ("", DataSanitizer.REDACTION_TEXT)+ ):+ logger.debug(+ f"Skipping empty secret write for {key} via "+ "api_update_setting (no-op)"+ )+ return jsonify(+ {+ "message": (+ f"Setting {key} unchanged (empty password ignored)"+ )+ }+ ), 200+# Coerce to correct Python type before saving.# Without this, values from JSON API requests are stored# as-is (e.g. string "5" instead of int 5 for number@@ -1098,7 +1177,16 @@ def api_update_setting(key, db_session=None):"message": f"Setting {key} created successfully","setting": {"key": db_setting.key,- "value": db_setting.value,+ # Don't echo a freshly-created password value+ # back in plaintext — redact like every other+ # response that ships settings to the browser.+ "value": (+ DataSanitizer.REDACTION_TEXT+ if DataSanitizer.is_sensitive_setting(+ key, db_setting.ui_element+ )+ else db_setting.value+ ),"type": db_setting.type.value,"name": db_setting.name,},diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.jsindex f99d7eaabf..746484751e 100644--- a/src/local_deep_research/web/static/js/components/settings.js+++ b/src/local_deep_research/web/static/js/components/settings.js@@ -1005,9 +1005,20 @@// Process settings to handle object values and check for corruptionallSettings = processSettings(data.settings);- // Store original values+ // Store original values for the auto-save dirty-check.+ // For password fields the JS render leaves the input+ // empty (see the renderSetting password branch), so+ // seed the baseline as empty too — otherwise the+ // first keystroke would compare against "[REDACTED]"+ // (the redacted sentinel from /settings/api per+ // PR #3947) instead of "" and the save semantics get+ // weird. Treating the redacted sentinel as "we don't+ // know the real value" is the right model.allSettings.forEach(setting => {- originalSettings[setting.key] = setting.value;+ originalSettings[setting.key] =+ setting.ui_element === 'password'+ ? ''+ : setting.value;});// Render settings by tab@@ -2263,16 +2274,47 @@// case 'custom_dropdown':default:- // Handle llm.model here explicitly if not handled by ui_element- // Default to text input- inputElement = `- <input type="${setting.ui_element === 'password' ? 'password' : 'text'}"- id="${settingId}" name="${setting.key}"- class="ldr-settings-input ldr-form-control"- value="${escapeHtml(String(setting.value !== null ? setting.value : ''))}"- ${!setting.editable ? 'disabled' : ''}- >- `;+ if (setting.ui_element === 'password') {+ // Render password inputs empty regardless of stored+ // value. Reasons:+ // 1. The Jinja2 server render does the same — keeps+ // both paths consistent.+ // 2. /settings/api now returns "[REDACTED]" for+ // password fields (PR #3947). If we wrote that+ // string into the input, a save without typing+ // would persist "[REDACTED]" as the API key.+ // 3. The placeholder telegraphs configuration state+ // without leaking the value or its length.+ // The "is configured" check accepts the redacted+ // sentinel as a positive signal — we know the value+ // is set, we just don't know its plaintext.+ const isConfigured =+ setting.value === '[REDACTED]' ||+ (setting.value !== null && setting.value !== '');+ const placeholder = isConfigured+ ? '(saved — type to change)'+ : '(not configured)';+ inputElement = `+ <input type="password"+ id="${settingId}" name="${setting.key}"+ class="ldr-settings-input ldr-form-control"+ value=""+ autocomplete="new-password"+ placeholder="${escapeHtml(placeholder)}"+ ${!setting.editable ? 'disabled' : ''}+ >+ `;+ } else {+ // Default to text input+ inputElement = `+ <input type="text"+ id="${settingId}" name="${setting.key}"+ class="ldr-settings-input ldr-form-control"+ value="${escapeHtml(String(setting.value !== null ? setting.value : ''))}"+ ${!setting.editable ? 'disabled' : ''}+ >+ `;+ }break;}diff --git a/src/local_deep_research/web/templates/components/settings_form.html b/src/local_deep_research/web/templates/components/settings_form.htmlindex aebbc61dcc..92f8a2c0b8 100644--- a/src/local_deep_research/web/templates/components/settings_form.html+++ b/src/local_deep_research/web/templates/components/settings_form.html@@ -195,12 +195,24 @@>{% elif setting.ui_element == "password" %}+ {# Render password inputs empty so the saved value never enters+ the HTML source (anyone with View Source on the settings page+ otherwise reads plaintext API keys). The placeholder+ telegraphs configuration state without leaking the secret's+ length. autocomplete="new-password" is the standard+ cross-browser opt-out from password-manager autofill on+ settings forms. To unset a password setting, clear the+ source env var or use settings import — submitting an empty+ value is a no-op enforced by the route handler. #}+ {% set _has_value = setting.value is not none and setting.value != "" %}<inputtype="password"id="{{ setting_id }}"name="{{ setting.key }}"class="ldr-settings-input ldr-form-control"- value="{{ setting.value if setting.value is not none else '' }}"+ value=""+ autocomplete="new-password"+ placeholder="{{ '(saved — type to change)' if _has_value else '(not configured)' }}"{% if not setting.editable %}disabled{% endif %}>diff --git a/tests/security/test_redact_settings_snapshot.py b/tests/security/test_redact_settings_snapshot.pyindex a45c379962..4c8889c04f 100644--- a/tests/security/test_redact_settings_snapshot.py+++ b/tests/security/test_redact_settings_snapshot.py@@ -109,3 +109,34 @@ def test_custom_redaction_text():snap = {"llm.openai.api_key": {"value": "sk-x", "ui_element": "password"}}out = DataSanitizer.redact_settings_snapshot(snap, redaction_text="***")assert out["llm.openai.api_key"]["value"] == "***"+++def test_is_sensitive_setting_predicate():+ """The shared predicate the GET redactor and the write-back guards both+ use: password ui_element OR a sensitive key suffix."""+ # ui_element wins regardless of key+ assert DataSanitizer.is_sensitive_setting("anything.here", "password")+ # sensitive suffix wins regardless of ui_element+ assert DataSanitizer.is_sensitive_setting("llm.openai.api_key", "text")+ assert DataSanitizer.is_sensitive_setting("x.password", None)+ assert DataSanitizer.is_sensitive_setting("x.secret", "textarea")+ # neither -> not sensitive+ assert not DataSanitizer.is_sensitive_setting("llm.model", "text")+ assert not DataSanitizer.is_sensitive_setting("search.tool", None)+++def test_redactor_and_predicate_agree():+ """Anything the predicate calls sensitive (and has a non-empty value)+ must be redacted by redact_settings_snapshot — they share one source."""+ snap = {+ "llm.openai.api_key": {"value": "sk-x", "ui_element": "text"},+ "foo.password": {"value": "pw", "ui_element": "text"},+ "llm.model": {"value": "gpt", "ui_element": "text"},+ }+ out = DataSanitizer.redact_settings_snapshot(snap)+ for key, entry in snap.items():+ sensitive = DataSanitizer.is_sensitive_setting(key, entry["ui_element"])+ if sensitive:+ assert out[key]["value"] == DataSanitizer.REDACTION_TEXT+ else:+ assert out[key]["value"] == entry["value"]diff --git a/tests/web/routes/test_settings_routes_deep_coverage2.py b/tests/web/routes/test_settings_routes_deep_coverage2.pyindex ca1e83c8ca..e5bc6d06b4 100644--- a/tests/web/routes/test_settings_routes_deep_coverage2.py+++ b/tests/web/routes/test_settings_routes_deep_coverage2.py@@ -680,6 +680,116 @@ class TestSaveAllSettingsMultipleMessage:assert "2" in data["message"] or "updated" in data["message"].lower()+class TestSaveAllSettingsSecretNoop:+ """POST /save_all_settings must treat ""/sentinel for a SECRET setting+ as a no-op (never overwrite the stored value). "Secret" is the same+ predicate the GET redactor uses: ui_element=='password' OR a sensitive+ key suffix — so a redacted GET round-trip can't destroy the secret."""++ def _post_and_assert_noop(self, setting, submitted_value):+ from local_deep_research.security.data_sanitizer import DataSanitizer # noqa: F401++ app = _create_test_app()+ with _authenticated_client(app, mock_settings=[setting]) as (+ client,+ mock_session,+ ):+ mock_session.query.return_value.all.side_effect = [+ [setting], # all_db_settings (carries ui_element)+ [setting], # echo query+ ]+ with patch(f"{MODULE}.set_setting", return_value=True) as set_mock:+ resp = client.post(+ f"{SETTINGS_PREFIX}/save_all_settings",+ json={setting.key: submitted_value},+ content_type="application/json",+ )+ assert resp.status_code == 200+ assert all(+ call.args[0] != setting.key for call in set_mock.call_args_list+ ), f"{setting.key} was written despite no-op guard"++ def test_empty_password_is_noop(self):+ s = _make_setting(+ key="llm.openai.api_key", ui_element="password", editable=True+ )+ s.type = "llm"+ self._post_and_assert_noop(s, "")++ def test_sentinel_password_is_noop(self):+ from local_deep_research.security.data_sanitizer import DataSanitizer++ s = _make_setting(+ key="llm.openai.api_key", ui_element="password", editable=True+ )+ s.type = "llm"+ self._post_and_assert_noop(s, DataSanitizer.REDACTION_TEXT)++ def test_sensitive_suffix_non_password_sentinel_is_noop(self):+ """Closes the read/write asymmetry: a secret stored with a+ non-password ui_element but a sensitive '.api_key' suffix is+ redacted on GET, so a save round-trip submits the sentinel — the+ guard must skip it too (it now shares the redactor's predicate)."""+ from local_deep_research.security.data_sanitizer import DataSanitizer++ s = _make_setting(+ key="llm.custom.api_key", ui_element="text", editable=True+ )+ s.type = "llm"+ self._post_and_assert_noop(s, DataSanitizer.REDACTION_TEXT)+++class TestSaveAllSettingsRedactsResponse:+ """The POST /save_all_settings response echoes the full settings dict;+ password values must be redacted in it so the endpoint never ships+ plaintext API keys back to the browser (matching GET /settings/api)."""++ def test_password_value_redacted_in_response(self):+ from local_deep_research.security.data_sanitizer import DataSanitizer++ app = _create_test_app()+ secret = _make_setting(+ key="llm.openai.api_key",+ value="sk-super-secret",+ ui_element="password",+ editable=True,+ )+ secret.type = "llm"+ plain = _make_setting(+ key="llm.model", value="gpt-4", ui_element="text", editable=True+ )+ plain.type = "llm"++ with _authenticated_client(app, mock_settings=[secret, plain]) as (+ client,+ mock_session,+ ):+ mock_session.query.return_value.all.side_effect = [+ [secret, plain], # initial fetch+ [secret, plain], # second query for all_settings echo+ ]+ with patch(+ f"{MODULE}.coerce_setting_for_write", return_value="gpt-3.5"+ ):+ with patch(+ f"{MODULE}.validate_setting", return_value=(True, None)+ ):+ with patch(f"{MODULE}.set_setting", return_value=True):+ resp = client.post(+ f"{SETTINGS_PREFIX}/save_all_settings",+ json={"llm.model": "gpt-3.5"},+ content_type="application/json",+ )+ assert resp.status_code == 200+ data = resp.get_json()+ echoed = data["settings"]["llm.openai.api_key"]+ assert echoed["value"] == DataSanitizer.REDACTION_TEXT+ # The plaintext secret must never appear anywhere in the response.+ assert "sk-super-secret" not in resp.get_data(as_text=True)+ # Non-secret settings pass through unredacted.+ assert data["settings"]["llm.model"]["value"] == "gpt-4"++# ---------------------------------------------------------------------------# save_all_settings - warning-affecting key# ---------------------------------------------------------------------------diff --git a/tests/web/routes/test_settings_routes_gaps_coverage.py b/tests/web/routes/test_settings_routes_gaps_coverage.pyindex 6f2762c87c..9455f2a034 100644--- a/tests/web/routes/test_settings_routes_gaps_coverage.py+++ b/tests/web/routes/test_settings_routes_gaps_coverage.py@@ -157,6 +157,147 @@ class TestApiGetAllSettingsRedaction:assert entry["type"] == "LLM"+# ===========================================================================+# Empty-password no-op safety net+#+# Companion fix to the /settings/api redaction. The render layer keeps+# password inputs empty so the saved value never enters the HTML — but+# the backend must also enforce that submitting "" for a password+# setting does NOT wipe the stored secret. Otherwise a stale tab, a+# direct cURL, or a buggy frontend can corrupt API keys.+# ===========================================================================+++def _make_password_db_setting(key="llm.openai.api_key", value="sk-existing"):+ """A mock Setting model row with ui_element='password'."""+ s = MagicMock()+ s.key = key+ s.value = value+ s.ui_element = "password"+ s.editable = True+ s.type = MagicMock(value="LLM")+ return s+++@contextmanager+def _client_with_db(app, db_setting):+ """Authenticated test client whose DB query for `Setting` returns+ `db_setting`. Overrides the more general `_authenticated_client`+ fixture's MagicMock so the route sees a controllable Setting row.+ """+ mock_db_mgr = Mock()+ mock_db_mgr.connections = {"testuser": True}+ mock_db_mgr.has_encryption = False++ db = MagicMock()+ db.query.return_value.filter.return_value.first.return_value = db_setting++ @contextmanager+ def _fake_session(*args, **kwargs):+ yield db++ patches = [+ patch(+ "local_deep_research.web.auth.decorators.db_manager",+ mock_db_mgr,+ ),+ patch(+ f"{DECORATOR_MODULE}.get_user_db_session",+ side_effect=_fake_session,+ ),+ patch(f"{MODULE}.settings_limit", lambda f: f),+ ]++ started = []+ try:+ for p in patches:+ started.append(p.start())+ with app.test_client() as client:+ with client.session_transaction() as sess:+ sess["username"] = "testuser"+ sess["session_id"] = "test-session-id"+ yield client, db+ finally:+ for p in patches:+ p.stop()+++class TestApiUpdateSettingEmptyPasswordNoop:+ """PUT /settings/api/<key> with value='' on a password setting must be+ a no-op (200 + message), not a write."""++ def test_empty_password_returns_200_without_writing(self):+ app = _create_test_app()+ existing = _make_password_db_setting(value="sk-real-existing")++ with _client_with_db(app, existing) as (client, db):+ resp = client.put(+ "/settings/api/llm.openai.api_key",+ json={"value": ""},+ )++ assert resp.status_code == 200+ body = resp.get_json()+ # Idempotent message — the route does NOT return an error+ # because client save indicators would otherwise show a+ # spurious failure when blurring an empty password field.+ assert "unchanged" in body["message"].lower()+ # The route never reached the write step — no commit was+ # called on the DB session, and the existing row's value is+ # untouched.+ db.commit.assert_not_called()+ assert existing.value == "sk-real-existing"++ def test_redacted_sentinel_returns_200_without_writing(self):+ """Submitting the redaction sentinel ("[REDACTED]") for a password+ setting must also be a no-op. GET /settings/api redacts password+ values to this sentinel, so a stale tab / automation round-trip+ would otherwise persist the literal "[REDACTED]" over the real+ secret."""+ from local_deep_research.security.data_sanitizer import DataSanitizer++ app = _create_test_app()+ existing = _make_password_db_setting(value="sk-real-existing")++ with _client_with_db(app, existing) as (client, db):+ resp = client.put(+ "/settings/api/llm.openai.api_key",+ json={"value": DataSanitizer.REDACTION_TEXT},+ )++ assert resp.status_code == 200+ body = resp.get_json()+ assert "unchanged" in body["message"].lower()+ db.commit.assert_not_called()+ assert existing.value == "sk-real-existing"++ def test_non_empty_password_does_not_match_noop_guard(self):+ """Control: the no-op guard must NOT fire for a non-empty value.++ We don't try to drive the full write path here (that exercises+ coercion + validation + DB session machinery and is covered by+ other integration tests). What this control proves is that the+ guard's specific 200-with-"unchanged"-message response does not+ return for a real value — meaning the guard correctly carved out+ only the empty-string case.+ """+ app = _create_test_app()+ existing = _make_password_db_setting(value="sk-old")++ with _client_with_db(app, existing) as (client, _db):+ resp = client.put(+ "/settings/api/llm.openai.api_key",+ json={"value": "sk-new"},+ )++ # The route may continue to error past our guard (write path+ # depends on machinery we haven't mocked) — that's fine. The+ # invariant we're proving: this is NOT the no-op 200 response.+ if resp.status_code == 200:+ body = resp.get_json() or {}+ assert "unchanged" not in (body.get("message") or "").lower()++# ===========================================================================# get_bulk_settings# ===========================================================================diff --git a/tests/web/routes/test_settings_routes_security.py b/tests/web/routes/test_settings_routes_security.pyindex d8107338b4..5df2cb9876 100644--- a/tests/web/routes/test_settings_routes_security.py+++ b/tests/web/routes/test_settings_routes_security.py@@ -251,6 +251,54 @@ class TestNewSettingNamespaceGate:), "Legitimate allow-listed key did not reach set_setting"+class TestSaveSettingsPasswordNoop:+ """save_settings (no-JS form POST) must not wipe a stored password when+ an empty value or the redaction sentinel is submitted — the same+ write-back guard the JSON save paths have."""++ def _password_setting(self):+ s = Mock()+ s.key = "llm.openai.api_key"+ s.value = "sk-existing"+ s.editable = True+ s.ui_element = "password"+ return s++ def _post(self, submitted_value):+ app = _create_test_app()+ pw = self._password_setting()+ mock_sm = Mock()+ mock_sm.set_setting.return_value = True+ with _authenticated_client(app, mock_settings=[pw]) as (client, _):+ with patch(+ "local_deep_research.web.utils.route_decorators.SettingsManager",+ return_value=mock_sm,+ ):+ resp = client.post(+ "/settings/save_settings",+ data={"llm.openai.api_key": submitted_value},+ )+ return resp, mock_sm++ def test_empty_password_form_post_is_noop(self):+ resp, mock_sm = self._post("")+ assert resp.status_code == 302+ assert all(+ call.args[0] != "llm.openai.api_key"+ for call in mock_sm.set_setting.call_args_list+ ), "Empty password reached set_setting via save_settings"++ def test_redacted_sentinel_form_post_is_noop(self):+ from local_deep_research.security.data_sanitizer import DataSanitizer++ resp, mock_sm = self._post(DataSanitizer.REDACTION_TEXT)+ assert resp.status_code == 302+ assert all(+ call.args[0] != "llm.openai.api_key"+ for call in mock_sm.set_setting.call_args_list+ ), "Redaction sentinel reached set_setting via save_settings"++# ---------------------------------------------------------------------------# Unit tests for _is_allowed_new_setting_key guards# ---------------------------------------------------------------------------diff --git a/tests/web/templates/__init__.py b/tests/web/templates/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/web/templates/test_settings_form_password_render.py b/tests/web/templates/test_settings_form_password_render.pynew file mode 100644index 0000000000..f67b2f7a0e--- /dev/null+++ b/tests/web/templates/test_settings_form_password_render.py@@ -0,0 +1,92 @@+"""Tests for the password branch of the ``settings_form.html`` macro.++Pins the contract that:+- The saved password value never enters the rendered HTML (no+ ``value="sk-..."`` attribute leak via View Source on the settings page).+- The configured/not-configured state is communicated via the+ ``placeholder`` attribute, not the value.+- ``autocomplete="new-password"`` is set so browser password managers+ don't offer to save the empty placeholder, and don't re-fill it on+ return visits.++The macro is rendered via a standalone Jinja2 environment pointing at+the project's ``templates/`` directory — no Flask app is required.+"""+# allow: no-sut-import — renders the real settings_form.html macro via+# Jinja2; the SUT here is a template file, not an importable Python module.++from pathlib import Path++import pytest+from jinja2 import Environment, FileSystemLoader, select_autoescape+++REPO_ROOT = Path(__file__).resolve().parents[3]+TEMPLATES_DIR = REPO_ROOT / "src" / "local_deep_research" / "web" / "templates"+++def env():+ """Jinja2 environment matching Flask's defaults for autoescape."""+ return Environment(+ loader=FileSystemLoader(str(TEMPLATES_DIR)),+ autoescape=select_autoescape(["html", "xml"]),+ )+++def _render_password_setting(env, value):+ """Render the macro with a password-typed setting and return the HTML."""+ tmpl = env.from_string(+ "{% from 'components/settings_form.html' import render_setting %}"+ "{{ render_setting(setting) }}"+ )+ return tmpl.render(+ setting={+ "key": "llm.openai.api_key",+ "name": "OpenAI API Key",+ "description": "Authentication key for OpenAI",+ "ui_element": "password",+ "value": value,+ "editable": True,+ }+ )+++def test_password_input_renders_empty_value(env):+ """The plaintext secret must not appear in the value attribute."""+ secret = "sk-real-secret-12345"+ html = _render_password_setting(env, secret)++ # The input is rendered with value=""+ assert 'value=""' in html+ # Belt-and-braces: the secret string is nowhere in the rendered HTML+ assert secret not in html+++def test_configured_state_shows_saved_placeholder(env):+ """A non-empty saved value reads as 'saved — type to change'."""+ html = _render_password_setting(env, "sk-something-set")+ assert "saved" in html.lower()+ assert "type to change" in html.lower()+++def test_not_configured_state_shows_placeholder(env):+ """An empty/None saved value reads as 'not configured'."""+ html_empty = _render_password_setting(env, "")+ html_none = _render_password_setting(env, None)+ assert "not configured" in html_empty.lower()+ assert "not configured" in html_none.lower()+++def test_autocomplete_new_password_attribute_set(env):+ """Without autocomplete='new-password' some browsers will still offer+ to autofill cached values; this is the standard cross-browser opt-out."""+ html = _render_password_setting(env, "sk-something")+ assert 'autocomplete="new-password"' in html+++def test_password_input_type_remains_password(env):+ """Sanity — the input is still type=password (we didn't accidentally+ flip it to text while reworking the value/placeholder logic)."""+ html = _render_password_setting(env, "sk-x")+ assert 'type="password"' in html