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.

Merge test/sqlcipher-integration-tests with SQLCipher 4.x fixes

LearningCircuit861b78d63e47
diff --cc src/local_deep_research/database/encrypted_db.py
index 0173902883,109ee19696..569d634be2
--- a/src/local_deep_research/database/encrypted_db.py
+++ b/src/local_deep_research/database/encrypted_db.py
@@@ -279,18 -264,11 +279,16 @@@ class DatabaseManager
)
cursor = conn.cursor()
+ # IMPORTANT: For SQLCipher 4.x, cipher settings MUST be set BEFORE the key
+ # Use creation_mode=False since we're opening an existing database
+ apply_cipher_settings_before_key(cursor, creation_mode=False)
+
# Use centralized SQLCipher setup
+ # Order is critical: key → pragmas → first database operation
set_sqlcipher_key(cursor, password)
- # Verify connection works
- if not verify_sqlcipher_connection(cursor):
- raise ValueError("Failed to verify database key")
-
- # Apply SQLCipher settings BEFORE any database operation (including verify)
+ # Apply SQLCipher and performance settings (those that go after the key)
++ # Note: kdf_iter can be set after key, but BEFORE any database operation
apply_sqlcipher_pragmas(cursor, creation_mode=False)
apply_performance_pragmas(cursor, username)
@@@ -391,53 -370,18 +393,54 @@@
)
cursor = conn.cursor()
+ # IMPORTANT: For SQLCipher 4.x, cipher settings MUST be set BEFORE the key
+ # Use creation_mode=False since we're opening an existing database
+ logger.debug(
+ "[SQLCIPHER DEBUG] open_user_database: Calling apply_cipher_settings_before_key"
+ )
+ try:
+ apply_cipher_settings_before_key(
+ cursor, creation_mode=False
+ )
+ except Exception as e:
+ logger.exception(
+ f"[SQLCIPHER DEBUG] open_user_database: apply_cipher_settings_before_key failed: {e}"
+ )
+ raise
+
# Use centralized SQLCipher setup
+ # Order is critical: key → pragmas → first database operation
- set_sqlcipher_key(cursor, password)
+ logger.debug(
+ "[SQLCIPHER DEBUG] open_user_database: Calling set_sqlcipher_key"
+ )
+ try:
+ set_sqlcipher_key(cursor, password)
+ except Exception as e:
+ logger.exception(
+ f"[SQLCIPHER DEBUG] open_user_database: set_sqlcipher_key failed: {e}"
+ )
+ raise
- # Verify connection works
- # Apply SQLCipher settings BEFORE any database operation (including verify)
++ # Apply SQLCipher and performance settings BEFORE any database operation
++ logger.debug(
++ "[SQLCIPHER DEBUG] open_user_database: Calling apply_sqlcipher_pragmas"
++ )
+ apply_sqlcipher_pragmas(cursor, creation_mode=False)
+ apply_performance_pragmas(cursor, username)
+
+ # Verify connection works (this is the first actual database operation)
+ logger.debug(
+ "[SQLCIPHER DEBUG] open_user_database: Verifying connection"
+ )
if not verify_sqlcipher_connection(cursor):
+ logger.error(
+ "[SQLCIPHER DEBUG] open_user_database: verify_sqlcipher_connection returned False!"
+ )
raise ValueError("Failed to verify database key")
- # Apply SQLCipher and performance settings (those that go after the key)
- logger.debug(
- "[SQLCIPHER DEBUG] open_user_database: Calling apply_sqlcipher_pragmas"
- )
- apply_sqlcipher_pragmas(cursor, creation_mode=False)
- apply_performance_pragmas(cursor, username)
-
+ logger.debug(
+ "[SQLCIPHER DEBUG] open_user_database: Connection created successfully"
+ )
cursor.close()
return conn
diff --cc src/local_deep_research/database/sqlcipher_utils.py
index fff03a7095,c06b15b218..d65534dbbe
--- a/src/local_deep_research/database/sqlcipher_utils.py
+++ b/src/local_deep_research/database/sqlcipher_utils.py
@@@ -166,73 -147,22 +166,75 @@@ def apply_cipher_settings_before_key
Args:
cursor_or_conn: SQLCipher cursor or connection object
- creation_mode: If True, applies settings for database creation.
- If False, applies settings for existing database access.
+ creation_mode: If True, use cipher_default_* for new databases.
+ If False, use cipher_* for opening existing databases.
username: Username to get settings for (if available)
"""
- # Get settings (from database if available, otherwise defaults)
settings = get_sqlcipher_settings(username)
- # Core settings needed for both creation and access
- # These must be set AFTER PRAGMA key and BEFORE the first database operation
- cursor_or_conn.execute(f"PRAGMA cipher_page_size = {settings['page_size']}")
+ logger.debug(
+ f"[SQLCIPHER DEBUG] apply_cipher_settings (pre-pragma): "
+ f"creation_mode={creation_mode}, settings={settings}"
+ )
+
+ # These MUST be set BEFORE the key for SQLCipher 4.x compatibility
+ # Use cipher_default_* for new databases, cipher_* for existing databases
+ if creation_mode:
+ # For new databases: cipher_default_* sets the defaults that apply
+ # when the key is set on a new database
+ pragma_prefix = "cipher_default_"
+ else:
+ # For existing databases: cipher_* sets the cipher settings needed
+ # to decrypt the database
+ pragma_prefix = "cipher_"
+
+ logger.debug(
+ f"[SQLCIPHER DEBUG] Setting {pragma_prefix}page_size = {settings['page_size']}"
+ )
cursor_or_conn.execute(
- f"PRAGMA cipher_hmac_algorithm = {settings['hmac_algorithm']}"
+ f"PRAGMA {pragma_prefix}page_size = {settings['page_size']}"
+ )
+ logger.debug(
+ f"[SQLCIPHER DEBUG] Setting {pragma_prefix}hmac_algorithm = {settings['hmac_algorithm']}"
)
cursor_or_conn.execute(
- f"PRAGMA cipher_kdf_algorithm = {settings['kdf_algorithm']}"
+ f"PRAGMA {pragma_prefix}hmac_algorithm = {settings['hmac_algorithm']}"
+ )
+ logger.debug(
+ f"[SQLCIPHER DEBUG] Setting {pragma_prefix}kdf_algorithm = {settings['kdf_algorithm']}"
)
+ cursor_or_conn.execute(
+ f"PRAGMA {pragma_prefix}kdf_algorithm = {settings['kdf_algorithm']}"
+ )
+ logger.debug(
+ "[SQLCIPHER DEBUG] apply_cipher_settings (pre-pragma): completed successfully"
+ )
+
+
+def apply_sqlcipher_pragmas(
+ cursor_or_conn: Any,
+ creation_mode: bool = False,
+ username: Optional[str] = None,
+) -> None:
+ """
+ Apply SQLCipher PRAGMA settings that are set AFTER the key.
+
+ NOTE: For SQLCipher 4.x compatibility, you MUST call
+ apply_cipher_settings_before_key() BEFORE set_sqlcipher_key(),
+ and then call this function AFTER set_sqlcipher_key().
+
+ Args:
+ cursor_or_conn: SQLCipher cursor or connection object
+ creation_mode: If True, applies settings for database creation.
+ If False, applies settings for existing database access.
+ username: Username to get settings for (if available)
+ """
+ # Get settings (from database if available, otherwise defaults)
+ settings = get_sqlcipher_settings(username)
+
+ # kdf_iter can be set after the key (applies to future derivation)
++ # Note: cipher_page_size, cipher_hmac_algorithm, cipher_kdf_algorithm
++ # must be set BEFORE the key - see apply_cipher_settings_before_key()
cursor_or_conn.execute(f"PRAGMA kdf_iter = {settings['kdf_iterations']}")
if creation_mode:
diff --cc tests/database/test_sqlcipher_utils.py
index c282e10b99,8f30743c85..7aff2fda88
--- a/tests/database/test_sqlcipher_utils.py
+++ b/tests/database/test_sqlcipher_utils.py
@@@ -102,7 -102,7 +102,12 @@@ class TestApplySqlcipherPragmas
"""Tests for apply_sqlcipher_pragmas function."""
def test_applies_core_pragmas(self):
-- """Test that core PRAGMA settings are applied."""
++ """Test that kdf_iter PRAGMA is applied (post-key setting).
++
++ Note: In SQLCipher 4.x, cipher_page_size, cipher_hmac_algorithm, and
++ cipher_kdf_algorithm must be set BEFORE the key via
++ apply_cipher_settings_before_key(). Only kdf_iter is set after the key.
++ """
from local_deep_research.database.sqlcipher_utils import (
apply_sqlcipher_pragmas,
)
@@@ -111,12 -111,13 +116,10 @@@
apply_sqlcipher_pragmas(mock_cursor, creation_mode=False)
-- # Check that core pragmas were executed
++ # Check that kdf_iter pragma was executed (the only post-key cipher setting)
call_args_list = [
call[0][0] for call in mock_cursor.execute.call_args_list
]
-- assert any("cipher_page_size" in arg for arg in call_args_list)
-- assert any("cipher_hmac_algorithm" in arg for arg in call_args_list)
- assert any("cipher_kdf_algorithm" in arg for arg in call_args_list)
assert any("kdf_iter" in arg for arg in call_args_list)
def test_applies_creation_mode_pragmas(self):
@@@ -135,6 -136,6 +138,71 @@@
assert any("cipher_memory_security" in arg for arg in call_args_list)
++class TestApplyCipherSettingsBeforeKey:
++ """Tests for apply_cipher_settings_before_key function (SQLCipher 4.x)."""
++
++ def test_applies_cipher_settings_for_existing_database(self):
++ """Test that cipher_* pragmas are set for existing databases (creation_mode=False)."""
++ from local_deep_research.database.sqlcipher_utils import (
++ apply_cipher_settings_before_key,
++ )
++
++ mock_cursor = Mock()
++
++ apply_cipher_settings_before_key(mock_cursor, creation_mode=False)
++
++ call_args_list = [
++ call[0][0] for call in mock_cursor.execute.call_args_list
++ ]
++ # Should use cipher_* prefix for existing databases
++ assert any("cipher_page_size" in arg for arg in call_args_list)
++ assert any("cipher_hmac_algorithm" in arg for arg in call_args_list)
++ assert any("cipher_kdf_algorithm" in arg for arg in call_args_list)
++ # Should NOT use cipher_default_* prefix
++ assert not any("cipher_default_" in arg for arg in call_args_list)
++
++ def test_applies_cipher_default_settings_for_new_database(self):
++ """Test that cipher_default_* pragmas are set for new databases (creation_mode=True)."""
++ from local_deep_research.database.sqlcipher_utils import (
++ apply_cipher_settings_before_key,
++ )
++
++ mock_cursor = Mock()
++
++ apply_cipher_settings_before_key(mock_cursor, creation_mode=True)
++
++ call_args_list = [
++ call[0][0] for call in mock_cursor.execute.call_args_list
++ ]
++ # Should use cipher_default_* prefix for new databases
++ assert any("cipher_default_page_size" in arg for arg in call_args_list)
++ assert any(
++ "cipher_default_hmac_algorithm" in arg for arg in call_args_list
++ )
++ assert any(
++ "cipher_default_kdf_algorithm" in arg for arg in call_args_list
++ )
++
++ def test_uses_settings_from_get_sqlcipher_settings(self):
++ """Test that settings values come from get_sqlcipher_settings."""
++ from local_deep_research.database.sqlcipher_utils import (
++ apply_cipher_settings_before_key,
++ )
++
++ mock_cursor = Mock()
++
++ with patch.dict(os.environ, {"LDR_DB_PAGE_SIZE": "4096"}):
++ apply_cipher_settings_before_key(mock_cursor, creation_mode=False)
++
++ call_args_list = [
++ call[0][0] for call in mock_cursor.execute.call_args_list
++ ]
++ page_size_call = [arg for arg in call_args_list if "page_size" in arg][
++ 0
++ ]
++ assert "4096" in page_size_call
++
++
class TestApplyPerformancePragmas:
"""Tests for apply_performance_pragmas function."""
@@@ -335,3 -336,161 +403,190 @@@ class TestCreateSqlcipherConnection
):
with pytest.raises(ValueError, match="Failed to establish"):
create_sqlcipher_connection("/tmp/test.db", "badpassword")
+
+
+ class TestPragmaOrder:
+ """Tests for correct PRAGMA execution order."""
+
- def test_key_before_cipher_pragmas(self):
- """Verify key is set before cipher pragmas in create_sqlcipher_connection."""
++ def test_sqlcipher_4x_pragma_order(self):
++ """Verify SQLCipher 4.x correct order: cipher settings → key → kdf_iter → verify.
++
++ In SQLCipher 4.x, cipher_page_size, cipher_hmac_algorithm, and
++ cipher_kdf_algorithm MUST be set BEFORE the key. Only kdf_iter
++ is set after the key.
++ """
+ from local_deep_research.database.sqlcipher_utils import (
+ create_sqlcipher_connection,
+ )
+
+ execution_order = []
+
+ def track_execute(sql, *args, **kwargs):
+ execution_order.append(sql)
+
+ mock_cursor = Mock()
+ mock_cursor.execute = Mock(side_effect=track_execute)
+ mock_cursor.fetchone.return_value = (1,)
+
+ mock_conn = Mock()
+ mock_conn.cursor.return_value = mock_cursor
+
+ mock_sqlcipher = Mock()
+ mock_sqlcipher.connect.return_value = mock_conn
+
+ with patch(
+ "local_deep_research.database.sqlcipher_compat.get_sqlcipher_module",
+ return_value=mock_sqlcipher,
+ ):
+ with patch(
+ "local_deep_research.database.sqlcipher_utils._get_key_from_password",
+ return_value=b"\x01\x02\x03",
+ ):
+ create_sqlcipher_connection("/tmp/test.db", "password")
+
+ # Find indices of key operations
+ key_idx = next(
+ i for i, sql in enumerate(execution_order) if "PRAGMA key" in sql
+ )
+ cipher_page_idx = next(
+ i
+ for i, sql in enumerate(execution_order)
+ if "cipher_page_size" in sql
+ )
+ kdf_iter_idx = next(
+ i for i, sql in enumerate(execution_order) if "kdf_iter" in sql
+ )
+ verify_idx = next(
+ i for i, sql in enumerate(execution_order) if "SELECT 1" in sql
+ )
+
- # Key MUST be first
- assert key_idx < cipher_page_idx, (
- "Key must be set before cipher_page_size"
++ # SQLCipher 4.x order: cipher_page_size MUST be BEFORE key
++ assert cipher_page_idx < key_idx, (
++ "cipher_page_size must be set BEFORE key (SQLCipher 4.x requirement)"
+ )
- assert key_idx < kdf_iter_idx, "Key must be set before kdf_iter"
+
- # Verify (SELECT 1) must be AFTER pragmas
- assert verify_idx > cipher_page_idx, (
- "Verification must be after cipher pragmas"
- )
++ # kdf_iter comes AFTER the key
++ assert key_idx < kdf_iter_idx, "kdf_iter must be set AFTER key"
++
++ # Verify (SELECT 1) must be AFTER all pragmas
+ assert verify_idx > kdf_iter_idx, "Verification must be after kdf_iter"
+
- def test_all_cipher_pragmas_present(self):
- """Verify all required cipher pragmas are executed."""
++ def test_all_cipher_pragmas_present_in_correct_functions(self):
++ """Verify cipher pragmas are in correct functions for SQLCipher 4.x.
++
++ In SQLCipher 4.x:
++ - apply_cipher_settings_before_key(): cipher_page_size, cipher_hmac_algorithm, cipher_kdf_algorithm
++ - apply_sqlcipher_pragmas(): only kdf_iter
++ """
+ from local_deep_research.database.sqlcipher_utils import (
++ apply_cipher_settings_before_key,
+ apply_sqlcipher_pragmas,
+ )
+
- mock_cursor = Mock()
- apply_sqlcipher_pragmas(mock_cursor, creation_mode=False)
-
- call_args = [call[0][0] for call in mock_cursor.execute.call_args_list]
++ # Test apply_cipher_settings_before_key - should have cipher settings
++ mock_cursor_before = Mock()
++ apply_cipher_settings_before_key(
++ mock_cursor_before, creation_mode=False
++ )
++ before_key_args = [
++ call[0][0] for call in mock_cursor_before.execute.call_args_list
++ ]
+
- required_pragmas = [
++ before_key_pragmas = [
+ "cipher_page_size",
+ "cipher_hmac_algorithm",
+ "cipher_kdf_algorithm",
- "kdf_iter",
+ ]
-
- for pragma in required_pragmas:
- assert any(pragma in arg for arg in call_args), (
- f"Missing pragma: {pragma}"
++ for pragma in before_key_pragmas:
++ assert any(pragma in arg for arg in before_key_args), (
++ f"Missing pragma in apply_cipher_settings_before_key: {pragma}"
+ )
+
- def test_pragma_order_in_apply_sqlcipher_pragmas(self):
- """Verify pragmas are applied in correct order within apply_sqlcipher_pragmas."""
++ # Test apply_sqlcipher_pragmas - should only have kdf_iter
++ mock_cursor_after = Mock()
++ apply_sqlcipher_pragmas(mock_cursor_after, creation_mode=False)
++ after_key_args = [
++ call[0][0] for call in mock_cursor_after.execute.call_args_list
++ ]
++
++ assert any("kdf_iter" in arg for arg in after_key_args), (
++ "Missing kdf_iter in apply_sqlcipher_pragmas"
++ )
++ # Verify cipher settings are NOT in apply_sqlcipher_pragmas
++ assert not any("cipher_page_size" in arg for arg in after_key_args), (
++ "cipher_page_size should NOT be in apply_sqlcipher_pragmas"
++ )
++ assert not any(
++ "cipher_hmac_algorithm" in arg for arg in after_key_args
++ ), "cipher_hmac_algorithm should NOT be in apply_sqlcipher_pragmas"
++ assert not any(
++ "cipher_kdf_algorithm" in arg for arg in after_key_args
++ ), "cipher_kdf_algorithm should NOT be in apply_sqlcipher_pragmas"
++
++ def test_apply_sqlcipher_pragmas_sets_kdf_iter(self):
++ """Verify apply_sqlcipher_pragmas only sets kdf_iter (post-key setting).
++
++ In SQLCipher 4.x, cipher_page_size, cipher_hmac_algorithm, and
++ cipher_kdf_algorithm are set via apply_cipher_settings_before_key()
++ BEFORE the key. Only kdf_iter is set via apply_sqlcipher_pragmas()
++ AFTER the key.
++ """
+ from local_deep_research.database.sqlcipher_utils import (
+ apply_sqlcipher_pragmas,
+ )
+
+ execution_order = []
+
+ def track_execute(sql, *args, **kwargs):
+ execution_order.append(sql)
+
+ mock_cursor = Mock()
+ mock_cursor.execute = Mock(side_effect=track_execute)
+
+ apply_sqlcipher_pragmas(mock_cursor, creation_mode=False)
+
- # cipher_page_size should come first among cipher pragmas
- cipher_page_idx = next(
- i
- for i, sql in enumerate(execution_order)
- if "cipher_page_size" in sql
- )
- hmac_idx = next(
- i
- for i, sql in enumerate(execution_order)
- if "cipher_hmac_algorithm" in sql
- )
- kdf_algo_idx = next(
- i
- for i, sql in enumerate(execution_order)
- if "cipher_kdf_algorithm" in sql
- )
- kdf_iter_idx = next(
- i for i, sql in enumerate(execution_order) if "kdf_iter" in sql
++ # kdf_iter should be present
++ assert any("kdf_iter" in sql for sql in execution_order), (
++ "kdf_iter pragma missing"
+ )
+
- # All cipher pragmas should be present
- assert cipher_page_idx >= 0, "cipher_page_size pragma missing"
- assert hmac_idx >= 0, "cipher_hmac_algorithm pragma missing"
- assert kdf_algo_idx >= 0, "cipher_kdf_algorithm pragma missing"
- assert kdf_iter_idx >= 0, "kdf_iter pragma missing"
++ # cipher settings should NOT be present (they're in apply_cipher_settings_before_key)
++ assert not any("cipher_page_size" in sql for sql in execution_order), (
++ "cipher_page_size should not be in apply_sqlcipher_pragmas"
++ )
++ assert not any(
++ "cipher_hmac_algorithm" in sql for sql in execution_order
++ ), "cipher_hmac_algorithm should not be in apply_sqlcipher_pragmas"
++ assert not any(
++ "cipher_kdf_algorithm" in sql for sql in execution_order
++ ), "cipher_kdf_algorithm should not be in apply_sqlcipher_pragmas"
+
+ def test_creation_mode_adds_memory_security_pragma(self):
+ """Verify creation_mode=True adds cipher_memory_security pragma."""
+ from local_deep_research.database.sqlcipher_utils import (
+ apply_sqlcipher_pragmas,
+ )
+
+ mock_cursor = Mock()
+ apply_sqlcipher_pragmas(mock_cursor, creation_mode=True)
+
+ call_args = [call[0][0] for call in mock_cursor.execute.call_args_list]
+
+ assert any("cipher_memory_security" in arg for arg in call_args), (
+ "cipher_memory_security pragma missing in creation mode"
+ )
+
+ def test_non_creation_mode_skips_memory_security_pragma(self):
+ """Verify creation_mode=False skips cipher_memory_security pragma."""
+ from local_deep_research.database.sqlcipher_utils import (
+ apply_sqlcipher_pragmas,
+ )
+
+ mock_cursor = Mock()
+ apply_sqlcipher_pragmas(mock_cursor, creation_mode=False)
+
+ call_args = [call[0][0] for call in mock_cursor.execute.call_args_list]
+
+ assert not any("cipher_memory_security" in arg for arg in call_args), (
+ "cipher_memory_security pragma should not be set in non-creation mode"
+ )