Skip to content

~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.

security: normalize invisible/whitespace padding in setting-key leaf before redaction (#5043)

LearningCircuit6e804ad3fbfa
diff --git a/changelog.d/5043.security.md b/changelog.d/5043.security.md
new file mode 100644
index 0000000000..9426f5396d
--- /dev/null
+++ b/changelog.d/5043.security.md
@@ -0,0 +1 @@
+Setting-secret detection now applies best-effort normalization to a key's last segment before matching — stripping surrounding whitespace and removing non-printable/default-ignorable characters plus known printable blanks — so padded keys such as `llm.openai.api_key ` or keys carrying zero-width/tag/blank characters are recognized as secrets and redacted by `GET /settings/api/bulk` instead of shipped in the clear.
diff --git a/src/local_deep_research/security/data_sanitizer.py b/src/local_deep_research/security/data_sanitizer.py
index fd6458fda2..e28f6b08fd 100644
--- a/src/local_deep_research/security/data_sanitizer.py
+++ b/src/local_deep_research/security/data_sanitizer.py
@@ -18,6 +18,58 @@ from typing import Any, Set
# cannot drift from what the redactor actually emits.
REDACTION_TEXT = "[REDACTED]"
+# Unicode 16.0 DerivedCoreProperties.txt, Default_Ignorable_Code_Point.
+# Most Unicode Default_Ignorable_Code_Point characters are non-printable and
+# are removed by str.isprintable(). These exceptions are printable combining
+# marks or letter-category fillers, so list them explicitly. Do not drop Mn as
+# a category: ordinary combining marks are visible parts of legitimate names.
+_PRINTABLE_DEFAULT_IGNORABLES = (
+ frozenset({0x034F}) # COMBINING GRAPHEME JOINER
+ | frozenset(range(0x115F, 0x1161)) # Hangul fillers
+ | frozenset(range(0x17B4, 0x17B6)) # Khmer inherent vowels
+ | frozenset(range(0x180B, 0x1810)) # Mongolian variation separators
+ | frozenset({0x3164, 0xFFA0}) # Hangul fillers
+ | frozenset(range(0xFE00, 0xFE10)) # Variation Selectors
+ | frozenset(range(0xE0100, 0xE01F0)) # Variation Selectors Supplement
+)
+
+# Printable characters that Unicode specifies as rendering blank but that are
+# not default ignorables. They pass str.isprintable() and setting-key validation,
+# so they can otherwise disguise a sensitive leaf in the bulk settings endpoint.
+_PRINTABLE_BLANKS = frozenset(
+ {
+ 0x2800, # BRAILLE PATTERN BLANK
+ 0x13441, # EGYPTIAN HIEROGLYPH FULL BLANK
+ 0x13442, # EGYPTIAN HIEROGLYPH HALF BLANK
+ 0x1D159, # MUSICAL SYMBOL NULL NOTEHEAD
+ }
+)
+
+
+def _visible_leaf(key: str) -> str:
+ """The key's last dotted segment, normalized for the sensitive-name check.
+
+ Defense in depth for the bulk-settings GET, which lacks the
+ authoritative ``ui_element == "password"`` signal and falls back to the key
+ name. Drops non-printable chars (control, format \u2014 zero-width/BOM/bidi/tag
+ chars/soft hyphen \u2014 and non-ASCII spaces) plus printable Unicode default
+ ignorables (variation selectors, combining grapheme joiner, and fillers)
+ and explicitly known printable blank characters, then strips ASCII space
+ and lowercases. Ordinary visible combining marks are retained. This
+ intentionally fails closed: removing invisible padding can collapse a
+ distinct key onto a sensitive name and over-redact its value, which is
+ safer than exposing a potentially disguised secret.
+ """
+ leaf = key.rsplit(".", 1)[-1]
+ leaf = "".join(
+ ch
+ for ch in leaf
+ if ch.isprintable()
+ and ord(ch) not in _PRINTABLE_DEFAULT_IGNORABLES
+ and ord(ch) not in _PRINTABLE_BLANKS
+ )
+ return leaf.strip().lower()
+
class DataSanitizer:
"""Utility class for removing sensitive information from data structures."""
@@ -71,7 +123,13 @@ class DataSanitizer:
k.lower()
for k in (sensitive_keys or DataSanitizer.DEFAULT_SENSITIVE_KEYS)
}
- return key.rsplit(".", 1)[-1].lower() in sens
+ # _visible_leaf normalizes away invisible/whitespace padding so a key
+ # like "api_key " or "api_key<zero-width>" still matches (see its
+ # docstring). Keep the raw-leaf match as well: callers may provide a
+ # custom sensitive name containing one of those characters, and an
+ # exact match must remain sensitive for backward compatibility.
+ raw_leaf = key.rsplit(".", 1)[-1].lower()
+ return raw_leaf in sens or _visible_leaf(key) in sens
@staticmethod
def redact_value(
diff --git a/tests/security/test_bulk_secret_name_coverage.py b/tests/security/test_bulk_secret_name_coverage.py
index b296907c3e..99bc1cd39f 100644
--- a/tests/security/test_bulk_secret_name_coverage.py
+++ b/tests/security/test_bulk_secret_name_coverage.py
@@ -42,3 +42,39 @@ def test_bulk_get_redacts_named_secret(leaf):
# mirror GET /settings/api/bulk: get_setting(key) then redact_value(key, None, value)
shipped = DataSanitizer.redact_value(key, None, manager.get_setting(key))
assert shipped == DataSanitizer.REDACTION_TEXT
+
+
+def test_bulk_get_redacts_named_secret_in_subtree():
+ """A subtree request (keys[]=integrations.oauth) must redact a nested
+ non-classic secret while keeping non-secret siblings — pins the added
+ names composing with redact_value's subtree recursion (#5028)."""
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+ session.add_all(
+ [
+ Setting(
+ key="integrations.oauth.client_secret",
+ value="topsecret-value",
+ type="app",
+ name="cs",
+ ui_element="password",
+ ),
+ Setting(
+ key="integrations.oauth.client_id",
+ value="public-id-123",
+ type="app",
+ name="cid",
+ ui_element="text",
+ ),
+ ]
+ )
+ session.commit()
+ manager = SettingsManager(db_session=session)
+
+ shipped = DataSanitizer.redact_value(
+ "integrations.oauth", None, manager.get_setting("integrations.oauth")
+ )
+ assert "topsecret-value" not in str(shipped)
+ assert shipped["client_secret"] == DataSanitizer.REDACTION_TEXT
+ assert shipped["client_id"] == "public-id-123"
diff --git a/tests/security/test_data_sanitizer.py b/tests/security/test_data_sanitizer.py
index 199327c0a2..e35aea189e 100644
--- a/tests/security/test_data_sanitizer.py
+++ b/tests/security/test_data_sanitizer.py
@@ -318,6 +318,92 @@ class TestExpandedSecretLeafNames:
assert DataSanitizer.redact_value(key, None, "value") == "value"
+class TestSensitiveLeafNormalization:
+ """A key whose leaf is padded with whitespace or a zero-width/invisible
+ char must still be recognized as a secret (fail closed), not slip past the
+ redactor.
+ """
+
+ def test_surrounding_whitespace_secret_is_sensitive(self):
+ # space (leading/trailing), tab, newline
+ for key in (
+ "llm.openai.api_key ",
+ "llm.openai. api_key",
+ "llm.openai.api_key" + chr(9),
+ "llm.openai.api_key" + chr(10),
+ ):
+ assert DataSanitizer.is_sensitive_setting(key), repr(key)
+ assert (
+ DataSanitizer.redact_value(key, None, "sk-x")
+ == DataSanitizer.REDACTION_TEXT
+ )
+
+ def test_invisible_padded_secret_is_sensitive(self):
+ # Padding across the invisible-char families, trailing and interleaved.
+ # The non-space chars (zero-width, control, tag chars, ...) pass
+ # is_valid_setting_key so a padded top-level key is creatable; NBSP is
+ # str.isspace() so it's write-rejected at top level but still reaches
+ # redaction as a nested JSON-value dict key.
+ pads = [
+ chr(0x200B), # zero-width space
+ chr(0xFEFF), # BOM
+ chr(0x7F), # C0 (DEL) control char
+ chr(0x0080), # C1 control char
+ chr(0x00AD), # soft hyphen
+ chr(0x180E), # Mongolian vowel separator (format char)
+ chr(0x034F), # combining grapheme joiner (printable Mn)
+ chr(0x180B), # Mongolian free variation selector (printable Mn)
+ chr(0x115F), # Hangul choseong filler (printable Lo)
+ chr(0x17B4), # Khmer vowel inherent AQ (printable Mn)
+ chr(0x17B5), # Khmer vowel inherent AA (printable Mn)
+ chr(0x2800), # Braille pattern blank (printable So)
+ chr(0x13441), # Egyptian hieroglyph full blank (printable Lo)
+ chr(0x13442), # Egyptian hieroglyph half blank (printable Lo)
+ chr(0x1D159), # Musical symbol null notehead (printable So)
+ chr(0xE0020), # Unicode tag char (invisible-smuggling family)
+ chr(0xFE0F), # variation selector (BMP)
+ chr(0xE0100), # variation selector (supplement plane)
+ chr(0x00A0), # NBSP (non-ASCII space)
+ ]
+ for pad in pads:
+ for key in ("x.api_key" + pad, "x.api" + pad + "key"):
+ assert DataSanitizer.is_sensitive_setting(key), repr(key)
+ assert (
+ DataSanitizer.redact_value(key, None, "sk-x")
+ == DataSanitizer.REDACTION_TEXT
+ )
+
+ def test_normalization_strips_only_invisible_chars(self):
+ # A non-secret leaf that is a secret name plus a normal char must stay
+ # readable — proves normalization removes ONLY invisible chars. "api_keyz"
+ # guards against stripping a legit ASCII char (-> "api_key"); "secreté"
+ # guards against stripping a legit non-ASCII letter (-> "secret").
+ for key in (
+ "x.api_keyz",
+ "x.password1",
+ "x.secretx",
+ "x.secreté",
+ "x.secret\u0301",
+ ):
+ assert not DataSanitizer.is_sensitive_setting(key), key
+ assert DataSanitizer.redact_value(key, None, "v") == "v"
+
+ def test_exact_custom_sensitive_name_with_invisible_char_is_preserved(self):
+ """Normalization must not break a pre-existing exact custom match."""
+ key = "x.custom_secret\u200b"
+ sensitive_keys = {"custom_secret\u200b"}
+
+ assert DataSanitizer.is_sensitive_setting(
+ key, sensitive_keys=sensitive_keys
+ )
+ assert (
+ DataSanitizer.redact_value(
+ key, None, "secret-value", sensitive_keys=sensitive_keys
+ )
+ == DataSanitizer.REDACTION_TEXT
+ )
+
+
class TestEdgeCases:
"""Edge case tests for DataSanitizer."""
diff --git a/tests/web/routes/test_settings_routes_gaps_coverage.py b/tests/web/routes/test_settings_routes_gaps_coverage.py
index bd9c4d18fc..41eaf57323 100644
--- a/tests/web/routes/test_settings_routes_gaps_coverage.py
+++ b/tests/web/routes/test_settings_routes_gaps_coverage.py
@@ -354,6 +354,30 @@ class TestGetBulkSettingsRedaction:
assert entry["exists"] is True
assert self.SECRET not in resp.get_data(as_text=True)
+ @pytest.mark.parametrize(
+ "pad", ["\u200b", "\u2800", "\U00013441", "\U00013442", "\U0001d159"]
+ )
+ def test_invisible_padded_password_key_is_redacted(self, pad):
+ """Exercise the HTTP route, including query parsing and serialization."""
+ app = _create_test_app()
+ key = "llm.openai.api_key" + pad
+ with _authenticated_client(app) as client:
+ with patch(
+ f"{MODULE}._get_setting_from_session",
+ return_value=self.SECRET,
+ ):
+ resp = client.get(
+ "/settings/api/bulk", query_string=[("keys[]", key)]
+ )
+
+ assert resp.status_code == 200
+ body = resp.get_json()
+ assert body["settings"][key] == {
+ "value": "[REDACTED]",
+ "exists": True,
+ }
+ assert self.SECRET not in resp.get_data(as_text=True)
+
def test_non_sensitive_key_passes_through(self):
"""Suffix outside DEFAULT_SENSITIVE_KEYS keeps its real value."""
app = _create_test_app()