~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): targeted hardening — cache, stale creds, TTL, unsafe logging (#2850)
LearningCircuitd03c16bb3e24
diff --git a/src/local_deep_research/database/sqlcipher_utils.py b/src/local_deep_research/database/sqlcipher_utils.pyindex a0ee21965e..4b40bd9244 100644--- a/src/local_deep_research/database/sqlcipher_utils.py+++ b/src/local_deep_research/database/sqlcipher_utils.py@@ -8,7 +8,6 @@ consistent password handling and PRAGMA settings across the codebase.import osimport secretsimport threading-from functools import lru_cachefrom hashlib import pbkdf2_hmacfrom pathlib import Pathfrom typing import Any, Dict, Optional, Union@@ -129,16 +128,12 @@ def has_per_database_salt(db_path: Union[str, Path]) -> bool:return get_salt_file_path(db_path).exists()-@lru_cache(maxsize=16)def _get_key_from_password(password: str, salt: bytes, kdf_iterations: int) -> bytes:"""Generates an encryption key from the user's password and salt.- Cached for performance. The cache key includes (password, salt, kdf_iterations)- so that different salts or iteration counts always produce different keys.-Args:password: The password.salt: The salt bytes to use for key derivation.diff --git a/src/local_deep_research/database/temp_auth.py b/src/local_deep_research/database/temp_auth.pyindex 637141b317..699fa7fbe1 100644--- a/src/local_deep_research/database/temp_auth.py+++ b/src/local_deep_research/database/temp_auth.py@@ -19,12 +19,12 @@ class TemporaryAuthStore(CredentialStoreBase):Passwords are stored in plain text in memory and expire after a short time."""- def __init__(self, ttl_seconds: int = 30):+ def __init__(self, ttl_seconds: int = 10):"""Initialize the temporary auth store.Args:- ttl_seconds: How long to keep auth data (default 30 seconds)+ ttl_seconds: How long to keep auth data (default 10 seconds)"""super().__init__(ttl_seconds)diff --git a/src/local_deep_research/settings/logger.py b/src/local_deep_research/settings/logger.pyindex b97a2fc63f..45f4db4efb 100644--- a/src/local_deep_research/settings/logger.py+++ b/src/local_deep_research/settings/logger.py@@ -6,7 +6,7 @@ Environment variable LDR_LOG_SETTINGS controls the verbosity:- "none" or "false": No settings logging at all (default)- "summary" or "info": Only log count and summary of settings- "debug" or "full": Log complete settings (with sensitive keys redacted)-- "debug_unsafe": Log complete settings including sensitive keys (DANGEROUS - only for debugging)+- "debug_unsafe": REMOVED for security — maps to "none" with a deprecation warning"""import os@@ -25,7 +25,16 @@ elif SETTINGS_LOG_LEVEL in ("true", "1", "yes", "info", "summary"):elif SETTINGS_LOG_LEVEL in ("debug", "full", "all"):SETTINGS_LOG_LEVEL = "debug"elif SETTINGS_LOG_LEVEL in ("debug_unsafe", "unsafe", "raw"):- SETTINGS_LOG_LEVEL = "debug_unsafe"+ import warnings++ warnings.warn(+ f"LDR_LOG_SETTINGS={os.getenv('LDR_LOG_SETTINGS')!r} is deprecated and has been "+ "removed for security. Use 'debug' for full settings with sensitive keys redacted. "+ "Defaulting to 'none'.",+ DeprecationWarning,+ stacklevel=2,+ )+ SETTINGS_LOG_LEVEL = "none"else:# Invalid value, default to noneSETTINGS_LOG_LEVEL = "none"@@ -48,7 +57,7 @@ def log_settings(- "none": No output- "summary": Log count and basic info at INFO level- "debug": Log full settings at DEBUG level (sensitive keys redacted)- - "debug_unsafe": Log full settings at DEBUG level (nothing redacted - DANGEROUS)+ - "debug_unsafe": REMOVED — maps to "none" with a deprecation warning"""log_level = force_level or SETTINGS_LOG_LEVEL@@ -68,13 +77,6 @@ def log_settings(else:logger.debug(f"{message}: {settings}")- elif log_level == "debug_unsafe":- # Log full settings at DEBUG level without redaction (DANGEROUS)- logger.debug(f"{message} (UNSAFE - includes secrets): {settings}")- logger.warning(- "Settings logged with sensitive information - use only for debugging!"- )-def redact_sensitive_keys(settings: Dict[str, Any]) -> Dict[str, Any]:"""@@ -148,6 +150,6 @@ def get_settings_log_level() -> str:Get the current settings logging level.Returns:- Current log level: "none", "summary", "debug", or "debug_unsafe"+ Current log level: "none", "summary", or "debug""""return SETTINGS_LOG_LEVELdiff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.pyindex 01acbfa101..290b97c071 100644--- a/src/local_deep_research/web/auth/routes.py+++ b/src/local_deep_research/web/auth/routes.py@@ -602,6 +602,40 @@ def change_password():# SQLCipher database. Do NOT add an auth-DB password-hash update# here; it would fail (User model has no set_password method) and# is architecturally unnecessary.++ # Clean up stale credentials before clearing session+ # (mirrors logout handler cleanup steps 1–4)+ session_id = session.get("session_id")++ # 1. Unregister from scheduler (removes stale credential)+ try:+ from ...news.subscription_manager.scheduler import (+ get_news_scheduler,+ )++ sched = get_news_scheduler()+ if sched.is_running:+ sched.unregister_user(username)+ except Exception:+ logger.warning(+ "Could not unregister user from scheduler",+ exc_info=True,+ )++ # 2. Close database connection (disposes old-password engine)+ db_manager.close_user_database(username)++ # 3. Destroy session record + clear password store+ if session_id:+ session_manager.destroy_session(session_id)++ from ...database.session_passwords import (+ session_password_store,+ )++ session_password_store.clear_session(username, session_id)++ # 4. Clear Flask session dictsession.clear()logger.info(f"Password changed for user {username}")diff --git a/tests/auth_tests/test_auth_routes.py b/tests/auth_tests/test_auth_routes.pyindex 1ce7a25e0a..85a3593cdb 100644--- a/tests/auth_tests/test_auth_routes.py+++ b/tests/auth_tests/test_auth_routes.py@@ -286,7 +286,7 @@ class TestAuthRoutes:def test_logout(self, client):"""Test logout functionality."""# Register and login- client.post(+ reg_response = client.post("/auth/register",data={"username": "testuser",@@ -294,6 +294,10 @@ class TestAuthRoutes:"confirm_password": "TestPass123","acknowledge": "true",},+ follow_redirects=False,+ )+ assert reg_response.status_code == 302, (+ f"Registration failed with status {reg_response.status_code}")# Verify logged in@@ -393,7 +397,7 @@ class TestAuthRoutes:assert data["authenticated"] is False# Register and check- client.post(+ reg_response = client.post("/auth/register",data={"username": "testuser",@@ -401,6 +405,10 @@ class TestAuthRoutes:"confirm_password": "TestPass123","acknowledge": "true",},+ follow_redirects=False,+ )+ assert reg_response.status_code == 302, (+ f"Registration failed with status {reg_response.status_code}")response = client.get("/auth/check")diff --git a/tests/auth_tests/test_sqlcipher_key_derivation.py b/tests/auth_tests/test_sqlcipher_key_derivation.pyindex 7c251ce3b9..3faf3021c9 100644--- a/tests/auth_tests/test_sqlcipher_key_derivation.py+++ b/tests/auth_tests/test_sqlcipher_key_derivation.py@@ -45,9 +45,6 @@ class TestKeyDerivation:"""Verify same password always produces same key."""password = "test_password_123"- # Clear cache to ensure fresh derivation- _get_key_from_password.cache_clear()-key1 = _get_key_from_password(password,LEGACY_PBKDF2_SALT,@@ -63,8 +60,6 @@ class TestKeyDerivation:def test_key_derivation_different_passwords(self):"""Verify different passwords produce different keys."""- _get_key_from_password.cache_clear()-key1 = _get_key_from_password("password1",LEGACY_PBKDF2_SALT,@@ -78,36 +73,8 @@ class TestKeyDerivation:assert key1 != key2, "Different passwords should produce different keys"- def test_key_derivation_caching(self):- """Verify key derivation results are cached correctly."""- _get_key_from_password.cache_clear()-- password = "cached_test_password"- key1 = _get_key_from_password(- password,- LEGACY_PBKDF2_SALT,- get_sqlcipher_settings()["kdf_iterations"],- )-- # Check cache info- cache_info = _get_key_from_password.cache_info()- assert cache_info.misses >= 1, "First call should be a cache miss"-- # Second call should hit cache- key2 = _get_key_from_password(- password,- LEGACY_PBKDF2_SALT,- get_sqlcipher_settings()["kdf_iterations"],- )- cache_info_after = _get_key_from_password.cache_info()- assert cache_info_after.hits >= 1, "Second call should be a cache hit"-- assert key1 == key2, "Cached key should match original"-def test_key_hex_encoding_only_hex_chars(self):"""Verify derived key only contains hex characters (SQL injection safe)."""- _get_key_from_password.cache_clear()-key = _get_key_from_password("any_password",LEGACY_PBKDF2_SALT,@@ -123,8 +90,6 @@ class TestKeyDerivation:def test_special_characters_in_password(self):"""Verify passwords with special characters are handled correctly."""- _get_key_from_password.cache_clear()-special_passwords = ["password with spaces","password'with'quotes",@@ -161,8 +126,6 @@ class TestKeyDerivation:def test_key_length_correct(self):"""Verify derived key has correct length (64 bytes = 512 bits for SHA512)."""- _get_key_from_password.cache_clear()-key = _get_key_from_password("test_password",LEGACY_PBKDF2_SALT,@@ -174,8 +137,6 @@ class TestKeyDerivation:def test_empty_password_produces_key(self):"""Verify empty password still produces a valid key (validation is elsewhere)."""- _get_key_from_password.cache_clear()-# Note: Empty password validation happens in DatabaseManager, not in key derivation# The key derivation function itself should work with any inputkey = _get_key_from_password(@@ -333,8 +294,6 @@ class TestKeyDerivationSecurity:def test_key_not_stored_in_plaintext(self):"""Verify derived key is bytes, not plaintext password."""- _get_key_from_password.cache_clear()-password = "my_secret_password"key = _get_key_from_password(password,@@ -357,15 +316,12 @@ class TestKeyDerivationSecurity:This is intentional for database compatibility - if salt changed,existing databases would become inaccessible."""- _get_key_from_password.cache_clear()-# Same password should always produce same key (fixed salt)key1 = _get_key_from_password("test",LEGACY_PBKDF2_SALT,get_sqlcipher_settings()["kdf_iterations"],)- _get_key_from_password.cache_clear()key2 = _get_key_from_password("test",LEGACY_PBKDF2_SALT,diff --git a/tests/auth_tests/test_sqlcipher_rekey.py b/tests/auth_tests/test_sqlcipher_rekey.pyindex 1c978592ca..b7cb776bba 100644--- a/tests/auth_tests/test_sqlcipher_rekey.py+++ b/tests/auth_tests/test_sqlcipher_rekey.py@@ -123,8 +123,6 @@ class TestRekeyFunctionality:def test_rekey_uses_pbkdf2_derivation(self):"""Verify rekey uses the same PBKDF2 key derivation as initial key."""- _get_key_from_password.cache_clear()-# Get derived key for a passwordpassword = "test_password_for_derivation"kdf_iterations = get_sqlcipher_settings()["kdf_iterations"]@@ -132,11 +130,7 @@ class TestRekeyFunctionality:password, LEGACY_PBKDF2_SALT, kdf_iterations)- # The rekey function should use the same derivation- cache_info = _get_key_from_password.cache_info()- assert cache_info.hits >= 0, "Function should use caching"-- # Derive again to verify same result+ # Derive again to verify same result (deterministic)derived_key_2 = _get_key_from_password(password, LEGACY_PBKDF2_SALT, kdf_iterations)diff --git a/tests/database/test_credential_store_behavior.py b/tests/database/test_credential_store_behavior.pyindex 55cdf31020..3e1568637f 100644--- a/tests/database/test_credential_store_behavior.py+++ b/tests/database/test_credential_store_behavior.py@@ -24,12 +24,12 @@ class TestCredentialStoreBaseInit:store = TemporaryAuthStore(ttl_seconds=60)assert store.ttl == 60- def test_default_ttl_is_30_seconds(self):- """Default TTL is 30 seconds."""+ def test_default_ttl_is_10_seconds(self):+ """Default TTL is 10 seconds."""from local_deep_research.database.temp_auth import TemporaryAuthStorestore = TemporaryAuthStore()- assert store.ttl == 30+ assert store.ttl == 10class TestCredentialStoreAuth:diff --git a/tests/database/test_temp_auth.py b/tests/database/test_temp_auth.pyindex 2b80eec501..7c56d50e17 100644--- a/tests/database/test_temp_auth.py+++ b/tests/database/test_temp_auth.py@@ -7,11 +7,11 @@ class TestTemporaryAuthStore:"""Tests for TemporaryAuthStore class."""def test_init_with_default_ttl(self):- """TemporaryAuthStore initializes with default 30-second TTL."""+ """TemporaryAuthStore initializes with default 10-second TTL."""from local_deep_research.database.temp_auth import TemporaryAuthStorestore = TemporaryAuthStore()- assert store.ttl == 30+ assert store.ttl == 10def test_init_with_custom_ttl(self):"""TemporaryAuthStore accepts custom TTL in seconds."""diff --git a/tests/settings/test_settings_logger.py b/tests/settings/test_settings_logger.pyindex 68276d8d07..af80fb63ff 100644--- a/tests/settings/test_settings_logger.py+++ b/tests/settings/test_settings_logger.py@@ -83,29 +83,65 @@ class TestLogSettingsDebugLevel:class TestLogSettingsDebugUnsafeLevel:- """Tests for log_settings with debug_unsafe level."""+ """Tests for debug_unsafe deprecation — maps to 'none'."""++ def test_debug_unsafe_maps_to_none(self):+ """Test that debug_unsafe is deprecated and maps to 'none'."""+ import warnings- def test_log_settings_debug_unsafe_level(self):- """Test that log_settings outputs full settings without redaction."""with patch.dict(os.environ, {"LDR_LOG_SETTINGS": "debug_unsafe"}):import importlibfrom local_deep_research.settings import logger as settings_logger- importlib.reload(settings_logger)+ with warnings.catch_warnings(record=True) as w:+ warnings.simplefilter("always")+ importlib.reload(settings_logger)++ # Should have emitted a DeprecationWarning+ deprecation_warnings = [+ x for x in w if issubclass(x.category, DeprecationWarning)+ ]+ assert len(deprecation_warnings) >= 1+ assert (+ "deprecated" in str(deprecation_warnings[0].message).lower()+ )++ assert settings_logger.get_settings_log_level() == "none"++ @pytest.mark.parametrize("env_value", ["unsafe", "raw"])+ def test_unsafe_aliases_map_to_none(self, env_value):+ """Test that 'unsafe' and 'raw' also map to 'none'."""+ import warnings++ with patch.dict(os.environ, {"LDR_LOG_SETTINGS": env_value}):+ import importlib+ from local_deep_research.settings import logger as settings_logger++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ importlib.reload(settings_logger)++ assert settings_logger.get_settings_log_level() == "none"++ def test_debug_unsafe_does_not_log_secrets(self):+ """Test that debug_unsafe no longer logs unredacted settings."""+ import warnings++ with patch.dict(os.environ, {"LDR_LOG_SETTINGS": "debug_unsafe"}):+ import importlib+ from local_deep_research.settings import logger as settings_logger++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ importlib.reload(settings_logger)with patch.object(settings_logger.logger, "debug") as mock_debug:- with patch.object(- settings_logger.logger, "warning"- ) as mock_warning:- settings_logger.log_settings(- {"api_key": "secret123"}, message="Test message"- )+ settings_logger.log_settings(+ {"api_key": "secret123"}, message="Test message"+ )- mock_debug.assert_called_once()- mock_warning.assert_called_once()- # Should contain warning about sensitive info- warning_msg = mock_warning.call_args[0][0]- assert "sensitive" in warning_msg.lower()+ # Should NOT have logged anything (level is "none")+ mock_debug.assert_not_called()class TestLogSettingsForcedLevel:@@ -335,9 +371,9 @@ class TestLogLevelMapping:("debug", "debug"),("full", "debug"),("all", "debug"),- ("debug_unsafe", "debug_unsafe"),- ("unsafe", "debug_unsafe"),- ("raw", "debug_unsafe"),+ ("debug_unsafe", "none"),+ ("unsafe", "none"),+ ("raw", "none"),("invalid_value", "none"), # Invalid defaults to none],)