~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(security): guard nested JSON secrets and anchor qualifier match (follow-up to #5771) (#6201)
LearningCircuit533a05b75f2d
diff --git a/.gitleaksignore b/.gitleaksignoreindex 2d8f44e614..2ece477b01 100644--- a/.gitleaksignore+++ b/.gitleaksignore@@ -754,3 +754,15 @@ e64710805cb5382ad1b658228911d8b6291ff0f5:src/local_deep_research/security/data_se64710805cb5382ad1b658228911d8b6291ff0f5:src/local_deep_research/security/data_sanitizer.py:credential-literal:95f36c295fc291f1aa0db5ac08f0f6da9bcee96717:src/local_deep_research/config.py:credential-literal:357fc48711a3b21779934bd5be60ac29112e338ec49:src/local_deep_research/api/research_functions.py:credential-literal:178++# --- Added 2026-09-04 (PR #6201): one credential-literal false positive in a+# changelog SENTENCE, not in code. The fragment described the JSON-string form+# of a masked container by spelling the shape out inline, and gitleaks read the+# quoted key/value pair as a credential — the "secret" it found is the+# "[REDACTED]" placeholder itself, i.e. the very output the change is about.+# The wording was already fixed in the tree (f00cd3c38 rewrote the sentence to+# describe the shape instead of quoting it), but CI scans the COMMIT RANGE, so+# the historical commit below still matches and a tree-level reword cannot+# clear it. Single fingerprint only — the rule keeps full coverage of the path+# and of every other commit.+b8606800887440ea31bd6a7c4a0392bea583177e:changelog.d/+redact-nested-json-secret-writeback.security.md:credential-literal:1diff --git a/changelog.d/5771.security.md b/changelog.d/5771.security.mdindex 8041dc5098..451892f0a1 100644--- a/changelog.d/5771.security.md+++ b/changelog.d/5771.security.md@@ -1 +1,3 @@Redact password-typed settings whose key is flat snake_case (for example `local_search_milvus_token`) from `GET /settings/api/bulk`. That endpoint has no `ui_element` metadata, so it falls back to matching the key's last dotted segment against a set of secret names — a key with no dots in it has the whole key as its "leaf" and matched nothing, shipping the value in the clear. The name check now also matches a secret name at an underscore boundary, while leaving capability flags (`requires_api_key`) and token counts (`max_tokens`) readable.++Note: no setting shipped by this project currently has the flat snake_case shape this fix targets — every shipped password-typed setting is a dotted key with an exact `api_key`/`password` leaf, which was already redacted before this change. The fix protects **user-created** settings (for example a self-hosted search engine a user adds under a `local_search_*`/`search.engine.web.*` key of their own choosing), not a live leak in any default configuration.diff --git a/changelog.d/6201.bugfix.md b/changelog.d/6201.bugfix.mdnew file mode 100644index 0000000000..7bc6995af0--- /dev/null+++ b/changelog.d/6201.bugfix.md@@ -0,0 +1 @@+Preserve stored nested secrets when saving masked multiselect values encoded as JSON, including edits to non-secret sibling fields.diff --git a/changelog.d/6201.security.md b/changelog.d/6201.security.mdnew file mode 100644index 0000000000..dda2fa9815--- /dev/null+++ b/changelog.d/6201.security.md@@ -0,0 +1,5 @@+Fixed a follow-up gap in #5771's settings-redaction work: the write-back guards that stop the `[REDACTED]` placeholder from being saved over a real secret checked only the *outer* setting key's sensitivity, so a secret nested a level or more inside a JSON-typed setting (for example a `stop_token`/`page_token`/`download_token` field inside an `llm.model_kwargs`-style dict) could still have its masked placeholder written back verbatim on save, silently discarding the real value. The guards now check every leaf of a dict/list value for the placeholder regardless of the outer key's name, and now merge a **partially**-masked container leaf-by-leaf instead of rejecting it outright: editing a plain sibling field (or a masked leaf's non-string sibling, like a port number) next to an untouched `[REDACTED]` secret restores the secret and saves the edit, rather than 400ing every GET-then-edit round-trip a client can construct. A masked leaf is restored from whatever the stored row actually holds — a list, a dict, a number or a boolean as well as a string — sharing only the emptiness half of the rule the redactor masks on, not its sensitivity check: because a `GET` collapses **any** non-empty value stored under one of the exact secret leaf names (`api_key`, `token`, `password`, `secret`, …) to a bare `[REDACTED]`, a merge that could only restore strings turned an untouched GET-then-save of such a setting into a permanent 400 the client could never satisfy — and on the settings page, where every rendered row is posted on save, that one row rolled back the entire save. Because the merge does not also require the leaf's own sub-key to be sensitive, a placeholder submitted over any other key is restored the same way from whatever non-empty value is stored there (e.g. a stored `{"port": 19530}` is never masked on read, but a submitted `{"port": "[REDACTED]"}` over it still restores `19530`). That allowance is scoped to a single object (and to a one-item list), where there is exactly one candidate entry to restore into: inside a list of **two or more** entries the same sibling edit is still deliberately refused with a 400, because by position alone it is indistinguishable from the permutation described next — such an edit has to be split into two writes (change or clear the secret first, then edit the sibling). The same masked container serialized as a JSON *string* rather than sent as a native object — the shape a `<textarea>`, or a client that `JSON.stringify()`'d the field, would send — is now recognized too, not only a native dict/list (recognition is a strict `json.loads` of a string that starts with `{`/`[`, so only well-formed JSON is decoded: a trailing comma, a leading BOM, a Python `repr()`, JSON with comments, a double-encoded string, or one nested past the depth cap still falls through and is written as the string it is) — this closes both a silent-data-loss path (the string form previously overwrote the stored dict verbatim) and, in an intermediate iteration, a secret-*disclosure* path where the restored/merged container could be run through the same string-typed coercion a plain "text"/"textarea" setting uses, flattening it to its Python `repr()` and persisting the real secret as an unredacted plain string; a merged/reconciled container is now always persisted as the container it is, never coerced through a scalar type. A same-length **permutation** of a **list** of dicts (e.g. two engine configs swapped) is now rejected rather than trusted positionally, since restoring a masked secret by index alone would silently rebind it to the wrong entry. This closes positional rebinding for lists specifically, not container rebinding in general: a dict-**keyed** container whose entries are swapped between their keys (and the same shape wrapped in one-item lists) is still accepted, because restoring by key is the same trust the single-object case documented below already accepts. The merged-vs-stored "did anything actually change" comparison is now type-aware, so e.g. `1` submitted over a stored `true` is recognized as a genuine edit instead of a false no-op. A sensitive `multiselect` setting's bare `[REDACTED]` round-trip (the shape `redact_value` produces for an exact-name match like `access_token` even when the real value is a list) no longer gets mis-parsed into a one-item list and spuriously rejected, and a **spliced** one (`"[REDACTED],new"`) on the same setting is now a hard 400 like every other ui_element — the multiselect comma-split previously turned that corrupted scalar into a list whose first item was an exact sentinel match and quietly merged it, persisting `["<real first item>", "new"]` with a 200 and destroying every stored item the client had not resent. Also hardened: the qualifier that keeps flag-like settings such as `requires_api_key` readable now requires an **exact** match on that literal leaf name, not merely a prefix (it previously matched a qualifier prefix combined with any sensitive suffix, which let real secrets like `db_skip_password` or `local_search_use_milvus_token` slip through unredacted); the settings-creation write paths now reject a placeholder-bearing value the way the update paths do, with one gap left open and documented rather than papered over: on the two bulk save routes the create guard is handed the raw submission and has no `ui_element` to decode it with, so a masked container submitted as a JSON *string* under a brand-new, non-sensitive key is still stored verbatim (the single-key `PUT` catches that shape only when the caller also supplies a `ui_element`). No secret can be lost that way — a brand-new key has no stored value to overwrite — so this is a data-integrity wart, not a disclosure or clobbering path; and the new redaction-guard helpers reject a pathologically deeply nested JSON payload with a clean 400 instead of crashing — on the **list** branch as well as the dict one, where the positional-rebinding gate and the type-aware equality helper it bottoms out in were initially left uncapped and could still reach a `RecursionError` (an opaque 500) for a list submitted against a stored list of the same over-deep shape. No shipped default setting is affected by any of these — every trigger requires a user-created setting, audited against all 586 keys the settings loader reads (not only the top-level `defaults/settings_*.json` files).++**Accepted trade-off, documented rather than reverted:** merging a partially-masked container also means a caller can edit a non-secret sibling of a restored secret (e.g. repoint a search engine's `url` while its `api_key` stays masked) without ever seeing the real secret. Egress/SSRF validation for such settings is keyed off fixed, known setting names — it does not inspect arbitrary user-defined JSON — so this is not, on its own, a new way to bypass egress policy for a *registered* setting, but it does mean a masked secret can end up silently pointed at a different destination than the one it was originally saved for. See `_merge_redacted_container`'s docstring for the full reasoning.++Separately, the `policy.*` audit log entry no longer records a changed setting's old/new value verbatim when that value is free-form. `_is_policy_setting` is a **prefix** match rather than an allow-list, and three keys already in its scope (`policy.trusted_search_engines`, `policy.trusted_inference_providers`, `llm.allowed_local_hostnames`) ship as editable JSON with no item schema — their egress validator skips non-string entries instead of rejecting them, so a list of dicts carrying an API key was accepted and then written to the log in plaintext at WARNING, on the bulk save paths as well as the single-key `PUT`. Values that cannot carry free-form text (booleans, numbers, null) and strings drawn from the key's own shipped `select` options are still recorded verbatim; anything else is recorded as structural metadata only — its type, plus its length for a string or its entry count for a container — with **no** value-derived token of any kind in the line. An intermediate version of this fix logged a stable truncated SHA-256 of the value; that is an offline dictionary oracle (anyone holding the log can confirm a guessed credential by hashing candidates offline), so it was replaced with the structure-only rendering. The corresponding trade-off is deliberate: change detection on free-form values is coarse (two different same-length secrets render identically), which is what guarantees the line can never be used to confirm a guess. The in-memory settings manager used by the programmatic API and the MCP server also stopped logging a value it fails to convert, matching the fix already applied to the database manager's converter.diff --git a/src/local_deep_research/api/settings_utils.py b/src/local_deep_research/api/settings_utils.pyindex b7ddfd89b0..58041e1b38 100644--- a/src/local_deep_research/api/settings_utils.py+++ b/src/local_deep_research/api/settings_utils.py@@ -61,8 +61,20 @@ class InMemorySettingsManager(ISettingsManager):try:return setting_type(value)except (ValueError, TypeError):+ # NEVER interpolate the VALUE here. This is the in-memory twin+ # of ``settings/manager.py``'s ``get_typed_setting_value``,+ # reached by the programmatic API and the MCP server, and a+ # settings value is a plausible secret carrier (an API key, or+ # a JSON container with one nested inside). The declared+ # ui_element and the value's type name identify the bad row+ # without disclosing it — the same fix applied to the DB+ # manager's converter in #6201.logger.warning(- f"Failed to convert value {value} to type {setting_type}"+ "Failed to convert a {} value for ui_element {} to type {} "+ "(value omitted)",+ type(value).__name__,+ ui_element,+ setting_type,)return valuediff --git a/src/local_deep_research/security/data_sanitizer.py b/src/local_deep_research/security/data_sanitizer.pyindex c526fbbf30..89d1dd1762 100644--- a/src/local_deep_research/security/data_sanitizer.py+++ b/src/local_deep_research/security/data_sanitizer.py@@ -89,15 +89,9 @@ def _is_empty_value(value: Any) -> bool:# than the secret itself. ``search.engine.web.brave.requires_api_key`` is a# checkbox saying an engine needs a key; masking it would ship "[REDACTED]" to# the settings UI in place of true/false and make the write-back no-op guards-# refuse legitimate writes. Consulted only by the underscore-suffix arm below —-# a leaf that *equals* a sensitive name has no qualifier to strip.-# This is a name-shape heuristic, so it is accepted as under-redaction risk-# for a future setting that reuses one of these qualifier prefixes on a key-# that actually stores a real string credential (rather than a boolean flag)-# -- test_every_shipped_password_setting_is_redacted-# (tests/security/test_bulk_secret_name_coverage.py) audits every shipped-# password-typed setting's key shape and fails the moment such a setting-# ships, so the gap does not survive silently.+# refuse legitimate writes. This vocabulary is retained for documentation and+# so a future confirmed shape can be added deliberately; only the single+# hardcoded leaf below is actually exempted (see ``_has_non_secret_qualifier``)._NON_SECRET_LEAF_PREFIXES = ("allow_","allows_",@@ -118,28 +112,68 @@ _NON_SECRET_LEAF_PREFIXES = ("uses_",)+# The ONE confirmed, load-bearing qualifier+suffix shape: used verbatim as a+# config dict key throughout the search-engine factories+# (``tests/security/test_factory_secret_redaction.py``,+# ``tests/security/test_noncollection_agent_enabled.py``) and shipped as the+# last dotted segment of ``search.engine.web.*.requires_api_key`` for every+# engine that needs one (``defaults/settings_*.json``).+_EXEMPT_QUALIFIER_LEAF = "requires_api_key"+def _has_non_secret_qualifier(leaf: str) -> bool:- """True when ``leaf`` carries a ``_NON_SECRET_LEAF_PREFIXES`` qualifier- at ANY underscore segment boundary, not only at the very start of the- string.-- A dotted key's leaf is a single segment (``requires_api_key``), so a- start-of-string check is enough on its own. But a flat snake_case key- has no dots at all, so its "leaf" (see ``_matches_sensitive_name``) is- the ENTIRE key — a qualifier that isn't the first segment, e.g.- ``llm_requires_api_key``, would slip past a ``startswith`` check even- though it is the exact same "flag about a secret" shape as- ``requires_api_key``. Checking every underscore boundary (the start of- the leaf, or immediately after an ``_``) catches the qualifier wherever- it falls in the key, at the cost of also matching it as a middle- segment (e.g. ``foo_use_bar``) — intentional, since the prefix list is- a name-shape heuristic, not a position rule.+ """True only for the ONE confirmed, load-bearing exemption: ``leaf`` is+ literally ``requires_api_key``.++ An earlier version exempted ANY leaf STARTING WITH ANY+ ``_NON_SECRET_LEAF_PREFIXES`` qualifier, combined with ANY sensitive+ suffix from ``DEFAULT_SENSITIVE_KEYS`` -- a combinatorial exemption this+ module's own docstrings never actually claimed ("only the exact+ ``requires_api_key`` shape ... is a carve-out") but the code granted+ anyway. That let a dotted key whose LAST SEGMENT genuinely starts with a+ qualifier immediately followed by an unrelated sensitive suffix --+ ``rag.skip_password``, ``llm.x.use_auth_token`` -- ship a real string+ credential in the clear, purely because its shape happened to resemble+ the one verified flag. Nothing confirms ``skip_password`` or+ ``use_auth_token`` are booleans rather than a badly-named credential the+ way ``requires_api_key`` is verified to be.++ An even earlier version matched the qualifier at ANY underscore+ boundary (``f"_{prefix}" in leaf``), not just the start; that was fixed+ first (see ``test_bulk_get_qualifier_mid_key_no_longer_exempts_a_real_secret``)+ and is a separate, already-closed gap from the one this narrows.++ Audit scope (post-#6201 review, item d -- corrected): the loader+ (``SettingsManager.default_settings``, ``settings/manager.py``) does+ ``defaults_path.rglob("*.json")``, which walks every subdirectory --+ not just the top-level ``defaults/settings_*.json`` files. The 478-key+ figure this docstring previously cited was only ``default_settings.json``+ (341 keys) plus the top-level ``settings_*.json`` files (137 keys); it+ omitted three subdirectories the loader also reads+ (``llm_providers/``, ``research_library/``, ``settings/search_engines/``,+ 108 more keys). Audited again against the FULL rglob'd scope -- 586+ keys as of this writing -- narrowing from the qualifier-prefix list to+ this single hardcoded leaf still changes zero shipped keys'+ classification, confirming the prefix list was never doing anything+ beyond gating this one shape in practice, over the scope the loader+ actually reads rather than a subset of it. A boolean/int value stays+ protected regardless of this function's answer -- ``redact_value``'s+ type guard leaves a bool/int/None leaf untouched on the broadened arm+ (see ``_is_exact_sensitive_match``).++ Blast radius, precisely (post-#6201 review, item R3): this changes+ behavior for a STRING value stored under a leaf shaped like this, AND+ for a dict/list one. A container that matches ONLY the broadened arm+ does not hit the type guard -- it takes the ``_force_redact_strings``+ branch instead, which masks every STRING leaf inside it regardless of+ the sub-key's name. Executed: with ``llm.x.use_auth_token`` exempted,+ ``{"a": "hello"}`` stays ``{"a": "hello"}``; without the exemption it+ becomes ``{"a": "[REDACTED]"}``. So a future addition to this+ vocabulary widens or narrows redaction for strings and for the string+ leaves nested inside containers -- only the bool/int/None half is+ genuinely unaffected."""- return any(- leaf.startswith(prefix) or f"_{prefix}" in leaf- for prefix in _NON_SECRET_LEAF_PREFIXES- )+ return leaf == _EXEMPT_QUALIFIER_LEAFdef _matches_sensitive_name(leaf: str, sensitive_names: Set[str]) -> bool:@@ -157,13 +191,19 @@ def _matches_sensitive_name(leaf: str, sensitive_names: Set[str]) -> bool:``local_search_milvus_api_key`` or ``some_password`` would have evadedarm 1 just as completely.- Arm 2 skips leaves carrying a ``_NON_SECRET_LEAF_PREFIXES`` qualifier- anywhere at an underscore boundary (see ``_has_non_secret_qualifier``),- so both ``requires_api_key`` (dotted leaf) and ``llm_requires_api_key``- (flat leaf, qualifier not in the first segment) stay readable while- ``milvus_api_key`` does not. Plural token counts (``max_tokens``,- ``supports_max_tokens``) end in ``_tokens``, a different suffix than- ``_token``, and stay readable too.+ Arm 2 skips a leaf that IS the ``requires_api_key`` shape (see+ ``_has_non_secret_qualifier``), so ``requires_api_key`` stays readable+ while ``milvus_api_key`` does not. This carve-out is a single hardcoded+ leaf, not a qualifier-prefix-plus-any-suffix combination: a namespaced+ flat key such as ``llm_requires_api_key``, a key where the qualifier+ word appears anywhere else before an unrelated sensitive suffix+ (``local_search_use_milvus_token``), and a DIFFERENT qualifier+suffix+ pairing that merely resembles the shape (``rag.skip_password``,+ ``llm.x.use_auth_token``) are all NOT exempted -- only the exact+ ``requires_api_key`` shape (as a whole key, or as a dotted key's last+ segment) is a confirmed, load-bearing carve-out. Plural token counts+ (``max_tokens``, ``supports_max_tokens``) end in ``_tokens``, a+ different suffix than ``_token``, and stay readable too."""if leaf in sensitive_names:return True@@ -185,10 +225,9 @@ def _is_exact_sensitive_match(values (e.g. a boolean under a key literally named ``api_key``) sincebefore this PR; that established behavior is intentionally left as-is.The broadened arm is a lexical suffix heuristic backed by a- hand-maintained non-secret-prefix carve-out (``_NON_SECRET_LEAF_PREFIXES``),- so a boolean/number setting whose name happens to lexically match a- sensitive suffix (a future ``verify_token``-style flag the carve-out- list doesn't yet know about) must NOT be redacted: replacing a bool/int+ single literal ``requires_api_key`` exemption, so a boolean/number+ setting whose name happens to lexically match a sensitive suffix+ (for example, a future ``verify_token``-style flag) must NOT be redacted: replacing a bool/intwith the "[REDACTED]" string corrupts it in the settings UI, whichonly special-cases real booleans when rendering a checkbox(``web/static/js/components/settings.js``), and silently writes backdiff --git a/src/local_deep_research/settings/manager.py b/src/local_deep_research/settings/manager.pyindex de6b7fe7b8..b4d565e729 100644--- a/src/local_deep_research/settings/manager.py+++ b/src/local_deep_research/settings/manager.py@@ -138,7 +138,7 @@ def _parse_multiselect(x):parsed = json.loads(stripped)if isinstance(parsed, list):return parsed- except (json.JSONDecodeError, ValueError):+ except (json.JSONDecodeError, ValueError, RecursionError):pass# Comma-separated fallbackreturn [item.strip() for item in stripped.split(",") if item.strip()]@@ -272,12 +272,111 @@ def _is_policy_setting(key: str) -> bool:"""Return True for security-relevant setting keys that need anaudit-log entry on change. Scope is intentionally narrow so thisaudit hook doesn't widen into general settings-change logging.++ Narrow is not the same as enumerated: the ``policy.`` arm is a PREFIX+ match, not an allowlist, so this covers every current and future+ ``policy.*`` key including ones a caller creates. See+ ``_policy_audit_value`` for why the audit line therefore cannot assume+ the values it records are scalars from a fixed vocabulary."""if key.startswith("policy."):return Truereturn key in _POLICY_AUDIT_KEYS+def _policy_audit_allowed_values(+ default_meta: Optional[Dict[str, Any]],+) -> Optional[List[Any]]:+ """The fixed vocabulary a policy setting's value must come from, or+ ``None`` when the key has no such vocabulary.++ Only a ``select``/``radio`` row with a static ``options`` list has one.+ Used by ``_policy_audit_value`` to decide whether a STRING value is+ safe to record verbatim: a value drawn from a shipped option list is a+ known token (``adaptive``, ``strict``, ...), not free-form input, so it+ cannot be a credential.+ """+ if not isinstance(default_meta, dict):+ return None+ if default_meta.get("ui_element") not in ("select", "radio"):+ return None+ options = default_meta.get("options")+ if not options:+ return None+ return [+ opt.get("value") if isinstance(opt, dict) else opt+ for opt in list(options)+ ]+++def _policy_audit_value(+ value: Any, allowed_values: Optional[List[Any]] = None+) -> str:+ """Render a value for the ``policy.*`` audit line so the line itself+ can never become a credential-disclosure channel.++ Recording old/new is the whole point of an audit entry, so this does+ not drop the information -- it drops the part that can carry a secret.+ The audit hook's scope was previously described as "``policy.*`` plus+ three keys holding booleans and a hostname list", which is not what the+ code does: ``_is_policy_setting`` PREFIX-matches ``policy.``, and three+ keys already in scope ship as free-form, editable JSON with no item+ schema at all -- ``policy.trusted_search_engines``,+ ``policy.trusted_inference_providers`` and+ ``llm.allowed_local_hostnames`` are all ``ui_element="json"``,+ ``editable=True``, default ``[]``. Their egress validator+ (``validate_trusted_search_engines``) ``continue``s past any non-``str``+ entry rather than rejecting it, so a list like+ ``[{"api_key": "sk-...", "name": "x"}]`` is accepted and reaches+ ``set_setting`` -- which then wrote both ``old=`` and ``new=`` to the+ log in plaintext at WARNING. That line also sits OUTSIDE the+ ``if commit:`` block, so the bulk save routes (``commit=False``) reach+ it too; it is not a PUT-only path (#6201 round 7).++ So plaintext is kept ONLY where the value is PROVEN unable to carry+ free-form text, and the proof is a check rather than a comment:++ * ``None``/``bool``/``int``/``float`` -- no string content at all;+ * a ``str`` that is one of the key's own registered ``select``+ options (see ``_policy_audit_allowed_values``) -- a fixed+ vocabulary shipped in ``defaults/``, e.g. ``policy.egress_scope``.++ Everything else -- a free-form string, a dict, a list, any other+ type -- is recorded as STRUCTURAL metadata only: the type name, plus+ the length when it is a string or the entry count when it is a+ container. No token derived from the value's CONTENT appears in the+ rendering. An earlier version logged a truncated SHA-256 of the+ value's canonical JSON; a stable unkeyed digest -- even cut to 64+ bits, re-truncated, or keyed with a key shipped in the repository --+ is an offline dictionary oracle: anyone holding the log can confirm+ a guessed credential by hashing candidates offline, which is exactly+ the disclosure this rendering exists to prevent (#6201 round 8: a+ common password was recovered from the logged prefix by an offline+ candidate list).++ The cost of structure-only recording is honest and deliberate:+ change detection on free-form values is COARSE. "still an+ 11-character string" / "the trusted-engine list went from 2 entries+ to 3" is all an auditor gets; two different 11-character secrets+ render IDENTICALLY, so the line can never confirm which candidate is+ the real value. A string's length narrows a candidate list but+ confirms nothing (every same-length candidate matches), which is+ what separates it from a digest. Scalars from a fixed vocabulary and+ values with no string content stay verbatim, so the policy decisions+ themselves -- the actual subject of this audit -- remain fully+ observable.+ """+ if value is None or isinstance(value, (bool, int, float)):+ return repr(value)+ if allowed_values and value in allowed_values:+ return repr(value)+ if isinstance(value, (dict, list)):+ return f"<{type(value).__name__}[{len(value)}]>"+ if isinstance(value, str):+ return f"<str[{len(value)}]>"+ return f"<{type(value).__name__}>"++def is_valid_setting_key(key: Any) -> bool:"""Return True if *key* is a well-formed setting key.@@ -387,6 +486,17 @@ def get_typed_setting_value()return default+ # NOTE: never interpolate a setting VALUE into the log lines below.+ # Any settings value is a plausible secret carrier — an API key, a+ # bearer token, or a JSON container with one nested inside — and this+ # converter is reached from every read path, including the+ # post-commit settings-changed emit that runs after+ # ``PUT /settings/api/{key}``. A malformed row (e.g. a dict stored in+ # a ``number`` row) would otherwise write the whole container, secret+ # included, to the log at WARNING level. The key, the declared+ # ui_element and the value's type name identify the bad row without+ # disclosing it. See #6201.+# Check environment variable first (highest priority).if check_env:env_value = check_env_setting(key)@@ -395,9 +505,11 @@ def get_typed_setting_value(return setting_type(env_value)except ValueError:logger.warning(- "Setting {} has invalid value {}. Falling back to DB.",+ "Setting {} has an invalid environment value of type {} "+ "for ui_element {} (value omitted). Falling back to DB.",key,- env_value,+ type(env_value).__name__,+ ui_element,)# If value is None (not in database), return default.@@ -409,9 +521,11 @@ def get_typed_setting_value(return setting_type(value)except (ValueError, TypeError):logger.warning(- "Setting {} has invalid value {}. Returning default.",+ "Setting {} has an invalid value of type {} for ui_element {} "+ "(value omitted). Returning default.",key,- value,+ type(value).__name__,+ ui_element,)return default@@ -1022,12 +1136,28 @@ class SettingsManager(ISettingsManager):# embeddings.require_local changes. Targeted scope — only# security-relevant settings are logged, to avoid widening# this PR into a general audit-log refactor.+ #+ # The values are rendered through ``_policy_audit_value``, NOT+ # interpolated raw: ``policy.`` is a prefix match and three of+ # the keys in scope hold free-form, user-editable JSON, so a+ # raw ``old={}``/``new={}`` here is a plaintext credential sink+ # (#6201 round 7). This line is also outside the ``if commit:``+ # block above on purpose — the bulk save routes pass+ # ``commit=False`` and must still be audited.if _is_policy_setting(key):+ try:+ _default_meta = self.default_settings.get(key)+ except Exception:+ # An audit line must never be able to fail the write it+ # is auditing; without the metadata every string simply+ # falls back to the structural form.+ _default_meta = None+ _audit_options = _policy_audit_allowed_values(_default_meta)logger.bind(policy_audit=True).warning("policy setting changed | key={} old={} new={}",key,- old_value,- value,+ _policy_audit_value(old_value, _audit_options),+ _policy_audit_value(value, _audit_options),)return True@@ -1612,12 +1742,20 @@ class SettingsManager(ISettingsManager):default_meta,)if invalid_reason is not None:+ # The value itself is never logged: an+ # imported settings value is a plausible+ # secret carrier. This mirrors the+ # equivalent line in+ # ``api/settings_utils.py``. ``invalid_reason``+ # is built from the *defaults* metadata+ # (min/max/options), never from the imported+ # value.logger.warning(- "Skipping import of setting {!r}: value "- "{!r} is invalid under the current defaults "- "schema — {}",+ "Skipping import of setting {!r}: value of "+ "type {} is invalid under the current "+ "defaults schema — {}",key,- setting_values.get("value"),+ type(setting_values.get("value")).__name__,invalid_reason,)continuediff --git a/src/local_deep_research/web/routers/settings.py b/src/local_deep_research/web/routers/settings.pyindex 6c04cbe640..e61004ee84 100644--- a/src/local_deep_research/web/routers/settings.py+++ b/src/local_deep_research/web/routers/settings.py@@ -52,6 +52,7 @@ from ..dependencies.rate_limit import (from ..dependencies.threadpool import run_db_syncfrom ..template_config import templates+import jsonimport mathimport platformimport time@@ -106,7 +107,23 @@ from ..services.settings_service import ()from ...security import safe_get-from ...security.data_sanitizer import DataSanitizer++# ``_is_empty_value`` is deliberately imported private (#6201): it is HALF+# of the predicate ``redact_value`` gates masking on -- the other half is+# ``is_sensitive_setting(key, ...)`` (``data_sanitizer.py``), which the+# write-back merge below does NOT consult. The merge must restore a masked+# leaf from at least the set of stored values that got masked in the first+# place -- a merge rule NARROWER than the mask rule's emptiness half turns+# an untouched GET-then-PUT round-trip into an unsatisfiable 400. Sharing+# this one predicate instead of re-deriving it keeps that emptiness half in+# lockstep; it does NOT make the merge equivalent to the mask rule as a+# whole, since the merge restores on the submitted leaf being the sentinel+# regardless of whether that leaf's own sub-key is sensitive -- e.g. a+# stored ``{"port": 19530}`` is never masked (``port`` is not sensitive),+# but a submitted ``{"port": "[REDACTED]"}`` over it is still restored to+# ``19530``. Narrowing ``DEFAULT_SENSITIVE_KEYS`` / ``is_sensitive_setting``+# therefore does NOT narrow what this merge will restore.+from ...security.data_sanitizer import DataSanitizer, _is_empty_valuefrom ..warning_checks import calculate_warningsfrom ..dependencies.json_body import json_body_error@@ -557,7 +574,29 @@ BLOCKED_SETTING_PREFIXES = frozenset()-def _container_embeds_sentinel(value: object, redaction_text: str) -> bool:+# Recursion cap for EVERY container helper below -- the sentinel/depth+# scanners, the merge, the positional-rebinding gate+# (``_non_sentinel_fields_match``) and the type-aware equality it bottoms+# out in (``_values_equal``). A helper in this family without the cap is+# a 500 waiting to happen even when the others have it, because+# ``_container_embeds_sentinel`` answers True unconditionally past its own+# cap and therefore KEEPS the callers walking a too-deep value (#6201+# round 7). json.loads accepts+# JSON nested roughly 900 levels deep, but these helpers recurse once per+# nesting level and hit Python's own call-stack RecursionError somewhere+# between depth ~499 and ~600 (exact threshold depends on what else is on+# the stack) -- well short of what a malicious/malformed payload can hand+# them. A real setting's JSON value is never more than a handful of levels+# deep, so a cap far below the crash point (and far above any legitimate+# value) lets a too-deep payload be rejected cleanly by the callers below+# instead of surfacing as an opaque 500 through the routes' broad+# ``except Exception``.+_MAX_CONTAINER_DEPTH = 64+++def _container_embeds_sentinel(+ value: object, redaction_text: str, _depth: int = 0+) -> bool:"""True when a dict/list contains the redaction sentinel as a substringof ANY string leaf, exact-leaf-match or partially spliced into one.@@ -567,103 +606,728 @@ def _container_embeds_sentinel(value: object, redaction_text: str) -> bool:produces such a container on the read side: every non-empty string leafbecomes the bare sentinel, regardless of its own sub-key name). bool/int/None leaves are never masked and so can never embed it.++ Past ``_MAX_CONTAINER_DEPTH`` levels this conservatively returns True+ (see ``_MAX_CONTAINER_DEPTH``'s comment) rather than recursing further:+ a value nested that deep cannot be proven safe, and every caller here+ treats "embeds the sentinel" as the signal to reject the write with a+ 400, which is the outcome we want for a pathological payload too."""+ if _depth > _MAX_CONTAINER_DEPTH:+ return Trueif isinstance(value, str):return redaction_text in valueif isinstance(value, dict):return any(- _container_embeds_sentinel(sub_val, redaction_text)+ _container_embeds_sentinel(sub_val, redaction_text, _depth + 1)for sub_val in value.values())if isinstance(value, list):return any(- _container_embeds_sentinel(item, redaction_text) for item in value+ _container_embeds_sentinel(item, redaction_text, _depth + 1)+ for item in value)return False-def _container_all_leaves_are_sentinel(- value: object, redaction_text: str-) -> bool:- """True when every non-empty string leaf inside a dict/list equals the- redaction sentinel EXACTLY -- i.e. the container is indistinguishable- from what ``_force_redact_strings`` would emit for it, so it can only be- an untouched GET round-trip rather than an edit.-- An empty/whitespace-only string leaf is not something- ``_force_redact_strings`` would have masked (it mirrors- ``_is_empty_value``'s carve-out), so it is not considered here either- and does not break purity. A single non-sentinel, non-empty string leaf- (a legitimately edited sibling field, e.g. a hostname retyped next to an- untouched ``"[REDACTED]"`` token) fails this and the container is then- handled as an edit by ``_container_embeds_sentinel`` instead, exactly- like a partially edited ``notifications.service_url`` string does.+def _container_exceeds_max_depth(value: object, _depth: int = 0) -> bool:+ """True when *value* nests a dict/list deeper than+ ``_MAX_CONTAINER_DEPTH``, independent of whether it contains the+ redaction sentinel anywhere.++ Checked ahead of the sentinel guards so a too-deep payload with NO+ sentinel in it gets its own error instead of+ ``_redaction_sentinel_error``'s "contains the redaction placeholder"+ message. ``_container_embeds_sentinel`` and ``_merge_redacted_container``+ both conservatively treat anything past the cap as "embeds it" /+ "unresolvable" regardless of actual content -- the right call for+ deciding to reject a payload that can't be proven safe, but the wrong+ reason to report when nothing in it actually matched the sentinel."""- if isinstance(value, str):- return not value.strip() or value == redaction_text+ if _depth > _MAX_CONTAINER_DEPTH:+ return Trueif isinstance(value, dict):- return all(- _container_all_leaves_are_sentinel(sub_val, redaction_text)+ return any(+ _container_exceeds_max_depth(sub_val, _depth + 1)for sub_val in value.values())if isinstance(value, list):- return all(- _container_all_leaves_are_sentinel(item, redaction_text)- for item in value+ return any(+ _container_exceeds_max_depth(item, _depth + 1) for item in value)- return True+ return False-def _container_matches_stored_shape(- value: object, stored_value: object, redaction_text: str+def _container_too_deep_error() -> str:+ """Explain the 400 raised when a dict/list value nests deeper than+ ``_MAX_CONTAINER_DEPTH`` -- a distinct condition from embedding the+ redaction sentinel and reported with its own message (see+ ``_container_exceeds_max_depth``), instead of the misleading+ "contains the redaction placeholder" wording a too-deep payload with+ no sentinel in it used to get by reusing ``_redaction_sentinel_error``.+ """+ return (+ "Value is nested too deeply to validate "+ f"(max {_MAX_CONTAINER_DEPTH} levels) — flatten it before saving."+ )+++def _container_rejection_error(ui_element: str | None, value: object) -> str:+ """Pick the right 400 message for a rejected dict/list write: the+ depth-cap message when *value* nests past ``_MAX_CONTAINER_DEPTH``+ (the cap itself is why it was rejected, whether or not it happens to+ also contain the sentinel), otherwise the usual+ redaction-sentinel message.+ """+ if isinstance(value, (dict, list)) and _container_exceeds_max_depth(value):+ return _container_too_deep_error()+ return _redaction_sentinel_error(ui_element)+++def _values_equal(a: object, b: object, _depth: int = 0) -> bool:+ """Type-aware equality for comparing a submitted/merged value against+ its stored counterpart.++ Plain ``==`` treats ``1 == True`` as equal (``bool`` is an ``int``+ subclass), so a checkbox submitted as ``1`` over a stored ``True`` --+ or ``{"enabled": 1}`` over a stored ``{"enabled": True}`` -- would+ look byte-for-byte identical to+ ``_resolve_container_secret_write``'s no-op check and silently+ discard a genuine type change instead of persisting it (#6201).+ ``bool`` is therefore checked FIRST, before the numeric case, because+ it IS an ``int``; dict/list are walked structurally rather than+ compared with their own ``==`` so a type mismatch nested inside a+ container is caught too, not just at the top level.++ ``int`` vs ``float`` is deliberately NOT a difference. This predicate+ also decides ``_non_sentinel_fields_match``, the gate that must see+ every visible field of a list item unchanged before a masked secret+ is restored by position -- and requiring ``type(a) is type(b)`` there+ made an ordinary browser round-trip UNSATISFIABLE. A stored+ ``[{"url": "a", "api_key": ..., "timeout": 30.0}, {...}]`` is served+ to the client with both keys masked; JavaScript has no ``30.0`` (its+ only number type is a double that serializes as ``30``), and+ ``settings.js`` additionally ``parseInt``s a decimal-free numeric+ before submitting. The client therefore CANNOT echo back a value+ ``type(a) is type(b)`` accepts, so every edit to a >=2-item list+ carrying a masked secret 400'd with "contains the redaction+ placeholder" no matter what the user did (#6201 round 5). Comparing+ numerics by value costs nothing the guard actually relies on: an+ attacker cannot use "same number, other numeric type" to disguise a+ reorder, because two list entries that differ ONLY in whether a+ number is stored as ``30`` or ``30.0`` are indistinguishable to any+ JSON client to begin with.++ Depth-capped like the other container walkers (see+ ``_MAX_CONTAINER_DEPTH``): past the cap this answers "not equal"+ rather than recursing into a stack overflow. That is the fail-closed+ answer for both callers -- ``_non_sentinel_fields_match`` treats it as+ "cannot prove this position is unchanged" (so a positional secret+ restore is refused) and ``_resolve_container_secret_write`` treats it+ as "not a no-op" (so nothing is silently swallowed). Without the cap a+ ~7 KB payload nested ~1000 levels deep against a stored value of the+ same shape raised an uncaught ``RecursionError`` that the write routes'+ broad ``except Exception`` turned into a 500 (#6201 round 7).+ """+ if _depth > _MAX_CONTAINER_DEPTH:+ return False+ if isinstance(a, dict) or isinstance(b, dict):+ if not (isinstance(a, dict) and isinstance(b, dict)):+ return False+ if a.keys() != b.keys():+ return False+ return all(_values_equal(a[k], b[k], _depth + 1) for k in a)+ if isinstance(a, list) or isinstance(b, list):+ if not (isinstance(a, list) and isinstance(b, list)):+ return False+ if len(a) != len(b):+ return False+ return all(_values_equal(x, y, _depth + 1) for x, y in zip(a, b))+ # bool BEFORE the numeric case: `bool` is an `int`, so a plain `==`+ # here would call `1` unchanged from a stored `True`.+ if isinstance(a, bool) or isinstance(b, bool):+ return type(a) is type(b) and a == b+ # Neither side is a bool by now, so `int`/`float` compare by VALUE:+ # `30 == 30.0` is the same number, and a JSON client has no way to+ # tell the two apart (see the docstring).+ return a == b+++def _non_sentinel_fields_match(+ value: object,+ stored_value: object,+ redaction_text: str,+ _depth: int = 0,) -> bool:- """True when every NON-maskable leaf of *value* -- anything that is not- a non-empty string, plus any empty/whitespace-only string leaf -- is- identical to the corresponding leaf of *stored_value*, with matching- dict keys / list lengths at every level of nesting.-- Maskable (non-empty string) leaves are exempt from the equality check:- those are expected to hold the redaction sentinel rather than the real- secret, and ``_container_all_leaves_are_sentinel`` already verifies- they are exactly that. What this function catches is the case that- slipped past round 4: a container round-trip where every string leaf- is untouched (still the sentinel) but a NON-string sibling was edited- -- e.g. ``{"token": "[REDACTED]", "port": 19530}`` submitted back as- ``{"token": "[REDACTED]", "port": 19531}``. Comparing only string- leaves against the sentinel can never see that edit; comparing the- non-maskable leaves against the stored row can.-- A maskable leaf whose stored counterpart was NOT itself a non-empty- string (or a structural mismatch -- different dict keys, different- list length, a dict submitted where the stored value is a list, etc.)- also fails this, since that cannot be an untouched round-trip either.+ """True when every leaf of *value* that is NOT the redaction sentinel+ equals ``stored_value``'s leaf at the same path -- i.e. nothing+ visible changed except the masked leaf(s).++ Used ONLY to gate positional secret restoration inside a LIST (see the+ list branch of ``_merge_redacted_container``): a same-length+ permutation of a list of dicts is indistinguishable from an in-place+ edit by position alone -- ``zip()`` pairs each submitted item with+ whatever stored item shares its index, not with the item it actually+ came from. Given stored ``[{url:a,api_key:K1},{url:b,api_key:K2}]``, a+ client that reorders the two entries and resubmits both with their+ (masked) ``api_key`` untouched would otherwise have K1 silently+ rebound to ``b`` and K2 to ``a`` -- restoring the WRONG secret under+ each url, not the one it actually belonged to (#6201). Requiring every+ visible field at that index to match before trusting the position+ catches this: a genuine in-place edit leaves everything but the+ secret leaf(s) unchanged, so it still matches; a reorder does not.++ This deliberately does NOT extend the "edit a sibling next to a+ restored secret" allowance ``_merge_redacted_container`` documents for+ a single dict/object -- that allowance is safe there because there is+ only one candidate object to restore into. Inside a list, the same+ allowance would make a sibling edit indistinguishable from a reorder,+ which is exactly the hole this closes. The accepted consequence: an+ ordinary edit to a NON-secret sibling field of a list item that also+ carries an untouched masked secret at the same index is rejected+ along with a genuine reorder -- the caller must split that into two+ writes (clear/replace the secret first, or edit the sibling via a+ request that doesn't also carry the sentinel) rather than combining+ them in one PUT.++ Depth-capped like every other container walker here (see+ ``_MAX_CONTAINER_DEPTH``). Past the cap this answers False -- "nothing+ proves this position still holds the same entry" -- which makes the+ caller reject the item rather than positionally rebind a secret into+ a container it could not finish inspecting. This helper and+ ``_values_equal`` were the last two in the merge path without a cap,+ and ``_merge_redacted_container``'s list branch called this one with+ no depth at all: a ~7 KB list whose first item nested ~1000 levels+ deep against a stored list of the same shape raised an uncaught+ ``RecursionError`` and surfaced as a 500 through the write routes'+ broad ``except Exception`` -- the exact outcome ``_MAX_CONTAINER_DEPTH``+ exists to prevent (#6201 round 7). Note the depth cap alone does not+ end the walk: ``_container_embeds_sentinel`` answers True+ unconditionally past its own cap, so this gate is still consulted for+ a too-deep item and must terminate on its own."""+ if _depth > _MAX_CONTAINER_DEPTH:+ return False+ if isinstance(value, str) and value == redaction_text:+ return Trueif isinstance(value, dict):- if not isinstance(stored_value, dict) or set(value.keys()) != set(- stored_value.keys()+ if not isinstance(stored_value, dict):+ return False+ # The submitted item's visible keys must exactly match the stored+ # item's keys, not just be a subset of them. A subset check lets a+ # client RENAME or DROP a visible field (e.g. resubmit ``url`` as+ # ``endpoint``, or omit it) to make an otherwise-mismatched item+ # look like a match: the renamed/added key isn't in ``stored_value``+ # so a subset walk would skip it, and the dropped key is simply+ # never visited from ``value.items()``. Either way position gets+ # trusted with nothing left to disprove it -- the exact bypass this+ # function exists to close (#6201 round 3 follow-up). Requiring+ # equal key sets also matches this module's own rule that adding a+ # field to a list item alongside a masked secret must be split into+ # two writes, rather than silently letting the extra field ride+ # along as if it always existed at this position.+ if value.keys() != stored_value.keys():+ return False+ for sub_key, sub_val in value.items():+ if not _non_sentinel_fields_match(+ sub_val, stored_value[sub_key], redaction_text, _depth + 1+ ):+ return False+ return True+ if isinstance(value, list):+ if not isinstance(stored_value, list) or len(stored_value) != len(+ value):return Falsereturn all(- _container_matches_stored_shape(- value[k], stored_value[k], redaction_text+ _non_sentinel_fields_match(+ sub_val, sub_stored, redaction_text, _depth + 1)- for k in value+ for sub_val, sub_stored in zip(value, stored_value))+ return _values_equal(value, stored_value, _depth)+++def _merge_redacted_container(+ value: object, stored_value: object, redaction_text: str, _depth: int = 0+) -> Tuple[object, bool]:+ """Merge a dict/list write against its stored counterpart, restoring+ the real secret under every leaf that is EXACTLY the redaction+ sentinel while keeping every other leaf's submitted value as-is -- so+ editing a non-secret sibling (or leaving a DIFFERENT secret leaf+ untouched) is saved instead of the whole container being rejected.++ ``redact_value`` (``security/data_sanitizer.py``) masks a container by+ SUB-KEY: in a MIXED container -- e.g. ``{"api_key": "sk-...",+ "description": "My engine", "requires_api_key": true}`` -- only the+ sensitive-named leaf becomes the sentinel; ordinary siblings stay+ plain. A caller that GETs, edits ``description``, and PUTs the result+ back therefore submits a container where exactly one leaf is the+ sentinel and the rest are ordinary values -- not the "every maskable+ leaf is the sentinel" shape round 5's fix required of the WHOLE+ container before treating it as anything but a corrupted edit.+ Rejecting that outright turns a legitimate edit into an unsatisfiable+ 400: the client can never construct a request this endpoint will+ accept, because it cannot see the real secret to resubmit it and any+ masked-leaf resubmission was treated as "embeds the sentinel". This+ function resolves it leaf-by-leaf instead of all-or-nothing.++ ACCEPTED RISK, DELIBERATE (post-#6201 review, item a): this leaf-by-+ leaf merge means a caller who has never seen the real secret can still+ edit a NON-secret sibling of it in the SAME write -- e.g. change+ ``search.engine.web.<engine>.url`` while ``api_key`` stays+ ``[REDACTED]`` -- and the merge restores the real key under the NEW+ url. A round of this feature's own review (round 5) rejected mixed+ containers outright specifically to prevent this; this round reverses+ that call because the outright rejection made the endpoint+ unsatisfiable for the overwhelmingly common case (any GET-then-edit of+ a mixed container at all, secret untouched). This is a real,+ consciously-accepted trade rather than an oversight: egress/SSRF+ validation for registered settings (``security/egress/validators.py``)+ keys off FIXED, known setting names, not the contents of arbitrary+ user-defined JSON, so this does not by itself hand a caller a new way+ to bypass egress policy for a setting the validators inspect. It DOES+ mean a masked secret can end up silently repointed at a different+ destination than the one it was originally saved under, without the+ caller ever needing to know the secret's value. If that trade+ ever needs tightening, the narrowing applied to LIST items below (see+ the list branch's docstring section) -- requiring every visible field+ at a position to match before trusting a positional secret restore --+ is the template: the same "verify nothing else changed" check could be+ applied to a bare dict's siblings too, at the cost of reintroducing+ the unsatisfiable-400 problem this round fixed.++ Returns ``(merged_value, rejected)``. ``rejected`` is True when a leaf+ cannot be resolved safely:++ * the leaf equals the sentinel exactly, but ``stored_value`` is+ itself empty (absent, ``""``, ``" "``, ``None``, ``[]`` or ``{}``)+ at that path -- there is nothing to "keep", so persisting it would+ write the literal placeholder text as the value. This checks only+ ``stored_value``'s emptiness, the same half of ``redact_value``'s+ gate that ``_is_empty_value`` implements -- it does NOT also check+ that the leaf's own sub-key is sensitive, so the restore set is a+ SUPERSET of the mask set: a stored ``{"port": 19530}`` is never+ masked on read (``port`` is not sensitive), but a submitted+ ``{"port": "[REDACTED]"}`` over it still restores ``19530`` here.+ Narrowing ``DEFAULT_SENSITIVE_KEYS`` / ``is_sensitive_setting``+ therefore does not narrow what this merge will restore;+ * the leaf merely CONTAINS the sentinel as a substring without being+ an exact match (e.g. a stale client's ``"[REDACTED],new-value"``)+ -- an edit, but a corrupted one that would splice the placeholder+ text into the stored value, the same corrupted-edit case the+ scalar arm of ``_embeds_redaction_sentinel`` rejects.++ A list is walked positionally only when the submitted and stored lists+ are the same length; a length change means there is no reliable+ correspondence between items, so any sentinel occurring in it can't be+ resolved and the whole list is rejected the same way an orphaned leaf+ is (matching the "can't confirm, so treat as unresolvable" stance the+ other container helpers take). A dict key absent from ``stored_value``+ is not itself an error -- it is an ordinary new field unless its own+ value happens to be the sentinel, which the orphan case above catches.++ Equal length is NOT sufficient on its own to trust a list's positions,+ though: a same-length PERMUTATION of a list of dicts is invisible to a+ plain ``zip()`` walk. Given stored ``[{url:a,api_key:K1},+ {url:b,api_key:K2}]``, a client that swaps the two entries and+ resubmits both with their ``api_key`` still masked would otherwise get+ K1 silently restored under ``b`` and K2 under ``a`` -- the wrong+ secret rebound to the wrong entry, not a rejection (#6201). Before+ restoring a sentinel-bearing dict/list item positionally, this walks+ it through ``_non_sentinel_fields_match`` first: every field at that+ index NOT equal to the sentinel must match the stored item at the same+ index, proving nothing but the masked leaf(s) changed there. A+ mismatch means the position can't be trusted to identify the same+ real-world entry the secret was read from, so that item's sentinel+ leaves are treated as unresolvable (rejected) rather than restored+ into what may be a different entry. This intentionally narrows the+ "edit a sibling next to a restored secret" allowance documented above+ to the single-object case -- inside a list it is indistinguishable+ from a reorder, so it isn't extended there.++ EXCEPTION: a single-element list (``len(value) == 1``) skips this+ sibling-match gate entirely. The gate exists solely to rule out a+ same-length reorder, and a list of one has no other position for its+ one item to have come from or gone to -- there is no reorder for a+ sibling edit to be confused with, so the "edit a sibling next to a+ restored secret" allowance the single-object dict case gets above+ applies here too.+ """+ # NOTE (fragility, deliberate): past the cap this does NOT reject on its+ # own -- it returns whatever ``_container_embeds_sentinel`` says, and that+ # helper's own cap makes it answer True unconditionally past this depth.+ # So the clean 400 a too-deep payload gets today is produced by that+ # helper's fail-closed default, not by this line. The composition is+ # correct (verified at 65/900/3000 levels), but it means a future edit+ # that makes ``_container_embeds_sentinel`` return a real answer past the+ # cap -- or drops its cap because "the callers already cap" -- would+ # silently turn a too-deep payload into an ACCEPTED merge here rather+ # than a rejection, with no test naming this line. Anything that touches+ # either cap must re-check this pair together; ``return value, True`` is+ # the equivalent that does not depend on the other helper, kept as a+ # call rather than a literal only so the two stay visibly coupled.+ if _depth > _MAX_CONTAINER_DEPTH:+ return value, _container_embeds_sentinel(value, redaction_text, _depth)++ if isinstance(value, dict):+ stored_dict = stored_value if isinstance(stored_value, dict) else {}+ merged: dict = {}+ rejected = False+ for sub_key, sub_val in value.items():+ merged_val, sub_rejected = _merge_redacted_container(+ sub_val, stored_dict.get(sub_key), redaction_text, _depth + 1+ )+ merged[sub_key] = merged_val+ rejected = rejected or sub_rejected+ return merged, rejected+if isinstance(value, list):- if not isinstance(stored_value, list) or len(value) != len(- stored_value- ):- return False- return all(- _container_matches_stored_shape(v, s, redaction_text)- for v, s in zip(value, stored_value)+ if isinstance(stored_value, list) and len(stored_value) == len(value):+ merged_list = []+ rejected = False+ for sub_val, sub_stored in zip(value, stored_value):+ # A single-element list has exactly one possible position+ # for its one item -- there is no OTHER index a reorder+ # could have moved it from or to, so the "position can't+ # be trusted" rationale below (which exists to catch a+ # same-length reorder) cannot apply. Skip the sibling-+ # match gate entirely for len == 1 rather than rejecting+ # an ordinary sibling edit next to a masked secret that+ # has no reorder to be confused with.+ if (+ len(value) != 1+ and _container_embeds_sentinel(+ sub_val, redaction_text, _depth + 1+ )+ and not _non_sentinel_fields_match(+ sub_val, sub_stored, redaction_text, _depth + 1+ )+ ):+ # A visible (non-sentinel) field at this index differs+ # from the stored item at the same index -- position+ # cannot be trusted to identify the same entry the+ # secret leaf was read from (e.g. a same-length+ # reorder). Reject rather than positionally rebind the+ # secret to a possibly different entry (#6201).+ merged_list.append(sub_val)+ rejected = True+ continue+ merged_val, sub_rejected = _merge_redacted_container(+ sub_val, sub_stored, redaction_text, _depth + 1+ )+ merged_list.append(merged_val)+ rejected = rejected or sub_rejected+ return merged_list, rejected+ return value, _container_embeds_sentinel(value, redaction_text, _depth)++ if isinstance(value, str):+ if value == redaction_text:+ # Restore from ANY non-empty stored value, not just a string+ # (#6201/#6213 item c). ``redact_value`` masks a nested leaf to+ # the bare sentinel for any non-empty value whose sub-key is an+ # exact ``DEFAULT_SENSITIVE_KEYS`` match -- a list, dict, int or+ # bool included -- so requiring ``isinstance(stored_value, str)``+ # here made the write-back rule STRICTER than the masking rule:+ # for all 18 exact sensitive leaf names, a stored list/dict/int/+ # bool leaf was masked on GET and then refused on PUT, an+ # unsatisfiable 400 the client could never construct a passing+ # request for (it cannot see the value the GET collapsed to one+ # string), and on ``save_all_settings`` a rejection rolls back+ # the WHOLE batch. Mirroring ``_is_empty_value`` -- the exact+ # gate ``redact_value`` masks on -- makes the round-trip a no-op+ # again. Every other rejection is unchanged: an empty stored+ # value ("", " ", None, [], {}) was never masked, so a sentinel+ # over it is still an orphan (below); a missing sub-key arrives+ # here as ``None`` from ``stored_dict.get(...)`` and is still+ # rejected; and a sentinel EMBEDDED in a longer string is still+ # the corrupted-edit case.+ if not _is_empty_value(stored_value):+ return stored_value, False+ return value, True+ if redaction_text in value:+ return value, True+ return value, False++ return value, False+++def _resolve_container_secret_write(+ value: object, stored_value: object, redaction_text: str+) -> Tuple[object, bool, bool]:+ """Decide the outcome of a dict/list write that may carry the+ redaction sentinel.++ Returns ``(effective_value, is_noop, is_rejected)``:++ * No sentinel anywhere in *value* -- pass it through untouched+ (``is_noop=False``, ``is_rejected=False``); there is nothing for+ this guard to do with an ordinary container write.+ * The sentinel is present but there is no ``stored_value`` to+ restore a masked leaf from -- rejected, same as before this only+ merges against a row that actually exists.+ * The sentinel is present and every occurrence resolves against+ ``stored_value`` (see ``_merge_redacted_container``) -- the merged+ container is the value to persist. If it is byte-for-byte+ identical to what's already stored, the write is a no-op (covers+ both the fully-masked round-trip and a partially-masked one where+ nothing actually changed); otherwise it is a genuine edit and the+ caller must persist the MERGED value, not the raw submitted+ *value*, which still carries the sentinel on its untouched leaves.+ * Any leaf cannot be resolved (see ``_merge_redacted_container``) --+ rejected.+ """+ if not _container_embeds_sentinel(value, redaction_text):+ return value, False, False+ if stored_value is None:+ return value, False, True+ merged, rejected = _merge_redacted_container(+ value, stored_value, redaction_text+ )+ if rejected:+ return value, False, True+ # Type-aware equality (#6201): plain ``==`` would call+ # ``{"enabled": 1}`` unchanged from a stored ``{"enabled": True}`` and+ # silently discard the type change as a false no-op.+ if _values_equal(merged, stored_value):+ return merged, True, False+ return merged, False, False+++def _coerced_for_guard(+ key: str, ui_element: str | None, value: object+) -> object:+ """Return *value* as the sentinel guards should see it, coerced to its+ stored shape when a JSON-STRING encoding would otherwise hide a masked+ container from them.++ ``PUT /settings/api/<key>`` and both bulk-save routes accept a "json"+ ui_element's value either as a native dict/list -- caught by the+ container arm of ``_is_secret_empty_noop`` / ``_embeds_redaction_sentinel``+ -- or as its JSON-STRING encoding, which ``coerce_setting_for_write`` ->+ ``get_typed_setting_value`` -> ``_parse_json_value``+ (``settings/manager.py``) decodes into the same dict, but only AFTER+ every guard call site runs its checks. A masked container submitted in+ string form therefore sails past the container arm (which only fires+ on an actual ``dict``/``list``) and falls through to the string arm,+ which is gated on the OUTER key's sensitivity -- exactly the+ "non-sensitive outer key with a sensitive nested leaf" case the+ container arm exists to close. Coercing here, before the guards run,+ closes that gap the same way the create path's registered-default+ branch already does (it coerces before its own guard call).++ Only a ``str`` is re-coerced, and the coerced result is used only if+ it actually becomes a dict/list: an already-dict/list *value* is+ already handled correctly by the container arm as-is, and running it+ back through a non-container ``ui_element`` (e.g. "text": ``str(value)``)+ would destroy that shape instead of revealing one. This return value+ is used ONLY to decide what the guards see and, when a sentinel is+ found, to compute the merged replacement value -- callers must keep+ persisting their own *value* (or that merge result) unchanged in every+ other case, never this function's return value directly, so an+ ordinary JSON-string write (no sentinel involved) is unaffected.++ A row's ``ui_element`` can itself disagree with its actual stored+ shape -- e.g. a ``PUT``-created key with no ``ui_element`` defaults to+ "text" (``models/settings.py``) even when a caller stores a dict/list+ value under it. For "text"/"textarea"/"password"/"select", the+ ui_element-based coercion above NEVER becomes a dict/list (their+ target type IS ``str``), so a masked container submitted in+ JSON-STRING form under one of THOSE elements would still sail past+ the container arm even after the coercion above (#6201). When the+ ui_element-based attempt didn't produce a container, this also tries+ a plain JSON decode of the same string independent of ``ui_element``+ entirely -- the row's ACTUAL stored shape decides whether this is a+ container write in disguise, not its declared type. Quiet on failure+ (unlike ``settings/manager.py``'s ``_parse_json_value``, which logs a+ warning on every non-JSON string): an ordinary "text" setting holding+ an ordinary non-JSON string is the overwhelmingly common case here and+ must not spam the log.++ The BARE sentinel (*value* exactly equal to the redaction text) is+ special-cased to skip coercion entirely and pass through unchanged.+ ``coerce_setting_for_write("multiselect", "[REDACTED]", ...)`` ->+ ``_parse_multiselect`` (``settings/manager.py``) sees a string starting+ with "[" that fails ``json.loads`` (the sentinel isn't valid JSON) and+ falls back to its comma-separated split, which -- since there is no+ comma -- wraps the whole string into a ONE-ELEMENT LIST,+ ``["[REDACTED]"]``. That list then looks like a malformed/rejected+ container write (a length-mismatch against a stored list of any other+ size) instead of the ordinary round-tripped sentinel it actually is,+ turning what used to be a 200 no-op into a 400 for a sensitive+ ``multiselect`` setting (#6201 item 6). The exact-match scalar arm of+ ``_is_secret_empty_noop`` / ``_embeds_redaction_sentinel`` handles a+ bare-string sentinel for a SENSITIVE key under every ui_element (both+ scalar arms are ``is_sensitive_setting``-gated -- a bare sentinel+ submitted for a NON-sensitive container row still persists verbatim+ over the stored container, which those arms do not cover), so there is+ nothing this coercion needs to reveal for that case.++ A SPLICED sentinel on a ``multiselect`` -- e.g. ``"[REDACTED],new"``+ from a stale client that rendered the mask and had a value appended --+ must skip the coercion for the same reason, and this one is a+ data-loss bug rather than a usability one. ``_parse_multiselect``'s+ comma-split fallback fires again (the whole string still isn't valid+ JSON) and turns the SPLICED scalar into ``["[REDACTED]", "new"]``,+ whose first item is now an EXACT sentinel match. The container arm+ then merges it positionally against a stored list of the same length+ and persists ``["A", "new"]`` with a 200 -- silently DESTROYING the+ stored ``"B"`` -- so the "contains the sentinel but is not equal to it+ => hard 400" rule that ``_merge_redacted_container`` documents (and+ that the scalar arm enforces, as the base branch did here) never fires+ at all. Splitting a spliced scalar into a list manufactures the exact+ match out of a corrupted edit, so malformed JSON carrying the sentinel+ is handed to the guards AS A STRING for this ui_element; the scalar arm+ of ``_embeds_redaction_sentinel`` then rejects it with the usual 400+ (#6201 round 7). Only ``multiselect`` needs this: ``json`` decodes+ with ``json.loads`` alone, which never invents list structure out of a+ non-JSON string. Valid JSON containers under ``multiselect`` must still+ be decoded before the guards run, so nested masks restore the stored+ secrets instead of being persisted literally.+ """+ if not isinstance(value, str) or not ui_element:+ return value+ if value == DataSanitizer.REDACTION_TEXT:+ return value+ # ``multiselect`` is the one ui_element whose coercion SPLITS a string+ # on commas, so a spliced sentinel ("[REDACTED],new") comes back as a+ # list whose first item is an exact sentinel match -- laundering a+ # corrupted edit into a merge that silently drops the stored items the+ # client did not resend. Keep it a string so the scalar arm can reject+ # it (see the docstring).+ if ui_element == "multiselect" and DataSanitizer.REDACTION_TEXT in value:+ # Strict JSON reveals real containers without the comma-split+ # fallback manufacturing a container from a corrupted scalar.+ try:+ parsed = json.loads(value)+ except (json.JSONDecodeError, ValueError, RecursionError):+ return value+ return parsed if isinstance(parsed, (dict, list)) else value+ # Only "json" and "multiselect" can actually decode a string into a+ # dict/list via ``coerce_setting_for_write`` -- every other+ # ui_element's converter (``float``, ``bool``, ``str``, ...) can never+ # produce one. Calling it for those elements anyway would run+ # ``coerce_setting_for_write`` a SECOND time on the exact same+ # (key, value, ui_element) once the caller coerces again for the+ # actual persisted write below (every string write on an existing+ # setting would otherwise pay for this twice): a failing conversion+ # (e.g. "abc" on a "number" row) would log its warning twice, and for+ # a "number"/"range" row this ran ``float(x)`` on the RAW submission+ # BEFORE the sentinel guards below get a chance to run. That used to+ # log the raw typed submission at WARNING on conversion failure --+ # exactly what the guards below exist to prevent from happening+ # unchecked. ``get_typed_setting_value`` no longer logs a setting+ # VALUE at all (#6201 round 6), so the disclosure half of this+ # rationale is now closed at the converter; the duplicate-work and+ # duplicate-warning halves stand on their own.+ # Skipping the call here for non-container-capable elements removes+ # that channel entirely; those elements still fall through to the+ # ui_element-independent JSON-shape check below, which is what+ # actually matters for detecting a container submitted under a+ # mismatched ui_element (see the docstring).+ if ui_element in ("json", "multiselect"):+ coerced = coerce_setting_for_write(+ key=key, value=value, ui_element=ui_element)- if isinstance(value, str) and value.strip():- # Maskable leaf: its own exactness is checked elsewhere. Just- # confirm the stored counterpart was maskable too, so a non-string- # leaf can't silently "become" a string one under this exemption.- return isinstance(stored_value, str) and bool(stored_value.strip())- return type(value) is type(stored_value) and value == stored_value+ if isinstance(coerced, (dict, list)):+ return coerced+ stripped = value.strip()+ if stripped and stripped[0] in "{[":+ try:+ parsed = json.loads(stripped)+ except (json.JSONDecodeError, ValueError, RecursionError):+ return value+ if isinstance(parsed, (dict, list)):+ return parsed+ return value+++def _reconciled_container_value_for_write(+ raw_value: object, guard_value: object, stored_value: object+) -> Tuple[object, bool]:+ """Return the value to actually PERSIST for a write that has already+ passed both sentinel guards (``_is_secret_empty_noop`` returned False+ and ``_embeds_redaction_sentinel`` returned False for *guard_value*).++ Returns ``(value_to_persist, is_reconciled_container)``.++ For a scalar, or a dict/list that embeds no sentinel at all, this is+ ``(raw_value, False)`` -- including when *guard_value* differs from+ *raw_value* (e.g. *guard_value* is the JSON-string-decoded form+ ``_coerced_for_guard`` produced purely to run the guards): an ordinary+ write, with no security-relevant transformation, must never be altered+ by this reconciliation step, or every other special-case handler+ downstream (checkbox coercion, the corrupted-value repair block) would+ see a different shape than it does today.++ Only when *guard_value* is a dict/list that DOES embed the sentinel+ does this return ``(effective, True)``, where ``effective`` is the+ MERGED container from ``_resolve_container_secret_write`` -- masked+ leaves restored to their stored secret, edited leaves as submitted --+ instead of *raw_value*, which still carries "[REDACTED]" on every+ untouched masked leaf and would otherwise be persisted verbatim.++ ``is_reconciled_container=True`` is the caller's signal to persist+ ``effective`` AS-IS, bypassing ``coerce_setting_for_write``. That+ coercion exists to turn a submitted SCALAR into the row's declared+ Python type (e.g. ``"5" -> 5`` for a number setting); every+ ui_element whose declared type is ``str`` -- "text", "textarea",+ "password", "select" -- would otherwise run a MERGED CONTAINER+ through ``str()``, flattening it to its Python repr and persisting a+ real, just-restored secret as a plain, non-redacted string under a+ key ``redact_value``/``is_sensitive_setting`` has no reason to treat+ as sensitive (#6201: this is exactly how the original fix for this+ function turned a data-loss bug into a disclosure one). A row's+ ``ui_element`` can disagree with its actual stored shape -- e.g. a+ ``PUT``-created key with no ``ui_element`` defaults to "text"+ (``models/settings.py``) even when its value is a dict -- so the+ submitted VALUE's shape, once reconciliation has happened, is what+ decides whether coercion is safe to run, not the row's declared type.+ ``coerce_setting_for_write``'s "json"/"multiselect" converters already+ pass a dict/list through unchanged, so skipping the call entirely for+ a reconciled container changes nothing for those two ui_elements --+ only "text"/"textarea"/"password"/"select" (whose converter is+ ``str``) and "number"/"checkbox"/"range"/"slider" (whose converter+ would silently discard the container's structure) are protected by+ this.+ """+ if not isinstance(guard_value, (dict, list)):+ return raw_value, False+ if not _container_embeds_sentinel(+ guard_value, DataSanitizer.REDACTION_TEXT+ ):+ return raw_value, False+ # NOTE (cross-helper coupling, deliberate but latent -- read before+ # editing either side). ``_is_rejected`` is DISCARDED here. When+ # ``_resolve_container_secret_write`` rejects -- an orphan sentinel+ # (a masked leaf with nothing in the stored row to restore it from), a+ # spliced "[REDACTED],x" leaf, a length-changed list, an untrusted+ # list position -- ``effective`` is the RAW submission, still carrying+ # the literal placeholder text, and this returns it with+ # ``is_reconciled_container=True``. Every caller reads that flag as+ # "persist as-is, skipping BOTH ``coerce_setting_for_write`` and+ # ``validate_setting``", so a rejected write would store "[REDACTED]"+ # as the credential with both checks bypassed.+ #+ # That is unreachable today, and only for one reason: all three call+ # sites run ``_embeds_redaction_sentinel`` FIRST, on the SAME+ # ``guard_value``, and it 400s on exactly the conditions that set+ # ``rejected`` here (it calls ``_resolve_container_secret_write`` with+ # the same arguments and returns its ``is_rejected``). By the time+ # this function runs, ``rejected`` is therefore always False. This is+ # the second undocumented coupling in this file (the first is+ # ``_merge_redacted_container``'s depth-cap NOTE) and is recorded+ # rather than removed because propagating the rejection would change+ # this helper's return arity at three call sites with three different+ # error conventions (a 400 JSONResponse, a per-key failed_count skip,+ # and a flash+302). If a caller is ever added that does NOT run+ # ``_embeds_redaction_sentinel`` on the same guard value first, or if+ # that guard's rejection conditions are narrowed, this becomes a live+ # fail-open and the rejection MUST be propagated instead.+ effective, _is_noop, _is_rejected = _resolve_container_secret_write(+ guard_value, stored_value, DataSanitizer.REDACTION_TEXT+ )+ return effective, Truedef _is_secret_empty_noop(@@ -681,52 +1345,56 @@ def _is_secret_empty_noop(whose control renders its real value, so an empty write there is adeliberate "clear it" gesture and must reach the database (#5960).- A dict/list value goes through the container arm: ``redact_value`` can- mask a container's string leaves via ``_force_redact_strings`` rather- than replacing the whole value with the bare sentinel (see its- docstring), so the exact-string check above never sees a container's- round-tripped sentinel. Without this arm, a GET-then-save-untouched- container -- e.g. ``{"uri": "[REDACTED]", "token": "[REDACTED]", "port":- 19530}`` -- would sail past every guard here (all are ``isinstance(value,- str)``-gated) and persist the sentinel over the real credential. Every- maskable (non-empty string) leaf must be exactly the sentinel for this- to count as untouched; a container that merely embeds it somewhere while- another leaf was edited is a corrupted edit, handled by- ``_embeds_redaction_sentinel`` instead.-- Checking string leaves alone is not enough, though: a container edit- that touches only a NON-string leaf (a port number, a bool toggle)- while every string leaf stays exactly the sentinel would still look- like a pure round-trip by that check alone, and the edit would be- silently discarded. ``stored_value`` -- the setting's current value in- the DB, threaded in by every call site that has a prior row to compare- against -- lets ``_container_matches_stored_shape`` catch that: the- container is only a genuine no-op if its non-maskable leaves are- byte-for-byte identical to what's already stored. If the caller has no- stored value to compare against (``stored_value is None``, e.g. no- prior row), a sentinel-bearing container can never be verified as an- untouched round-trip and is therefore never treated as this kind of- no-op -- it falls through to ``_embeds_redaction_sentinel``, which- rejects it with a 400 instead of risking a silent drop or a silent- sentinel write.+ A dict/list value goes through the container arm, delegated to+ ``_resolve_container_secret_write`` / ``_merge_redacted_container``:+ ``redact_value`` can mask a container's string leaves via+ ``_force_redact_strings`` or by SUB-KEY rather than replacing the whole+ value with the bare sentinel (see its docstring), so the exact-string+ check above never sees a container's round-tripped sentinel. Without+ this arm, a GET-then-save-untouched container -- e.g. ``{"uri":+ "[REDACTED]", "token": "[REDACTED]", "port": 19530}`` -- would sail past+ every guard here (all are ``isinstance(value, str)``-gated) and persist+ the sentinel over the real credential.++ The merge is per-LEAF, not all-or-nothing: every leaf that is exactly+ the sentinel is checked against ``stored_value`` at the same path, and+ every other leaf (an edited sibling, a non-string port/toggle) is kept+ as submitted. The write is a no-op only when that merge comes out+ byte-for-byte identical to what's already stored -- i.e. nothing about+ the container actually changed. A container that merges to something+ DIFFERENT from what's stored is a genuine edit (handled by+ ``_embeds_redaction_sentinel``'s reject path only if a leaf can't be+ resolved; otherwise it is written, see the update-route call sites,+ which persist the merged value rather than this function's raw+ argument). If the caller has no stored value to compare against+ (``stored_value is None``, e.g. no prior row), a sentinel-bearing+ container can never be verified as an untouched round-trip and is+ therefore never treated as this kind of no-op.++ The dict/list arm runs BEFORE the ``is_sensitive_setting`` gate below,+ unlike the string arm: ``redact_value`` recurses into a container by+ SUB-KEY, so a setting whose OUTER key is not itself sensitive (e.g.+ ``llm.model_kwargs``) can still have a sensitive-named leaf inside it+ (``stop_token``, ``page_token``) masked to the sentinel on the way out.+ Gating the container check on the outer key's sensitivity -- as this+ function used to -- means that sentinel round-trips straight back into+ the leaf on the very next save, since no guard ever looked at it. The+ literal string "[REDACTED]" is not a value any real setting leaf would+ hold, sensitive or not, so scanning every dict/list write for it+ unconditionally closes that gap without needing to re-derive which+ nested leaf name is "sensitive" here."""+ if isinstance(value, (dict, list)):+ _effective, is_noop, _is_rejected = _resolve_container_secret_write(+ value, stored_value, DataSanitizer.REDACTION_TEXT+ )+ return is_noopif not DataSanitizer.is_sensitive_setting(key, ui_element):return Falseif isinstance(value, str):return value == DataSanitizer.REDACTION_TEXT or (value == "" and ui_element == "password")- if isinstance(value, (dict, list)):- return (- stored_value is not None- and _container_embeds_sentinel(value, DataSanitizer.REDACTION_TEXT)- and _container_all_leaves_are_sentinel(- value, DataSanitizer.REDACTION_TEXT- )- and _container_matches_stored_shape(- value, stored_value, DataSanitizer.REDACTION_TEXT- )- )return False@@ -779,32 +1447,58 @@ def _embeds_redaction_sentinel(is a hard 400 rather than a no-op: unlike the exact-match case the usermade an edit, and silently dropping it would look like a successful save.- A dict/list value takes the container arm. There are two ways a- container can embed the sentinel without being the pure round-trip- ``_is_secret_empty_noop`` claims:-- 1. Not every maskable (non-empty string) leaf is exactly the- sentinel (``_container_all_leaves_are_sentinel`` is False) --- at least one string leaf was edited while another still carries- "[REDACTED]" verbatim, e.g. a hostname retyped next to an- untouched token field.- 2. Every maskable leaf IS exactly the sentinel, but a non-maskable- leaf (a port number, a bool toggle) does not match what's- currently stored -- ``_container_matches_stored_shape`` is False,- or there is no ``stored_value`` to compare against at all. This- is the case round 4 missed: a container that looks like a pure- string round-trip but actually carries an edit to a non-string- sibling. Silently persisting it would splice the sentinel into- the stored credential's string leaves; silently treating it as a- no-op (what ``_is_secret_empty_noop`` used to do) would discard- the non-string edit instead. Neither is acceptable, so both- shapes get the same 400 as the plain string case.-- Without a ``stored_value`` to check case 2 against, a sentinel-bearing- container can never be proven to be an untouched round-trip, so it is- conservatively treated as case 2 (400) rather than risking a silent- drop or a silent sentinel write.+ A dict/list value takes the container arm, delegated to+ ``_resolve_container_secret_write`` / ``_merge_redacted_container``.+ This is a REJECT only, never a silent partial write: a container is+ rejected when++ 1. a leaf equals the sentinel exactly but ``stored_value`` is itself+ empty (a newly-introduced key, a structural mismatch, or no+ ``stored_value`` at all) -- there is nothing to "keep", so+ persisting it would write the literal placeholder text. This is+ only the emptiness half of the check ``redact_value`` masks on;+ the leaf's own sub-key sensitivity is never consulted here, so a+ sentinel restores from ANY non-empty stored value at that path,+ not only one that was actually masked (a stored ``{"port":+ 19530}`` is never masked on read, but a submitted ``{"port":+ "[REDACTED]"}`` over it still restores ``19530``). Narrowing+ ``DEFAULT_SENSITIVE_KEYS`` / ``is_sensitive_setting`` therefore+ does not narrow what this merge will restore; or+ 2. a leaf merely CONTAINS the sentinel as a substring without being+ an exact match (e.g. a stale client's rendered+ "[REDACTED],new-value") -- an edit, but a corrupted one that+ would splice the placeholder text into the stored value, same as+ the plain string case below.++ A container where every sentinel-bearing leaf DOES resolve against+ ``stored_value`` is NOT rejected here, even when other, non-masked+ leaves were edited or a masked leaf's non-string sibling changed:+ ``redact_value`` masks a container by SUB-KEY, so a MIXED container --+ e.g. ``{"api_key": "[REDACTED]", "description": "My engine",+ "requires_api_key": true}`` -- has only its sensitive leaf masked, and+ an untouched GET-then-PUT round-trip of it, or an edit to+ ``description``, must not become an unsatisfiable 400 the client can+ never construct a passing request for (round 5 required EVERY maskable+ leaf be exactly the sentinel, rejecting exactly this shape). Merging+ the resolvable case instead of rejecting it is what lets+ ``_is_secret_empty_noop`` recognize the true no-op and the+ update-route call sites persist the resolved edit -- see+ ``_reconciled_container_value_for_write``.++ The dict/list arm runs BEFORE the ``is_sensitive_setting`` gate below,+ for the same reason ``_is_secret_empty_noop`` does: ``redact_value``+ masks a container by SUB-KEY, so an outer key that is not itself+ sensitive (``llm.model_kwargs``) can still carry a masked leaf+ (``stop_token``) that this function must catch on write-back. No real+ setting leaf ever legitimately holds the literal string+ "[REDACTED]", so checking every dict/list write for it, regardless of+ the outer key, cannot reject a value nothing would ever submit."""+ if isinstance(value, (dict, list)):+ _effective, _is_noop, is_rejected = _resolve_container_secret_write(+ value, stored_value, DataSanitizer.REDACTION_TEXT+ )+ return is_rejectedif not DataSanitizer.is_sensitive_setting(key, ui_element):return Falseif isinstance(value, str):@@ -812,16 +1506,6 @@ def _embeds_redaction_sentinel(DataSanitizer.REDACTION_TEXT in valueand value != DataSanitizer.REDACTION_TEXT)- if isinstance(value, (dict, list)):- if not _container_embeds_sentinel(value, DataSanitizer.REDACTION_TEXT):- return False- if not _container_all_leaves_are_sentinel(- value, DataSanitizer.REDACTION_TEXT- ):- return True- return stored_value is None or not _container_matches_stored_shape(- value, stored_value, DataSanitizer.REDACTION_TEXT- )return False@@ -838,15 +1522,20 @@ def _embeds_sentinel_on_create(round-trip" exemption here (unlike ``_is_secret_empty_noop`` on theupdate path) because creation has no prior stored value for an untouchedfield to round-trip from.++ The dict/list check runs regardless of the outer key's sensitivity, for+ the same reason as the update-path guards: a container's sensitive leaf+ can be named differently than its outer key, and no legitimate value+ ever contains the literal sentinel string."""+ if isinstance(value, (dict, list)):+ return _container_embeds_sentinel(value, DataSanitizer.REDACTION_TEXT)if not DataSanitizer.is_sensitive_setting(key, ui_element if isinstance(ui_element, str) else None):return Falseif isinstance(value, str):return DataSanitizer.REDACTION_TEXT in value- if isinstance(value, (dict, list)):- return _container_embeds_sentinel(value, DataSanitizer.REDACTION_TEXT)return False@@ -953,6 +1642,19 @@ def _save_all_settings_sync(form_data: dict, username: str):# Get the setting metadata from pre-fetched dictcurrent_setting = all_db_settings.get(key)+ # The sentinel guards below must see a JSON-STRING-encoded+ # container coerced to its real dict/list shape, or a+ # masked container submitted in that form (a supported+ # input shape for a "json" ui_element) sails past the+ # container arm entirely -- see ``_coerced_for_guard``.+ _guard_value = (+ _coerced_for_guard(+ current_setting.key, current_setting.ui_element, value+ )+ if current_setting+ else value+ )+# SAFETY NET: the redaction sentinel is never a "clear the# value" request, and neither is an empty string on a# password input. Reasons:@@ -975,7 +1677,7 @@ def _save_all_settings_sync(form_data: dict, username: str):if current_setting and _is_secret_empty_noop(key,current_setting.ui_element,- value,+ _guard_value,current_setting.value,):logger.debug(@@ -990,7 +1692,7 @@ def _save_all_settings_sync(form_data: dict, username: str):if current_setting and _embeds_redaction_sentinel(key,current_setting.ui_element,- value,+ _guard_value,current_setting.value,):logger.warning(@@ -1003,8 +1705,8 @@ def _save_all_settings_sync(form_data: dict, username: str):{"key": key,"name": current_setting.name,- "error": _redaction_sentinel_error(- current_setting.ui_element+ "error": _container_rejection_error(+ current_setting.ui_element, _guard_value),})@@ -1014,8 +1716,22 @@ def _save_all_settings_sync(form_data: dict, username: str):# This prevents incorrect triggering of corrupted value detectionif current_setting and current_setting.ui_element == "checkbox":if not isinstance(value, bool):+ # Never interpolate a settings VALUE into a log+ # line -- same rule as ``manager.py``'s converter+ # (#6201). A checkbox row can hold an arbitrary+ # submitted value here (that is exactly why this+ # branch exists), and a stale client or a+ # mis-registered ui_element can put a credential or+ # a secret-bearing container in it. The key, the+ # type name and the length identify the bad+ # submission without disclosing it.logger.debug(- f"Converting checkbox {key} from {type(value).__name__} to bool: {value}"+ "Converting checkbox {} from {} (len={}) to bool",+ key,+ type(value).__name__,+ len(value)+ if isinstance(value, (str, list, dict, tuple))+ else "n/a",)value = parse_boolean(value)form_data[key] = (@@ -1107,17 +1823,63 @@ def _save_all_settings_sync(form_data: dict, username: str):# "multiselect" ui_elements.if current_setting:+ # If the guards above let this through because a masked+ # container's sentinel leaves resolved against the+ # stored row (see ``_reconciled_container_value_for_write``),+ # persist the MERGED value -- secrets restored, edits+ # applied -- not the raw submission, which still carries+ # "[REDACTED]" on every untouched masked leaf. An+ # ordinary write (no sentinel involved) is returned+ # unchanged, so this has no effect on it.+ value, _is_reconciled_container = (+ _reconciled_container_value_for_write(+ value, _guard_value, current_setting.value+ )+ )+# Coerce to correct Python type (e.g. str "5" → int 5# for number settings, str "true" → bool for checkboxes).- converted_value = coerce_setting_for_write(- key=current_setting.key,- value=value,- ui_element=current_setting.ui_element,+ # A reconciled secret-bearing container is persisted+ # exactly as merged instead: coercing it through a+ # str-typed ui_element ("text"/"textarea"/"select")+ # would flatten it to its Python repr, persisting a+ # just-restored secret as a plain string (#6201). See+ # ``_reconciled_container_value_for_write``'s docstring.+ converted_value = (+ value+ if _is_reconciled_container+ else coerce_setting_for_write(+ key=current_setting.key,+ value=value,+ ui_element=current_setting.ui_element,+ ))- # Validate the setting- is_valid, error_message = validate_setting(- current_setting, converted_value+ # Validate the setting. A reconciled secret-bearing+ # container must never reach ``validate_setting``, and+ # the load-bearing reason is TYPE REJECTION rather than+ # logging: for a "number"/"range" row the value flows+ # into ``get_typed_setting_value``'s bare ``float(x)``,+ # which fails, so the row is reported "Value must be a+ # number" and the merged edit -- with the secret just+ # restored into it -- is lost. That same converter also+ # used to log the raw value at WARNING; that half is+ # closed at the converter as of #6201 round 6 and no+ # longer justifies the skip on its own (see+ # ``_coerced_for_guard``, whose comment says the same).+ # Only a user-constructed row (dict/list value on a+ # non-container ui_element) can reach this; skipping+ # validation is safe for the secret itself because the+ # merge already resolved the container against the+ # stored row. ACCEPTED LOSS: it does also skip the+ # options-membership / min-max / checkbox-type checks+ # for such a row, so e.g. a "select" row already+ # holding a container accepts a merged container with+ # no options check.+ is_valid, error_message = (+ (True, None)+ if _is_reconciled_container+ else validate_setting(current_setting, converted_value))if is_valid:@@ -1186,7 +1948,9 @@ def _save_all_settings_sync(form_data: dict, username: str):"name": key.split(".")[-1].replace("_", " ").title(),- "error": _redaction_sentinel_error(None),+ "error": _container_rejection_error(+ None, value+ ),})continue@@ -1556,6 +2320,12 @@ def _save_settings_sync(form_data: dict, username: str) -> dict:rejected_count = 0changed_settings: list[str] = []sentinel_rejected_ui_elements: list[str | None] = []+ # Parallel to sentinel_rejected_ui_elements: whether that specific+ # rejection was the depth cap rather than an actual sentinel, so the+ # aggregated flash message below doesn't misreport a too-deep+ # payload as "contains the redaction placeholder" (see+ # ``_container_too_deep_error``).+ sentinel_rejected_too_deep: list[bool] = []for key, value in form_data.items():try:db_setting = all_db_settings.get(key)@@ -1574,6 +2344,43 @@ def _save_settings_sync(form_data: dict, username: str) -> dict:rejected_count += 1continue+ # Creation has no prior value, so the sentinel cannot mean+ # "keep the stored secret" — every occurrence is a+ # corrupted client value that would be stored verbatim as+ # the credential. This is the one write path that never+ # had this check wired in (#5947 added it to+ # save_all_settings and api_update_setting, but not here);+ # ui_element is unknown at creation time, so sensitivity is+ # decided by the key's leaf name alone, same as the other+ # create paths.+ if db_setting is None and _embeds_sentinel_on_create(+ key, None, value+ ):+ logger.warning(+ "Rejected redaction-sentinel value for new key "+ "{!r} via save_settings (user={!r})",+ key,+ username,+ )+ sentinel_rejected_ui_elements.append(None)+ sentinel_rejected_too_deep.append(+ isinstance(value, (dict, list))+ and _container_exceeds_max_depth(value)+ )+ continue++ # See ``_coerced_for_guard``: the sentinel guards must see a+ # JSON-string-encoded container coerced to its real+ # dict/list shape, or a masked container submitted in that+ # form sails past the container arm entirely.+ _guard_value = (+ _coerced_for_guard(+ db_setting.key, db_setting.ui_element, value+ )+ if db_setting+ else value+ )+# SAFETY NET: the redaction sentinel is a no-op for every# sensitive setting, and an empty string is a no-op only for# password inputs — never "clear my key". The no-JS form@@ -1584,7 +2391,7 @@ def _save_settings_sync(form_data: dict, username: str) -> dict:# Matches the guards in save_all_settings +# api_update_setting.if db_setting and _is_secret_empty_noop(- key, db_setting.ui_element, value, db_setting.value+ key, db_setting.ui_element, _guard_value, db_setting.value):logger.debug(f"Skipping empty secret write for {key} via "@@ -1597,7 +2404,7 @@ def _save_settings_sync(form_data: dict, username: str) -> dict:# so collect it rather than saving a secret with "[REDACTED]"# spliced into it (#5947).if db_setting and _embeds_redaction_sentinel(- key, db_setting.ui_element, value, db_setting.value+ key, db_setting.ui_element, _guard_value, db_setting.value):logger.warning("Rejected redaction-sentinel value for {!r} via "@@ -1606,6 +2413,10 @@ def _save_settings_sync(form_data: dict, username: str) -> dict:username,)sentinel_rejected_ui_elements.append(db_setting.ui_element)+ sentinel_rejected_too_deep.append(+ isinstance(_guard_value, (dict, list))+ and _container_exceeds_max_depth(_guard_value)+ )continueif db_setting:@@ -1632,12 +2443,28 @@ def _save_settings_sync(form_data: dict, username: str) -> dict:):value = None- value = coerce_setting_for_write(- key=db_setting.key,- value=value,- ui_element=db_setting.ui_element,+ # Persist the MERGED value when a masked container's+ # sentinel leaves resolved against the stored row+ # (see ``_reconciled_container_value_for_write``); an+ # ordinary write is returned unchanged.+ value, _is_reconciled_container = (+ _reconciled_container_value_for_write(+ value, _guard_value, db_setting.value+ ))+ # A reconciled secret-bearing container is persisted+ # exactly as merged: coercing it through a str-typed+ # ui_element would flatten it to its Python repr and+ # disclose a just-restored secret as a plain string+ # (#6201). See _reconciled_container_value_for_write.+ if not _is_reconciled_container:+ value = coerce_setting_for_write(+ key=db_setting.key,+ value=value,+ ui_element=db_setting.ui_element,+ )+# Validate against the setting's constraints (options# membership, numeric bounds, checkbox type) — the same# check save_all_settings (~line 655) and@@ -1648,7 +2475,29 @@ def _save_settings_sync(form_data: dict, username: str) -> dict:# Best-effort semantics preserved: an invalid key is# skipped and counted in failed_count, the rest of the# batch still validates, saves, and commits.- if value is not None:+ #+ # A reconciled secret-bearing container skips+ # ``validate_setting`` the same way it skips coercion+ # above. The load-bearing reason is TYPE REJECTION, not+ # logging: ``validate_setting`` runs the value through+ # ``get_typed_setting_value`` for the row's DECLARED+ # ui_element, so a dict/list on a "number"/"range" row+ # comes back "Value must be a number" and the merged+ # edit -- with the secret just restored into it -- is+ # lost. Its other former reason (that same path logged+ # the raw, secret-bearing value at WARNING) is closed+ # at the converter itself as of #6201 round 6, so it no+ # longer justifies anything on its own;+ # ``_coerced_for_guard``'s comment already says this.+ # ACCEPTED LOSS: skipping validation also skips the+ # options-membership / min-max / checkbox-type checks,+ # so e.g. a "select" row that already holds a container+ # accepts a merged container with no options check.+ # Bounded to rows already holding a container under a+ # scalar ui_element -- a user-constructed shape -- and+ # the merge itself already resolved every leaf against+ # the stored row (#6201).+ if value is not None and not _is_reconciled_container:is_valid, error_message = validate_setting(db_setting, value)@@ -1689,6 +2538,7 @@ def _save_settings_sync(form_data: dict, username: str) -> dict:"failed": failed_count + 1,"rejected": rejected_count,"sentinel_rejected": sentinel_rejected_ui_elements,+ "sentinel_rejected_too_deep": sentinel_rejected_too_deep,}return {@@ -1697,6 +2547,7 @@ def _save_settings_sync(form_data: dict, username: str) -> dict:"failed": failed_count,"rejected": rejected_count,"sentinel_rejected": sentinel_rejected_ui_elements,+ "sentinel_rejected_too_deep": sentinel_rejected_too_deep,}@@ -1730,15 +2581,32 @@ async def save_settings(# input, where an empty write is a no-op rather than a clear (see# ``_redaction_sentinel_error``)._rejected_uis = outcome["sentinel_rejected"]+ _too_deep = outcome.get("sentinel_rejected_too_deep") or []_hint_ui = ("password"if any(ui == "password" for ui in _rejected_uis)else None)+ # Every rejection in this batch was the depth cap, not an actual+ # sentinel -- say so instead of claiming the value "contains the+ # redaction placeholder" (see ``_container_too_deep_error``). A+ # MIXED batch (some too-deep, some an actual sentinel) states+ # both reasons instead of only the sentinel wording, which used+ # to silently drop the too-deep explanation for whichever+ # settings in the batch were rejected for that reason instead.+ if _too_deep and all(_too_deep):+ _message = _container_too_deep_error()+ elif _too_deep and any(_too_deep):+ _message = (+ _redaction_sentinel_error(_hint_ui)+ + " (Some of these were instead rejected for nesting too "+ "deeply to validate — flatten those before saving.)"+ )+ else:+ _message = _redaction_sentinel_error(_hint_ui)flash(request,- f"Rejected {len(_rejected_uis)} settings: "- + _redaction_sentinel_error(_hint_ui),+ f"Rejected {len(_rejected_uis)} settings: " + _message,"error",)elif outcome.get("failed"):@@ -3848,6 +4716,16 @@ def _api_update_setting_sync(data, key, username):status_code=403,)+ # See ``_coerced_for_guard``: the sentinel guards must see a+ # JSON-string-encoded container coerced to its real+ # dict/list shape, or a masked container submitted in that+ # form (a supported shape for PUT .../<key> with+ # ``{"value": "<json string>"}``) sails past the container+ # arm entirely.+ _guard_value = _coerced_for_guard(+ db_setting.key, db_setting.ui_element, value+ )+# The redaction sentinel is a no-op for any sensitive# setting, and an empty string is a no-op only for password# inputs (which render blank, so an untouched field must not@@ -3855,7 +4733,7 @@ def _api_update_setting_sync(data, key, username):# save_all_settings/save_settings. The idempotent 200 keeps# client-side save indicators from erroring (#5960).if _is_secret_empty_noop(- key, db_setting.ui_element, value, db_setting.value+ key, db_setting.ui_element, _guard_value, db_setting.value):logger.debug(f"Skipping sensitive value write for {key} via "@@ -3873,7 +4751,7 @@ def _api_update_setting_sync(data, key, username):# while the exact-match case above stays an idempotent 200# no-op (#5947).if _embeds_redaction_sentinel(- key, db_setting.ui_element, value, db_setting.value+ key, db_setting.ui_element, _guard_value, db_setting.value):logger.warning("Rejected redaction-sentinel value for {!r} via "@@ -3883,27 +4761,65 @@ def _api_update_setting_sync(data, key, username):)return JSONResponse({- "error": _redaction_sentinel_error(- db_setting.ui_element+ "error": _container_rejection_error(+ db_setting.ui_element, _guard_value)},status_code=400,)if value is not None and not is_openai_chunk_size:+ # Persist the MERGED value when a masked container's+ # sentinel leaves resolved against the stored row (see+ # ``_reconciled_container_value_for_write``); an+ # ordinary write is returned unchanged.+ value, _is_reconciled_container = (+ _reconciled_container_value_for_write(+ value, _guard_value, db_setting.value+ )+ )+# Coerce to the correct Python type before saving (e.g.# string "5" -> int 5 for a number setting). chunk_size# was already coerced and bounds-checked above against# the registry, which is authoritative for a setting's- # type; the row is only data.- value = coerce_setting_for_write(- key=db_setting.key,- value=value,- ui_element=db_setting.ui_element,- )+ # type; the row is only data. A reconciled secret-+ # bearing container is persisted exactly as merged+ # instead -- coercing it through a str-typed ui_element+ # would flatten it to its Python repr and disclose a+ # just-restored secret as a plain string (#6201).+ if not _is_reconciled_container:+ value = coerce_setting_for_write(+ key=db_setting.key,+ value=value,+ ui_element=db_setting.ui_element,+ )- is_valid, error_message = validate_setting(- db_setting, value+ # A reconciled secret-bearing container skips+ # ``validate_setting`` the same way it skips coercion+ # above. The load-bearing reason is TYPE REJECTION, not+ # logging: ``validate_setting`` runs the value through+ # ``get_typed_setting_value`` for the row's DECLARED+ # ui_element, so a dict/list on a "number"/"range" row+ # comes back "Value must be a number" and the merged+ # edit -- with the secret just restored into it -- is+ # lost. Its other former reason (that same path logged+ # the raw, secret-bearing value at WARNING) is closed+ # at the converter itself as of #6201 round 6, so it no+ # longer justifies anything on its own;+ # ``_coerced_for_guard``'s comment already says this.+ # ACCEPTED LOSS: skipping validation also skips the+ # options-membership / min-max / checkbox-type checks,+ # so e.g. a "select" row that already holds a container+ # accepts a merged container with no options check.+ # Bounded to rows already holding a container under a+ # scalar ui_element -- a user-constructed shape -- and+ # the merge itself already resolved every leaf against+ # the stored row (#6201).+ is_valid, error_message = (+ (True, None)+ if _is_reconciled_container+ else validate_setting(db_setting, value))if not is_valid:logger.warning(@@ -4062,7 +4978,22 @@ def _api_update_setting_sync(data, key, username):# client value that would be stored verbatim as the credential# (#5947)._create_ui = setting_dict.get("ui_element")- if _embeds_sentinel_on_create(key, _create_ui, value):+ # This is the one create branch that never coerces before its+ # guard: the REGISTERED-default branch above already coerces+ # `value` in place before reaching here, but a genuinely new+ # (unregistered) key has no coercion step of its own. Without+ # this, a masked container submitted as its JSON-string+ # encoding -- caught for a registered key -- would sail past+ # the container arm here the same way it did on the update+ # paths (see ``_coerced_for_guard``). Only takes effect when+ # the caller explicitly provided ``ui_element`` in the request+ # body (custom keys have none registered to infer it from).+ _create_guard_value = _coerced_for_guard(+ key,+ _create_ui if isinstance(_create_ui, str) else None,+ value,+ )+ if _embeds_sentinel_on_create(key, _create_ui, _create_guard_value):logger.warning("Rejected redaction-sentinel value for {!r} via ""api_update_setting create (user={!r})",@@ -4071,8 +5002,9 @@ def _api_update_setting_sync(data, key, username):)return JSONResponse({- "error": _redaction_sentinel_error(- _create_ui if isinstance(_create_ui, str) else None+ "error": _container_rejection_error(+ _create_ui if isinstance(_create_ui, str) else None,+ _create_guard_value,)},status_code=400,@@ -4121,12 +5053,23 @@ def _api_update_setting_sync(data, key, username):# Don't echo a freshly-created password back in# plaintext — redact like every other settings# response that ships to the browser.- "value": (- DataSanitizer.REDACTION_TEXT- if DataSanitizer.is_sensitive_setting(- key, db_setting.ui_element- )- else db_setting.value+ #+ # Route this through ``redact_value`` rather+ # than ``is_sensitive_setting`` (#6201, R4).+ # ``is_sensitive_setting`` is a NAME predicate+ # with no type guard; ``redact_value`` adds the+ # guard every read path already applies, so a+ # checkbox/number row whose name merely matches+ # the broadened snake_case arm (e.g.+ # ``llm.x_supports_api_key``) keeps its typed+ # value instead of echoing the string+ # "[REDACTED]" that no GET of the same row+ # would ever return. It also masks nested+ # string leaves inside a created container,+ # which the bare sentinel substitution could+ # not express at all.+ "value": DataSanitizer.redact_value(+ key, db_setting.ui_element, db_setting.value),"type": db_setting.type.value,"name": db_setting.name,diff --git a/tests/api/test_settings_utils_typed_value.py b/tests/api/test_settings_utils_typed_value.pyindex 6514a81684..2932384c6c 100644--- a/tests/api/test_settings_utils_typed_value.py+++ b/tests/api/test_settings_utils_typed_value.py@@ -159,3 +159,53 @@ class TestGetTypedValueConversionFailure:def test_none_for_number(self, manager):result = manager._get_typed_value({"ui_element": "number"}, None)assert result is None+++class TestGetTypedValueConversionFailureNeverLogsValue:+ """The conversion-failure WARNING must not interpolate the value.++ This is the sink #6201 changed from a raw f-string that interpolated+ the value, to a value-omitted form. Round 8 / B3: the change had NO+ direct regression test on this call path, so restoring the raw+ interpolation passed every test in this file.++ EXACT REVERT THIS CATCHES: restoring+ ``logger.warning(f"Failed to convert value {value} to type "+ f"{setting_type}")`` in ``InMemorySettingsManager._get_typed_value``+ -- the repr of the dict (nested secret included) or of the scalar+ secret then reaches the captured log.++ The POSITIVE CONTROL is not optional: the package disables its own+ loguru namespace at import, so "no secret captured" passes with+ nothing captured at all. The control is the warning itself, which+ must still name the declared ui_element and the value's type name.+ """++ def test_container_secret_never_logged(self, manager, loguru_caplog):+ secret = "sk-live-typed-value-8842"++ with loguru_caplog.at_level("WARNING"):+ # float(dict) raises TypeError -> the exact branch that used+ # to interpolate the whole container.+ result = manager._get_typed_value(+ {"ui_element": "number"}, {"stop_token": secret, "retries": 4}+ )++ assert result == {"stop_token": secret, "retries": 4}+ assert "number" in loguru_caplog.text # positive control+ assert "dict" in loguru_caplog.text # the kept diagnostic+ assert secret not in loguru_caplog.text+ assert "stop_token" not in loguru_caplog.text++ def test_scalar_secret_never_logged(self, manager, loguru_caplog):+ secret = "s3cr3t-typed-value-env-0417"++ with loguru_caplog.at_level("WARNING"):+ # float(str) raises ValueError -> the scalar arm of the same+ # sink (an LDR_* override is where a provider key lives).+ result = manager._get_typed_value({"ui_element": "number"}, secret)++ assert result == secret+ assert "number" in loguru_caplog.text # positive control+ assert "str" in loguru_caplog.text # the kept diagnostic+ assert secret not in loguru_caplog.textdiff --git a/tests/security/test_bulk_secret_name_coverage.py b/tests/security/test_bulk_secret_name_coverage.pyindex 036b3c6d8e..25ef0ce8da 100644--- a/tests/security/test_bulk_secret_name_coverage.py+++ b/tests/security/test_bulk_secret_name_coverage.py@@ -15,6 +15,26 @@ is why #5762 slipped through), it ENUMERATES the shippedsetting declared ``ui_element: "password"``. Add a new secret setting whose keythe predicate does not recognize and this test fails before the leak ships.+IMPORTANT CAVEAT verified against the merge commit that added the broadened+underscore-suffix arm (#5771, 0a75d2df5): every one of the 34 settings this+test currently enumerates is a *dotted* key with an exact ``api_key`` or+``password`` leaf (e.g. ``llm.openai.api_key``), which arm 1 (exact match)+already redacted before #5771. No shipped setting has the flat snake_case+shape (``local_search_milvus_token``-style, no dots) that the broadened arm+exists to catch — that key is used only in this file's own docstrings and+synthetic test cases below. So this test currently passes identically with+the broadened arm reverted; it guards against a *regression* in the exact-+match arm and against a future password setting shaped so the qualifier+carve-out wrongly exempts it (see the comment above+``_NON_SECRET_LEAF_PREFIXES`` in ``data_sanitizer.py``), but it does not+exercise, and cannot fail on, the flat-key broadening itself. That coverage+lives in ``test_bulk_get_redacts_secret_key_shapes`` and+``test_bulk_get_redacts_named_secret`` below, which use synthetic+flat-key names precisely because no shipped setting takes that shape yet —+today, the broadened arm protects only USER-CREATED settings (e.g. a+self-hosted search engine's user-added ``*_token``/``*_api_key`` config),+not anything this project ships.+Its mirror, ``test_no_shipped_non_secret_setting_is_redacted``, pins the otherdirection: widening the predicate must not start masking ordinary settings.``search.engine.web.*.requires_api_key`` is a checkbox whose leaf ends in@@ -50,7 +70,7 @@ def _iter_shipped_settings():dict carrying setting metadata as an entry rather than assuming a depth."""for path in sorted(DEFAULTS_DIR.rglob("*.json")):- data = json.loads(path.read_text())+ data = json.loads(path.read_text(encoding="utf-8"))stack = [data]while stack:node = stack.pop()@@ -87,7 +107,23 @@ SHIPPED_NON_SECRET_SETTINGS = [def _bulk_shipped(key, value="topsecret-value"):- """What ``GET /settings/api/bulk`` would put on the wire for ``key``."""+ """``redact_value`` applied the way the bulk GET applies it: with NO+ ``ui_element``, which is the asymmetry these tests exist to cover.++ NOT a stand-in for the endpoint (post-#6201 review, R2). An earlier+ docstring claimed this was "what ``GET /settings/api/bulk`` would put+ on the wire", which it is not: the route reaches ``redact_value``+ through the TYPED getter, so a container on a str-typed row arrives+ here as a Python repr rather than a container and ships in the clear+ (#6222). This helper answers only the NAME question -- does the+ sanitizer recognize ``key`` as a secret when it is given no+ ``ui_element`` to help it -- which is exactly the property the+ enumeration tests below assert over every shipped setting. The+ endpoint itself is pinned end-to-end in+ ``tests/security/test_settings_egress_and_secrets_fastapi.py::+ TestBulkSecretWriteBackAndEcho::+ test_bulk_settings_get_leaks_a_container_row_xfail_6222``.+ """return DataSanitizer.redact_value(key, None, value)@@ -234,24 +270,83 @@ def test_bulk_get_masks_string_leaves_inside_a_broadened_match_container():}-def test_bulk_get_leaves_qualifier_named_flag_readable_mid_key():- """Carve-out semantics regression: ``_NON_SECRET_LEAF_PREFIXES`` must- apply wherever the qualifier falls in a FLAT snake_case key, not only at- its very first segment.-- A flat key has no dots, so its "leaf" (see ``_matches_sensitive_name``)- is the entire key. ``llm_requires_api_key`` is the same "flag ABOUT a- secret" shape as the dotted ``search.engine.web.brave.requires_api_key``- (already pinned above), but the qualifier ``requires_`` is not the first- segment. It must be recognized and left readable either way -- for a- bool (round 2's type guard already prevents corruption there) and for a- same-shape string (the residual hazard this test pins: without the- fix, the carve-out silently misses the qualifier and over-redacts the- string).+def test_bulk_get_leaves_qualifier_named_flag_readable_at_leaf_start():+ """The genuine, load-bearing carve-out: a leaf that STARTS WITH a+ ``_NON_SECRET_LEAF_PREFIXES`` qualifier stays readable.++ ``requires_api_key`` is a real, shipped shape --+ ``search.engine.web.*.requires_api_key`` for every search engine that+ needs one (``defaults/settings_*.json``) -- and the identical string is+ used verbatim as a config dict key throughout the search-engine+ factories (``tests/security/test_factory_secret_redaction.py``,+ ``tests/security/test_noncollection_agent_enabled.py``). Both the exact+ flat form and a dotted key's last segment must stay readable, for a+ bool and for a string.++ SCOPE NOTE: this is a CONTROL, not a pin on this round's narrowing. It+ passes identically against every prior version of+ ``_has_non_secret_qualifier`` -- the unanchored substring check, the+ ``startswith``-anchored prefix list, and the single-leaf carve-out all+ leave ``requires_api_key`` readable. What actually falsifies a revert+ of the narrowing is its two siblings below+ (``test_bulk_get_qualifier_mid_key_no_longer_exempts_a_real_secret``+ and the ``rag.skip_password`` / ``llm.x.use_auth_token`` case). This+ test exists to catch the opposite mistake: a narrowing that goes too+ far and starts redacting the one shape that must stay readable.+ """+ for key in ("requires_api_key", "search.engine.web.brave.requires_api_key"):+ assert _bulk_shipped(key, True) is True+ assert _bulk_shipped(key, False) is False+ assert _bulk_shipped(key, "plain-value") == "plain-value"+++def test_bulk_get_qualifier_mid_key_no_longer_exempts_a_real_secret():+ """Anchoring regression for the post-#5771 review (defect 2):+ ``_has_non_secret_qualifier`` used to match a qualifier at ANY+ underscore boundary, not just the start of the leaf -- so a qualifier+ word appearing anywhere before an otherwise-unrelated sensitive suffix+ silently exempted a real secret from redaction.++ Each of these ships in the clear before the fix and must be redacted+ after it. None is the ``requires_api_key`` shape pinned above --+ a namespace segment leads every one of them, not a qualifier:++ * ``db_skip_password`` / ``vault_show_secret`` -- qualifier+ immediately precedes the noun, but is not the leaf's first segment.+ * ``x_needs_auth_token`` -- ``needs_`` precedes the 2-word compound+ ``auth_token``, still not the first segment.+ * ``local_search_use_milvus_token`` -- ``use_`` is two segments+ before the actual credential noun (``milvus_token``'s ``token``),+ the clearest case of the qualifier being unrelated to the secret it+ happened to exempt.++ A synthetic flat key that WOULD have been protected by the old+ mid-string rule -- ``llm_requires_api_key`` -- is included too: nothing+ in its shape distinguishes it from ``db_skip_password``, so it is no+ longer treated as safe for a string value (a bool/int stays protected+ regardless, by the type guard in ``redact_value``, independent of this+ predicate)."""- assert _bulk_shipped("llm_requires_api_key", True) is True- assert _bulk_shipped("llm_requires_api_key", False) is False- assert _bulk_shipped("llm_requires_api_key", "plain-value") == "plain-value"+ now_sensitive = [+ "db_skip_password",+ "x_needs_auth_token",+ "local_search_use_milvus_token",+ "vault_show_secret",+ "llm_requires_api_key",+ ]+ for key in now_sensitive:+ assert DataSanitizer.is_sensitive_setting(key), (+ f"{key!r} must be recognized as sensitive after anchoring the "+ "qualifier to the start of the leaf"+ )+ assert (+ _bulk_shipped(key, "a-real-secret-value")+ == DataSanitizer.REDACTION_TEXT+ )+ # The type guard still protects a bool/int leaf under a name-only+ # (non-exact) sensitive match, independent of the qualifier fix.+ assert _bulk_shipped(key, True) is True+ assert _bulk_shipped(key, False) is False# A real secret with an unrelated prefix segment is still redacted --# the carve-out must not become a blanket exemption for any multi-segment@@ -262,6 +357,46 @@ def test_bulk_get_leaves_qualifier_named_flag_readable_mid_key():)+def test_qualifier_carve_out_does_not_extend_past_requires_api_key():+ """Post-#6201 review: ``_has_non_secret_qualifier`` used to exempt ANY+ leaf STARTING WITH ANY ``_NON_SECRET_LEAF_PREFIXES`` qualifier, combined+ with ANY sensitive suffix -- not just the one confirmed, load-bearing+ shape (``requires_api_key``) its own docstring claimed. A DOTTED key's+ last segment genuinely starting with a qualifier immediately followed+ by an unrelated sensitive suffix -- ``rag.skip_password``,+ ``llm.x.use_auth_token`` -- was exempted the same way, even though+ nothing confirms either is a boolean flag rather than a real credential+ stored under a badly-named key.++ ``requires_api_key`` itself, both as a flat key and as a dotted key's+ last segment, must stay the one exemption -- pinned already by+ ``test_bulk_get_leaves_qualifier_named_flag_readable_at_leaf_start``.+ """+ now_sensitive = [+ "rag.skip_password",+ "llm.x.use_auth_token",+ "skip_password",+ "use_auth_token",+ ]+ for key in now_sensitive:+ assert DataSanitizer.is_sensitive_setting(key), (+ f"{key!r} must be recognized as sensitive: only the exact "+ "requires_api_key shape is a carve-out"+ )+ assert (+ _bulk_shipped(key, "a-real-secret-value")+ == DataSanitizer.REDACTION_TEXT+ )+ # The type guard still protects a bool leaf under a name-only match.+ assert _bulk_shipped(key, True) is True+ assert _bulk_shipped(key, False) is False++ # requires_api_key is unaffected by the narrowing.+ for key in ("requires_api_key", "search.engine.web.brave.requires_api_key"):+ assert not DataSanitizer.is_sensitive_setting(key)+ assert _bulk_shipped(key, "plain-value") == "plain-value"++@pytest.fixturedef manager_factory():"""Create managers and release their sessions and engines after a test."""diff --git a/tests/security/test_settings_egress_and_secrets_fastapi.py b/tests/security/test_settings_egress_and_secrets_fastapi.pyindex 65749d3c83..02ff23a50f 100644--- a/tests/security/test_settings_egress_and_secrets_fastapi.py+++ b/tests/security/test_settings_egress_and_secrets_fastapi.py@@ -11,9 +11,9 @@ COVERAGE AREA 1 -- model-discovery egress policy on``GET /settings/api/available-models``(6 deleted tests). This route reads STORED PROVIDER CREDENTIALS and contactsprovider model-listing endpoints, so ``_resolve_model_discovery_policy``- (``settings.py:268``) and ``_model_discovery_provider_allowed``- (``settings.py:331``) are the gate that decides whether a user's API key- leaves the box. At the review snapshot, only the+ and ``_model_discovery_provider_allowed`` (both in+ ``web/routers/settings.py``) are the gate that decides whether a user's+ API key leaves the box. At the review snapshot, only the``settings_unavailable`` 503 arm had coverage(``tests/security/test_strict_policy_settings_snapshots.py::test_model_discovery_rejects_query_failure_before_cache_provider_or_credential``);@@ -32,7 +32,8 @@ contracts:round-trip (``test_sensitive_setting_get_is_redacted_and_roundtrip_safe``);this file covers only what that file does NOT -- the two BULK endpoints,the no-JS form POST, the ``ui_element != "password"`` sensitive-suffix- asymmetry, the bulk-save RESPONSE echo (``settings.py:933``, a payload+ asymmetry, the bulk-save RESPONSE echo (the+ ``"settings"`` key of ``_save_all_settings_sync``'s response, a payloadnothing on the branch reads), and secret redaction surviving the ``LDR_*``env overlay on both branches of ``GET /settings/api/{key}``.Post-conditions are asserted against the STORED DB ROW, not the API read@@ -42,7 +43,9 @@ contracts:COVERAGE AREA 3 -- the non-editable-setting 403 on``PUT``/``DELETE /settings/api/{key}``- (``settings.py:3232`` / ``:3550``). The two nearest branch tests pass+ (the ``if not db_setting.editable`` branch of+ ``_api_update_setting_sync`` / ``api_delete_setting``). The two nearest+ branch tests passvacuously: ``test_settings_env_lock_403.py::TestEnvLockedSettingReturns403::test_put_without_env_lock_is_unaffected`` asserts only that the error textlacks "environment-locked" (true of a 200), and@@ -52,15 +55,17 @@ COVERAGE AREA 3 -- the non-editable-setting 403 onhandlers, all 12 tests across those two files still pass, while bothrefusal tests below fail.-COVERAGE AREA 4 -- ``_filter_editable_settings`` (``settings.py:245``) had no+COVERAGE AREA 4 -- ``_filter_editable_settings`` had nodirect references under ``tests/`` at the review snapshot. It is the authzgate on both bulk- write paths (``:566`` JSON save, ``:1080`` no-JS form save): without it any+ write paths (``_save_all_settings_sync``, the JSON save, and+ ``_save_settings_sync``, the no-JS form save): without it anylogged-in user can flip a non-editable global-policy flag such as``app.allow_registrations`` through a bulk save. Covered here directly andat both call sites. The two call-site tests are defence-in-depth: with onlythe filter disabled they still pass, because ``SettingsManager.set_setting``- carries its own ``editable`` guard (``settings/manager.py:825``). Disabling+ carries its own ``editable`` guard (the ``if not setting.editable``+ branch of ``SettingsManager.set_setting``). Disablingboth layers fails them, which is the property worth pinning -- the outcomethe user sees, not one particular implementation of it.@@ -69,16 +74,25 @@ Harness: the ``auth_client`` idiom from ``tests/web/routers/test_settings_api.pythe live FastAPI app, a freshly registered + logged-in throwaway user, and areal CSRF token (CSRF is ASGI-middleware-enforced, not a config flag). Theper-client ``X-Forwarded-For`` comes from a MONOTONIC counter rather than a-random address: rate limiting is keyed on client IP, and random addresses-collide across a large session, producing 429s unrelated to the guard under-test. Every setting mutated is restored in a ``finally``. No network, no LLM:+random address; note this is defence-in-depth only, NOT what keeps this+module under the limit. ``settings_limit``+(``web/dependencies/rate_limit.py``) is a shared limit keyed by+``_user_key`` -- ``user:<username>`` for a logged-in request -- so a+distinct source IP buys the settings routes nothing once the throwaway user+is logged in. What actually keeps the suite green is the autouse+``limiter.reset()`` in ``tests/conftest.py``. The counter still matters for+the routes and middleware that DO bucket on client IP (the unauthenticated+register/login calls the fixture makes, and the default-key limits), where+random addresses collide across a large session and produce 429s unrelated+to the guard under test. Every setting mutated is restored in a ``finally``.+No network, no LLM:the only outbound calls the route would make are stubbed and asserted on."""import itertoolsimport jsonimport uuid-from contextlib import ExitStack+from contextlib import ExitStack, contextmanagerfrom datetime import UTC, datetimefrom types import SimpleNamespacefrom unittest.mock import MagicMock, patch@@ -86,6 +100,8 @@ from unittest.mock import MagicMock, patchimport pytestfrom fastapi.testclient import TestClient+from local_deep_research.security.data_sanitizer import DataSanitizer+SETTINGS = "local_deep_research.web.routers.settings"PROVIDERS = "local_deep_research.llm.providers"POLICY = "local_deep_research.security.egress.policy"@@ -95,6 +111,23 @@ REDACTED = "[REDACTED]"# not called SECRET_KEY: the repo's file-whitelist scanner matches# `SECRET_KEY = "..."` as a hardcoded Flask secret and fails CI on it.SECRET_SETTING_NAME = "llm.openai.api_key"+# The NON-SECRET sibling leaf used by the mixed-container tests below, whose+# premise is "one leaf stays masked while a VISIBLE sibling is edited". The+# sibling name must be one `_matches_sensitive_name`+# (``security/data_sanitizer.py``) does NOT match, or GET masks it too and the+# premise is unsatisfiable: the test can neither read "old-value" back from the+# masked GET nor assert "new-value" on the GET that follows the edit.+# `page_token` is the trap -- it looks innocuous but ends in `_token`, so the+# broadened underscore-suffix arm masks it, exactly as+# `test_nested_json_leaf_sentinel_round_trip_is_a_noop` (which deliberately+# uses TWO sensitive-named leaves) asserts. Executed against the sanitizer at+# this nesting, `description`, `model`, `stop_sequence`, `temperature`,+# `endpoint` and `note` all stay readable; `description` is used here. The+# choice keeps the tests revert-sensitive: `str({"stop_token": <secret>,+# "description": "new-value"})` still embeds the secret verbatim, so both the+# `type(stored) is dict` and the `real_secret not in ...text` assertions flip+# if the coercion skip is reverted.+PLAIN_SIBLING_LEAF = "description"# Non-editable + user-visible consequence: a regression here lets any logged-in# user re-open registrations on a locked-down deployment.NON_EDITABLE_KEY = "app.allow_registrations"@@ -109,9 +142,14 @@ _IP_COUNTER = itertools.count(1)def _next_forwarded_for() -> str:"""A fresh client IP from a monotonic counter.- Rate limiting buckets on the client IP. A random address collides across a- large session and produces 429s that look like guard failures; a counter- cannot.+ The IP-keyed rate limits (the default ``key_func``, and the+ unauthenticated register/login calls the module fixture makes before a+ session exists) bucket on the client IP. A random address collides+ across a large session and produces 429s that look like guard failures;+ a counter cannot. The SETTINGS routes are not among them --+ ``settings_limit`` is keyed per USER (``_user_key`` in+ ``web/dependencies/rate_limit.py``), and the autouse ``limiter.reset()``+ in ``tests/conftest.py`` is what keeps those within budget."""n = next(_IP_COUNTER)return f"10.{n // 254 % 254 + 1}.{n % 254 + 1}.23"@@ -209,6 +247,37 @@ def _stored_value(username, password, key):return _MISSING if row is None else row.value+@contextmanager+def _captured_warnings():+ """Collect every rendered WARNING-or-worse loguru line emitted inside+ the block, as a list of strings.++ ``local_deep_research/__init__.py`` calls+ ``logger.disable("local_deep_research")``, so without the explicit+ ``enable`` here the routers' own warnings never reach ANY sink and a+ "the secret was not logged" assertion would pass vacuously -- which is+ why every test using this also asserts a POSITIVE CONTROL line was+ captured. Same enable/add/remove/disable idiom as+ ``tests/security/test_egress_fullsearch.py``; the ``disable`` in the+ ``finally`` restores the package's own default state, not a state this+ helper invented.+ """+ from loguru import logger++ rendered: list[str] = []++ def _sink(message):+ rendered.append(str(message))++ logger.enable("local_deep_research")+ sink_id = logger.add(_sink, level="WARNING", diagnose=False)+ try:+ yield rendered+ finally:+ logger.remove(sink_id)+ logger.disable("local_deep_research")++def _set_stored_value(username, password, key, value):"""Write a value straight onto the stored row (used only to restore statea test perturbed -- the API cannot restore a secret, because writing a@@ -772,6 +841,628 @@ class TestBulkSecretWriteBackAndEcho:username, password, SECRET_SETTING_NAME, original_secret)+ def test_no_js_form_post_rejects_sentinel_on_a_brand_new_key(+ self, settings_user+ ):+ """Regression for the post-#5771 review: the no-JS ``POST+ /settings/save_settings`` fallback (``_save_settings_sync``) is the+ one write route out of three that never wired in+ ``_embeds_sentinel_on_create``. ``save_all_settings`` and+ ``api_update_setting`` both reject a sentinel-bearing value on+ creation (there is no prior stored value for it to be an untouched+ round-trip of, so every occurrence is a corrupted client value); this+ route let it straight through to ``set_setting``, persisting the+ literal ``"[REDACTED]"`` string as a brand-new credential's value.++ The key is chosen so it does not exist yet (namespace validation+ takes the creation branch) and ends in a sensitive suffix, so the+ guard actually has something to check.+ """+ client, username, password = settings_user+ key = f"llm.probe_{uuid.uuid4().hex[:6]}.api_key"+ assert _stored_value(username, password, key) is _MISSING+ try:+ resp = client.post(+ "/settings/save_settings",+ data={+ key: f"sk-corrupted-{REDACTED}-value",+ "csrf_token": _csrf_token(client),+ },+ follow_redirects=False,+ )+ assert resp.status_code == 302, resp.text[:300]++ # The row must never have been created with the sentinel spliced+ # into it -- neither present with the corrupted value, nor+ # present at all.+ stored = _stored_value(username, password, key)+ assert stored is _MISSING, (+ f"sentinel-bearing value was persisted for a brand-new key: {stored!r}"+ )+ finally:+ client.delete(f"/settings/api/{key}")++ def test_nested_json_leaf_sentinel_round_trip_is_a_noop(+ self, settings_user+ ):+ """Regression for the post-#5771 review: a secret nested INSIDE a+ JSON-typed setting whose OUTER key is not itself sensitive.++ ``redact_value`` recurses a container by sub-key name, so+ ``llm.<probe>.model_kwargs`` (not a sensitive key) can still have a+ nested ``stop_token``/``page_token`` leaf masked on GET (same+ recursion a ``get_setting("llm")`` subtree request uses). But all+ three write-back guards gated their dict/list check on+ ``is_sensitive_setting(OUTER key)`` -- which is False here -- so an+ untouched GET round-trip sailed straight past every guard and+ persisted the literal ``"[REDACTED]"`` string over the real nested+ secret. The guards now check every dict/list write for the sentinel+ regardless of the outer key.+ """+ client, username, password = settings_user+ key = f"llm.probe_{uuid.uuid4().hex[:6]}.model_kwargs"+ real_value = {+ "stop_token": "s3cr3t-nested-9911",+ "page_token": "s3cr3t-nested-4420",+ }+ try:+ create = client.put(+ f"/settings/api/{key}", json={"value": real_value}+ )+ assert create.status_code == 201, create.text[:300]++ # Premise: the outer key is not itself a sensitive name.+ assert not any(+ key.rsplit(".", 1)[-1] == n+ for n in ("api_key", "password", "secret", "token")+ )++ meta = client.get(f"/settings/api/{key}").json()+ # ... yet the nested sensitive-named leaves are masked on GET.+ assert meta["value"] == {+ "stop_token": REDACTED,+ "page_token": REDACTED,+ }++ # An untouched round-trip: submit exactly what the GET returned.+ resp = client.put(+ f"/settings/api/{key}", json={"value": meta["value"]}+ )+ assert resp.status_code == 200, resp.text[:300]++ stored = _stored_value(username, password, key)+ assert stored == real_value, (+ "nested secret was clobbered by the redaction sentinel on "+ f"an untouched round-trip: {stored!r}"+ )+ finally:+ client.delete(f"/settings/api/{key}")++ def test_nested_json_leaf_sentinel_string_encoded_round_trip_is_a_noop(+ self, settings_user+ ):+ """Regression for defect (1) in the post-#6201 review: the SAME+ nested secret as ``test_nested_json_leaf_sentinel_round_trip_is_a_noop``+ above, but submitted in its JSON-STRING encoding rather than as a+ native dict.++ ``PUT /settings/api/<key>`` accepting ``{"value": "<json string>"}``+ is a supported input shape -- ``_parse_json_value``+ (``settings/manager.py``) exists precisely to decode it ("Form POST+ and env var overrides arrive as raw strings"). Every write-back+ guard call site coerced the submitted value AFTER running the+ sentinel guards, so the container arm (which only fires on an+ actual ``dict``/``list``) never saw this shape: the still-string+ value fell through to the string arm, gated on the OUTER key's+ sensitivity (False here, same as the dict-shaped case above), sailed+ through untouched, and was THEN coerced into a dict carrying the+ literal sentinel -- clobbering the real secret the same way a+ dict-shaped submission did before #6201's original fix, just+ through a different encoding of the identical payload.++ The setting must be explicitly ``ui_element="json"`` for the+ string-to-dict coercion (and therefore this bug) to engage at all;+ the sibling test above lets the key default to ``ui_element="text"``,+ under which a JSON string is stored as a literal string and never+ becomes a container.+ """+ client, username, password = settings_user+ key = f"llm.probe_{uuid.uuid4().hex[:6]}.model_kwargs"+ real_value = {+ "stop_token": "s3cr3t-nested-string-9911",+ "page_token": "s3cr3t-nested-string-4420",+ }+ try:+ create = client.put(+ f"/settings/api/{key}",+ json={"value": real_value, "ui_element": "json"},+ )+ assert create.status_code == 201, create.text[:300]++ meta = client.get(f"/settings/api/{key}").json()+ assert meta["value"] == {+ "stop_token": REDACTED,+ "page_token": REDACTED,+ }++ # Submit the masked value in its JSON-STRING encoding -- the+ # shape a <textarea> form POST, or a client that+ # JSON.stringify()'d the field before sending, would produce --+ # not as a native dict.+ resp = client.put(+ f"/settings/api/{key}",+ json={"value": json.dumps(meta["value"])},+ )+ assert resp.status_code == 200, resp.text[:300]++ stored = _stored_value(username, password, key)+ assert stored == real_value, (+ "nested secret was clobbered by the STRING-ENCODED "+ f"redaction sentinel on an untouched round-trip: {stored!r}"+ )++ # An edit to one leaf alongside an untouched, still-masked+ # sibling must also survive the string encoding: the secret+ # leaf is restored, the edit is kept.+ edited = dict(meta["value"])+ edited["page_token"] = "new-nested-value"+ resp2 = client.put(+ f"/settings/api/{key}", json={"value": json.dumps(edited)}+ )+ assert resp2.status_code == 200, resp2.text[:300]+ stored2 = _stored_value(username, password, key)+ assert stored2 == {+ "stop_token": real_value["stop_token"],+ "page_token": "new-nested-value",+ }+ finally:+ client.delete(f"/settings/api/{key}")++ def test_mixed_container_partial_mask_round_trips_and_edits_without_400(+ self, settings_user+ ):+ """Regression for defect (2) in the post-#6201 review: a container+ where only SOME leaves are sensitive-named -- the shape every+ shipped ``search.engine.web.<engine>`` config dict has (an+ ``api_key``/``requires_api_key``/``description`` mix), and the+ changelog's own motivating "user-added engine" scenario -- must+ stay editable.++ ``redact_value`` masks a container by SUB-KEY, so GET on a mixed+ container masks only its sensitive-named leaf; ordinary siblings+ come back plain. #6201 required EVERY maskable leaf to be exactly+ the sentinel before treating a dict/list write as anything but a+ corrupted edit, which made this GET's own output impossible to+ PUT back: an untouched round-trip, or an edit to a plain sibling,+ both 400'd with "contains the redaction placeholder" even though+ the client never saw, and therefore could not resubmit, the real+ secret. The write must merge per-leaf instead.+ """+ client, username, password = settings_user+ key = f"llm.probe_{uuid.uuid4().hex[:6]}.engine_config"+ real_value = {+ "api_key": "sk-real-engine-secret-7734",+ "description": "My self-hosted engine",+ "requires_api_key": True,+ "max_results": 10,+ }+ try:+ create = client.put(+ f"/settings/api/{key}",+ json={"value": real_value, "ui_element": "json"},+ )+ assert create.status_code == 201, create.text[:300]++ meta = client.get(f"/settings/api/{key}").json()+ # Only the sensitive-named leaf is masked; ordinary siblings+ # -- including the OTHER boolean/string fields -- stay plain.+ assert meta["value"] == {+ "api_key": REDACTED,+ "description": "My self-hosted engine",+ "requires_api_key": True,+ "max_results": 10,+ }++ # An untouched GET -> PUT round-trip must be a no-op, not a 400.+ resp = client.put(+ f"/settings/api/{key}", json={"value": meta["value"]}+ )+ assert resp.status_code == 200, resp.text[:300]+ assert _stored_value(username, password, key) == real_value++ # Editing a NON-masked sibling while the masked secret leaf+ # stays "[REDACTED]" must save -- secret preserved, edit+ # applied -- not 400.+ edited = dict(meta["value"])+ edited["description"] = ""+ edited["max_results"] = 25+ resp2 = client.put(f"/settings/api/{key}", json={"value": edited})+ assert resp2.status_code == 200, resp2.text[:300]+ assert _stored_value(username, password, key) == {+ "api_key": real_value["api_key"],+ "description": "",+ "requires_api_key": True,+ "max_results": 25,+ }++ # A genuinely new sentinel -- a key with no stored counterpart+ # to restore it from -- is still rejected, not silently merged.+ orphaned = dict(edited)+ orphaned["new_field"] = REDACTED+ resp3 = client.put(f"/settings/api/{key}", json={"value": orphaned})+ assert resp3.status_code == 400, resp3.text[:300]+ assert _stored_value(username, password, key) == {+ "api_key": real_value["api_key"],+ "description": "",+ "requires_api_key": True,+ "max_results": 25,+ }+ finally:+ client.delete(f"/settings/api/{key}")++ # ------------------------------------------------------------------+ # BL1 (post-#6201 review; #6213 item c): a masked leaf whose STORED+ # value is not a string.+ #+ # ``redact_value`` collapses ANY non-empty value to the BARE sentinel+ # when the sub-key is an exact ``DEFAULT_SENSITIVE_KEYS`` match -- a+ # list, a dict, an int and a bool as readily as a string (the exact-+ # match arm runs before the container arm, so the value's type never+ # gets a say). The write-back merge, however, used to restore a+ # sentinel leaf only from ``isinstance(stored_value, str) and+ # stored_value.strip()``. That made the merge rule STRICTER than the+ # masking rule, so for every one of the 18 exact sensitive leaf names+ # an untouched GET-then-save of a list/dict/int/bool leaf was a+ # permanent 400 the client could not possibly satisfy -- it cannot see+ # the value the GET collapsed to one string, and on+ # ``save_all_settings`` the rejection rolls back the WHOLE batch.+ #+ # Each case is ``(leaf name, stored value)``; the last is the string+ # control, the one shape that always worked, kept so a regression that+ # broke restoration outright cannot hide behind these tests.+ _MASKED_LEAF_CASES = [+ ("api_key", ["sk-list-9911", "sk-list-4420"]),+ ("token", {"header": "X-Auth", "value": "sk-dict-9911"}),+ ("secret", 19530),+ ("password", True),+ ("api_key", "sk-string-control-9911"),+ ]+ _MASKED_LEAF_IDS = ["list", "dict", "int", "bool", "str-control"]++ @pytest.mark.parametrize("route", ["put", "save_all", "form"])+ @pytest.mark.parametrize(+ "leaf,stored_leaf", _MASKED_LEAF_CASES, ids=_MASKED_LEAF_IDS+ )+ def test_masked_non_string_leaf_round_trips_on_every_write_route(+ self, settings_user, route, leaf, stored_leaf+ ):+ """An untouched GET -> save of a masked NON-STRING leaf is a 200+ no-op that leaves the stored value byte-identical, on all three+ write routes.++ EXACT REVERT THIS CATCHES: restoring the+ ``if isinstance(stored_value, str) and stored_value.strip():``+ condition in ``_merge_redacted_container``'s string arm in place of+ ``if not _is_empty_value(stored_value):``. Under the reverted+ condition every non-``str-control`` case below is rejected --+ ``_merge_redacted_container`` returns ``(value, True)``,+ ``_embeds_redaction_sentinel`` returns that verbatim, and each+ route answers 400 (the form route answers 302 with the write+ dropped) -- while the ``str-control`` case stays green, which is+ exactly the asymmetry the parametrization exists to expose.+ """+ client, username, password = settings_user+ suffix = uuid.uuid4().hex[:6]+ key = f"llm.probe_{suffix}.model_kwargs"+ real_value = {leaf: stored_leaf, PLAIN_SIBLING_LEAF: "old-value"}+ try:+ create = client.put(+ f"/settings/api/{key}", json={"value": real_value}+ )+ assert create.status_code == 201, create.text[:300]++ # PREMISE 1: the OUTER key is not itself sensitive, so this is+ # the nested-leaf path, not the whole-setting one.+ assert not DataSanitizer.is_sensitive_setting(key)+ # PREMISE 2: the leaf IS an exact sensitive name, and the+ # sibling is not -- otherwise the shape below is unreachable.+ assert leaf in DataSanitizer.DEFAULT_SENSITIVE_KEYS+ assert not DataSanitizer.is_sensitive_setting(PLAIN_SIBLING_LEAF)++ # PREMISE 3 (the one BL1 turns on): the GET collapses a+ # non-string leaf to the BARE sentinel, exactly like a string+ # one -- the client has no way to resubmit the real value.+ meta = client.get(f"/settings/api/{key}").json()+ masked = {leaf: REDACTED, PLAIN_SIBLING_LEAF: "old-value"}+ assert meta["value"] == masked, (+ f"a stored {type(stored_leaf).__name__} under the exact "+ f"sensitive leaf {leaf!r} did not mask to the bare "+ f"sentinel: {meta['value']!r}"+ )++ # Submit back EXACTLY what the GET returned -- no edit at all.+ if route == "put":+ resp = client.put(+ f"/settings/api/{key}", json={"value": meta["value"]}+ )+ assert resp.status_code == 200, resp.text[:300]+ elif route == "save_all":+ resp = client.post(+ "/settings/save_all_settings", json={key: meta["value"]}+ )+ assert resp.status_code == 200, resp.text[:300]+ assert "errors" not in resp.json(), resp.text[:300]+ else:+ resp = client.post(+ "/settings/save_settings",+ data={+ key: json.dumps(meta["value"]),+ "csrf_token": _csrf_token(client),+ },+ follow_redirects=False,+ )+ assert resp.status_code == 302, resp.text[:300]++ stored = _stored_value(username, password, key)+ assert stored == real_value, (+ f"an untouched round-trip of a masked "+ f"{type(stored_leaf).__name__} leaf via {route} did not "+ f"preserve the stored value: {stored!r}"+ )+ # `==` alone would let a bool through as an int and vice versa.+ assert type(stored[leaf]) is type(stored_leaf), (+ f"the restored leaf changed type: got "+ f"{type(stored[leaf]).__name__}, want "+ f"{type(stored_leaf).__name__}"+ )+ finally:+ client.delete(f"/settings/api/{key}")++ @pytest.mark.parametrize(+ "leaf,stored_leaf", _MASKED_LEAF_CASES, ids=_MASKED_LEAF_IDS+ )+ def test_sibling_edit_beside_a_masked_non_string_leaf_keeps_the_secret(+ self, settings_user, leaf, stored_leaf+ ):+ """The ordinary workflow: GET, edit a VISIBLE sibling, PUT back+ with the secret still masked. The stored non-string leaf must+ survive unchanged and the edit must land.++ This is the case the round-trip test above cannot cover: a pure+ round-trip short-circuits as a no-op inside+ ``_resolve_container_secret_write`` before the merged value is ever+ persisted, so only a GENUINE edit proves the restored value is what+ actually reaches the row.+ """+ client, username, password = settings_user+ suffix = uuid.uuid4().hex[:6]+ key = f"llm.probe_{suffix}.model_kwargs"+ real_value = {leaf: stored_leaf, PLAIN_SIBLING_LEAF: "old-value"}+ try:+ create = client.put(+ f"/settings/api/{key}", json={"value": real_value}+ )+ assert create.status_code == 201, create.text[:300]++ meta = client.get(f"/settings/api/{key}").json()+ edited = dict(meta["value"])+ edited[PLAIN_SIBLING_LEAF] = "new-value"+ resp = client.put(f"/settings/api/{key}", json={"value": edited})+ assert resp.status_code == 200, resp.text[:300]++ stored = _stored_value(username, password, key)+ assert stored == {+ leaf: stored_leaf,+ PLAIN_SIBLING_LEAF: "new-value",+ }, (+ "the sibling edit either dropped the edit or clobbered the "+ f"stored secret: {stored!r}"+ )+ assert type(stored[leaf]) is type(stored_leaf)++ # And the restored value never reaches a reader.+ get_after = client.get(f"/settings/api/{key}")+ assert get_after.json()["value"] == {+ leaf: REDACTED,+ PLAIN_SIBLING_LEAF: "new-value",+ }+ finally:+ client.delete(f"/settings/api/{key}")++ @pytest.mark.parametrize(+ "orphan_stored",+ [+ {"host": "h"},+ {"api_key": ""},+ {"api_key": " "},+ {"api_key": []},+ {"api_key": {}},+ {"api_key": None},+ ],+ ids=[+ "absent",+ "empty-str",+ "blank-str",+ "empty-list",+ "empty-dict",+ "none",+ ],+ )+ def test_orphan_sentinel_is_still_rejected_after_the_non_string_widening(+ self, settings_user, orphan_stored+ ):+ """NEGATIVE CONTROL for the two tests above: widening the restore+ from "non-empty string" to "non-empty value" must not turn a+ sentinel with NO stored counterpart into an accepted write.++ Every stored row here is one ``redact_value`` would NOT have masked+ -- the leaf is absent, or its value is empty by ``_is_empty_value``'s+ own rule -- so a submitted ``[REDACTED]`` under it is a fabricated+ placeholder, not a round-trip, and persisting it would store the+ literal text as the credential. Without this the widening could be+ silently loosened to "restore whatever is there, including nothing"+ and every test above would still pass.+ """+ client, username, password = settings_user+ suffix = uuid.uuid4().hex[:6]+ key = f"llm.probe_{suffix}.model_kwargs"+ try:+ create = client.put(+ f"/settings/api/{key}", json={"value": orphan_stored}+ )+ assert create.status_code == 201, create.text[:300]++ # PREMISE: the GET does NOT produce this shape -- it is a+ # client fabrication, which is why rejecting it costs nothing.+ assert client.get(f"/settings/api/{key}").json()["value"] != {+ "api_key": REDACTED+ }++ resp = client.put(+ f"/settings/api/{key}", json={"value": {"api_key": REDACTED}}+ )+ assert resp.status_code == 400, resp.text[:300]++ stored = _stored_value(username, password, key)+ assert stored == orphan_stored, (+ f"a rejected orphan sentinel still changed the row: {stored!r}"+ )+ finally:+ client.delete(f"/settings/api/{key}")++ def test_put_create_echo_uses_the_same_redactor_as_every_read(+ self, settings_user+ ):+ """The 201 CREATE echo must go through ``redact_value``, not the+ bare ``is_sensitive_setting`` NAME predicate (post-#6201 review,+ R4).++ ``is_sensitive_setting`` has no type guard; ``redact_value`` does.+ After this PR narrowed the qualifier exemption to the literal+ ``requires_api_key`` leaf, a CHECKBOX row whose name merely matches+ the broadened snake_case arm (``..._supports_api_key``) is a+ sensitive NAME with a boolean value -- so the old echo answered the+ string "[REDACTED]" for a row every GET returns as ``False``,+ corrupting the checkbox the client had just created (the settings+ UI renders ``checked`` only for a literal ``True``).++ EXACT REVERT THIS CATCHES: replacing the echo's+ ``DataSanitizer.redact_value(key, db_setting.ui_element,+ db_setting.value)`` with+ ``REDACTION_TEXT if is_sensitive_setting(key, db_setting.ui_element)+ else db_setting.value``. Both halves below flip under it: the+ boolean becomes the sentinel string, and the container's real+ nested secret is no longer masked leaf-by-leaf.+ """+ client, username, password = settings_user+ suffix = uuid.uuid4().hex[:6]+ bool_key = f"llm.probe_{suffix}_supports_api_key"+ container_key = f"llm.probe_{suffix}.model_kwargs"+ real_secret = f"s3cr3t-create-echo-{suffix}"+ try:+ # PREMISE: the name IS sensitive -- otherwise the old echo+ # never fired and this test would pass vacuously.+ assert DataSanitizer.is_sensitive_setting(bool_key, "checkbox")++ create = client.put(+ f"/settings/api/{bool_key}",+ json={"value": False, "ui_element": "checkbox"},+ )+ assert create.status_code == 201, create.text[:300]+ echoed = create.json()["setting"]["value"]+ assert echoed is False, (+ "the 201 create echo answered "+ f"{echoed!r} for a checkbox row -- every GET of the same "+ "row returns False, so the echo corrupted it"+ )+ # The echo must agree with the read path it is standing in for.+ assert (+ client.get(f"/settings/api/{bool_key}").json()["value"] is False+ )++ # The other half: the old form could only answer a BARE+ # sentinel, so for a container under a NON-sensitive outer key+ # it answered the raw container -- nested secret included.+ create2 = client.put(+ f"/settings/api/{container_key}",+ json={+ "value": {+ "api_key": real_secret,+ PLAIN_SIBLING_LEAF: "d",+ }+ },+ )+ assert create2.status_code == 201, create2.text[:300]+ assert real_secret not in create2.text, (+ "the 201 create echo shipped a freshly-created nested "+ f"secret in plaintext: {create2.text[:300]}"+ )+ assert create2.json()["setting"]["value"] == {+ "api_key": REDACTED,+ PLAIN_SIBLING_LEAF: "d",+ }+ finally:+ client.delete(f"/settings/api/{bool_key}")+ client.delete(f"/settings/api/{container_key}")++ def test_put_create_rejects_a_json_string_encoded_masked_container(+ self, settings_user+ ):+ """The CREATE path must decode a JSON-STRING encoded container+ before its sentinel guard runs (post-#6201 review, R6).++ Creation has no prior value, so every occurrence of the sentinel --+ exact match included -- is a corrupted client value that would be+ stored verbatim as the credential. ``_embeds_sentinel_on_create``+ catches that for a NATIVE dict, but a ``<textarea>`` (or a client+ that ``JSON.stringify()``'d the field) sends the same container as+ a string, and the outer key here is not a sensitive name, so the+ string arm of that guard does not fire either.++ EXACT REVERT THIS CATCHES: dropping the ``_create_guard_value =+ _coerced_for_guard(...)`` line in ``_api_update_setting_sync``'s+ create branch and passing the raw ``value`` to+ ``_embeds_sentinel_on_create``. Verified by reading the guard:+ without the coercion it sees the plain string+ '{"api_key": "[REDACTED]"}', ``_container_embeds_sentinel`` never+ runs on it, ``is_sensitive_setting`` is False for a+ ``*.model_kwargs`` key, and the create returns 201 with the literal+ placeholder text persisted as the value -- so the+ ``status_code == 400`` assertion below is the one that flips.+ """+ client, username, password = settings_user+ suffix = uuid.uuid4().hex[:6]+ key = f"llm.probe_{suffix}.model_kwargs"+ encoded = json.dumps({"api_key": REDACTED, PLAIN_SIBLING_LEAF: "d"})+ try:+ # PREMISE: the outer key is not sensitive, so nothing but the+ # coercion can make the guard see a container here.+ assert not DataSanitizer.is_sensitive_setting(key, "textarea")++ resp = client.put(+ f"/settings/api/{key}",+ json={"value": encoded, "ui_element": "textarea"},+ )+ assert resp.status_code == 400, (+ "a JSON-string encoded masked container was accepted on "+ f"create: {resp.status_code} {resp.text[:300]}"+ )+ # Nothing was created, so the placeholder was not persisted.+ assert _stored_value(username, password, key) is _MISSING, (+ "the rejected create still wrote a row"+ )++ # ALLOW COUNTERPART: the same shape with no sentinel in it must+ # still create normally, so "rejects everything" cannot pass.+ clean = json.dumps({"api_key": f"sk-real-{suffix}"})+ ok = client.put(+ f"/settings/api/{key}",+ json={"value": clean, "ui_element": "textarea"},+ )+ assert ok.status_code == 201, ok.text[:300]+ finally:+ client.delete(f"/settings/api/{key}")+def test_sensitive_suffix_setting_with_text_ui_element_round_trips_safely(self, settings_user):@@ -844,6 +1535,886 @@ class TestBulkSecretWriteBackAndEcho:finally:client.delete(f"/settings/api/{key}")+ def test_nested_secret_edit_under_default_text_ui_element_does_not_leak(+ self, settings_user+ ):+ """Regression, end-to-end, for defect (1) in the post-#6201 review:+ the previous round's fix for this exact scenario converted a data+ LOSS bug into a secret DISCLOSURE bug.++ A ``PUT``-created key with no ``ui_element`` defaults to "text"+ (``models/settings.py``) -- exactly the row this test creates, the+ same shape ``test_nested_json_leaf_sentinel_round_trip_is_a_noop``+ above uses for its pure round-trip. This test instead performs a+ GENUINE EDIT (one leaf changes, the sibling stays masked), which is+ the shape that actually reaches the coercion call: a pure no-op+ round-trip short-circuits before it. Every write-back call site ran+ ``coerce_setting_for_write(value, ui_element="text")`` on the+ MERGED container afterward, and "text"'s target type is ``str`` --+ flattening the dict to its Python repr and persisting the+ just-restored secret as a plain, non-redacted string under a key+ nothing downstream treats as sensitive.++ Assertions follow the review's own instruction: check the+ PERSISTED value's TYPE (proves coercion was skipped, not just that+ the request returned 200) and that a subsequent GET does not leak+ the secret in the clear (proves no disclosure), rather than+ trusting the status code alone.+ """+ client, username, password = settings_user+ key = f"llm.probe_{uuid.uuid4().hex[:6]}.model_kwargs"+ real_secret = "s3cr3t-nested-genuine-edit-8823"+ real_value = {"stop_token": real_secret, "description": "old-value"}+ # PREMISE (round-5 regression): the sibling leaf must be one the+ # sanitizer does NOT mask, or GET returns it as "[REDACTED]" and+ # the "edit a still-visible sibling" scenario below is+ # unsatisfiable. Asserted rather than assumed -- the round-5+ # version of this test used `page_token`, which ends in `_token`+ # and IS masked. See PLAIN_SIBLING_LEAF.+ assert PLAIN_SIBLING_LEAF in real_value+ assert not DataSanitizer.is_sensitive_setting(PLAIN_SIBLING_LEAF)+ assert DataSanitizer.is_sensitive_setting("stop_token")+ try:+ # No ui_element supplied -> defaults to "text".+ create = client.put(+ f"/settings/api/{key}", json={"value": real_value}+ )+ assert create.status_code == 201, create.text[:300]++ meta = client.get(f"/settings/api/{key}").json()+ assert meta["ui_element"] == "text"+ assert meta["value"] == {+ "stop_token": REDACTED,+ "description": "old-value",+ }++ # A GENUINE edit: description changes, stop_token stays masked.+ edited = dict(meta["value"])+ edited["description"] = "new-value"+ resp = client.put(f"/settings/api/{key}", json={"value": edited})+ assert resp.status_code == 200, resp.text[:300]++ # (1a) The persisted TYPE must be a dict, never a str -- a str+ # here means the merged container was flattened by coercion.+ stored = _stored_value(username, password, key)+ assert type(stored) is dict, (+ "reconciled container was coerced to a "+ f"{type(stored).__name__} instead of persisted as a dict "+ f"-- got {stored!r}"+ )+ assert stored == {+ "stop_token": real_secret,+ "description": "new-value",+ }++ # (1b) No subsequent read discloses the secret in the clear.+ get_after = client.get(f"/settings/api/{key}")+ assert real_secret not in get_after.text, (+ "the real secret leaked through a GET response: "+ f"{get_after.text[:300]}"+ )+ assert get_after.json()["value"] == {+ "stop_token": REDACTED,+ "description": "new-value",+ }++ # Same check against the bulk listing, which echoes every+ # setting's value in one response.+ # NOTE (post-#6201 review, R2): this is+ # ``api_get_all_settings`` (@router.get("/api")), NOT+ # ``get_bulk_settings`` (@router.get("/api/bulk")). An earlier+ # version of this assertion called the same URL while its+ # message claimed the BULK endpoint -- and the bulk endpoint+ # does leak this exact row (#6222), so the message asserted a+ # false negative about a route it never touched. The bulk+ # endpoint is covered on its own, as a strict xfail, in+ # ``test_bulk_settings_get_leaks_a_container_row_xfail_6222``.+ all_settings = client.get("/settings/api")+ assert real_secret not in all_settings.text, (+ "the real secret leaked through GET /settings/api "+ "(api_get_all_settings)"+ )+ finally:+ client.delete(f"/settings/api/{key}")++ def test_nested_json_leaf_sentinel_string_edit_under_text_ui_element(+ self, settings_user+ ):+ """Regression, end-to-end, for defect (2) in the post-#6201 review,+ extending ``test_nested_json_leaf_sentinel_string_encoded_round_trip_+ is_a_noop`` above (which only covers ``ui_element="json"``) to+ "text"/"textarea", the row shape defect (1)'s own test uses.++ ``coerce_setting_for_write``'s target type for "text"/"textarea" IS+ ``str``, so it can NEVER decode a JSON string into a dict -- the+ ui_element-based half of ``_coerced_for_guard``'s fix is a no-op+ for these ui_elements. Without the ui_element-independent JSON+ decode fallback, a masked container submitted in its JSON-STRING+ encoding under "text"/"textarea" would still sail past the+ container arm, fall to the outer-key-gated string arm (not+ sensitive here), and overwrite the stored dict with the literal+ string -- silent data loss of both the structure and the sibling+ edit.+ """+ client, username, password = settings_user+ key = f"llm.probe_{uuid.uuid4().hex[:6]}.model_kwargs"+ real_secret = "s3cr3t-nested-string-text-4420"+ real_value = {"stop_token": real_secret, "description": "old-value"}+ # PREMISE (round-5 regression): the sibling leaf must be one the+ # sanitizer does NOT mask, or GET returns it as "[REDACTED]" and+ # the "edit a still-visible sibling" scenario below is+ # unsatisfiable. Asserted rather than assumed -- the round-5+ # version of this test used `page_token`, which ends in `_token`+ # and IS masked. See PLAIN_SIBLING_LEAF.+ assert PLAIN_SIBLING_LEAF in real_value+ assert not DataSanitizer.is_sensitive_setting(PLAIN_SIBLING_LEAF)+ assert DataSanitizer.is_sensitive_setting("stop_token")+ try:+ create = client.put(+ f"/settings/api/{key}",+ json={"value": real_value, "ui_element": "textarea"},+ )+ assert create.status_code == 201, create.text[:300]++ meta = client.get(f"/settings/api/{key}").json()+ assert meta["ui_element"] == "textarea"+ assert meta["value"] == {+ "stop_token": REDACTED,+ "description": "old-value",+ }++ # Submit the masked value in its JSON-STRING encoding, with an+ # edit to the non-masked sibling leaf.+ edited = dict(meta["value"])+ edited["description"] = "new-value"+ resp = client.put(+ f"/settings/api/{key}", json={"value": json.dumps(edited)}+ )+ assert resp.status_code == 200, resp.text[:300]++ stored = _stored_value(username, password, key)+ assert stored == {+ "stop_token": real_secret,+ "description": "new-value",+ }, (+ "nested secret was clobbered by the STRING-ENCODED "+ f"redaction sentinel under ui_element='textarea': {stored!r}"+ )+ finally:+ client.delete(f"/settings/api/{key}")++ def test_save_all_settings_reconciled_container_is_not_coerced_to_str(+ self, settings_user+ ):+ """Round-5 defect (1): the coercion skip in ``_save_all_settings_sync``+ had NO end-to-end test, so reverting it -- which reinstates the+ round-1 repr-flattening DISCLOSURE bug on this route -- failed+ nothing.++ ``test_nested_secret_edit_under_default_text_ui_element_does_not_leak``+ above pins the identical property, but only for+ ``_api_update_setting_sync``. Every other+ ``save_all_settings`` sentinel test on this class is scalar-only, and+ the unit test in+ ``tests/security/test_settings_secret_redaction_isolation.py``+ exercises ``_reconciled_container_value_for_write`` in isolation --+ neither reaches the ``value if _is_reconciled_container else+ coerce_setting_for_write(...)`` expression in this route.++ EXACT REVERT THIS CATCHES: replacing that expression in+ ``_save_all_settings_sync`` with an unconditional+ ``coerce_setting_for_write(key=..., value=value,+ ui_element=current_setting.ui_element)``. The row here is+ ``ui_element="text"`` (the default for a PUT-created key with no+ ``ui_element``), whose converter IS ``str``, so the reverted call+ flattens the just-merged dict to its Python repr and persists the+ restored secret as a plain string under a key nothing downstream+ treats as sensitive -- which ``redact_value`` then ships back+ verbatim on the next GET.+ """+ client, username, password = settings_user+ suffix = uuid.uuid4().hex[:6]+ key = f"llm.probe_{suffix}.model_kwargs"+ real_secret = f"s3cr3t-saveall-{suffix}"+ real_value = {"stop_token": real_secret, "description": "old-value"}+ # PREMISE (round-5 regression): the sibling leaf must be one the+ # sanitizer does NOT mask, or GET returns it as "[REDACTED]" and+ # the "edit a still-visible sibling" scenario below is+ # unsatisfiable. Asserted rather than assumed -- the round-5+ # version of this test used `page_token`, which ends in `_token`+ # and IS masked. See PLAIN_SIBLING_LEAF.+ assert PLAIN_SIBLING_LEAF in real_value+ assert not DataSanitizer.is_sensitive_setting(PLAIN_SIBLING_LEAF)+ assert DataSanitizer.is_sensitive_setting("stop_token")+ try:+ # No ui_element supplied -> defaults to "text" (str converter).+ create = client.put(+ f"/settings/api/{key}", json={"value": real_value}+ )+ assert create.status_code == 201, create.text[:300]+ meta = client.get(f"/settings/api/{key}").json()+ assert meta["ui_element"] == "text"+ assert meta["value"] == {+ "stop_token": REDACTED,+ "description": "old-value",+ }++ # A GENUINE edit: description changes, stop_token stays masked.+ # A pure round-trip short-circuits as a no-op before ever+ # reaching the coercion call, so it cannot pin this.+ edited = dict(meta["value"])+ edited["description"] = "new-value"+ resp = client.post(+ "/settings/save_all_settings", json={key: edited}+ )+ assert resp.status_code == 200, resp.text[:300]+ assert key in resp.json()["updated"], resp.text[:300]++ # (a) The persisted TYPE proves coercion was skipped. A `str`+ # here is the reverted behaviour, and it embeds the secret.+ stored = _stored_value(username, password, key)+ assert type(stored) is dict, (+ "reconciled container was coerced to a "+ f"{type(stored).__name__} by save_all_settings instead of "+ f"persisted as a dict -- got {stored!r}"+ )+ assert stored == {+ "stop_token": real_secret,+ "description": "new-value",+ }++ # (b) The secret reaches no reader. The save response echoes+ # every setting (`response_data["settings"]`), and the GET+ # would ship a flattened string through `redact_value`+ # untouched, so both are checked -- not just the status code.+ assert real_secret not in resp.text, (+ "the real secret leaked through the save_all_settings "+ f"response echo: {resp.text[:300]}"+ )+ get_after = client.get(f"/settings/api/{key}")+ assert real_secret not in get_after.text, (+ "the real secret leaked through a GET after "+ f"save_all_settings: {get_after.text[:300]}"+ )+ assert get_after.json()["value"] == {+ "stop_token": REDACTED,+ "description": "new-value",+ }+ # NOTE (post-#6201 review, R2): this is+ # ``api_get_all_settings`` (@router.get("/api")), NOT+ # ``get_bulk_settings`` (@router.get("/api/bulk")). An earlier+ # version of this assertion called the same URL while its+ # message claimed the BULK endpoint -- and the bulk endpoint+ # does leak this exact row (#6222), so the message asserted a+ # false negative about a route it never touched. The bulk+ # endpoint is covered on its own, as a strict xfail, in+ # ``test_bulk_settings_get_leaks_a_container_row_xfail_6222``.+ all_settings = client.get("/settings/api")+ assert real_secret not in all_settings.text, (+ "the real secret leaked through GET /settings/api "+ "(api_get_all_settings)"+ )+ finally:+ client.delete(f"/settings/api/{key}")++ def test_save_settings_form_reconciled_container_is_not_coerced_to_str(+ self, settings_user+ ):+ """Round-5 defect (1), the no-JS form half: the coercion skip in+ ``_save_settings_sync`` had no end-to-end test either.++ This route reads ``await request.form()``, so every value arrives as+ a STRING -- the ``<textarea>`` JSON-string shape. ``_coerced_for_guard``+ decodes it for the guards, ``_reconciled_container_value_for_write``+ returns the merged dict, and the skip is what stops that dict being+ handed straight back to ``coerce_setting_for_write``.++ EXACT REVERT THIS CATCHES: dropping the ``if not+ _is_reconciled_container:`` condition around the+ ``value = coerce_setting_for_write(...)`` call in+ ``_save_settings_sync``. Under ``ui_element="textarea"`` (converter+ ``str``) the merged dict is flattened to its Python repr, storing+ the just-restored secret in the clear -- and, because a Python repr+ is not valid JSON, silently destroying the container shape as well.++ The route answers with a 302 + flash message rather than a JSON+ body, so the post-conditions are asserted against the STORED ROW and+ a subsequent GET, which is where a leak would actually surface.+ """+ client, username, password = settings_user+ suffix = uuid.uuid4().hex[:6]+ key = f"llm.probe_{suffix}.model_kwargs"+ real_secret = f"s3cr3t-formpost-{suffix}"+ real_value = {"stop_token": real_secret, "description": "old-value"}+ # PREMISE (round-5 regression): the sibling leaf must be one the+ # sanitizer does NOT mask, or GET returns it as "[REDACTED]" and+ # the "edit a still-visible sibling" scenario below is+ # unsatisfiable. Asserted rather than assumed -- the round-5+ # version of this test used `page_token`, which ends in `_token`+ # and IS masked. See PLAIN_SIBLING_LEAF.+ assert PLAIN_SIBLING_LEAF in real_value+ assert not DataSanitizer.is_sensitive_setting(PLAIN_SIBLING_LEAF)+ assert DataSanitizer.is_sensitive_setting("stop_token")+ try:+ create = client.put(+ f"/settings/api/{key}",+ json={"value": real_value, "ui_element": "textarea"},+ )+ assert create.status_code == 201, create.text[:300]+ meta = client.get(f"/settings/api/{key}").json()+ assert meta["ui_element"] == "textarea"+ assert meta["value"] == {+ "stop_token": REDACTED,+ "description": "old-value",+ }++ edited = dict(meta["value"])+ edited["description"] = "new-value"+ resp = client.post(+ "/settings/save_settings",+ data={+ key: json.dumps(edited),+ "csrf_token": _csrf_token(client),+ },+ follow_redirects=False,+ )+ assert resp.status_code == 302, resp.text[:300]++ stored = _stored_value(username, password, key)+ assert type(stored) is dict, (+ "reconciled container was coerced to a "+ f"{type(stored).__name__} by the no-JS form save instead of "+ f"persisted as a dict -- got {stored!r}"+ )+ assert stored == {+ "stop_token": real_secret,+ "description": "new-value",+ }++ get_after = client.get(f"/settings/api/{key}")+ assert real_secret not in get_after.text, (+ "the real secret leaked through a GET after the no-JS form "+ f"save: {get_after.text[:300]}"+ )+ assert get_after.json()["value"] == {+ "stop_token": REDACTED,+ "description": "new-value",+ }+ # NOTE (post-#6201 review, R2): this is+ # ``api_get_all_settings`` (@router.get("/api")), NOT+ # ``get_bulk_settings`` (@router.get("/api/bulk")). An earlier+ # version of this assertion called the same URL while its+ # message claimed the BULK endpoint -- and the bulk endpoint+ # does leak this exact row (#6222), so the message asserted a+ # false negative about a route it never touched. The bulk+ # endpoint is covered on its own, as a strict xfail, in+ # ``test_bulk_settings_get_leaks_a_container_row_xfail_6222``.+ all_settings = client.get("/settings/api")+ assert real_secret not in all_settings.text, (+ "the real secret leaked through GET /settings/api "+ "(api_get_all_settings)"+ )+ finally:+ client.delete(f"/settings/api/{key}")++ @pytest.mark.xfail(+ strict=True,+ raises=AssertionError,+ reason=(+ "#6222: GET /settings/api/bulk reads through the TYPED getter, "+ "which maps ui_element 'text' to str and hands redact_value a "+ "Python repr of the container instead of the container. The "+ "outer key is not a sensitive name, so the repr -- nested "+ "secret and all -- ships in the clear. Pre-existing and "+ "byte-identical on base; tracked in #6222. When #6222 lands "+ "this test XPASSes and strict=True fails it, which is the "+ "signal to drop the mark."+ ),+ )+ def test_bulk_settings_get_leaks_a_container_row_xfail_6222(+ self, settings_user+ ):+ """The assertion three sibling tests were TRYING to make.++ Post-#6201 review, R2: those tests called ``GET /settings/api``+ (``api_get_all_settings``) while their message named the BULK+ endpoint. This is the real ``GET /settings/api/bulk``+ (``get_bulk_settings``, ``@router.get("/api/bulk")``) against the+ same row shape, so the gap is pinned by an executable expectation+ instead of a passing assertion about an untested route.++ Every PREMISE below uses ``pytest.fail`` rather than ``assert``, so+ only the #6222 leak itself can satisfy the ``raises=AssertionError``+ xfail -- a broken fixture, a changed create contract or a renamed+ route surfaces as a real failure instead of hiding inside it.+ """+ client, username, password = settings_user+ suffix = uuid.uuid4().hex[:6]+ key = f"llm.probe_{suffix}.model_kwargs"+ real_secret = f"s3cr3t-bulk-{suffix}"+ real_value = {"stop_token": real_secret, PLAIN_SIBLING_LEAF: "d"}+ try:+ create = client.put(+ f"/settings/api/{key}", json={"value": real_value}+ )+ if create.status_code != 201:+ pytest.fail(f"premise: create failed: {create.text[:300]}")+ meta = client.get(f"/settings/api/{key}")+ if (+ meta.status_code != 200+ or meta.json().get("ui_element") != "text"+ ):+ pytest.fail(+ f"premise: unexpected row metadata: {meta.text[:300]}"+ )+ # The SINGULAR GET is correctly redacted -- the contrast is the+ # point, so a redaction regression there cannot pass this test.+ if real_secret in meta.text:+ pytest.fail(+ "premise: the singular GET leaked the secret too, so "+ "this test no longer isolates the bulk endpoint"+ )++ bulk = client.get("/settings/api/bulk", params={"keys[]": key})+ if bulk.status_code != 200:+ pytest.fail(f"premise: bulk GET failed: {bulk.text[:300]}")+ if key not in bulk.json().get("settings", {}):+ pytest.fail(+ "premise: the bulk GET did not return the requested key, "+ f"so it cannot be leaking it: {bulk.text[:300]}"+ )++ assert real_secret not in bulk.text, (+ "the real secret leaked through GET /settings/api/bulk "+ f"(#6222): {bulk.text[:300]}"+ )+ finally:+ client.delete(f"/settings/api/{key}")++ def test_reconciled_container_on_a_number_row_is_never_logged(+ self, settings_user+ ):+ """Round-5 defect (1), second half: the ``validate_setting`` skip had+ NO test at ANY of the three call sites, even though its stated+ rationale is a secret DISCLOSURE channel.++ A dict/list value can sit on a ``number`` row -- ``ui_element`` is+ caller-supplied metadata on a new key and is never reconciled+ against the value's actual shape. Feeding a merged container to+ ``validate_setting`` there reaches ``get_typed_setting_value``'s+ bare ``float(value)``, which raises ``TypeError``; the row is then+ rejected ("Value must be a number") and the legitimate edit is+ lost.++ SCOPE CORRECTION (round 6). This test was originally written as a+ LEAK test: the ``TypeError`` handler used to log ``"Setting {key}+ has invalid value {value}"`` at WARNING -- the whole container,+ secret leaf included -- so reverting either skip disclosed the+ restored secret to the log. It went red anyway, because the leak+ was never confined to the two write-back call sites this test+ reverts: ``PUT /settings/api/<key>`` commits and then emits a+ settings-changed event, whose ``get_setting(key)`` reaches the+ same converter with the same container AFTER both skips have+ already done their job. The fix was therefore made in the+ converter (``settings/manager.py``), which no longer logs a+ setting VALUE on any path; see+ ``test_typed_value_converter_never_logs_the_value_itself`` below,+ which pins that directly. The log assertions kept here are the+ END-TO-END form of the same property -- no secret reaches the log+ through ANY of the three write routes, whatever they call -- and+ they are what caught this in the first place.++ EXACT REVERTS THIS STILL CATCHES, at all three write routes:+ * dropping the ``validate_setting`` skip -- the container is+ rejected as "Value must be a number", so the PUT/bulk calls+ below stop returning 200/302 and the final ``stored ==``+ assertion loses the edit; and+ * reinstating the setting value in either of the converter's+ two WARNING lines -- the leak assertion below fires again.++ What this test does NOT catch, and where that coverage lives: a+ coercion-only revert on a NUMERIC row is invisible here.+ ``coerce_setting_for_write`` returns the submitted value unchanged+ when a numeric conversion fails (see its ``numeric_ui and coerced+ is None`` branch), so the stored row is identical either way, and+ the converter no longer logs anything incriminating. The coercion+ skip is pinned instead by the four+ ``..._is_not_coerced_to_str`` / ``..._does_not_leak`` tests above,+ on "text"/"textarea" rows -- the shape where coercion actually+ does damage, because ``str()`` flattens the merged container to a+ Python repr carrying the restored secret in the clear.++ The POSITIVE CONTROL is not optional: the package disables its own+ loguru namespace at import, so "no secret in the captured lines"+ would pass even if nothing was ever captured. The control asserts a+ known router WARNING from the same routes, in the same capture+ block, did arrive.+ """+ client, username, password = settings_user+ suffix = uuid.uuid4().hex[:6]+ key = f"llm.probe_{suffix}.cfg"+ control_key = f"auth.probe_{suffix}_control"+ real_secret = f"s3cr3t-number-row-{suffix}"+ real_value = {"stop_token": real_secret, "retries": 3}+ try:+ create = client.put(+ f"/settings/api/{key}",+ json={"value": real_value, "ui_element": "number"},+ )+ assert create.status_code == 201, create.text[:300]+ meta = client.get(f"/settings/api/{key}").json()+ # The premise: a container value on a NUMERIC row. `float()`+ # cannot convert it, which is the whole hazard.+ assert meta["ui_element"] == "number"+ assert meta["value"] == {"stop_token": REDACTED, "retries": 3}++ with _captured_warnings() as lines:+ # A genuine edit through each of the three write routes in+ # turn: `retries` changes, `stop_token` stays masked.+ put_resp = client.put(+ f"/settings/api/{key}",+ json={"value": {"stop_token": REDACTED, "retries": 4}},+ )+ assert put_resp.status_code == 200, put_resp.text[:300]++ bulk_resp = client.post(+ "/settings/save_all_settings",+ json={key: {"stop_token": REDACTED, "retries": 5}},+ )+ assert bulk_resp.status_code == 200, bulk_resp.text[:300]+ assert key in bulk_resp.json()["updated"], bulk_resp.text[:300]++ form_resp = client.post(+ "/settings/save_settings",+ data={+ key: json.dumps({"stop_token": REDACTED, "retries": 6}),+ "csrf_token": _csrf_token(client),+ },+ follow_redirects=False,+ )+ assert form_resp.status_code == 302, form_resp.text[:300]++ # POSITIVE CONTROL: a key outside the allowed namespaces+ # makes `_save_all_settings_sync` log+ # "Security: Rejected setting outside allowed namespaces:+ # '<key>'" at WARNING. If this line is missing, the sink is+ # not wired up and the secret assertions below prove+ # nothing.+ control = client.post(+ "/settings/save_all_settings",+ json={control_key: "x"},+ )+ assert control.status_code == 400, control.text[:300]++ assert any(control_key in line for line in lines), (+ "log capture is not wired up: the router's namespace-"+ "rejection WARNING for the control key never reached the "+ f"sink (captured {len(lines)} line(s))"+ )+ leaked = [line for line in lines if real_secret in line]+ assert not leaked, (+ "the restored secret was written to the log on a number "+ "row -- by the converter's own WARNING (see "+ "get_typed_setting_value in settings/manager.py), by "+ "validate_setting/coerce_setting_for_write, or by the "+ f"post-commit settings-changed read: {leaked[0][:300]}"+ )++ # All three edits landed, so none of them was silently rejected+ # by a validator that should never have seen this value.+ stored = _stored_value(username, password, key)+ assert stored == {"stop_token": real_secret, "retries": 6}, (+ f"a write route dropped the reconciled edit: {stored!r}"+ )+ finally:+ client.delete(f"/settings/api/{key}")++ def test_typed_value_converter_never_logs_the_value_itself(self):+ """Round-6 defect (1): the leak was in the CONVERTER, not at any one+ call site, and no route-level skip could close it.++ ``test_reconciled_container_on_a_number_row_is_never_logged`` above+ covers the three write routes. It still went red, because a FOURTH+ path reaches the same converter with the restored container and is+ not a write-back call site at all:+ ``PUT /settings/api/<key>`` calls ``set_setting(...)`` with no+ ``commit=`` argument, which defaults to ``commit=True``, so+ ``SettingsManager.set_setting`` commits and then calls+ ``_emit_settings_changed([key])`` -> ``get_setting(key)`` ->+ ``get_typed_setting_value``. On a ``number``/``range``/``slider``+ row holding a dict, ``_parse_number``'s bare ``float(value)``+ raises ``TypeError`` and the handler logged the whole container --+ restored secret included -- at WARNING. The bulk routes pass+ ``commit=False`` and never emit, which is why only the PUT path+ tripped it and only the leak assertion failed.++ Skipping the converter at a fourth call site would have been+ whack-a-mole: ``_validate_imported_setting_value`` reaches it too,+ and so does any future reader. The fix is that+ ``get_typed_setting_value`` no longer logs a setting VALUE at all+ -- a settings value is, by this PR's own premise, a plausible+ secret carrier. This test pins the converter directly, so it fails+ if the value is ever reinstated in EITHER of that function's two+ warning lines, whichever route happens to reach it.++ EXACT REVERT THIS CATCHES: restoring ``key, value`` (or ``key,+ env_value``) as the interpolated arguments of either+ ``logger.warning("Setting {} has ... value {} ...")`` call in+ ``settings/manager.py``.++ The POSITIVE CONTROL is not optional here either: the package+ disables its own loguru namespace at import, so "no secret in the+ captured lines" would pass with nothing captured at all. The+ control is the diagnostic the line MUST still carry -- the key.+ """+ from local_deep_research.settings.manager import (+ get_typed_setting_value,+ )++ key = "llm.probe_converter_unit.cfg"+ db_secret = "s3cr3t-converter-db-7731"+ env_secret = "s3cr3t-converter-env-7731"++ with _captured_warnings() as lines:+ # (a) The DB arm: a container on a `number` row. `float(dict)`+ # raises TypeError -- the exact branch the failing CI job hit.+ db_result = get_typed_setting_value(+ key=key,+ value={"stop_token": db_secret, "retries": 4},+ ui_element="number",+ default=None,+ check_env=False,+ )+ # (b) The sibling arm, same function: an env override that+ # cannot be converted. `float(str)` raises ValueError and the+ # handler logged `env_value` -- an LDR_* override is where a+ # provider API key most often lives.+ with patch.dict(+ "os.environ",+ {"LDR_LLM_PROBE_CONVERTER_UNIT_CFG": env_secret},+ ):+ env_result = get_typed_setting_value(+ key=key,+ value=None,+ ui_element="number",+ default=None,+ check_env=True,+ )++ assert db_result is None+ assert env_result is None++ # POSITIVE CONTROL: both warnings reached the sink AND still name+ # the key, which is the diagnostic that must survive the fix.+ assert sum(1 for line in lines if key in line) >= 2, (+ "log capture is not wired up, or the converter's warnings no "+ "longer name the setting key (captured "+ f"{len(lines)} line(s)): {lines}"+ )++ for secret in (db_secret, env_secret):+ leaked = [line for line in lines if secret in line]+ assert not leaked, (+ "get_typed_setting_value wrote a setting value to the log: "+ f"{leaked[0][:300]}"+ )+ # Not even the container's structure: a sub-key name can itself be+ # the interesting half of a leak.+ assert not [line for line in lines if "stop_token" in line], lines++ # What the line must still say instead of the value: the type it+ # actually got, so a malformed row stays diagnosable.+ assert any("dict" in line for line in lines), lines++ def test_masked_list_edit_survives_javascript_number_normalization(+ self, settings_user+ ):+ """Round-5 defect (2): ``_values_equal`` required ``type(a) is+ type(b)`` for numerics, which made an ordinary browser round-trip of+ a >=2-item list UNSATISFIABLE.++ ``_non_sentinel_fields_match`` (the anti-permutation gate) demands+ every visible field of a list item equal its stored counterpart+ before a masked secret is restored by position. A stored ``30.0``+ can never be echoed back as a float by a browser: JavaScript's only+ number type is a double that serializes as ``30``, and+ ``settings.js`` additionally ``parseInt``s a decimal-free numeric+ before submitting. Under type-strict equality the gate therefore+ rejected EVERY submission -- including an untouched round-trip --+ with a 400 "contains the redaction placeholder" that no client could+ ever construct a passing request for.++ EXACT REVERT THIS CATCHES: restoring ``type(a) is type(b) and+ a == b`` in ``_values_equal``'s numeric arm. Case (a) then 400s+ instead of 200, and case (b)'s genuine edit is refused.++ Case (c) is the falsifier: the gate must still reject a real+ permutation submitted with the SAME int-vs-float normalization, so+ the fix cannot be mistaken for "the numeric comparison was what+ closed the permutation hole".+ """+ client, username, password = settings_user+ suffix = uuid.uuid4().hex[:6]+ key = f"llm.probe_{suffix}.endpoints"+ secret_a = f"K1-{suffix}"+ secret_b = f"K2-{suffix}"+ # `timeout` is a float in the DB; `url`/`timeout` are non-sensitive+ # leaves, so they stay visible on GET and become the gate's+ # comparison material.+ real_value = [+ {"url": "https://a.example", "api_key": secret_a, "timeout": 30.0},+ {"url": "https://b.example", "api_key": secret_b, "timeout": 30.0},+ ]+ try:+ create = client.put(+ f"/settings/api/{key}",+ json={"value": real_value, "ui_element": "json"},+ )+ assert create.status_code == 201, create.text[:300]+ meta = client.get(f"/settings/api/{key}").json()+ assert meta["value"] == [+ {+ "url": "https://a.example",+ "api_key": REDACTED,+ "timeout": 30.0,+ },+ {+ "url": "https://b.example",+ "api_key": REDACTED,+ "timeout": 30.0,+ },+ ]++ # What a JS client actually sends back: ints, not floats.+ round_trip = [+ {+ "url": "https://a.example",+ "api_key": REDACTED,+ "timeout": 30,+ },+ {+ "url": "https://b.example",+ "api_key": REDACTED,+ "timeout": 30,+ },+ ]++ # (a) The untouched round-trip is a no-op, not a 400.+ resp = client.put(+ f"/settings/api/{key}", json={"value": round_trip}+ )+ assert resp.status_code == 200, (+ "a plain GET-then-PUT round-trip of a masked 2-item list "+ f"was rejected: {resp.text[:300]}"+ )+ assert _stored_value(username, password, key) == real_value++ # (b) A genuine edit -- entry 0's key replaced, entry 1's left+ # masked -- saves, and entry 1's secret is restored to the entry+ # it actually belonged to.+ new_secret = f"K1-rotated-{suffix}"+ edited = [dict(item) for item in round_trip]+ edited[0]["api_key"] = new_secret+ resp2 = client.put(f"/settings/api/{key}", json={"value": edited})+ assert resp2.status_code == 200, resp2.text[:300]+ assert _stored_value(username, password, key) == [+ {+ "url": "https://a.example",+ "api_key": new_secret,+ "timeout": 30,+ },+ {+ "url": "https://b.example",+ "api_key": secret_b,+ "timeout": 30,+ },+ ]+ assert new_secret not in client.get(f"/settings/api/{key}").text++ # (c) FALSIFIER: the same int-normalized shape, but the two+ # entries swapped, is still refused -- positional restoration+ # would rebind each secret to the wrong url.+ permuted = [+ {+ "url": "https://b.example",+ "api_key": REDACTED,+ "timeout": 30,+ },+ {+ "url": "https://a.example",+ "api_key": REDACTED,+ "timeout": 30,+ },+ ]+ resp3 = client.put(f"/settings/api/{key}", json={"value": permuted})+ assert resp3.status_code == 400, (+ "a same-length permutation of a masked list was accepted: "+ f"{resp3.text[:300]}"+ )+ assert _stored_value(username, password, key) == [+ {+ "url": "https://a.example",+ "api_key": new_secret,+ "timeout": 30,+ },+ {+ "url": "https://b.example",+ "api_key": secret_b,+ "timeout": 30,+ },+ ]+ finally:+ client.delete(f"/settings/api/{key}")++ @pytest.mark.parametrize(+ "route", ["put", "save_all_settings", "save_settings"]+ )+ def test_multiselect_json_preserves_nested_masked_secrets(+ self, settings_user, route+ ):+ """Strict JSON containers must reach the guards before multiselect coercion."""+ client, username, password = settings_user+ key = f"llm.probe_{uuid.uuid4().hex[:6]}.config"+ real_value = [{"stop_token": "synthetic-alpha", "retries": 3}]+ try:+ created = client.put(+ f"/settings/api/{key}",+ json={"value": real_value, "ui_element": "multiselect"},+ )+ assert created.status_code == 201, created.text[:300]+ masked = client.get(f"/settings/api/{key}").json()["value"]+ assert masked == [{"stop_token": REDACTED, "retries": 3}]++ # Cover both an unchanged round-trip and an ordinary sibling edit.+ for retries in (3, 4):+ masked[0]["retries"] = retries+ encoded = json.dumps(masked)+ if route == "put":+ response = client.put(+ f"/settings/api/{key}", json={"value": encoded}+ )+ elif route == "save_all_settings":+ response = client.post(+ "/settings/save_all_settings", json={key: encoded}+ )+ else:+ response = client.post(+ "/settings/save_settings",+ data={key: encoded, "csrf_token": _csrf_token(client)},+ follow_redirects=False,+ )+ assert response.status_code in (200, 302, 303), response.text[+ :300+ ]+ assert _stored_value(username, password, key) == [+ {"stop_token": "synthetic-alpha", "retries": retries}+ ]+ assert (+ client.get(f"/settings/api/{key}").json()["value"] == masked+ )+ finally:+ client.delete(f"/settings/api/{key}")+@pytest.mark.timeout(180)class TestSecretRedactionSurvivesEnvOverlay:diff --git a/tests/security/test_settings_secret_redaction_isolation.py b/tests/security/test_settings_secret_redaction_isolation.pyindex 4c7a329591..9e3ca157ba 100644--- a/tests/security/test_settings_secret_redaction_isolation.py+++ b/tests/security/test_settings_secret_redaction_isolation.py@@ -56,6 +56,7 @@ import osos.environ.setdefault("LDR_DISABLE_RATE_LIMITING", "true")import pytest # noqa: E402+from contextlib import contextmanager # noqa: E402from local_deep_research.security.data_sanitizer import DataSanitizer # noqa: E402from local_deep_research.settings.logger import redact_sensitive_keys # noqa: E402@@ -386,6 +387,14 @@ def test_embedded_sentinel_predicate():# ``_embeds_redaction_sentinel`` / ``_embeds_sentinel_on_create``.# --------------------------------------------------------------------------- #BROADENED_ARM_KEY = "local_search_milvus_token"+# An outer key that is NOT itself sensitive. ``redact_value`` recurses a+# container by SUB-KEY, so a leaf named for an exact+# ``DEFAULT_SENSITIVE_KEYS`` entry is masked here regardless of the+# outer key -- and, unlike the broadened-arm key above, regardless of+# the leaf VALUE's type (the exact-match arm returns the bare sentinel+# before the container arm is reached). This is the only key class that+# can produce a bare sentinel over a stored list/dict/int/bool leaf.+NON_SENSITIVE_OUTER_KEY = "llm.model_kwargs"def test_container_sentinel_roundtrip_is_noop():@@ -433,8 +442,31 @@ def test_container_sentinel_roundtrip_is_noop():stored_with_blank,)- # A non-sensitive key's identical-looking container is not special-cased.- assert not _is_secret_empty_noop(+ # A non-sensitive key's identical-looking container IS still a no-op.+ #+ # PREMISE CHANGE (post-#6201 review, item 4): earlier rounds gated the+ # dict/list arm on ``is_sensitive_setting(key)`` the same way the plain+ # string arm still is, so this assertion used to be ``assert not+ # _is_secret_empty_noop(...)`` -- a non-sensitive outer key's container+ # was deliberately NOT treated as a no-op round-trip. That premise was+ # reversed a few rounds later (see ``_is_secret_empty_noop``'s own+ # docstring, "The dict/list arm runs BEFORE the ``is_sensitive_setting``+ # gate"): ``redact_value`` masks a container by SUB-KEY, so an outer key+ # that is not itself sensitive (``llm.model_kwargs``) can still carry a+ # sensitive-named leaf (``stop_token``) that gets masked on GET. Gating+ # the container check on the OUTER key's sensitivity meant that leaf's+ # sentinel round-tripped straight back into the DB on the very next+ # save, because no guard ever looked at it (#6201's disclosure bug was+ # a direct consequence of this same "gate on outer key" mistake+ # resurfacing in the coercion step). The literal string "[REDACTED]" is+ # not a value any real setting leaf would hold, sensitive-key or not,+ # so the container arm now scans every dict/list write for it+ # unconditionally -- which makes this exact round-trip a no-op+ # regardless of ``llm.some_plain_setting`` not itself being a+ # sensitive-named key. This test was left asserting the OLD premise+ # (a red test at HEAD); the assertion below pins the current, intended+ # behaviour instead.+ assert _is_secret_empty_noop("llm.some_plain_setting", None, roundtrip, stored)@@ -445,22 +477,38 @@ def test_container_sentinel_roundtrip_is_noop():assert _embeds_redaction_sentinel(BROADENED_ARM_KEY, None, roundtrip, None)-def test_container_partial_edit_still_embeds_sentinel():- """(b) A container that still carries "[REDACTED]" in some leaf but is- NOT the pure untouched round-trip -- a leaf with the sentinel spliced- into it, or a legitimately edited sibling next to an untouched- sentinel leaf -- is a corrupted/partial edit and must be rejected with- the same 400 semantics as the string case, not silently persisted with- "[REDACTED]" overwriting the real secret.+def test_container_spliced_sentinel_is_rejected_but_mixed_edit_merges():+ """(b) A leaf with the sentinel SPLICED into it (not an exact match) is+ always a corrupted edit and must be rejected with the same 400+ semantics as the plain string case, not silently persisted with+ "[REDACTED]" spliced into the real secret.++ A container where a DIFFERENT leaf was legitimately edited while a+ secret leaf stays verbatim "[REDACTED]" is NOT the same thing, and+ must not get the same reject-outright treatment (round 5's fix, since+ corrected -- see the follow-up round this test now pins):+ ``redact_value`` masks a container by SUB-KEY, so a mixed container+ such as ``{"uri": "...", "token": "...", "port": 19530}`` under a key+ that matches only the broadened arm has just its ``token`` masked on+ GET. Requiring EVERY maskable leaf to be exactly the sentinel before+ treating the container as anything but a corrupted edit made that+ GET's own output un-resubmittable: a client can never see the real+ secret to resend it, and any masked-leaf resubmission looked+ "corrupted". The write must instead merge -- restore ``token`` from+ the stored row, keep the edited ``host``/``port`` as submitted -- and+ save, not 400."""from local_deep_research.web.routers.settings import (_embeds_redaction_sentinel,_is_secret_empty_noop,+ _reconciled_container_value_for_write,)stored = {"uri": "mysql://real", "token": "s3cr3t-real", "port": 19530}- # A leaf with the sentinel spliced into it rather than exactly equal.+ # A leaf with the sentinel spliced into it rather than exactly equal:+ # always a corrupted edit, regardless of what else in the container+ # changed.spliced = {"uri": REDACTED,"token": f"pre{REDACTED}post",@@ -469,18 +517,30 @@ def test_container_partial_edit_still_embeds_sentinel():assert _embeds_redaction_sentinel(BROADENED_ARM_KEY, None, spliced, stored)assert not _is_secret_empty_noop(BROADENED_ARM_KEY, None, spliced, stored)- # A non-secret sibling legitimately edited while the secret leaves are- # still verbatim "[REDACTED]" -- must still be rejected, not silently- # persisted (which would overwrite uri/token with the sentinel) or- # silently dropped (which would lose the host edit).+ # A non-secret sibling legitimately edited (a new "host" key, an+ # updated "port") while the secret leaves are still verbatim+ # "[REDACTED]" must MERGE and save: the secret leaves restore from+ # `stored`, the edits are kept, and this is neither a no-op nor a+ # rejection.mixed = {"uri": REDACTED,"token": REDACTED,"host": "new-host.example.com","port": 19531,}- assert _embeds_redaction_sentinel(BROADENED_ARM_KEY, None, mixed, stored)+ assert not _embeds_redaction_sentinel(+ BROADENED_ARM_KEY, None, mixed, stored+ )assert not _is_secret_empty_noop(BROADENED_ARM_KEY, None, mixed, stored)+ assert _reconciled_container_value_for_write(mixed, mixed, stored) == (+ {+ "uri": "mysql://real",+ "token": "s3cr3t-real",+ "host": "new-host.example.com",+ "port": 19531,+ },+ True,+ )# A genuinely fresh value with no sentinel anywhere trips neither guard.fresh = {"uri": "mysql://real", "token": "s3cr3t-real", "port": 19530}@@ -490,34 +550,41 @@ def test_container_partial_edit_still_embeds_sentinel():assert not _is_secret_empty_noop(BROADENED_ARM_KEY, None, fresh, stored)-def test_container_non_string_leaf_edit_is_not_a_silent_noop():- """R1d / round 5 (#6089-follow-up): editing ONLY a non-string leaf- inside a sensitive container -- e.g. a port number -- while every- string leaf stays exactly "[REDACTED]" must NOT be silently discarded- as a no-op, and must NOT be silently persisted with the sentinel- spliced into the string leaves either. It must be rejected with the- same 400 "retype the whole value" semantics as any other corrupted- container edit.+def test_container_non_string_leaf_edit_merges_and_saves():+ """R1d / round 5 (#6089-follow-up), corrected by the next round: editing+ ONLY a non-string leaf inside a sensitive container -- e.g. a port+ number -- while every string leaf stays exactly "[REDACTED]" must NOT+ be silently discarded as a no-op (round 4's bug -- see the docstring+ below), and must NOT have the sentinel spliced into a string leaf+ either. Round 5 fixed both by rejecting the whole container outright;+ that overshot -- editing a non-secret sibling of a real secret is a+ completely ordinary edit, and rejecting it makes the container+ un-savable without retyping a secret the client cannot see. The+ correct outcome is a MERGE: the secret leaf restores from the stored+ row, the non-string edit is kept, and the write is neither a no-op+ nor a rejection.Round 4's ``_container_all_leaves_are_sentinel`` only ever inspectedSTRING leaves, so a stored ``{"token": "s", "port": 19530}`` submittedback as ``{"token": "[REDACTED]", "port": 19531}`` looked identical to- a pure round-trip and the port edit vanished silently. This pins the- fix: the no-op arm now also requires non-string leaves to match the- stored row.+ a pure round-trip and the port edit vanished silently."""from local_deep_research.web.routers.settings import (_embeds_redaction_sentinel,_is_secret_empty_noop,+ _reconciled_container_value_for_write,)stored = {"token": "s", "port": 19530}port_edit = {"token": REDACTED, "port": 19531}assert not _is_secret_empty_noop(BROADENED_ARM_KEY, None, port_edit, stored)- assert _embeds_redaction_sentinel(+ assert not _embeds_redaction_sentinel(BROADENED_ARM_KEY, None, port_edit, stored)+ assert _reconciled_container_value_for_write(+ port_edit, port_edit, stored+ ) == ({"token": "s", "port": 19531}, True)# An untouched round-trip against the same stored row stays a no-op.untouched = {"token": REDACTED, "port": 19530}@@ -526,56 +593,1174 @@ def test_container_non_string_leaf_edit_is_not_a_silent_noop():BROADENED_ARM_KEY, None, untouched, stored)- # A bool-toggle sibling edit is caught the same way.+ # A bool-toggle sibling edit is merged and saved the same way.stored_with_flag = {"token": "s", "enabled": False}flag_edit = {"token": REDACTED, "enabled": True}assert not _is_secret_empty_noop(BROADENED_ARM_KEY, None, flag_edit, stored_with_flag)- assert _embeds_redaction_sentinel(+ assert not _embeds_redaction_sentinel(BROADENED_ARM_KEY, None, flag_edit, stored_with_flag)+ assert _reconciled_container_value_for_write(+ flag_edit, flag_edit, stored_with_flag+ ) == ({"token": "s", "enabled": True}, True)-def test_container_cross_type_leaf_edit_is_not_a_silent_noop():- """#6181: the non-maskable-leaf comparison must be type-strict. Python- equality is not: ``1 == 1.0`` and ``True == 1`` are both true, so a- stored ``{"token": "s", "mode": 1}`` submitted back as- ``{"token": "[REDACTED]", "mode": True}`` (or ``1.0``) would slip past- the no-op arm as an untouched round-trip and drop the requested type- change. The stored-shape check now requires identical type AND value.+def test_container_orphan_sentinel_is_rejected():+ """A sentinel-exact leaf with NO corresponding secret in the stored row+ -- a brand-new key the client happened to set to the literal+ placeholder text, or a structural mismatch -- cannot be resolved by+ the merge and must still be rejected, unlike the resolvable mixed-edit+ case above."""from local_deep_research.web.routers.settings import (_embeds_redaction_sentinel,_is_secret_empty_noop,)- stored = {"token": "s", "mode": 1}+ stored = {"token": "s", "port": 19530}- bool_for_int = {"token": REDACTED, "mode": True}+ # "new_secret" has no counterpart in `stored` to restore from.+ new_key_sentinel = {+ "token": REDACTED,+ "new_secret": REDACTED,+ "port": 19530,+ }+ assert _embeds_redaction_sentinel(+ BROADENED_ARM_KEY, None, new_key_sentinel, stored+ )assert not _is_secret_empty_noop(- BROADENED_ARM_KEY, None, bool_for_int, stored+ BROADENED_ARM_KEY, None, new_key_sentinel, stored)- assert _embeds_redaction_sentinel(- BROADENED_ARM_KEY, None, bool_for_int, stored++ # A leaf whose stored counterpart is EMPTY -- by ``_is_empty_value``'s+ # own rule, the same rule ``redact_value`` gates masking on -- is an+ # orphan too: nothing was masked, so the sentinel cannot have come+ # from a round-trip and there is nothing to restore.+ for empty in ("", " ", None, [], {}):+ stored_empty = {"token": empty, "port": 19530}+ assert (+ DataSanitizer.redact_value(+ NON_SENSITIVE_OUTER_KEY, None, stored_empty+ )+ == stored_empty+ ), (+ "premise broken: an empty stored leaf was masked after all, so "+ f"the sentinel below WOULD be a legitimate round-trip ({empty!r})"+ )+ assert _embeds_redaction_sentinel(+ NON_SENSITIVE_OUTER_KEY,+ None,+ {"token": REDACTED, "port": 19530},+ stored_empty,+ ), (+ f"an orphan sentinel over an empty stored leaf was accepted ({empty!r})"+ )+++def test_container_sentinel_over_a_non_string_stored_leaf_restores_it():+ """A masked leaf whose stored value is a list/dict/int/bool must be+ RESTORED from it, not rejected (post-#6201 review BL1, #6213 item c).++ ``redact_value`` masks a nested leaf to the bare sentinel for ANY+ non-empty value when the sub-key is an exact ``DEFAULT_SENSITIVE_KEYS``+ match -- the exact-match arm runs before the container arm, so the+ value's type never gets a say. An earlier version of this test asserted+ the OPPOSITE, with two defects worth naming so they are not+ reintroduced:++ * its rationale ("the stored counterpart is not a (non-empty)+ string, so there is nothing maskable to have restored the sentinel+ from") was false -- ``redact_value`` masks ``{"token": 42}`` to+ ``{"token": "[REDACTED]"}`` under a non-sensitive outer key, and+ ``42`` is exactly what should be restored; and+ * it used ``BROADENED_ARM_KEY``, for which the shape is UNREACHABLE+ (asserted below): that key matches only the broadened snake_case+ arm, whose container path is ``_force_redact_strings``, and that+ leaves a non-string leaf alone. So the assertion pinned a+ rejection using the one key class that can never produce it, while+ for the key class that CAN -- any non-sensitive outer key -- the+ pinned behaviour was a permanent, unsatisfiable 400.+ """+ from local_deep_research.web.routers.settings import (+ _embeds_redaction_sentinel,+ _is_secret_empty_noop,+ _reconciled_container_value_for_write,)- float_for_int = {"token": REDACTED, "mode": 1.0}- assert not _is_secret_empty_noop(- BROADENED_ARM_KEY, None, float_for_int, stored+ for stored_leaf in (42, True, False, 0, ["a", "b"], {"h": "v"}):+ stored = {"token": stored_leaf, "port": 19530}+ masked = DataSanitizer.redact_value(+ NON_SENSITIVE_OUTER_KEY, None, stored+ )+ # PREMISE: the GET really does produce the bare sentinel here.+ assert masked == {"token": REDACTED, "port": 19530}, (+ f"a stored {type(stored_leaf).__name__} under the exact leaf "+ f"'token' did not mask to the bare sentinel: {masked!r}"+ )+ # ...so submitting it straight back must be a recognized no-op.+ assert not _embeds_redaction_sentinel(+ NON_SENSITIVE_OUTER_KEY, None, masked, stored+ ), (+ f"an untouched round-trip of a stored "+ f"{type(stored_leaf).__name__} leaf was rejected -- the client "+ "cannot satisfy this request, it never saw the real value"+ )+ assert _is_secret_empty_noop(+ NON_SENSITIVE_OUTER_KEY, None, masked, stored+ )+ # ...and a sibling edit beside it restores the stored value with+ # its TYPE intact (``==`` alone would let True pass as 1).+ edit = dict(masked)+ edit["port"] = 19531+ merged, is_reconciled = _reconciled_container_value_for_write(+ edit, edit, stored+ )+ assert is_reconciled is True+ assert merged == {"token": stored_leaf, "port": 19531}+ assert type(merged["token"]) is type(stored_leaf)++ # NEGATIVE CONTROL, in the same arm the widening changed: a sentinel+ # SPLICED into a longer string is still a corrupted edit, whatever the+ # stored leaf's type. The widening moved one condition two lines above+ # this branch, so a future edit that collapses the two would silently+ # start restoring over a spliced value; nothing else pins the container+ # form of the splice (the existing CORRUPT_VALUES tests are all scalar+ # and multiselect).+ for stored_leaf in (42, True, ["a"], {"h": "v"}, "s3cr3t-real"):+ for spliced in (f"{REDACTED},new", f"new,{REDACTED}", f"x{REDACTED}"):+ assert _embeds_redaction_sentinel(+ NON_SENSITIVE_OUTER_KEY,+ None,+ {"token": spliced, "port": 19530},+ {"token": stored_leaf, "port": 19530},+ ), (+ "a spliced sentinel was accepted over a stored "+ f"{type(stored_leaf).__name__} leaf ({spliced!r})"+ )++ # The BROADENED-ARM key cannot reach this shape at all: its container+ # path is ``_force_redact_strings``, which leaves a non-string leaf+ # alone, so the GET returns the row unmasked and there is no sentinel+ # to round-trip. Asserted so the key choice above stays deliberate.+ assert DataSanitizer.redact_value(+ BROADENED_ARM_KEY, None, {"token": 42}+ ) == {"token": 42}+++def test_coerce_setting_for_write_would_flatten_a_reconciled_container():+ """The HAZARD behind the coercion skip, stated as an executable fact --+ NOT as a stand-in for the call sites.++ Running a merged, secret-bearing container through+ ``coerce_setting_for_write`` under a str-typed ui_element+ ("text"/"textarea"/"password"/"select") flattens it to its Python REPR+ via ``str()``, turning a just-restored secret into a plain,+ non-redacted string persisted under a key nothing downstream treats as+ sensitive -- which ``redact_value`` then ships back verbatim on the+ next GET. That is how #6201 round 1 turned a data-LOSS bug into a+ secret-DISCLOSURE bug.++ WHAT THIS TEST DELIBERATELY DOES NOT DO (round-5 review, defect 1):+ an earlier version of it re-implemented the call sites' own+ ``merged if is_reconciled_container else coerce_setting_for_write(...)``+ decision inside the test body and asserted on the result. That reads+ as coverage while pinning nothing: reverting the skip in+ ``_save_all_settings_sync`` or ``_save_settings_sync`` left it green,+ because the test never called a route. A test that reproduces the+ logic it is testing is worse than no test. The call sites are pinned+ end-to-end instead, one route-level test each, in+ ``tests/security/test_settings_egress_and_secrets_fastapi.py``:++ * ``test_save_all_settings_reconciled_container_is_not_coerced_to_str``+ * ``test_save_settings_form_reconciled_container_is_not_coerced_to_str``+ * ``test_nested_secret_edit_under_default_text_ui_element_does_not_leak``+ (``_api_update_setting_sync``)+ * ``test_reconciled_container_on_a_number_row_is_never_logged``+ (both the coercion and the ``validate_setting`` skip, all three+ routes, via the WARNING those converters emit on a numeric row)++ What is left here is the part that genuinely belongs in isolation: the+ merge contract (``_reconciled_container_value_for_write`` restores the+ secret, keeps the edit, and flags the result as reconciled) and proof+ that the coercion those call sites skip really would leak.+ """+ from local_deep_research.web.routers.settings import (+ _reconciled_container_value_for_write,+ coerce_setting_for_write,+ )++ key = "llm.probe.model_kwargs" # not itself a sensitive-named key+ stored = {"stop_token": "s3cr3t-real-9911", "page_token": "old-value"}+ # A genuine edit: page_token changes, stop_token stays masked. A pure+ # no-op round-trip short-circuits before the coercion call, so it is+ # not the shape that matters here.+ edit = {"stop_token": REDACTED, "page_token": "new-value"}++ merged, is_reconciled_container = _reconciled_container_value_for_write(+ edit, edit, stored+ )+ assert is_reconciled_container is True, (+ "the caller's signal to skip coercion was not raised for a merged "+ "secret-bearing container"+ )+ assert merged == {+ "stop_token": "s3cr3t-real-9911",+ "page_token": "new-value",+ }++ # The hazard itself: this is what the call sites must NOT do with+ # `merged`. Asserting it here documents why the skip exists and fails+ # if `coerce_setting_for_write` ever stops flattening containers (at+ # which point the skip's rationale, and its docstrings, need revisiting+ # rather than silently rotting).+ would_have_leaked = coerce_setting_for_write(+ key=key, value=merged, ui_element="text"+ )+ assert type(would_have_leaked) is str+ assert "s3cr3t-real-9911" in would_have_leaked+++def test_values_equal_treats_int_and_float_as_the_same_number():+ """Round-5 defect (2): ``_values_equal`` required ``type(a) is type(b)``+ for numerics, which made an ordinary browser round-trip of a masked+ >=2-item list UNSATISFIABLE.++ ``_non_sentinel_fields_match`` -- the anti-permutation gate -- calls+ this on every visible leaf, and a stored ``30.0`` can never be echoed+ back as a float by a browser: JavaScript's only number type is a+ double that serializes as ``30``, and ``settings.js`` additionally+ ``parseInt``s a decimal-free numeric before submitting. So the gate+ rejected EVERY submission, untouched round-trips included, with a 400+ the client had no way to satisfy.++ The end-to-end consequence is pinned by+ ``test_masked_list_edit_survives_javascript_number_normalization``+ (``tests/security/test_settings_egress_and_secrets_fastapi.py``),+ including the falsifier that a real permutation is still refused. This+ test pins the predicate itself, at every place it recurses.+ """+ from local_deep_research.web.routers.settings import (+ _non_sentinel_fields_match,+ _values_equal,+ )++ assert _values_equal(30, 30.0)+ assert _values_equal(30.0, 30)+ assert _values_equal({"timeout": 30}, {"timeout": 30.0})+ assert _values_equal([{"timeout": 30}], [{"timeout": 30.0}])+ # Same number, still not the same VALUE when it differs.+ assert not _values_equal(30, 31)+ assert not _values_equal(1, 1.5)+ # A number is still not a string spelling of that number.+ assert not _values_equal(30, "30")++ # The gate this predicate exists for: the visible fields of a masked+ # list item, echoed back with JavaScript's integer normalization,+ # must count as unchanged.+ stored_item = {"url": "https://a.example", "api_key": "K1", "timeout": 30.0}+ echoed_item = {+ "url": "https://a.example",+ "api_key": REDACTED,+ "timeout": 30,+ }+ assert _non_sentinel_fields_match(echoed_item, stored_item, REDACTED)+ # ... while a changed visible field still is not.+ moved_item = {+ "url": "https://b.example",+ "api_key": REDACTED,+ "timeout": 30,+ }+ assert not _non_sentinel_fields_match(moved_item, stored_item, REDACTED)+++def test_values_equal_still_treats_bool_and_int_as_different():+ """The round-3 fix that must NOT regress: ``bool`` is an ``int``+ subclass, so a plain ``==`` calls ``1`` unchanged from a stored+ ``True`` and ``_resolve_container_secret_write``'s no-op check would+ silently DISCARD a genuine type change instead of persisting it.++ Loosening the numeric comparison for round-5 defect (2) had to keep+ this: ``bool`` is checked FIRST, before the numeric arm it would+ otherwise fall into.+ """+ from local_deep_research.web.routers.settings import (+ _resolve_container_secret_write,+ _values_equal,+ )++ assert not _values_equal(1, True)+ assert not _values_equal(True, 1)+ assert not _values_equal(0, False)+ assert not _values_equal(False, 0)+ assert not _values_equal(True, 1.0)+ assert not _values_equal(1.0, True)+ assert not _values_equal({"enabled": 1}, {"enabled": True})+ assert not _values_equal([{"enabled": 1}], [{"enabled": True}])+ # ... and a bool IS equal to the same bool.+ assert _values_equal(True, True)+ assert _values_equal({"enabled": False}, {"enabled": False})++ # End of the chain that actually matters: `{"enabled": 1}` over a+ # stored `{"enabled": True}` is a genuine EDIT, not a no-op, so the+ # merged container must be written rather than dropped.+ merged, is_noop, is_rejected = _resolve_container_secret_write(+ {"token": REDACTED, "enabled": 1},+ {"token": "s3cr3t-bool-arm", "enabled": True},+ REDACTED,+ )+ assert is_rejected is False+ assert is_noop is False, (+ "a bool -> int type change next to a restored secret was "+ "misreported as an untouched round-trip and would be discarded"+ )+ assert merged == {"token": "s3cr3t-bool-arm", "enabled": 1}+++def test_text_ui_element_json_string_sentinel_bypass_is_closed():+ """Defect (2) in the post-#6201 review: the JSON-STRING encoding of a+ masked container must be caught by the guards even under a+ "text"/"textarea" ui_element, not only "json".++ ``_coerced_for_guard`` only promoted a JSON-string value to a dict/list+ when ``coerce_setting_for_write`` did -- but for "text"/"textarea" (and+ "select"/"password"), that function's target type IS ``str``, so it+ NEVER produces a dict/list. A masked container submitted in its+ JSON-string form under one of those ui_elements therefore stayed a+ plain string, fell to the outer-key-gated string arm (not sensitive+ here), and was accepted untouched -- silently overwriting the stored+ dict with the literal string, e.g. ``'{"stop_token":"[REDACTED]"}'``+ (silent DATA LOSS, the sibling defect to (1)'s disclosure).+ """+ import json++ from local_deep_research.web.routers.settings import (+ _coerced_for_guard,+ _embeds_redaction_sentinel,+ _is_secret_empty_noop,+ _reconciled_container_value_for_write,+ )++ key = "llm.probe.model_kwargs"+ stored = {"stop_token": "s3cr3t-real-4420", "page_token": "old-value"}++ for ui_element in ("text", "textarea", "select"):+ # A pure round-trip, submitted in JSON-STRING form.+ roundtrip_str = json.dumps(+ {"stop_token": REDACTED, "page_token": "old-value"}+ )+ guard_rt = _coerced_for_guard(key, ui_element, roundtrip_str)+ assert isinstance(guard_rt, dict), (+ f"{ui_element}: JSON-string container not decoded for the guards"+ )+ assert _is_secret_empty_noop(key, ui_element, guard_rt, stored), (+ f"{ui_element}: JSON-string round-trip not recognized as a no-op"+ )+ assert not _embeds_redaction_sentinel(key, ui_element, guard_rt, stored)++ # A genuine edit, also submitted in JSON-STRING form: must merge,+ # not overwrite the stored dict with the literal masked string.+ edit_str = json.dumps(+ {"stop_token": REDACTED, "page_token": "new-value"}+ )+ guard_edit = _coerced_for_guard(key, ui_element, edit_str)+ assert isinstance(guard_edit, dict), (+ f"{ui_element}: JSON-string edit not decoded for the guards"+ )+ assert not _is_secret_empty_noop(key, ui_element, guard_edit, stored)+ assert not _embeds_redaction_sentinel(+ key, ui_element, guard_edit, stored+ )+ merged, is_reconciled = _reconciled_container_value_for_write(+ edit_str, guard_edit, stored+ )+ assert is_reconciled is True+ assert merged == {+ "stop_token": "s3cr3t-real-4420",+ "page_token": "new-value",+ }, f"{ui_element}: secret was clobbered instead of restored"++ # Control: an ordinary, non-JSON string is unaffected (no accidental+ # decode, still a plain scalar write).+ assert (+ _coerced_for_guard("app.some_text", "text", "just a plain value")+ == "just a plain value"+ )+++def test_list_of_dicts_permutation_does_not_rebind_secrets():+ """Defect (3) in the post-#6201 review: a same-length PERMUTATION of a+ list of dicts must not positionally rebind a restored secret to the+ WRONG entry.++ ``_merge_redacted_container`` walks a same-length list by ``zip()``+ position. Given stored ``[{url:a,api_key:K1},{url:b,api_key:K2}]``, a+ client that reorders the two entries and resubmits both with their+ ``api_key`` still masked would, before this fix, get K1 silently+ restored under ``b`` and K2 under ``a`` -- the WRONG secret bound to+ each url, not a rejection. The fix requires every visible (non-+ sentinel) field at an index to match the stored item at that same+ index before trusting the position; a permutation fails that check and+ is rejected instead.+ """+ from local_deep_research.web.routers.settings import (+ _embeds_redaction_sentinel,+ _merge_redacted_container,+ )++ key = "search.engine.web.probe.instances"+ stored = [+ {"url": "host-a.example.com", "api_key": "K1-real-secret"},+ {"url": "host-b.example.com", "api_key": "K2-real-secret"},+ ]++ # Same length, entries SWAPPED, both api_key leaves masked.+ permuted = [+ {"url": "host-b.example.com", "api_key": REDACTED},+ {"url": "host-a.example.com", "api_key": REDACTED},+ ]+ merged, rejected = _merge_redacted_container(permuted, stored, REDACTED)+ assert rejected is True, (+ "a same-length permutation must be rejected, not silently "+ "resolved by position"+ )+ assert _embeds_redaction_sentinel(key, None, permuted, stored)++ # Had this NOT been rejected, position-based restoration would have+ # bound K1 (host-a's real secret) under host-b and vice versa -- the+ # wrong secret under the wrong url. Not asserted directly (the write+ # is rejected, so `merged` is never persisted); this sanity check just+ # confirms the rejection isn't accidentally a no-op in disguise.+ assert merged != stored++ # CONTROL: an in-place round-trip (same positions, same urls) still+ # resolves correctly -- the fix must not break the ordinary case.+ in_place = [+ {"url": "host-a.example.com", "api_key": REDACTED},+ {"url": "host-b.example.com", "api_key": REDACTED},+ ]+ merged_ok, rejected_ok = _merge_redacted_container(+ in_place, stored, REDACTED+ )+ assert rejected_ok is False+ assert merged_ok == stored+++def test_list_of_dicts_rename_or_drop_field_does_not_rebind_secrets():+ """Follow-up to defect (3): the straight-swap permutation above is+ caught, but ``_non_sentinel_fields_match``'s dict branch only walked+ the SUBMITTED item's keys and skipped any key absent from the stored+ item -- it never required the stored item's visible keys to all be+ present in the submission. That means a client can bypass the+ permutation guard without ever "matching" on a renamed field: RENAME+ the visible field (old key vanishes, new key is skipped because it+ isn't in ``stored_value``), DROP it entirely (same effect), or do it+ in two separate writes that individually only ever touch known field+ names. Each shape below still rebinds K1 <-> K2 to the wrong url if+ the key-equality check in ``_non_sentinel_fields_match`` is removed+ (i.e. reverting to ``if sub_key not in stored_value: continue``).+ """+ from local_deep_research.web.routers.settings import (+ _merge_redacted_container,+ )++ stored = [+ {"url": "host-a.example.com", "api_key": "K1-real-secret"},+ {"url": "host-b.example.com", "api_key": "K2-real-secret"},+ ]++ # --- Shape 1: RENAME the visible field (url -> endpoint) -------------+ # The old key "url" disappears from the submission and the new key+ # "endpoint" isn't in `stored_value`, so a subset-only key walk finds+ # nothing to disprove the position and treats this as an in-place+ # edit -- letting the swap through under a different field name.+ renamed = [+ {"endpoint": "host-b.example.com", "api_key": REDACTED},+ {"endpoint": "host-a.example.com", "api_key": REDACTED},+ ]+ merged, rejected = _merge_redacted_container(renamed, stored, REDACTED)+ assert rejected is True, (+ "renaming the visible field must not bypass the permutation guard"+ )+ assert merged != [+ {"endpoint": "host-b.example.com", "api_key": "K1-real-secret"},+ {"endpoint": "host-a.example.com", "api_key": "K2-real-secret"},+ ], "the wrong secret must not be rebound to the wrong endpoint"++ # --- Shape 2: DROP the visible field entirely -------------------------+ # No renamed field at all -- just the masked secret, swapped in+ # position. Same bypass: the visible key set no longer matches, so+ # there is nothing left for a subset-only walk to compare.+ dropped = [{"api_key": REDACTED}, {"api_key": REDACTED}]+ merged_dropped, rejected_dropped = _merge_redacted_container(+ dropped, stored, REDACTED+ )+ assert rejected_dropped is True, (+ "dropping the visible field must not bypass the permutation guard "+ "(this is also exactly the setup for the two-step bypass below)"+ )++ # --- Shape 3: the same bypass split into two separate writes, using+ # only unmodified field names at every step (no renaming needed) -----+ # Step 1: submit both items with ONLY api_key visible (masked). If+ # this is wrongly accepted as a no-op-shaped edit, the stored rows+ # lose their "url" field entirely and become indistinguishable by+ # position.+ step1 = [{"api_key": REDACTED}, {"api_key": REDACTED}]+ merged1, rejected1 = _merge_redacted_container(step1, stored, REDACTED)+ assert rejected1 is True, (+ "step 1 of the two-step bypass (submitting only the secret field) "+ "must be rejected -- it would otherwise silently drop 'url' and "+ "set up step 2 to rebind the wrong secret"+ )+ # Even if step 1 were (wrongly) accepted, step 2 -- reintroducing+ # "url" with the entries swapped -- must independently be rejected+ # against whatever step 1 actually persisted. Simulate the worst case+ # where step 1's merged value (dropping "url") became the new stored+ # state, and confirm step 2 is still caught.+ worst_case_stored_after_step1 = [+ {"api_key": "K1-real-secret"},+ {"api_key": "K2-real-secret"},+ ]+ step2 = [+ {"api_key": REDACTED, "url": "host-b.example.com"},+ {"api_key": REDACTED, "url": "host-a.example.com"},+ ]+ merged2, rejected2 = _merge_redacted_container(+ step2, worst_case_stored_after_step1, REDACTED+ )+ assert rejected2 is True, (+ "step 2 of the two-step bypass (reintroducing 'url' on the swapped "+ "entries) must be rejected -- otherwise the wrong secret is bound "+ "to the wrong url across two otherwise-unremarkable writes"+ )+ assert merged2 != [+ {"api_key": "K1-real-secret", "url": "host-b.example.com"},+ {"api_key": "K2-real-secret", "url": "host-a.example.com"},+ ]++ # CONTROL: a genuine in-place edit that keeps the exact same key set+ # at each index must still be accepted -- the key-equality check must+ # not over-reject ordinary edits.+ in_place_edit = [+ {"url": "host-a.example.com", "api_key": REDACTED},+ {"url": "host-b.example.com", "api_key": REDACTED},+ ]+ merged_ok, rejected_ok = _merge_redacted_container(+ in_place_edit, stored, REDACTED+ )+ assert rejected_ok is False+ assert merged_ok == stored+++def test_single_element_list_sibling_edit_is_not_rejected():+ """Recordable (5) in the post-#6201 review: the list branch's sibling-+ match gate exists only to catch a same-length REORDER (see+ ``test_list_of_dicts_permutation_does_not_rebind_secrets``), but it+ was applied unconditionally, including to a single-element list.+ A list of one item has no other position for that item to have been+ reordered from or to, so an ordinary sibling edit next to a masked+ secret in a length-1 list must merge like the single-object dict case+ does, not be rejected as if it were indistinguishable from a reorder.+ """+ from local_deep_research.web.routers.settings import (+ _merge_redacted_container,+ )++ stored = [{"url": "host-a.example.com", "api_key": "K1-real-secret"}]++ # Sibling field edited, the only secret leaf still masked.+ edited = [{"url": "host-a-renamed.example.com", "api_key": REDACTED}]+ merged, rejected = _merge_redacted_container(edited, stored, REDACTED)+ assert rejected is False, (+ "a sibling edit in a single-element list has no reorder to be "+ "confused with and must not be rejected"+ )+ assert merged == [+ {"url": "host-a-renamed.example.com", "api_key": "K1-real-secret"}+ ]++ # CONTROL: a genuine pure round-trip (no edit) still resolves the+ # secret and is a no-op.+ roundtrip = [{"url": "host-a.example.com", "api_key": REDACTED}]+ merged_rt, rejected_rt = _merge_redacted_container(+ roundtrip, stored, REDACTED+ )+ assert rejected_rt is False+ assert merged_rt == stored+++def test_container_no_op_check_is_type_aware():+ """Defect (5) in the post-#6201 review: the merged-vs-stored no-op+ comparison must be type-aware. Plain ``==`` treats ``1 == True`` as+ equal, so ``{"enabled": 1}`` submitted over a stored+ ``{"enabled": True, ...}`` would look byte-for-byte identical and the+ genuine type-changing edit would be silently discarded as a no-op.+ """+ from local_deep_research.web.routers.settings import (+ _is_secret_empty_noop,+ _reconciled_container_value_for_write,+ )++ key = "llm.probe.model_kwargs"+ stored = {"enabled": True, "api_key": "s3cr3t-real-type-aware"}+ type_changed = {"enabled": 1, "api_key": REDACTED}++ assert not _is_secret_empty_noop(key, None, type_changed, stored), (+ "1 vs True must not be treated as an unchanged value"+ )+ merged, is_reconciled = _reconciled_container_value_for_write(+ type_changed, type_changed, stored+ )+ assert is_reconciled is True+ assert merged == {"enabled": 1, "api_key": "s3cr3t-real-type-aware"}+ assert type(merged["enabled"]) is int++ # CONTROL: a true round-trip (identical types) is still a no-op.+ true_roundtrip = {"enabled": True, "api_key": REDACTED}+ assert _is_secret_empty_noop(key, None, true_roundtrip, stored)+++def test_sensitive_multiselect_bare_sentinel_roundtrip_stays_a_noop():+ """Defect (6) in the post-#6201 review: a bare "[REDACTED]" string+ round-tripped for a sensitive ``multiselect`` setting must stay a+ 200 no-op regardless of the stored list's length.++ ``redact_value`` masks an EXACT-match sensitive setting (e.g. a key+ literally named ``access_token``) to the bare sentinel STRING even+ when its real value is a list -- the exact/password arm returns+ ``redaction_text`` outright for any non-empty value, container or not.+ A client that GETs and saves that field back untouched resubmits the+ bare string. ``_coerced_for_guard`` used to run it through+ ``coerce_setting_for_write("multiselect", ...)``, whose+ ``_parse_multiselect`` comma-separated fallback wraps an un-quoted,+ comma-less string into a ONE-ELEMENT LIST (``["[REDACTED]"]``) -- which+ then looks like a malformed/rejected container write (a length+ mismatch) against any stored list whose length isn't 1, turning what+ used to be an idempotent 200 into a 400.+ """+ from local_deep_research.web.routers.settings import (+ _coerced_for_guard,+ _embeds_redaction_sentinel,+ _is_secret_empty_noop,+ coerce_setting_for_write,+ )++ key = "llm.probe.access_token" # exact-match sensitive leaf+ stored = ["tok-real-1", "tok-real-2", "tok-real-3"] # length != 1++ guard_value = _coerced_for_guard(key, "multiselect", REDACTED)+ assert guard_value == REDACTED, (+ "the bare sentinel must not be mangled into a list before the "+ "guards see it"+ )+ assert _is_secret_empty_noop(key, "multiselect", guard_value, stored)+ assert not _embeds_redaction_sentinel(+ key, "multiselect", guard_value, stored+ )++ # REGRESSION PROOF: the raw (un-guarded) coercion is exactly the+ # one-element-list mangling that used to reach the guards and cause+ # the false rejection.+ raw_coerced = coerce_setting_for_write(+ key=key, value=REDACTED, ui_element="multiselect"+ )+ assert raw_coerced == [REDACTED]+ assert not _is_secret_empty_noop(key, "multiselect", raw_coerced, stored)+++def test_policy_audit_line_cannot_carry_a_credential():+ """The ``policy.*`` audit line records old/new for FREE-FORM JSON keys,+ so it must not interpolate their values in plaintext.++ Round 6 left ``SettingsManager.set_setting``'s audit line logging+ ``old={}``/``new={}`` raw, on the stated grounds that its scope is+ "``policy.*`` plus three keys holding booleans and a hostname list".+ That is not what the code does. ``_is_policy_setting`` PREFIX-matches+ ``policy.`` rather than consulting an allowlist, and three keys already+ in scope ship as free-form editable JSON with no item schema:+ ``policy.trusted_search_engines``,+ ``policy.trusted_inference_providers`` and+ ``llm.allowed_local_hostnames`` (all ``ui_element="json"``,+ ``editable=True``, default ``[]``). Their egress validator+ ``continue``s past non-``str`` entries, so a list of dicts carrying an+ API key is accepted, reaches ``set_setting``, and used to be written to+ the log in plaintext at WARNING -- a value-logging path that never went+ through ``get_typed_setting_value``, which is what round 6's+ root-cause framing assumed covered every such path.++ The audit line still records old/new; it records the value's SHAPE+ (type, length/entry count), never its content, and never a+ deterministic fingerprint of its content (#6201 rounds 7-8).+ """+ from local_deep_research.settings.manager import (+ _is_policy_setting,+ _policy_audit_allowed_values,+ _policy_audit_value,)++ # The scope really is a prefix, not an allowlist.+ assert _is_policy_setting("policy.trusted_search_engines")+ assert _is_policy_setting("policy.some_future_key")+ assert _is_policy_setting("llm.allowed_local_hostnames")+ assert not _is_policy_setting("llm.temperature")++ secret = "sk-live-must-not-reach-the-log"+ leaky_list = [{"name": "x", "api_key": secret}]+ rendered = _policy_audit_value(leaky_list)+ assert secret not in rendered+ assert "api_key" not in rendered+ assert rendered == "<list[1]>"++ # A free-form STRING value is de-valued the same way -- a+ # ``policy.*`` key created through the API has no fixed vocabulary.+ assert secret not in _policy_audit_value(secret)+ assert _policy_audit_value(secret) == f"<str[{len(secret)}]>"++ # NO DICTIONARY ORACLE (round 8): the rendering carries structural+ # metadata only -- type, length for a string, entry count for a+ # container -- and NO token derived from the value's content. An+ # earlier version logged a truncated SHA-256 of the canonical JSON,+ # and an offline candidate list recovered a common password from+ # that prefix (probe: pr-6201-policy-digest-probe.txt). Two distinct+ # same-shape values must therefore render IDENTICALLY: that is+ # exactly the property that makes the line useless for confirming a+ # guessed credential.+ assert "password123" not in _policy_audit_value("password123")+ assert _policy_audit_value("password123") == _policy_audit_value(+ "swordfish42"+ )+ assert _policy_audit_value("password123") == "<str[11]>"+ assert _policy_audit_value(leaky_list) == _policy_audit_value(+ [{"api_key": secret, "name": "x"}]+ )+ # Different CONTENT, same shape: indistinguishable in the log. The+ # coarse "did it change" signal survives at the shape level only+ # (see the count assertion below) -- the tradeoff that kills the+ # oracle.+ assert _policy_audit_value(leaky_list) == _policy_audit_value(+ [{"name": "x", "api_key": "sk-live-something-else"}]+ )+ assert _policy_audit_value(leaky_list) != _policy_audit_value(+ [+ {"name": "x", "api_key": "sk-live-something-else"},+ {"name": "y", "api_key": "sk-live-another-one"},+ ]+ )++ # Plaintext is KEPT where it is proven safe by a check, not a comment:+ # values with no string content at all, and a string drawn from the+ # key's own shipped ``select`` vocabulary (``policy.egress_scope``).+ assert _policy_audit_value(True) == "True"+ assert _policy_audit_value(False) == "False"+ assert _policy_audit_value(None) == "None"+ assert _policy_audit_value(7) == "7"++ scope_options = _policy_audit_allowed_values(+ {+ "ui_element": "select",+ "options": [{"value": "adaptive"}, {"value": "strict"}],+ }+ )+ assert scope_options == ["adaptive", "strict"]+ assert _policy_audit_value("adaptive", scope_options) == "'adaptive'"+ # ...but a string that is NOT in the vocabulary is still de-valued,+ # so a rogue value cannot ride in on a select-typed key.+ assert secret not in _policy_audit_value(secret, scope_options)++ # A ``json`` row has no vocabulary to vouch for anything.+ assert (+ _policy_audit_allowed_values({"ui_element": "json", "options": None})+ is None+ )+ assert _policy_audit_allowed_values(None) is None+++def test_shipped_policy_audit_keys_include_free_form_json_containers():+ """Pins the premise of the test above against the shipped defaults: the+ ``policy.*`` audit scope is not "booleans and a hostname list"."""+ import json as _json+ from pathlib import Path++ import local_deep_research.defaults as _defaults+ from local_deep_research.settings.manager import _is_policy_setting++ defaults_path = Path(_defaults.__file__).parent / "default_settings.json"+ shipped = _json.loads(defaults_path.read_text(encoding="utf-8"))++ free_form = {+ key: meta+ for key, meta in shipped.items()+ if _is_policy_setting(key)+ and meta.get("ui_element") == "json"+ and meta.get("editable") is True+ }+ assert set(free_form) == {+ "policy.trusted_search_engines",+ "policy.trusted_inference_providers",+ "llm.allowed_local_hostnames",+ }, (+ "the policy audit scope's free-form JSON keys changed; re-check "+ "_policy_audit_value's rationale"+ )+++def test_set_setting_policy_audit_sink_never_logs_the_values():+ """The ``set_setting`` call site -- not just the helper -- must render+ old/new through ``_policy_audit_value`` (round 8 / B2: the helper-only+ tests above passed even with the call site reverted to raw old/new).++ Drives the REAL sink: a ``SettingsManager`` on an in-memory SQLite+ session, two ``set_setting`` calls on a ``policy.*`` key -- the+ second one changes a stored secret-bearing list, so the audit line+ has both an ``old=`` and a ``new=`` that carry distinct secrets --+ and the second call uses ``commit=False`` to pin the PR's own claim+ that the audit line fires on the bulk (``commit=False``) routes too.+ The key is deliberately NOT in the shipped defaults, so the+ ``default_settings.get(key)`` lookup at the call site finds no+ metadata and no ``select`` vocabulary can vouch for anything.++ EXACT REVERT THIS CATCHES: in ``SettingsManager.set_setting``,+ replacing the two ``_policy_audit_value(old_value/_audit_options)`` /+ ``_policy_audit_value(value/_audit_options)`` arguments of the+ ``logger.bind(policy_audit=True).warning(...)`` call with the raw+ ``old_value`` / ``value`` -- the repr of both secret-bearing lists+ (sub-key names included) then reaches the captured log and both the+ non-presence and the rendering assertions below fail.++ The POSITIVE CONTROL is not optional: the package disables its own+ loguru namespace at import, so "no secret in the captured text"+ passes with nothing captured at all. The control line is the audit+ WARNING itself, which must name the key.+ """+ from sqlalchemy import create_engine+ from sqlalchemy.orm import sessionmaker++ from local_deep_research.database.models import Base+ from local_deep_research.settings.manager import SettingsManager++ key = "policy.probe_audit_sink_round8"+ old_secret = "sk-live-old-must-not-reach-the-log-8841"+ new_secret = "sk-live-new-must-not-reach-the-log-0417"++ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()+ try:+ manager = SettingsManager(db_session=session)+ assert manager.set_setting(key, [{"name": "x", "api_key": old_secret}])++ with _captured_audit_warnings() as lines:+ # commit=False: the bulk-save shape. The audit line sits+ # outside ``if commit:`` and must still fire.+ assert manager.set_setting(+ key, [{"name": "x", "api_key": new_secret}], commit=False+ )++ # POSITIVE CONTROL: the audit line was emitted, reached the+ # sink, and names the key.+ audit_lines = [ln for ln in lines if "policy setting changed" in ln]+ assert any(key in ln for ln in audit_lines), (+ "log capture is not wired up, or the policy audit line no "+ f"longer fires on the commit=False route (captured {lines!r})"+ )++ # Neither the old nor the new secret -- nor the container's+ # sub-key names -- may appear anywhere in the captured text.+ for forbidden in (old_secret, new_secret, "api_key"):+ leaked = [ln for ln in lines if forbidden in ln]+ assert not leaked, (+ f"{forbidden!r} reached the log: {leaked[0][:300]}"+ )++ # Machine-observable rendering pin: old and new are structural+ # only. A same-length string with different content, or a+ # same-shape list, is indistinguishable here -- that is the+ # anti-oracle property itself.+ the_line = next(ln for ln in audit_lines if key in ln)+ assert "old=<list[1]> new=<list[1]>" in the_line, the_line[:300]+ finally:+ session.close()+ engine.dispose()+++@contextmanager+def _captured_audit_warnings():+ """Collect every rendered WARNING-or-worse loguru line emitted inside+ the block.++ The local twin of ``_captured_warnings`` in+ ``test_settings_egress_and_secrets_fastapi.py``: the package calls+ ``logger.disable("local_deep_research")`` at import, so without the+ explicit enable the audit line never reaches any sink and a+ "nothing leaked" assertion would pass vacuously. Same+ enable/add/remove/disable idiom; ``disable`` in the ``finally``+ restores the package's own default state.+ """+ from loguru import logger++ rendered: list[str] = []++ def _sink(message):+ rendered.append(str(message))++ logger.enable("local_deep_research")+ sink_id = logger.add(_sink, level="WARNING", diagnose=False)+ try:+ yield rendered+ finally:+ logger.remove(sink_id)+ logger.disable("local_deep_research")+++def test_sensitive_multiselect_spliced_sentinel_is_rejected_not_merged():+ """A SPLICED sentinel on a sensitive ``multiselect`` must be a hard+ 400, not a 200 that silently destroys the stored items.++ ``_coerced_for_guard`` special-cased only the BARE sentinel. A spliced+ one ("[REDACTED],new" -- what a stale client that rendered the mask and+ had a value appended submits) still went through+ ``coerce_setting_for_write(..., "multiselect")`` ->+ ``_parse_multiselect``, whose comma-split fallback fires because the+ string isn't valid JSON. That turns the corrupted SCALAR into+ ``["[REDACTED]", "new"]``, a list whose first item is now an EXACT+ sentinel match -- so the container arm merges it positionally against+ the stored list and persists ``["A", "new"]`` with a 200, DROPPING the+ stored ``"B"`` the client never resent. The "contains the sentinel but+ is not equal to it => hard 400" rule that+ ``_merge_redacted_container``'s own docstring states (and that the+ scalar arm applies to every other ui_element) never fired, because the+ split manufactured the exact match out of a corrupted edit. Silent+ data loss on a sensitive setting, and length-dependent: three items+ submitted against two stored happened to 400 on the length check,+ which is why it hid (#6201 round 7).+ """+ from local_deep_research.web.routers.settings import (+ _coerced_for_guard,+ _embeds_redaction_sentinel,+ _is_secret_empty_noop,+ _resolve_container_secret_write,+ coerce_setting_for_write,+ )++ key = "llm.probe.access_token" # exact-match sensitive leaf+ stored = ["tok-real-1", "tok-real-2"] # same length as the split++ for spliced in (f"{REDACTED},new", f"new,{REDACTED}"):+ guard_value = _coerced_for_guard(key, "multiselect", spliced)+ assert guard_value == spliced, (+ "a spliced sentinel must reach the guards AS A STRING; "+ "splitting it on commas manufactures an exact-match list item"+ )+ assert not _is_secret_empty_noop(+ key, "multiselect", guard_value, stored+ )+ assert _embeds_redaction_sentinel(+ key, "multiselect", guard_value, stored+ )++ # REGRESSION PROOF: the raw (un-guarded) coercion is exactly the split+ # that used to reach the container arm, and the container arm then+ # merges it into a 200 that loses "tok-real-2".+ raw_coerced = coerce_setting_for_write(+ key=key, value=f"{REDACTED},new", ui_element="multiselect"+ )+ assert raw_coerced == [REDACTED, "new"]+ merged, is_noop, is_rejected = _resolve_container_secret_write(+ raw_coerced, stored, REDACTED+ )+ assert (is_noop, is_rejected) == (False, False)+ assert merged == ["tok-real-1", "new"] # "tok-real-2" destroyed++ # CONTROL: the BARE sentinel round-trip stays the 200 no-op the+ # sibling test above pins -- this narrowing must not turn it into a+ # 400, and an ordinary multiselect edit must still coerce to a list.+ bare = _coerced_for_guard(key, "multiselect", REDACTED)+ assert bare == REDACTED+ assert _is_secret_empty_noop(key, "multiselect", bare, stored)+ assert not _embeds_redaction_sentinel(key, "multiselect", bare, stored)+ assert _coerced_for_guard(key, "multiselect", "alpha,beta") == [+ "alpha",+ "beta",+ ]+++def test_depth_cap_rejection_has_its_own_message_not_the_sentinel_one():+ """A payload nested past ``_MAX_CONTAINER_DEPTH`` is rejected -- it+ can't be proven free of the sentinel that deep -- but when it+ genuinely contains none, the 400 must say so is nested too deeply, not+ claim it "contains the redaction placeholder" (which+ ``_redaction_sentinel_error`` -- reused unconditionally for every+ dict/list rejection before this fix -- would say regardless of+ whether a sentinel is anywhere in it).+ """+ from local_deep_research.web.routers.settings import (+ _MAX_CONTAINER_DEPTH,+ _container_rejection_error,+ _embeds_redaction_sentinel,+ _redaction_sentinel_error,+ )++ def nest(n, leaf="ordinary-value"):+ value = leaf+ for _ in range(n):+ value = {"k": value}+ return value++ too_deep_no_sentinel = nest(_MAX_CONTAINER_DEPTH + 2)+ stored = nest(_MAX_CONTAINER_DEPTH + 2)++ # Still rejected -- can't be proven safe that deep -- but for a+ # different reason than the sentinel case.assert _embeds_redaction_sentinel(- BROADENED_ARM_KEY, None, float_for_int, stored+ BROADENED_ARM_KEY, None, too_deep_no_sentinel, stored+ )+ message = _container_rejection_error(None, too_deep_no_sentinel)+ assert "nested too deeply" in message+ assert DataSanitizer.REDACTION_TEXT not in message+ assert message != _redaction_sentinel_error(None)++ # A shallow, ordinary sentinel-bearing container keeps the usual+ # message.+ ordinary_reject_message = _container_rejection_error(+ None, {"token": REDACTED, "port": 19531})+ assert ordinary_reject_message == _redaction_sentinel_error(None)+++def test_depth_cap_covers_the_list_positional_gate_not_just_the_dict_branch():+ """The depth cap must hold on the LIST branch too, where an uncapped+ walker used to reach a real ``RecursionError`` -> HTTP 500.++ ``_merge_redacted_container``'s dict branch caps itself, so a plain+ over-deep dict has always been rejected cleanly (its sibling test+ above pins that). Its LIST branch is different: before asking+ ``_merge_redacted_container`` to recurse, it consults+ ``_non_sentinel_fields_match`` -- the positional-rebinding gate -- and+ that helper (plus ``_values_equal``, which it bottoms out in) were the+ last two in the merge path with NO depth parameter and no cap, and the+ list branch called the gate with no depth argument at all. Nothing+ stops the gate being reached for a pathological item either:+ ``_container_embeds_sentinel`` answers True unconditionally past its+ own cap, so the gate is consulted for EVERY too-deep list item, and no+ sentinel needs to be present anywhere for that to happen.++ A ~7 KB list whose first item nested past the interpreter's recursion+ limit against a stored list of the same shape therefore raised an+ uncaught ``RecursionError``, which the write routes' broad+ ``except Exception`` turned into an opaque 500 -- falsifying both+ ``_MAX_CONTAINER_DEPTH``'s own comment ("instead of surfacing as an+ opaque 500") and this feature's changelog claim of a clean 400. It is+ also a regression against the pre-#6201 behaviour, where the container+ arm sat BEHIND ``is_sensitive_setting`` and a non-sensitive key like+ ``search.favorites`` never reached these helpers at all; moving the+ container arm in front of that gate exposed the uncapped walk to every+ dict/list write (#6201 round 7).++ Revert either cap (drop the ``_depth`` parameter/guard from+ ``_non_sentinel_fields_match`` or ``_values_equal``, or stop threading+ ``_depth + 1`` from the list branch) and the first assertion below+ raises ``RecursionError`` instead of returning a bool.+ """+ import sys- # Same type and value stays a genuine no-op.- untouched = {"token": REDACTED, "mode": 1}- assert _is_secret_empty_noop(BROADENED_ARM_KEY, None, untouched, stored)+ from local_deep_research.web.routers.settings import (+ _container_rejection_error,+ _embeds_redaction_sentinel,+ _is_secret_empty_noop,+ _non_sentinel_fields_match,+ _values_equal,+ )++ def nest(n, leaf):+ value = leaf+ for _ in range(n):+ value = {"k": value}+ return value++ # Deeper than the interpreter can recurse, so an uncapped walker+ # cannot answer at all -- while ``json.loads`` happily parses this+ # from a request body (it does not consume a Python frame per level)+ # and the request-size middleware only caps BYTES, of which this is a+ # few kilobytes.+ depth = sys.getrecursionlimit() + 500+ submitted = [nest(depth, REDACTED), {"ordinary": 1}]+ stored = [nest(depth, "real-secret"), {"ordinary": 1}]++ # Both write guards must ANSWER -- a clean 400 -- rather than raise.+ assert (+ _is_secret_empty_noop(BROADENED_ARM_KEY, "json", submitted, stored)+ is False+ )+ assert (+ _embeds_redaction_sentinel(BROADENED_ARM_KEY, "json", submitted, stored)+ is True+ )+ assert "nested too deeply" in _container_rejection_error("json", submitted)++ # The two helpers the list branch reaches must terminate on their own,+ # fail-closed: "cannot prove this position is unchanged" / "cannot+ # prove these are equal", never a stack overflow.+ assert (+ _non_sentinel_fields_match(+ nest(depth, REDACTED), nest(depth, "real-secret"), REDACTED+ )+ is False+ )+ assert _values_equal(nest(depth, "same"), nest(depth, "same")) is False++ # CONTROL: the cap must not have swallowed ordinary-depth lists --+ # a normal positional round-trip is still recognised as a no-op.+ shallow = [+ {"url": "a", "api_key": REDACTED},+ {"url": "b", "api_key": REDACTED},+ ]+ shallow_stored = [+ {"url": "a", "api_key": "K1-real"},+ {"url": "b", "api_key": "K2-real"},+ ]+ assert _is_secret_empty_noop(+ BROADENED_ARM_KEY, "json", shallow, shallow_stored+ )assert not _embeds_redaction_sentinel(- BROADENED_ARM_KEY, None, untouched, stored+ BROADENED_ARM_KEY, "json", shallow, shallow_stored)+def test_container_boolean_edit_is_saved_and_browser_numbers_round_trip():+ """Keep the boolean/integer distinction while accepting JSON number normalization."""+ from local_deep_research.web.routers.settings import (+ _embeds_redaction_sentinel,+ _is_secret_empty_noop,+ _reconciled_container_value_for_write,+ )++ stored = {"token": "s", "mode": 1}+ bool_for_int = {"token": REDACTED, "mode": True}+ assert not _is_secret_empty_noop(+ BROADENED_ARM_KEY, None, bool_for_int, stored+ )+ assert not _embeds_redaction_sentinel(+ BROADENED_ARM_KEY, None, bool_for_int, stored+ )+ merged, reconciled = _reconciled_container_value_for_write(+ bool_for_int, bool_for_int, stored+ )+ assert reconciled+ assert merged["mode"] is True+ assert merged["token"] == "s"++ # JSON.stringify cannot preserve the Python int/float distinction.+ # These equivalent numeric values are an unchanged browser round-trip.+ for mode in (1, 1.0):+ untouched = {"token": REDACTED, "mode": mode}+ assert _is_secret_empty_noop(BROADENED_ARM_KEY, None, untouched, stored)+ assert not _embeds_redaction_sentinel(+ BROADENED_ARM_KEY, None, untouched, stored+ )++def test_container_sentinel_on_create_has_no_noop_exemption():"""Creation has no prior stored value, so unlike the update path, eventhe pure round-trip shape (every leaf exactly the sentinel) cannot meandiff --git a/tests/settings/test_import_settings_validation.py b/tests/settings/test_import_settings_validation.pyindex 3a20f6faa8..69ad634920 100644--- a/tests/settings/test_import_settings_validation.py+++ b/tests/settings/test_import_settings_validation.py@@ -516,3 +516,89 @@ class TestUnknownUiElementImport:assert returned == "the_default"assert "Got unknown type" in loguru_caplog.text+ assert returned == "the_default"+ assert "Got unknown type" in loguru_caplog.text+++class TestImportSkipWarningNeverLogsValue:+ """The invalid-import skip WARNING must not interpolate the value.++ #6201 changed this sink (``SettingsManager.import_settings``) from+ logging the raw ``setting_values.get('value')`` to logging only its+ type name. Round 8 / B3: that change had NO direct regression test+ on this call path, so restoring the raw value passed every test in+ this file. An imported value is exactly as plausible a secret+ carrier as a stored one (a pre-upgrade export can carry an API key+ under any key name), and the skip line fires at WARNING on every+ rejected entry.++ EXACT REVERT THIS CATCHES: restoring+ ``logger.warning("Skipping import of setting {!r}: value {!r} is "+ "invalid under the current defaults schema - {}", key,+ "setting_values.get('value'), invalid_reason)`` in+ ``settings/manager.py::import_settings`` -- the repr of the secret+ then reaches the captured log.++ The POSITIVE CONTROL is not optional (the package disables its own+ loguru namespace at import): the skip WARNING itself, naming the+ key, is the control line.+ """++ KEY = "app.probe_import_sink_round8"+ META = {+ "value": "adaptive",+ "type": "APP",+ "name": "Probe Import Sink",+ "ui_element": "select",+ "options": [{"value": "adaptive"}, {"value": "strict"}],+ }++ @pytest.fixture+ def session(self):+ from sqlalchemy import create_engine+ from sqlalchemy.orm import sessionmaker++ from local_deep_research.database.models import Base++ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ Session = sessionmaker(bind=engine)+ session = Session()+ yield session+ session.close()+ engine.dispose()++ def test_rejected_secret_value_never_logged(self, session, loguru_caplog):+ from local_deep_research.database.models import Setting+ from local_deep_research.settings.manager import SettingsManager++ secret = "sk-live-import-must-not-reach-the-log-6201"+ manager = SettingsManager(db_session=session)+ manager.default_settings = {+ **manager.default_settings,+ self.KEY: dict(self.META),+ }++ with loguru_caplog.at_level("WARNING"):+ manager.import_settings(+ {self.KEY: {**self.META, "value": secret}},+ overwrite=True,+ )++ # POSITIVE CONTROL: the skip fired, reached the sink, and names+ # the key (the schema reason is built from the defaults metadata,+ # never from the imported value).+ assert "Skipping import of setting" in loguru_caplog.text+ assert self.KEY in loguru_caplog.text++ # The value itself -- a distinct secret fixture -- must not+ # appear anywhere in the captured text.+ assert secret not in loguru_caplog.text++ # The line still carries the kept diagnostic: the value's TYPE+ # name, so a bad row stays diagnosable without disclosure.+ assert "str" in loguru_caplog.text++ # Behavior pin: a rejected entry is skipped, not stored.+ stored = session.query(Setting).filter(Setting.key == self.KEY).first()+ assert stored is None