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.

feat: move security hardening to security/ module (#2594)

LearningCircuit29e68152e378
diff --git a/.github/scripts/file-whitelist-check.sh b/.github/scripts/file-whitelist-check.sh
index 43c83f9cc3..c1342d7051 100755
--- a/.github/scripts/file-whitelist-check.sh
+++ b/.github/scripts/file-whitelist-check.sh
@@ -142,6 +142,7 @@ SAFE_FILENAME_PATTERNS=(
".*session_passwords\.py$"
".*change_password\.html$"
"tests/ui_tests/.*password.*\.js$"
+".*password_validator\.py$"
)
# Check if filename looks suspicious
diff --git a/src/local_deep_research/defaults/settings_security.json b/src/local_deep_research/defaults/settings_security.json
index dcdf9ac451..0c75e655af 100644
--- a/src/local_deep_research/defaults/settings_security.json
+++ b/src/local_deep_research/defaults/settings_security.json
@@ -70,5 +70,29 @@
"ui_element": "number",
"value": 2,
"visible": true
+ },
+ "security.account_lockout_threshold": {
+ "category": "security",
+ "description": "Number of consecutive failed login attempts before an account is temporarily locked out. Only configurable via environment variable (LDR_SECURITY_ACCOUNT_LOCKOUT_THRESHOLD).",
+ "editable": false,
+ "max_value": 50,
+ "min_value": 3,
+ "name": "Account Lockout Threshold",
+ "type": "APP",
+ "ui_element": "number",
+ "value": 10,
+ "visible": false
+ },
+ "security.account_lockout_duration_minutes": {
+ "category": "security",
+ "description": "Duration in minutes that an account remains locked after exceeding the failed login threshold. Only configurable via environment variable (LDR_SECURITY_ACCOUNT_LOCKOUT_DURATION_MINUTES).",
+ "editable": false,
+ "max_value": 60,
+ "min_value": 1,
+ "name": "Account Lockout Duration (Minutes)",
+ "type": "APP",
+ "ui_element": "number",
+ "value": 15,
+ "visible": false
}
}
diff --git a/src/local_deep_research/security/__init__.py b/src/local_deep_research/security/__init__.py
index 48b3b7c5dc..3d953dc704 100644
--- a/src/local_deep_research/security/__init__.py
+++ b/src/local_deep_research/security/__init__.py
@@ -17,6 +17,9 @@ from .safe_requests import safe_get, safe_post, SafeSession
from .security_headers import SecurityHeaders
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 .module_whitelist import (
get_safe_module_class,
ModuleNotAllowedError,
@@ -82,4 +85,8 @@ __all__ = [
"get_safe_module_class",
"ModuleNotAllowedError",
"ALLOWED_MODULES",
+ "AccountLockoutManager",
+ "get_account_lockout_manager",
+ "PasswordValidator",
+ "sanitize_for_log",
]
diff --git a/src/local_deep_research/security/account_lockout.py b/src/local_deep_research/security/account_lockout.py
new file mode 100644
index 0000000000..b0d25555b4
--- /dev/null
+++ b/src/local_deep_research/security/account_lockout.py
@@ -0,0 +1,106 @@
+"""Per-user account lockout after repeated failed login attempts.
+
+Complements the per-IP rate limiting in ``web/utils/rate_limiter.py`` by
+tracking failures at the *username* level. A user who exceeds the
+configured threshold is temporarily locked out regardless of the source IP.
+
+Note: lockout state is in-memory and per-process. In multi-worker
+deployments (e.g. gunicorn), each worker maintains separate state.
+"""
+
+import threading
+from datetime import datetime, timedelta, timezone
+
+from loguru import logger
+
+from .security_settings import get_security_default
+
+
+class AccountLockoutManager:
+ """Track failed login attempts and lock accounts after a threshold."""
+
+ _MAX_STATE_ENTRIES = 10_000
+
+ def __init__(
+ self,
+ threshold: int | None = None,
+ lockout_minutes: int | None = None,
+ ) -> None:
+ if threshold is None:
+ threshold = get_security_default(
+ "security.account_lockout_threshold", 10
+ )
+ if lockout_minutes is None:
+ lockout_minutes = get_security_default(
+ "security.account_lockout_duration_minutes", 15
+ )
+
+ self.threshold: int = threshold
+ self.lockout_minutes: int = lockout_minutes
+
+ # {username: {"count": int, "locked_until": datetime | None}}
+ self._state: dict[str, dict] = {}
+ self._lock = threading.Lock()
+
+ # ------------------------------------------------------------------
+ # Public API
+ # ------------------------------------------------------------------
+
+ def is_locked(self, username: str) -> bool:
+ """Return ``True`` if *username* is currently locked out."""
+ with self._lock:
+ entry = self._state.get(username)
+ if entry is None:
+ return False
+ locked_until = entry.get("locked_until")
+ if locked_until is None:
+ return False
+ if datetime.now(timezone.utc) >= locked_until:
+ # Lockout expired — reset automatically
+ self._state.pop(username, None)
+ logger.info("Account lockout expired")
+ return False
+ return True
+
+ 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()
+ entry = self._state.setdefault(
+ username, {"count": 0, "locked_until": None}
+ )
+ entry["count"] += 1
+ if entry["count"] >= self.threshold:
+ entry["locked_until"] = datetime.now(timezone.utc) + timedelta(
+ minutes=self.lockout_minutes
+ )
+ logger.warning(
+ "Account locked after {} failed attempts",
+ self.threshold,
+ )
+
+ def record_success(self, username: str) -> None:
+ """Clear the failure counter for *username* after a successful login."""
+ with self._lock:
+ removed = self._state.pop(username, None)
+ if removed is not None:
+ logger.info("Account lockout cleared after successful login")
+
+
+# ------------------------------------------------------------------
+# Module-level singleton
+# ------------------------------------------------------------------
+
+_manager: AccountLockoutManager | None = None
+_singleton_lock = threading.Lock()
+
+
+def get_account_lockout_manager() -> AccountLockoutManager:
+ """Return the module-level singleton ``AccountLockoutManager``."""
+ global _manager
+ if _manager is None:
+ with _singleton_lock:
+ if _manager is None:
+ _manager = AccountLockoutManager()
+ return _manager
diff --git a/src/local_deep_research/security/log_sanitizer.py b/src/local_deep_research/security/log_sanitizer.py
new file mode 100644
index 0000000000..04365dbdda
--- /dev/null
+++ b/src/local_deep_research/security/log_sanitizer.py
@@ -0,0 +1,26 @@
+"""Sanitize raw strings before writing them to log output.
+
+``data_sanitizer.py`` handles dict-key redaction (e.g. stripping API keys
+from structured data). This module handles a different concern: making a
+single *string value* safe to include in a log line by removing
+non-printable characters and truncating to a reasonable length.
+"""
+
+import re
+
+
+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.
+ * 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)
+ if len(cleaned) > max_length:
+ cleaned = (
+ cleaned[: max_length - 3] + "..."
+ if max_length > 3
+ else cleaned[:max_length]
+ )
+ return cleaned
diff --git a/src/local_deep_research/security/password_validator.py b/src/local_deep_research/security/password_validator.py
new file mode 100644
index 0000000000..d406f28612
--- /dev/null
+++ b/src/local_deep_research/security/password_validator.py
@@ -0,0 +1,37 @@
+"""Password strength validation.
+
+Follows the ``URLValidator`` pattern — a class with static methods so
+callers can use ``PasswordValidator.validate_strength(pw)`` without
+instantiation.
+"""
+
+import re
+
+
+class PasswordValidator:
+ """Validate password strength requirements."""
+
+ @staticmethod
+ def validate_strength(password: str) -> list[str]:
+ """Return a list of error strings for *password*.
+
+ An empty list means the password meets all requirements.
+
+ Checks:
+ - Minimum length of 8 characters
+ - At least one uppercase letter
+ - At least one lowercase letter
+ - At least one digit
+ """
+ errors: list[str] = []
+
+ if len(password) < 8:
+ errors.append("Password must be at least 8 characters")
+ if not re.search(r"[A-Z]", password):
+ errors.append("Password must contain at least one uppercase letter")
+ if not re.search(r"[a-z]", password):
+ errors.append("Password must contain at least one lowercase letter")
+ if not re.search(r"\d", password):
+ errors.append("Password must contain at least one digit")
+
+ return errors
diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.py
index 41b8d59be5..9edd58b5c0 100644
--- a/src/local_deep_research/web/auth/routes.py
+++ b/src/local_deep_research/web/auth/routes.py
@@ -32,6 +32,9 @@ from ..utils.rate_limiter import login_limit, registration_limit
from urllib.parse import urlparse
from ...security.url_validator import URLValidator
+from ...security.account_lockout import get_account_lockout_manager
+from ...security.password_validator import PasswordValidator
+from ...security.log_sanitizer import sanitize_for_log
auth_bp = Blueprint("auth", __name__, url_prefix="/auth")
@@ -95,12 +98,28 @@ def login():
allow_registrations=config.get("allow_registrations", True),
), 400
+ # Check account lockout before attempting credential verification
+ lockout_mgr = get_account_lockout_manager()
+ if lockout_mgr.is_locked(username):
+ logger.warning(
+ f"Login attempt for locked account: {sanitize_for_log(username)}"
+ )
+ flash("Account is temporarily locked. Please try again later.", "error")
+ return render_template(
+ "auth/login.html",
+ has_encryption=db_manager.has_encryption,
+ allow_registrations=config.get("allow_registrations", True),
+ ), 429
+
# Try to open user's encrypted database
engine = db_manager.open_user_database(username, password)
if engine is None:
# Invalid credentials or database doesn't exist
- logger.warning(f"Failed login attempt for username: {username}")
+ lockout_mgr.record_failure(username)
+ logger.warning(
+ f"Failed login attempt for username: {sanitize_for_log(username)}"
+ )
flash("Invalid username or password", "error")
return render_template(
"auth/login.html",
@@ -108,7 +127,13 @@ def login():
allow_registrations=config.get("allow_registrations", True),
), 401
- # Success! Create session
+ # Success — clear any prior failure count
+ lockout_mgr.record_success(username)
+
+ # Prevent session fixation by clearing old session data before creating new
+ session.clear()
+
+ # Create session
session_id = session_manager.create_session(username, remember)
session["session_id"] = session_id
session["username"] = username
@@ -288,8 +313,8 @@ def register():
if not password:
errors.append("Password is required")
- elif len(password) < 8:
- errors.append("Password must be at least 8 characters")
+ else:
+ errors.extend(PasswordValidator.validate_strength(password))
if password != confirm_password:
errors.append("Passwords do not match")
@@ -347,6 +372,9 @@ def register():
# Create encrypted database for user
db_manager.create_user_database(username, password)
+ # Prevent session fixation by clearing old session data
+ session.clear()
+
# Auto-login after registration
session_id = session_manager.create_session(username, False)
session["session_id"] = session_id
@@ -509,8 +537,8 @@ def change_password():
if not new_password:
errors.append("New password is required")
- elif len(new_password) < 8:
- errors.append("New password must be at least 8 characters")
+ else:
+ errors.extend(PasswordValidator.validate_strength(new_password))
if new_password != confirm_password:
errors.append("New passwords do not match")
diff --git a/tests/api_tests/test_csrf_header.py b/tests/api_tests/test_csrf_header.py
index bb906e77a3..5aeb4a9b4a 100644
--- a/tests/api_tests/test_csrf_header.py
+++ b/tests/api_tests/test_csrf_header.py
@@ -21,7 +21,7 @@ class TestCSRFHeader:
# In test mode, CSRF is disabled, so we can login without token
login_data = {
"username": test_username,
- "password": "testpassword123",
+ "password": "TestPass123",
}
# First register the user
@@ -29,8 +29,8 @@ class TestCSRFHeader:
"/auth/register",
data={
"username": test_username,
- "password": "testpassword123",
- "confirm_password": "testpassword123",
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
"acknowledge": "true",
},
)
diff --git a/tests/api_tests/test_fresh_session.py b/tests/api_tests/test_fresh_session.py
index 158b279702..b5b4aa6e2a 100644
--- a/tests/api_tests/test_fresh_session.py
+++ b/tests/api_tests/test_fresh_session.py
@@ -25,7 +25,7 @@ class TestFreshSession:
# Create unique test username to avoid conflicts
test_username = f"testuser_fresh_{int(time.time() * 1000)}"
- test_password = "testpassword123"
+ test_password = "TestPass123"
# Register user first (in case it doesn't exist)
register_data = {
@@ -106,7 +106,7 @@ class TestFreshSession:
# Create unique test username to avoid conflicts
test_username = f"testuser_api_{int(time.time() * 1000)}"
- test_password = "testpassword123"
+ test_password = "TestPass123"
register_data = {
"username": test_username,
diff --git a/tests/api_tests/test_proper_csrf.py b/tests/api_tests/test_proper_csrf.py
index b8893c878d..6ed206f006 100644
--- a/tests/api_tests/test_proper_csrf.py
+++ b/tests/api_tests/test_proper_csrf.py
@@ -27,7 +27,7 @@ class TestProperCSRF:
# Create unique test username to avoid conflicts
test_username = f"testuser_csrf_{int(time.time() * 1000)}"
- test_password = "testpassword123"
+ test_password = "TestPass123"
# Register user first
register_data = {
@@ -128,7 +128,7 @@ class TestProperCSRF:
# Try to login without CSRF token
login_data = {
"username": "testuser",
- "password": "testpassword123",
+ "password": "TestPass123",
# No csrf_token
}
@@ -153,7 +153,7 @@ class TestProperCSRF:
# Use an invalid CSRF token
login_data = {
"username": "testuser",
- "password": "testpassword123",
+ "password": "TestPass123",
"csrf_token": "invalid_token_12345",
}
diff --git a/tests/api_tests/test_research_api_debug.py b/tests/api_tests/test_research_api_debug.py
index 7c7a0b874e..0db848c820 100644
--- a/tests/api_tests/test_research_api_debug.py
+++ b/tests/api_tests/test_research_api_debug.py
@@ -22,7 +22,7 @@ class ResearchAPIDebugTest:
# Create unique username to avoid conflicts
timestamp = int(time.time() * 1000)
self.username = f"testuser_{timestamp}"
- self.password = "testpassword123" # At least 8 characters
+ self.password = "TestPass123" # At least 8 characters
def run_all_tests(self):
"""Run all debug tests."""
diff --git a/tests/api_tests/test_session_persistence.py b/tests/api_tests/test_session_persistence.py
index 6b98accdf6..8b4ba0b23d 100644
--- a/tests/api_tests/test_session_persistence.py
+++ b/tests/api_tests/test_session_persistence.py
@@ -12,7 +12,7 @@ class TestSessionPersistence:
"""Test that session persists after login."""
# Create unique test username to avoid conflicts
test_username = f"testuser_session_{int(time.time() * 1000)}"
- test_password = "testpassword123"
+ test_password = "TestPass123"
# Get login page
response = client.get("/auth/login")
diff --git a/tests/api_tests/test_simple_auth.py b/tests/api_tests/test_simple_auth.py
index 391eccec3d..4cb9851ac4 100644
--- a/tests/api_tests/test_simple_auth.py
+++ b/tests/api_tests/test_simple_auth.py
@@ -12,7 +12,7 @@ class TestSimpleAuth:
"""Test the login flow."""
# Create unique test username to avoid conflicts
test_username = f"testuser_simple_{int(time.time() * 1000)}"
- test_password = "testpassword123"
+ test_password = "TestPass123"
# 1. Get login page
response = client.get("/auth/login")
diff --git a/tests/api_tests/test_without_csrf.py b/tests/api_tests/test_without_csrf.py
index dec5ff2b22..8359344be9 100644
--- a/tests/api_tests/test_without_csrf.py
+++ b/tests/api_tests/test_without_csrf.py
@@ -15,8 +15,8 @@ class TestWithoutCSRF:
# Register user
register_data = {
"username": "testuser_nocsrf",
- "password": "testpassword123",
- "confirm_password": "testpassword123",
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
"acknowledge": "true",
}
client.post("/auth/register", data=register_data)
@@ -24,7 +24,7 @@ class TestWithoutCSRF:
# Try login without CSRF token
login_data = {
"username": "testuser_nocsrf",
- "password": "testpassword123",
+ "password": "TestPass123",
}
# Direct POST without getting the login page first
@@ -50,7 +50,7 @@ class TestWithoutCSRF:
client = app.test_client()
# Try login without CSRF token (CSRF should be enabled)
- login_data = {"username": "testuser", "password": "testpassword123"}
+ login_data = {"username": "testuser", "password": "TestPass123"}
# Direct POST without CSRF token
response = client.post(
diff --git a/tests/api_tests_with_login/pytest_tests/conftest.py b/tests/api_tests_with_login/pytest_tests/conftest.py
index 5037c21cba..e1132f4a35 100644
--- a/tests/api_tests_with_login/pytest_tests/conftest.py
+++ b/tests/api_tests_with_login/pytest_tests/conftest.py
@@ -15,7 +15,7 @@ import os
BASE_URL = os.environ.get("LDR_TEST_BASE_URL", "http://127.0.0.1:5000")
# Use UUID for unique usernames to avoid collisions in parallel tests
TEST_USERNAME = f"testuser_{uuid.uuid4().hex[:12]}"
-TEST_PASSWORD = "testpass123"
+TEST_PASSWORD = "TestPass123"
class AuthHelper:
diff --git a/tests/auth_tests/test_auth_integration.py b/tests/auth_tests/test_auth_integration.py
index 3b296e4cc4..e192c8fd88 100644
--- a/tests/auth_tests/test_auth_integration.py
+++ b/tests/auth_tests/test_auth_integration.py
@@ -94,8 +94,8 @@ class TestAuthIntegration:
"/auth/register",
data={
"username": "integrationtest",
- "password": "testpassword123", # pragma: allowlist secret
- "confirm_password": "testpassword123", # pragma: allowlist secret
+ "password": "TestPass123", # pragma: allowlist secret
+ "confirm_password": "TestPass123", # pragma: allowlist secret
"acknowledge": "true",
},
follow_redirects=True,
@@ -134,7 +134,7 @@ class TestAuthIntegration:
# 8. Login again
response = client.post(
"/auth/login",
- data={"username": "integrationtest", "password": "testpassword123"},
+ data={"username": "integrationtest", "password": "TestPass123"},
follow_redirects=True,
)
assert response.status_code == 200
@@ -150,8 +150,8 @@ class TestAuthIntegration:
"/auth/register",
data={
"username": "user1",
- "password": "password1",
- "confirm_password": "password1",
+ "password": "Password1X",
+ "confirm_password": "Password1X",
"acknowledge": "true",
},
)
@@ -169,8 +169,8 @@ class TestAuthIntegration:
"/auth/register",
data={
"username": "user2",
- "password": "password2",
- "confirm_password": "password2",
+ "password": "Password2X",
+ "confirm_password": "Password2X",
"acknowledge": "true",
},
)
@@ -196,8 +196,8 @@ class TestAuthIntegration:
"/auth/register",
data={
"username": "sessiontest",
- "password": "testpassword123", # pragma: allowlist secret
- "confirm_password": "testpassword123", # pragma: allowlist secret
+ "password": "TestPass123", # pragma: allowlist secret
+ "confirm_password": "TestPass123", # pragma: allowlist secret
"acknowledge": "true",
},
)
@@ -246,8 +246,8 @@ class TestAuthIntegration:
"/auth/register",
data={
"username": "apitest",
- "password": "testpassword123", # pragma: allowlist secret
- "confirm_password": "testpassword123", # pragma: allowlist secret
+ "password": "TestPass123", # pragma: allowlist secret
+ "confirm_password": "TestPass123", # pragma: allowlist secret
"acknowledge": "true",
},
)
@@ -273,8 +273,8 @@ class TestAuthIntegration:
"/auth/register",
data={
"username": "changetest",
- "password": "oldpassword123",
- "confirm_password": "oldpassword123",
+ "password": "OldPass123",
+ "confirm_password": "OldPass123",
"acknowledge": "true",
},
)
@@ -283,9 +283,9 @@ class TestAuthIntegration:
response = client.post(
"/auth/change-password",
data={
- "current_password": "oldpassword123",
- "new_password": "newpassword456", # pragma: allowlist secret
- "confirm_password": "newpassword456",
+ "current_password": "OldPass123",
+ "new_password": "NewPass456", # pragma: allowlist secret
+ "confirm_password": "NewPass456",
},
follow_redirects=True,
)
@@ -300,14 +300,14 @@ class TestAuthIntegration:
# Old password should fail
response = client.post(
"/auth/login",
- data={"username": "changetest", "password": "oldpassword123"},
+ data={"username": "changetest", "password": "OldPass123"},
)
assert response.status_code == 401
# New password should work
response = client.post(
"/auth/login",
- data={"username": "changetest", "password": "newpassword456"},
+ data={"username": "changetest", "password": "NewPass456"},
follow_redirects=True,
)
assert response.status_code == 200
diff --git a/tests/auth_tests/test_auth_rate_limiting.py b/tests/auth_tests/test_auth_rate_limiting.py
index fc3894eb0c..8c27194024 100644
--- a/tests/auth_tests/test_auth_rate_limiting.py
+++ b/tests/auth_tests/test_auth_rate_limiting.py
@@ -135,8 +135,8 @@ class TestAuthRateLimiting:
"/auth/register",
data={
"username": f"newuser{i}",
- "password": "testpass123",
- "confirm_password": "testpass123",
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
"acknowledge": "true",
},
follow_redirects=False,
@@ -157,8 +157,8 @@ class TestAuthRateLimiting:
"/auth/register",
data={
"username": f"newuser{i}",
- "password": "testpass123",
- "confirm_password": "testpass123",
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
"acknowledge": "true",
},
)
@@ -168,8 +168,8 @@ class TestAuthRateLimiting:
"/auth/register",
data={
"username": "newuser4",
- "password": "testpass123",
- "confirm_password": "testpass123",
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
"acknowledge": "true",
},
)
@@ -189,8 +189,8 @@ class TestAuthRateLimiting:
"/auth/register",
data={
"username": "newuser1",
- "password": "testpass123",
- "confirm_password": "testpass123",
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
"acknowledge": "true",
},
)
@@ -263,7 +263,7 @@ class TestAuthRateLimiting:
from local_deep_research.database.encrypted_db import db_manager
test_username = "ratelimituser"
- test_password = "testpass123"
+ test_password = "TestPass123"
# Create user if doesn't exist
if not db_manager.user_exists(test_username):
@@ -307,8 +307,8 @@ class TestAuthRateLimiting:
"/auth/register",
data={
"username": "ratelimituser", # Exists from previous test
- "password": "testpass123",
- "confirm_password": "testpass123",
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
"acknowledge": "true",
},
)
diff --git a/tests/auth_tests/test_auth_routes.py b/tests/auth_tests/test_auth_routes.py
index 55aefe48b8..1ce7a25e0a 100644
--- a/tests/auth_tests/test_auth_routes.py
+++ b/tests/auth_tests/test_auth_routes.py
@@ -98,8 +98,8 @@ class TestAuthRoutes:
"/auth/register",
data={
"username": "testuser",
- "password": "testpassword123",
- "confirm_password": "testpassword123",
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
"acknowledge": "true",
},
follow_redirects=True,
@@ -129,8 +129,8 @@ class TestAuthRoutes:
"/auth/register",
data={
"username": "@invalid!user",
- "password": "testpassword123",
- "confirm_password": "testpassword123",
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
"acknowledge": "true",
},
)
@@ -155,8 +155,8 @@ class TestAuthRoutes:
"/auth/register",
data={
"username": "testuser",
- "password": "testpassword123",
- "confirm_password": "testpassword123",
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
"acknowledge": "false",
},
)
@@ -169,8 +169,8 @@ class TestAuthRoutes:
"/auth/register",
data={
"username": "x",
- "password": "testpassword123",
- "confirm_password": "testpassword123",
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
"acknowledge": "true",
},
)
@@ -185,8 +185,8 @@ class TestAuthRoutes:
"/auth/register",
data={
"username": "",
- "password": "testpassword123",
- "confirm_password": "testpassword123",
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
"acknowledge": "true",
},
)
@@ -198,8 +198,8 @@ class TestAuthRoutes:
"/auth/register",
data={
"username": " ",
- "password": "testpassword123",
- "confirm_password": "testpassword123",
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
"acknowledge": "true",
},
)
@@ -217,8 +217,8 @@ class TestAuthRoutes:
"/auth/register",
data={
"username": "testuser",
- "password": "testpassword123",
- "confirm_password": "testpassword123",
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
"acknowledge": "true",
},
)
@@ -231,8 +231,8 @@ class TestAuthRoutes:
"/auth/register",
data={
"username": "testuser",
- "password": "otherpassword123",
- "confirm_password": "otherpassword123",
+ "password": "OtherPass123",
+ "confirm_password": "OtherPass123",
"acknowledge": "true",
},
)
@@ -250,8 +250,8 @@ class TestAuthRoutes:
"/auth/register",
data={
"username": "testuser",
- "password": "testpassword123",
- "confirm_password": "testpassword123",
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
"acknowledge": "true",
},
)
@@ -262,7 +262,7 @@ class TestAuthRoutes:
# Login
response = client.post(
"/auth/login",
- data={"username": "testuser", "password": "testpassword123"},
+ data={"username": "testuser", "password": "TestPass123"},
follow_redirects=True,
)
@@ -290,8 +290,8 @@ class TestAuthRoutes:
"/auth/register",
data={
"username": "testuser",
- "password": "testpassword123",
- "confirm_password": "testpassword123",
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
"acknowledge": "true",
},
)
@@ -321,8 +321,8 @@ class TestAuthRoutes:
"/auth/register",
data={
"username": "testuser",
- "password": "oldpassword123",
- "confirm_password": "oldpassword123",
+ "password": "OldPass123",
+ "confirm_password": "OldPass123",
"acknowledge": "true",
},
)
@@ -331,9 +331,9 @@ class TestAuthRoutes:
response = client.post(
"/auth/change-password",
data={
- "current_password": "oldpassword123",
- "new_password": "newpassword456",
- "confirm_password": "newpassword456",
+ "current_password": "OldPass123",
+ "new_password": "NewPass456",
+ "confirm_password": "NewPass456",
},
follow_redirects=False,
)
@@ -349,7 +349,7 @@ class TestAuthRoutes:
# Try to login with new password
response = client.post(
"/auth/login",
- data={"username": "testuser", "password": "newpassword456"},
+ data={"username": "testuser", "password": "NewPass456"},
follow_redirects=True,
)
@@ -362,8 +362,8 @@ class TestAuthRoutes:
"/auth/register",
data={
"username": "testuser",
- "password": "testpassword123",
- "confirm_password": "testpassword123",
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
"acknowledge": "true",
},
)
@@ -376,7 +376,7 @@ class TestAuthRoutes:
"/auth/login",
data={
"username": "testuser",
- "password": "testpassword123",
+ "password": "TestPass123",
"remember": "true",
},
)
@@ -397,8 +397,8 @@ class TestAuthRoutes:
"/auth/register",
data={
"username": "testuser",
- "password": "testpassword123",
- "confirm_password": "testpassword123",
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
"acknowledge": "true",
},
)
@@ -439,8 +439,8 @@ class TestAuthRoutes:
"/auth/register",
data={
"username": "testuser_blocked",
- "password": "testpassword123",
- "confirm_password": "testpassword123",
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
"acknowledge": "true",
},
follow_redirects=False,
diff --git a/tests/conftest.py b/tests/conftest.py
index 27071c3fdc..d8f4434733 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -250,7 +250,7 @@ def authenticated_client(app, temp_data_dir):
"""Create a test client with an authenticated user."""
# Create unique test username using UUID to avoid conflicts in parallel tests
test_username = generate_unique_test_username()
- test_password = "testpassword123"
+ test_password = "TestPass123"
# Clear any existing user database
encrypted_db_dir = temp_data_dir / "encrypted_databases"
diff --git a/tests/security/test_account_lockout.py b/tests/security/test_account_lockout.py
new file mode 100644
index 0000000000..d984718cbc
--- /dev/null
+++ b/tests/security/test_account_lockout.py
@@ -0,0 +1,72 @@
+"""Tests for per-user account lockout."""
+
+from local_deep_research.security.account_lockout import AccountLockoutManager
+
+
+class TestAccountLockout:
+ """Unit tests for AccountLockoutManager."""
+
+ def _make_manager(self, threshold=3, lockout_minutes=15):
+ return AccountLockoutManager(
+ threshold=threshold, lockout_minutes=lockout_minutes
+ )
+
+ def test_not_locked_initially(self):
+ mgr = self._make_manager()
+ assert mgr.is_locked("alice") is False
+
+ def test_not_locked_below_threshold(self):
+ mgr = self._make_manager(threshold=3)
+ mgr.record_failure("alice")
+ mgr.record_failure("alice")
+ assert mgr.is_locked("alice") is False
+
+ def test_locked_at_threshold(self):
+ mgr = self._make_manager(threshold=3)
+ for _ in range(3):
+ mgr.record_failure("alice")
+ assert mgr.is_locked("alice") is True
+
+ def test_success_resets_lockout(self):
+ mgr = self._make_manager(threshold=3)
+ for _ in range(3):
+ mgr.record_failure("alice")
+ assert mgr.is_locked("alice") is True
+ mgr.record_success("alice")
+ assert mgr.is_locked("alice") is False
+
+ def test_counter_resets_after_success(self):
+ mgr = self._make_manager(threshold=10)
+ for _ in range(9):
+ mgr.record_failure("alice")
+ mgr.record_success("alice")
+ # After reset, 9 more failures should not lock (threshold is 10)
+ for _ in range(9):
+ mgr.record_failure("alice")
+ assert mgr.is_locked("alice") is False
+
+ def test_independent_users(self):
+ mgr = self._make_manager(threshold=3)
+ for _ in range(3):
+ mgr.record_failure("alice")
+ assert mgr.is_locked("alice") is True
+ assert mgr.is_locked("bob") is False
+
+ def test_success_on_nonexistent_user_is_noop(self):
+ mgr = self._make_manager()
+ # Should not raise
+ mgr.record_success("nonexistent")
+ assert mgr.is_locked("nonexistent") is False
+
+ def test_state_cleared_when_exceeds_max_entries(self):
+ 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
+ mgr.record_failure("attacker")
+ # State was cleared then the new entry added
+ 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
new file mode 100644
index 0000000000..5de0114578
--- /dev/null
+++ b/tests/security/test_log_sanitizer.py
@@ -0,0 +1,31 @@
+"""Tests for log string sanitization."""
+
+from local_deep_research.security.log_sanitizer import sanitize_for_log
+
+
+class TestLogSanitizer:
+ """Unit tests for sanitize_for_log."""
+
+ def test_normal_string_passes_through(self):
+ assert sanitize_for_log("hello") == "hello"
+
+ def test_non_printable_chars_stripped(self):
+ assert sanitize_for_log("hello\x00world\x07") == "helloworld"
+
+ def test_truncation_respects_max_length(self):
+ result = sanitize_for_log("a" * 100, max_length=10)
+ assert result == "a" * 7 + "..."
+ assert len(result) == 10
+
+ def test_no_truncation_at_exact_max_length(self):
+ result = sanitize_for_log("a" * 50, max_length=50)
+ assert result == "a" * 50
+
+ def test_empty_string(self):
+ assert sanitize_for_log("") == ""
+
+ def test_newlines_stripped(self):
+ assert sanitize_for_log("line1\nline2") == "line1line2"
+
+ def test_tabs_stripped(self):
+ assert sanitize_for_log("col1\tcol2") == "col1col2"
diff --git a/tests/security/test_password_validator.py b/tests/security/test_password_validator.py
new file mode 100644
index 0000000000..67214aba14
--- /dev/null
+++ b/tests/security/test_password_validator.py
@@ -0,0 +1,32 @@
+"""Tests for password strength validation."""
+
+from local_deep_research.security.password_validator import PasswordValidator
+
+
+class TestPasswordValidator:
+ """Unit tests for PasswordValidator.validate_strength."""
+
+ def test_valid_password(self):
+ errors = PasswordValidator.validate_strength("StrongP4ss")
+ assert errors == []
+
+ def test_too_short(self):
+ errors = PasswordValidator.validate_strength("Ab1")
+ assert any("8 characters" in e for e in errors)
+
+ def test_missing_uppercase(self):
+ errors = PasswordValidator.validate_strength("lowercase1")
+ assert any("uppercase" in e for e in errors)
+
+ def test_missing_lowercase(self):
+ errors = PasswordValidator.validate_strength("UPPERCASE1")
+ assert any("lowercase" in e for e in errors)
+
+ def test_missing_digit(self):
+ errors = PasswordValidator.validate_strength("NoDigitsHere")
+ assert any("digit" in e for e in errors)
+
+ def test_multiple_errors_for_weak_password(self):
+ errors = PasswordValidator.validate_strength("abc")
+ # Should flag: too short, no uppercase, no digit
+ assert len(errors) >= 3
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index 94b5f24dda..778d65fc15 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -7552,6 +7552,30 @@
"value": "searxng",
"visible": true
},
+ "security.account_lockout_duration_minutes": {
+ "category": "security",
+ "description": "Duration in minutes that an account remains locked after exceeding the failed login threshold. Only configurable via environment variable (LDR_SECURITY_ACCOUNT_LOCKOUT_DURATION_MINUTES).",
+ "editable": false,
+ "max_value": 60,
+ "min_value": 1,
+ "name": "Account Lockout Duration (Minutes)",
+ "type": "APP",
+ "ui_element": "number",
+ "value": 15,
+ "visible": false
+ },
+ "security.account_lockout_threshold": {
+ "category": "security",
+ "description": "Number of consecutive failed login attempts before an account is temporarily locked out. Only configurable via environment variable (LDR_SECURITY_ACCOUNT_LOCKOUT_THRESHOLD).",
+ "editable": false,
+ "max_value": 50,
+ "min_value": 3,
+ "name": "Account Lockout Threshold",
+ "type": "APP",
+ "ui_element": "number",
+ "value": 10,
+ "visible": false
+ },
"security.rate_limit_default": {
"category": "security",
"description": "Default rate limit for all HTTP endpoints. Configured via LDR_SECURITY_RATE_LIMIT_DEFAULT environment variable. Multiple limits can be separated by semicolons (e.g., '5000 per hour;50000 per day'). Format: 'N per hour/minute/day'. Requires server restart.",