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: refine redact_secrets after AI code review (#4073)

LearningCircuitb9cdfa6db7c6
diff --git a/src/local_deep_research/security/__init__.py b/src/local_deep_research/security/__init__.py
index 9d366ff792..8c528a99e2 100644
--- a/src/local_deep_research/security/__init__.py
+++ b/src/local_deep_research/security/__init__.py
@@ -19,7 +19,11 @@ from .ssrf_validator import validate_url, get_safe_url, is_ip_blocked
from .url_validator import URLValidator
from .account_lockout import AccountLockoutManager, get_account_lockout_manager
from .password_validator import PasswordValidator
-from .log_sanitizer import sanitize_for_log, strip_control_chars
+from .log_sanitizer import (
+ redact_secrets,
+ sanitize_for_log,
+ strip_control_chars,
+)
from .filename_sanitizer import sanitize_filename, UnsafeFilenameError
from .module_whitelist import (
get_safe_module_class,
@@ -72,6 +76,7 @@ __all__ = [
"AccountLockoutManager",
"get_account_lockout_manager",
"PasswordValidator",
+ "redact_secrets",
"sanitize_for_log",
"strip_control_chars",
"sanitize_filename",
diff --git a/src/local_deep_research/security/log_sanitizer.py b/src/local_deep_research/security/log_sanitizer.py
index 5000dcad6e..cb7dcbf5fd 100644
--- a/src/local_deep_research/security/log_sanitizer.py
+++ b/src/local_deep_research/security/log_sanitizer.py
@@ -66,9 +66,9 @@ def redact_secrets(
message: str,
*secrets: Optional[str],
min_length: int = _MIN_SECRET_LENGTH,
- token: str = _REDACTION_TOKEN,
+ replacement: str = _REDACTION_TOKEN,
) -> str:
- """Replace each occurrence of any *secret* in *message* with *token*.
+ """Replace each occurrence of any *secret* in *message* with *replacement*.
Use this before writing a string to a log sink, returning it in an
error response, or persisting it \u2014 when the string may have been
@@ -82,19 +82,28 @@ def redact_secrets(
form is NOT redacted unless the caller also passes that
transformed form.
+ When multiple secrets are passed, they are applied in descending
+ length order so a shorter secret that happens to be a substring of
+ a longer one cannot consume part of the longer match. Example:
+ given secrets ``"abc12345"`` and ``"sk-abc12345"``, the longer one
+ is replaced first.
+
Args:
message: The string to scrub. Returned unchanged if falsy.
*secrets: Zero or more candidate secret values. ``None`` and
- values shorter than *min_length* are skipped (see below).
+ values shorter than *min_length* are silently skipped \u2014 the
+ caller is responsible for noticing missing config.
min_length: Minimum secret length to redact. Values shorter than
this are skipped to avoid corrupting normal message content
(a 1- or 2-character secret would match too aggressively).
- Defaults to 8.
- token: Replacement string. Defaults to ``"***REDACTED***"``. # gitleaks:allow
+ Defaults to 8. Real API keys and session tokens are
+ typically 16+ characters.
+ replacement: String written in place of each redacted secret.
+ Defaults to ``"***REDACTED***"``.
Returns:
*message* with every occurrence of each qualifying secret
- replaced by *token*.
+ replaced.
See ``tests/security/test_log_sanitizer.py::TestRedactSecrets`` for
worked examples (doctest examples are omitted because the
@@ -103,7 +112,13 @@ def redact_secrets(
"""
if not message:
return message
- for secret in secrets:
- if secret and len(secret) >= min_length:
- message = message.replace(secret, token)
+ # Longest-first prevents a shorter overlapping secret from
+ # truncating a longer one once the replacement token is in place.
+ ordered = sorted(
+ (s for s in secrets if s and len(s) >= min_length),
+ key=len,
+ reverse=True,
+ )
+ for secret in ordered:
+ message = message.replace(secret, replacement)
return message
diff --git a/tests/security/test_log_sanitizer.py b/tests/security/test_log_sanitizer.py
index 51e4c64294..e6a44e278d 100644
--- a/tests/security/test_log_sanitizer.py
+++ b/tests/security/test_log_sanitizer.py
@@ -138,12 +138,53 @@ class TestRedactSecrets:
def test_message_without_secret_returned_unchanged(self):
assert redact_secrets("hello world", "sk-abc1234567") == "hello world"
- def test_custom_token(self):
+ def test_custom_replacement(self):
result = redact_secrets(
- "key=sk-abc1234567", "sk-abc1234567", token="[KEY]"
+ "key=sk-abc1234567", "sk-abc1234567", replacement="[KEY]"
)
assert result == "key=[KEY]"
+ def test_empty_replacement_strips_secret(self):
+ # Replacement may be empty — strips the secret entirely. This
+ # is the right answer when the secret's presence itself is
+ # sensitive (not just its value).
+ result = redact_secrets(
+ "before sk-abc1234567 after", "sk-abc1234567", replacement=""
+ )
+ assert result == "before after"
+
+ def test_overlapping_secrets_redacted_longest_first(self):
+ # If two secrets overlap (one is a substring of the other), the
+ # function must apply the longer one first so a shorter
+ # secret cannot consume part of the longer match. Without
+ # length-sorting, the test fails: redacting "abc12345" first
+ # would leave "sk-***REDACTED***" in the message, then the
+ # longer "sk-abc12345" no longer matches.
+ result = redact_secrets(
+ "found sk-abc12345 here", "abc12345", "sk-abc12345"
+ )
+ assert result == "found ***REDACTED*** here"
+ assert "abc12345" not in result
+
+ def test_redaction_is_not_recursive(self):
+ # If a secret happens to equal the replacement token, the
+ # function does not loop forever — it does a single pass per
+ # secret and ``str.replace`` is not recursive.
+ result = redact_secrets("X ***REDACTED*** Y", "***REDACTED***")
+ # The pre-existing token gets replaced with the same token —
+ # net no-op, but importantly: no recursion, no exception.
+ assert result == "X ***REDACTED*** Y"
+
+ def test_importable_from_security_package(self):
+ # ``redact_secrets`` is exported from
+ # ``local_deep_research.security`` so future callers don't need
+ # to know the submodule path.
+ from local_deep_research.security import (
+ redact_secrets as exported,
+ )
+
+ assert exported is redact_secrets
+
@pytest.mark.parametrize(
"secret",
[