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.

fix: security hardening follow-up improvements (#2625)

LearningCircuitb09fa168328a
diff --git a/src/local_deep_research/security/__init__.py b/src/local_deep_research/security/__init__.py
index 3d953dc704..5c52016e8f 100644
--- a/src/local_deep_research/security/__init__.py
+++ b/src/local_deep_research/security/__init__.py
@@ -19,7 +19,7 @@ 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
+from .log_sanitizer import sanitize_for_log, strip_control_chars
from .module_whitelist import (
get_safe_module_class,
ModuleNotAllowedError,
@@ -89,4 +89,5 @@ __all__ = [
"get_account_lockout_manager",
"PasswordValidator",
"sanitize_for_log",
+ "strip_control_chars",
]
diff --git a/src/local_deep_research/security/account_lockout.py b/src/local_deep_research/security/account_lockout.py
index b0d25555b4..02db3ba405 100644
--- a/src/local_deep_research/security/account_lockout.py
+++ b/src/local_deep_research/security/account_lockout.py
@@ -62,11 +62,34 @@ class AccountLockoutManager:
return False
return True
+ def _evict(self) -> None:
+ """Remove expired/unlocked entries to reclaim memory.
+
+ Must be called while ``self._lock`` is held.
+ """
+ now = datetime.now(timezone.utc)
+ expired_keys = [
+ key
+ for key, entry in self._state.items()
+ if entry.get("locked_until") is None or entry["locked_until"] <= now
+ ]
+ for key in expired_keys:
+ del self._state[key]
+
+ logger.info(
+ "Evicted {} expired/unlocked lockout entries", len(expired_keys)
+ )
+
+ # Last resort: if still over limit, blanket clear
+ if len(self._state) > self._MAX_STATE_ENTRIES:
+ self._state.clear()
+ logger.info("Blanket-cleared lockout state (still over limit)")
+
def record_failure(self, username: str) -> None:
"""Record a failed login attempt for *username*."""
with self._lock:
if len(self._state) > self._MAX_STATE_ENTRIES:
- self._state.clear()
+ self._evict()
entry = self._state.setdefault(
username, {"count": 0, "locked_until": None}
)
diff --git a/src/local_deep_research/security/log_sanitizer.py b/src/local_deep_research/security/log_sanitizer.py
index 04365dbdda..ea0b6fb09b 100644
--- a/src/local_deep_research/security/log_sanitizer.py
+++ b/src/local_deep_research/security/log_sanitizer.py
@@ -8,15 +8,22 @@ non-printable characters and truncating to a reasonable length.
import re
+# Strip C0/C1 control characters but preserve valid Unicode (accented, CJK, etc.)
+_CONTROL_CHAR_RE = re.compile(r"[\x00-\x1f\x7f-\x9f]")
+
+
+def strip_control_chars(value: str) -> str:
+ """Remove C0/C1 control characters from *value*, preserving Unicode."""
+ return _CONTROL_CHAR_RE.sub("", value)
+
def sanitize_for_log(value: str, max_length: int = 50) -> str:
"""Return a log-safe version of *value*.
- * Non-printable characters (control chars, etc.) are stripped.
+ * Control characters (C0/C1) are stripped; valid Unicode is preserved.
* The result is truncated to *max_length* characters.
"""
- # Strip non-printable / non-ASCII characters (keep printable ASCII 0x20-0x7E)
- cleaned = re.sub(r"[^\x20-\x7E]", "", value)
+ cleaned = strip_control_chars(value)
if len(cleaned) > max_length:
cleaned = (
cleaned[: max_length - 3] + "..."
diff --git a/src/local_deep_research/utilities/log_utils.py b/src/local_deep_research/utilities/log_utils.py
index 4f694d1575..17b62dab8d 100644
--- a/src/local_deep_research/utilities/log_utils.py
+++ b/src/local_deep_research/utilities/log_utils.py
@@ -265,6 +265,13 @@ def config_logger(name: str, debug: bool = False) -> None:
debug: Whether to enable unsafe debug logging.
"""
+ from ..security.log_sanitizer import strip_control_chars
+
+ def _sanitize_record(record):
+ record["message"] = strip_control_chars(record["message"])
+
+ logger.configure(patcher=_sanitize_record)
+
logger.enable("local_deep_research")
logger.remove()
diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.py
index 9edd58b5c0..2f18c23e68 100644
--- a/src/local_deep_research/web/auth/routes.py
+++ b/src/local_deep_research/web/auth/routes.py
@@ -28,7 +28,11 @@ from .session_manager import (
session_manager,
) # singleton from session_manager module
from ..server_config import load_server_config
-from ..utils.rate_limiter import login_limit, registration_limit
+from ..utils.rate_limiter import (
+ login_limit,
+ password_change_limit,
+ registration_limit,
+)
from urllib.parse import urlparse
from ...security.url_validator import URLValidator
@@ -511,19 +515,31 @@ def check_auth():
return jsonify({"authenticated": False}), 401
-@auth_bp.route("/change-password", methods=["GET", "POST"])
+@auth_bp.route("/change-password", methods=["GET"])
+def change_password_page():
+ """
+ Change password page (GET only).
+ Not rate limited - viewing the page should always work.
+ """
+ username = session.get("username")
+ if not username:
+ return redirect(url_for("auth.login"))
+
+ return render_template("auth/change_password.html")
+
+
+@auth_bp.route("/change-password", methods=["POST"])
+@password_change_limit
def change_password():
"""
- Change password for current user.
+ Change password handler (POST only).
Requires current password and re-encrypts database.
+ Rate limited to prevent brute-force of current password.
"""
username = session.get("username")
if not username:
return redirect(url_for("auth.login"))
- if request.method == "GET":
- return render_template("auth/change_password.html")
-
# POST - Handle password change
current_password = request.form.get("current_password", "")
new_password = request.form.get("new_password", "")
diff --git a/src/local_deep_research/web/utils/rate_limiter.py b/src/local_deep_research/web/utils/rate_limiter.py
index 72f688405c..dc520942ff 100644
--- a/src/local_deep_research/web/utils/rate_limiter.py
+++ b/src/local_deep_research/web/utils/rate_limiter.py
@@ -82,3 +82,8 @@ settings_limit = limiter.shared_limit(
SETTINGS_RATE_LIMIT,
scope="settings",
)
+
+password_change_limit = limiter.shared_limit(
+ LOGIN_RATE_LIMIT,
+ scope="password_change",
+)
diff --git a/tests/conftest.py b/tests/conftest.py
index d8f4434733..502b2566ed 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -117,6 +117,14 @@ def reset_all_singletons():
except ImportError:
pass
+ # AccountLockoutManager singleton
+ try:
+ from local_deep_research.security import account_lockout
+
+ account_lockout._manager = None
+ except ImportError:
+ pass
+
# AdaptiveRateLimitTracker
try:
from local_deep_research.web_search_engines.rate_limiting import (
diff --git a/tests/security/test_account_lockout.py b/tests/security/test_account_lockout.py
index d984718cbc..567bf64d41 100644
--- a/tests/security/test_account_lockout.py
+++ b/tests/security/test_account_lockout.py
@@ -1,5 +1,8 @@
"""Tests for per-user account lockout."""
+from datetime import datetime, timedelta, timezone
+from unittest.mock import patch
+
from local_deep_research.security.account_lockout import AccountLockoutManager
@@ -58,15 +61,84 @@ class TestAccountLockout:
mgr.record_success("nonexistent")
assert mgr.is_locked("nonexistent") is False
- def test_state_cleared_when_exceeds_max_entries(self):
+ def test_lockout_expires_after_duration(self):
+ mgr = self._make_manager(threshold=3, lockout_minutes=15)
+ now = datetime(2026, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
+
+ with patch(
+ "local_deep_research.security.account_lockout.datetime"
+ ) as mock_dt:
+ mock_dt.now.return_value = now
+ mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
+ for _ in range(3):
+ mgr.record_failure("alice")
+
+ # Still locked 14 minutes later
+ with patch(
+ "local_deep_research.security.account_lockout.datetime"
+ ) as mock_dt:
+ mock_dt.now.return_value = now + timedelta(minutes=14)
+ assert mgr.is_locked("alice") is True
+
+ # Unlocked at exactly 15 minutes
+ with patch(
+ "local_deep_research.security.account_lockout.datetime"
+ ) as mock_dt:
+ mock_dt.now.return_value = now + timedelta(minutes=15)
+ assert mgr.is_locked("alice") is False
+
+ def test_eviction_removes_unlocked_entries(self):
+ """Eviction should remove unlocked/expired entries, not blanket clear."""
mgr = self._make_manager(threshold=5)
mgr._MAX_STATE_ENTRIES = 100
- # Fill state beyond the limit
- for i in range(101):
- mgr._state[f"user_{i}"] = {"count": 1, "locked_until": None}
- assert len(mgr._state) == 101
- # Next record_failure should trigger the clear
+ now = datetime.now(timezone.utc)
+
+ # Add unlocked entries (count < threshold, no locked_until)
+ for i in range(90):
+ mgr._state[f"unlocked_{i}"] = {"count": 1, "locked_until": None}
+
+ # Add expired locked entries
+ for i in range(10):
+ mgr._state[f"expired_{i}"] = {
+ "count": 5,
+ "locked_until": now - timedelta(minutes=1),
+ }
+
+ # Add actively locked entries
+ for i in range(5):
+ mgr._state[f"locked_{i}"] = {
+ "count": 5,
+ "locked_until": now + timedelta(minutes=10),
+ }
+
+ assert len(mgr._state) == 105
+
+ # Trigger eviction via record_failure
+ mgr.record_failure("attacker")
+
+ # Actively locked entries should survive
+ for i in range(5):
+ assert f"locked_{i}" in mgr._state
+ # New entry should exist
+ assert "attacker" in mgr._state
+ # Unlocked/expired entries should be gone
+ assert not any(k.startswith("unlocked_") for k in mgr._state)
+ assert not any(k.startswith("expired_") for k in mgr._state)
+
+ def test_blanket_clear_as_last_resort(self):
+ """If eviction can't reduce below limit, blanket clear."""
+ mgr = self._make_manager(threshold=3)
+ mgr._MAX_STATE_ENTRIES = 10
+ now = datetime.now(timezone.utc)
+
+ # Fill with actively locked entries (can't be evicted)
+ for i in range(15):
+ mgr._state[f"locked_{i}"] = {
+ "count": 5,
+ "locked_until": now + timedelta(hours=1),
+ }
+
mgr.record_failure("attacker")
- # State was cleared then the new entry added
+ # Should have blanket-cleared then added new entry
assert len(mgr._state) == 1
assert "attacker" in mgr._state
diff --git a/tests/security/test_log_sanitizer.py b/tests/security/test_log_sanitizer.py
index 5de0114578..3d80677c5e 100644
--- a/tests/security/test_log_sanitizer.py
+++ b/tests/security/test_log_sanitizer.py
@@ -1,6 +1,9 @@
"""Tests for log string sanitization."""
-from local_deep_research.security.log_sanitizer import sanitize_for_log
+from local_deep_research.security.log_sanitizer import (
+ sanitize_for_log,
+ strip_control_chars,
+)
class TestLogSanitizer:
@@ -29,3 +32,31 @@ class TestLogSanitizer:
def test_tabs_stripped(self):
assert sanitize_for_log("col1\tcol2") == "col1col2"
+
+ def test_unicode_preserved(self):
+ assert sanitize_for_log("café") == "café"
+
+ def test_cjk_preserved(self):
+ assert sanitize_for_log("你好") == "你好"
+
+ def test_control_chars_stripped_unicode_preserved(self):
+ assert sanitize_for_log("café\x00\x07") == "café"
+
+
+class TestStripControlChars:
+ """Unit tests for strip_control_chars."""
+
+ def test_strips_c0_control_chars(self):
+ assert strip_control_chars("a\x00b\x1fc") == "abc"
+
+ def test_strips_c1_control_chars(self):
+ assert strip_control_chars("a\x7fb\x9fc") == "abc"
+
+ def test_preserves_normal_text(self):
+ assert strip_control_chars("hello world") == "hello world"
+
+ def test_preserves_unicode(self):
+ assert strip_control_chars("café 你好 émoji") == "café 你好 émoji"
+
+ def test_empty_string(self):
+ assert strip_control_chars("") == ""
diff --git a/tests/security/test_password_validator.py b/tests/security/test_password_validator.py
index 67214aba14..be702932ad 100644
--- a/tests/security/test_password_validator.py
+++ b/tests/security/test_password_validator.py
@@ -30,3 +30,19 @@ class TestPasswordValidator:
errors = PasswordValidator.validate_strength("abc")
# Should flag: too short, no uppercase, no digit
assert len(errors) >= 3
+
+ def test_exactly_8_chars_valid(self):
+ errors = PasswordValidator.validate_strength("Abcdef1x")
+ assert errors == []
+
+ def test_7_chars_invalid(self):
+ errors = PasswordValidator.validate_strength("Abcde1x")
+ assert any("8 characters" in e for e in errors)
+
+ def test_special_chars_allowed(self):
+ errors = PasswordValidator.validate_strength("P@ssw0rd!")
+ assert errors == []
+
+ def test_very_long_password_valid(self):
+ errors = PasswordValidator.validate_strength("A1" + "a" * 200)
+ assert errors == []
diff --git a/tests/web/auth/test_auth_routes.py b/tests/web/auth/test_auth_routes.py
index 175317ceb6..2fae1b45d7 100644
--- a/tests/web/auth/test_auth_routes.py
+++ b/tests/web/auth/test_auth_routes.py
@@ -1177,6 +1177,7 @@ class TestRegistrationTimingAttackPrevention:
)
mock_session.rollback = MagicMock()
mock_session.close = MagicMock()
+ # auth_db_session() is used as a context manager
mock_auth_db.return_value.__enter__ = MagicMock(
return_value=mock_session
)