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: SQLCipher key derivation & crypto security fixes

LearningCircuitf18883b8403e
diff --git a/src/local_deep_research/database/sqlcipher_utils.py b/src/local_deep_research/database/sqlcipher_utils.py
index e7bd941f8f..7705dd26a8 100644
--- a/src/local_deep_research/database/sqlcipher_utils.py
+++ b/src/local_deep_research/database/sqlcipher_utils.py
@@ -5,14 +5,18 @@ This module centralizes all SQLCipher-specific operations to ensure
consistent password handling and PRAGMA settings across the codebase.
"""
+import os
+import threading
from typing import Any, Optional
from hashlib import pbkdf2_hmac
-from functools import cache
+from cachetools import TTLCache
from loguru import logger
+_key_cache = TTLCache(maxsize=50, ttl=300)
+_key_cache_lock = threading.Lock()
+
-@cache
def _get_key_from_password(password: str) -> bytes:
"""
Generates an encryption key from the user's password.
@@ -24,6 +28,12 @@ def _get_key_from_password(password: str) -> bytes:
The generated key.
"""
+ # Check TTL-bounded cache first
+ with _key_cache_lock:
+ cached = _key_cache.get(password)
+ if cached is not None:
+ return cached
+
# Generate a secure key based on the password.
settings = get_sqlcipher_settings()
logger.info("Generating DB encryption key...")
@@ -40,6 +50,10 @@ def _get_key_from_password(password: str) -> bytes:
logger.info("Generated DB encryption key.")
+ # Store in TTL-bounded cache
+ with _key_cache_lock:
+ _key_cache[password] = key
+
return key
@@ -66,7 +80,8 @@ def set_sqlcipher_rekey(cursor_or_conn: Any, new_password: str) -> None:
cursor_or_conn: SQLCipher cursor or connection object
new_password: The new password to use for encryption
"""
- hex_password = new_password.encode("utf-8").hex()
+ key = _get_key_from_password(new_password)
+ hex_password = key.hex()
# Handle SQLAlchemy connections that need text()
if hasattr(cursor_or_conn, "execute") and hasattr(
@@ -110,6 +125,10 @@ VALID_KDF_ALGORITHMS = frozenset(
# user's password into a hex key format. The actual encryption salt is
# managed by SQLCipher on a per-database basis, providing proper salt
# uniqueness. See: https://www.zetetic.net/sqlcipher/sqlcipher-api/#key
+#
+# Security note: A static salt weakens PBKDF2's resistance to rainbow tables,
+# but changing it would break all existing databases with no migration path.
+# SQLCipher's internal per-database salt provides the primary defense here.
# WARNING: Do NOT change this value - it would break all existing databases!
PBKDF2_PLACEHOLDER_SALT = b"no salt"
@@ -152,8 +171,6 @@ def get_sqlcipher_settings(username: Optional[str] = None) -> dict:
Returns:
Dictionary with SQLCipher configuration
"""
- import os
-
# Get and validate HMAC algorithm
hmac_raw = os.environ.get("LDR_DB_HMAC_ALGORITHM", DEFAULT_HMAC_ALGORITHM)
hmac_algorithm = _validate_pragma_param(
@@ -210,9 +227,20 @@ def apply_sqlcipher_pragmas(
if creation_mode:
# Additional settings only needed during creation
+ # cipher_memory_security is a runtime PRAGMA that does not affect stored
+ # database format. ON (default) zeroes memory after use for security;
+ # OFF improves performance at the cost of residual plaintext in memory.
+ mem_security = os.environ.get(
+ "LDR_DB_CIPHER_MEMORY_SECURITY", "ON"
+ ).upper()
+ if mem_security not in ("ON", "OFF"):
+ logger.warning(
+ f"Invalid LDR_DB_CIPHER_MEMORY_SECURITY value '{mem_security}', using 'ON'"
+ )
+ mem_security = "ON"
cursor_or_conn.execute(
- "PRAGMA cipher_memory_security = OFF"
- ) # Better performance
+ f"PRAGMA cipher_memory_security = {mem_security}"
+ )
def apply_performance_pragmas(
@@ -228,8 +256,6 @@ def apply_performance_pragmas(
cursor_or_conn: SQLCipher cursor or connection object
username: Username to get settings for (not used anymore)
"""
- import os
-
# Default values that are always applied
cursor_or_conn.execute("PRAGMA temp_store = MEMORY")
cursor_or_conn.execute("PRAGMA busy_timeout = 10000") # 10 second timeout
diff --git a/src/local_deep_research/news/subscription_manager/scheduler.py b/src/local_deep_research/news/subscription_manager/scheduler.py
index 393a004070..ea2b25dea3 100644
--- a/src/local_deep_research/news/subscription_manager/scheduler.py
+++ b/src/local_deep_research/news/subscription_manager/scheduler.py
@@ -406,7 +406,7 @@ class NewsScheduler:
password = session_info["password"]
logger.debug(
- f"Got password for {username}, length: {len(password) if password else 0}"
+ f"Got password for {username}: {'present' if password else 'missing'}"
)
# Get user's subscriptions from their encrypted database
diff --git a/tests/database/test_sqlcipher_utils.py b/tests/database/test_sqlcipher_utils.py
index c282e10b99..63e633224a 100644
--- a/tests/database/test_sqlcipher_utils.py
+++ b/tests/database/test_sqlcipher_utils.py
@@ -335,3 +335,159 @@ class TestCreateSqlcipherConnection:
):
with pytest.raises(ValueError, match="Failed to establish"):
create_sqlcipher_connection("/tmp/test.db", "badpassword")
+
+
+class TestSetSqlcipherRekey:
+ """Tests for set_sqlcipher_rekey function — CRITICAL security fix."""
+
+ def test_rekey_uses_pbkdf2_derived_key(self):
+ """Test that rekey uses _get_key_from_password, not raw UTF-8 hex."""
+ from local_deep_research.database.sqlcipher_utils import (
+ set_sqlcipher_rekey,
+ )
+
+ mock_cursor = Mock()
+ # Remove SQLAlchemy-like interface so we take the raw cursor path
+ mock_cursor.execute.__self__ = None
+ del mock_cursor.execute.__self__
+
+ with patch(
+ "local_deep_research.database.sqlcipher_utils._get_key_from_password"
+ ) as mock_get_key:
+ mock_get_key.return_value = b"\xab\xcd\xef"
+ set_sqlcipher_rekey(mock_cursor, "newpass")
+
+ # Verify _get_key_from_password was called with the new password
+ mock_get_key.assert_called_once_with("newpass")
+
+ # Verify the hex key from PBKDF2 is used, not raw UTF-8 hex
+ call_args = mock_cursor.execute.call_args[0][0]
+ assert "PRAGMA rekey" in call_args
+ assert "abcdef" in call_args # hex of b"\xab\xcd\xef"
+
+ def test_rekey_key_format_matches_set_key(self):
+ """Test that rekey produces same hex format as set_key."""
+ from local_deep_research.database.sqlcipher_utils import (
+ set_sqlcipher_key,
+ set_sqlcipher_rekey,
+ )
+
+ mock_cursor = Mock()
+
+ fake_key = b"\x01\x02\x03\x04"
+ with patch(
+ "local_deep_research.database.sqlcipher_utils._get_key_from_password",
+ return_value=fake_key,
+ ):
+ set_sqlcipher_key(mock_cursor, "testpass")
+ key_sql = mock_cursor.execute.call_args[0][0]
+
+ mock_cursor.reset_mock()
+ # For rekey, ensure we use the raw cursor path
+ if hasattr(mock_cursor.execute, "__self__"):
+ del mock_cursor.execute.__self__
+ set_sqlcipher_rekey(mock_cursor, "testpass")
+ rekey_sql = mock_cursor.execute.call_args[0][0]
+
+ # Both should use the same hex encoding of the PBKDF2 key
+ hex_key = fake_key.hex()
+ assert f"x'{hex_key}'" in key_sql
+ assert f"x'{hex_key}'" in rekey_sql
+
+
+class TestCipherMemorySecurityEnvVar:
+ """Tests for configurable cipher_memory_security."""
+
+ def test_defaults_to_on(self):
+ """Test that cipher_memory_security defaults to ON."""
+ from local_deep_research.database.sqlcipher_utils import (
+ apply_sqlcipher_pragmas,
+ )
+
+ mock_cursor = Mock()
+
+ with patch.dict(os.environ, {}, clear=False):
+ os.environ.pop("LDR_DB_CIPHER_MEMORY_SECURITY", None)
+ apply_sqlcipher_pragmas(mock_cursor, creation_mode=True)
+
+ call_args_list = [
+ call[0][0] for call in mock_cursor.execute.call_args_list
+ ]
+ mem_calls = [
+ arg for arg in call_args_list if "cipher_memory_security" in arg
+ ]
+ assert len(mem_calls) == 1
+ assert "ON" in mem_calls[0]
+
+ def test_respects_off_env_var(self):
+ """Test that LDR_DB_CIPHER_MEMORY_SECURITY=OFF is respected."""
+ from local_deep_research.database.sqlcipher_utils import (
+ apply_sqlcipher_pragmas,
+ )
+
+ mock_cursor = Mock()
+
+ with patch.dict(os.environ, {"LDR_DB_CIPHER_MEMORY_SECURITY": "OFF"}):
+ apply_sqlcipher_pragmas(mock_cursor, creation_mode=True)
+
+ call_args_list = [
+ call[0][0] for call in mock_cursor.execute.call_args_list
+ ]
+ mem_calls = [
+ arg for arg in call_args_list if "cipher_memory_security" in arg
+ ]
+ assert len(mem_calls) == 1
+ assert "OFF" in mem_calls[0]
+
+ def test_invalid_value_falls_back_to_on(self):
+ """Test that invalid value falls back to ON."""
+ from local_deep_research.database.sqlcipher_utils import (
+ apply_sqlcipher_pragmas,
+ )
+
+ mock_cursor = Mock()
+
+ with patch.dict(
+ os.environ, {"LDR_DB_CIPHER_MEMORY_SECURITY": "INVALID"}
+ ):
+ apply_sqlcipher_pragmas(mock_cursor, creation_mode=True)
+
+ call_args_list = [
+ call[0][0] for call in mock_cursor.execute.call_args_list
+ ]
+ mem_calls = [
+ arg for arg in call_args_list if "cipher_memory_security" in arg
+ ]
+ assert len(mem_calls) == 1
+ assert "ON" in mem_calls[0]
+
+
+class TestTTLKeyCache:
+ """Tests for TTL-bounded key cache."""
+
+ def test_cache_returns_same_key_for_same_password(self):
+ """Test that cache returns consistent results."""
+ from local_deep_research.database.sqlcipher_utils import (
+ _get_key_from_password,
+ _key_cache,
+ )
+
+ # Clear cache before test
+ _key_cache.clear()
+
+ key1 = _get_key_from_password("test_cache_password")
+ key2 = _get_key_from_password("test_cache_password")
+ assert key1 == key2
+
+ def test_different_passwords_produce_different_keys(self):
+ """Test that different passwords give different keys."""
+ from local_deep_research.database.sqlcipher_utils import (
+ _get_key_from_password,
+ _key_cache,
+ )
+
+ _key_cache.clear()
+
+ key1 = _get_key_from_password("password_a_unique")
+ key2 = _get_key_from_password("password_b_unique")
+ assert key1 != key2