~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
test: add SQLCipher integration tests and pragma order verification
LearningCircuite8a7121dd6b8
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex a7fe4ad269..109ee19696 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -265,16 +265,17 @@ class DatabaseManager:cursor = conn.cursor()# Use centralized SQLCipher setup+ # Order is critical: key → pragmas → first database operationset_sqlcipher_key(cursor, password)- # Verify connection works- if not verify_sqlcipher_connection(cursor):- raise ValueError("Failed to verify database key")-- # Apply SQLCipher and performance settings+ # Apply SQLCipher settings BEFORE any database operation (including verify)apply_sqlcipher_pragmas(cursor, creation_mode=False)apply_performance_pragmas(cursor, username)+ # Verify connection works (this is the first actual database operation)+ if not verify_sqlcipher_connection(cursor):+ raise ValueError("Failed to verify database key")+cursor.close()return conn@@ -370,16 +371,17 @@ class DatabaseManager:cursor = conn.cursor()# Use centralized SQLCipher setup+ # Order is critical: key → pragmas → first database operationset_sqlcipher_key(cursor, password)- # Verify connection works- if not verify_sqlcipher_connection(cursor):- raise ValueError("Failed to verify database key")-- # Apply SQLCipher and performance settings+ # Apply SQLCipher settings BEFORE any database operation (including verify)apply_sqlcipher_pragmas(cursor, creation_mode=False)apply_performance_pragmas(cursor, username)+ # Verify connection works (this is the first actual database operation)+ if not verify_sqlcipher_connection(cursor):+ raise ValueError("Failed to verify database key")+cursor.close()return conndiff --git a/src/local_deep_research/database/sqlcipher_utils.py b/src/local_deep_research/database/sqlcipher_utils.pyindex 75eb0ecb27..c8b36876ba 100644--- a/src/local_deep_research/database/sqlcipher_utils.py+++ b/src/local_deep_research/database/sqlcipher_utils.py@@ -151,10 +151,14 @@ def apply_sqlcipher_pragmas(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 operationcursor_or_conn.execute(f"PRAGMA cipher_page_size = {settings['page_size']}")cursor_or_conn.execute(f"PRAGMA cipher_hmac_algorithm = {settings['hmac_algorithm']}")+ cursor_or_conn.execute(+ f"PRAGMA cipher_kdf_algorithm = {settings['kdf_algorithm']}"+ )cursor_or_conn.execute(f"PRAGMA kdf_iter = {settings['kdf_iterations']}")if creation_mode:diff --git a/tests/database/test_sqlcipher_integration.py b/tests/database/test_sqlcipher_integration.pynew file mode 100644index 0000000000..61f789db84--- /dev/null+++ b/tests/database/test_sqlcipher_integration.py@@ -0,0 +1,270 @@+"""Integration tests for SQLCipher with real encryption (not mocked).++These tests verify the actual SQLCipher encryption flow, including:+- Registration followed by immediate login (the critical failing case)+- Thread-safe sessions for metrics+- Password verification (wrong password should fail)+- Multi-user isolation+"""++import pytest+++def _sqlcipher_available():+ """Check if SQLCipher is available."""+ try:+ from local_deep_research.database.sqlcipher_compat import (+ get_sqlcipher_module,+ )++ get_sqlcipher_module()+ return True+ except ImportError:+ return False+++def isolated_db_manager(tmp_path, monkeypatch):+ """Create DatabaseManager with isolated temp directory."""+ monkeypatch.setenv("LDR_DB_KDF_ITERATIONS", "1000") # Fast for testing+ monkeypatch.setenv("LDR_ALLOW_UNENCRYPTED", "false") # Require encryption++ from local_deep_research.database.encrypted_db import DatabaseManager++ manager = DatabaseManager()+ # Point to temp directory+ manager.data_dir = tmp_path / "encrypted_databases"+ manager.data_dir.mkdir(parents=True, exist_ok=True)++ yield manager++ # Cleanup+ for username in list(manager.connections.keys()):+ manager.close_user_database(username)+++ not _sqlcipher_available(), reason="SQLCipher not installed"+)+class TestSQLCipherIntegration:+ """Real SQLCipher tests (not mocked)."""++ def test_register_then_immediate_login(self, isolated_db_manager):+ """+ Critical test: Registration followed by immediate login.+ This is the exact flow that failed in UI tests.+ """+ username = "testuser"+ password = "SecurePassword123!"++ # Register (create database)+ engine = isolated_db_manager.create_user_database(username, password)+ assert engine is not None++ # Close the connection (simulates end of registration request)+ isolated_db_manager.close_user_database(username)++ # Login (open existing database) - THIS IS WHERE IT FAILED+ engine = isolated_db_manager.open_user_database(username, password)+ assert engine is not None, "Failed to open database after registration"++ # Verify database is functional+ from sqlalchemy import text++ with engine.connect() as conn:+ result = conn.execute(text("SELECT 1"))+ assert result.fetchone()[0] == 1++ def test_thread_safe_session_after_create(self, isolated_db_manager):+ """Test thread-safe session works after database creation."""+ username = "testuser"+ password = "SecurePassword123!"++ # Create database+ isolated_db_manager.create_user_database(username, password)++ # Create thread-safe session (used for metrics)+ session = isolated_db_manager.create_thread_safe_session_for_metrics(+ username, password+ )+ assert session is not None++ # Verify session works+ from sqlalchemy import text++ result = session.execute(text("SELECT 1"))+ assert result.fetchone()[0] == 1+ session.close()++ def test_wrong_password_fails(self, isolated_db_manager):+ """Verify that wrong password actually fails (encryption works)."""+ username = "testuser"+ password = "CorrectPassword123!"++ # Create database+ isolated_db_manager.create_user_database(username, password)+ isolated_db_manager.close_user_database(username)++ # Attempt to open with wrong password+ engine = isolated_db_manager.open_user_database(+ username, "WrongPassword!"+ )+ assert engine is None, "Should fail with wrong password"++ def test_multiple_users_isolated(self, isolated_db_manager):+ """Test that multiple users have separate encrypted databases."""+ users = [+ ("user1", "Password1!"),+ ("user2", "Password2!"),+ ("user3", "Password3!"),+ ]++ # Create all users+ for username, password in users:+ isolated_db_manager.create_user_database(username, password)++ # Close all connections+ for username, _ in users:+ isolated_db_manager.close_user_database(username)++ # Reopen each user - verify each password only works for its database+ for username, password in users:+ # Correct password works+ engine = isolated_db_manager.open_user_database(username, password)+ assert engine is not None, f"Failed to open {username}'s database"+ isolated_db_manager.close_user_database(username)++ # Wrong passwords fail+ for other_user, other_pass in users:+ if other_user != username:+ engine = isolated_db_manager.open_user_database(+ username, other_pass+ )+ assert engine is None, (+ f"{other_user}'s password should not work for {username}"+ )++ def test_reopen_multiple_times(self, isolated_db_manager):+ """Test database can be opened and closed multiple times."""+ username = "testuser"+ password = "SecurePassword123!"++ # Create database+ isolated_db_manager.create_user_database(username, password)++ # Open and close multiple times+ for i in range(5):+ isolated_db_manager.close_user_database(username)+ engine = isolated_db_manager.open_user_database(username, password)+ assert engine is not None, (+ f"Failed to reopen database on iteration {i}"+ )++ # Verify it works each time+ from sqlalchemy import text++ with engine.connect() as conn:+ result = conn.execute(text("SELECT 1"))+ assert result.fetchone()[0] == 1++ def test_database_persists_data(self, isolated_db_manager):+ """Test that data persists across close/open cycles."""+ username = "testuser"+ password = "SecurePassword123!"++ # Create database+ isolated_db_manager.create_user_database(username, password)++ # Insert data+ from sqlalchemy import text++ engine = isolated_db_manager.connections[username]+ with engine.connect() as conn:+ conn.execute(+ text(+ "CREATE TABLE IF NOT EXISTS test_data (id INTEGER, value TEXT)"+ )+ )+ conn.execute(text("INSERT INTO test_data VALUES (1, 'test_value')"))+ conn.commit()++ # Close and reopen+ isolated_db_manager.close_user_database(username)+ engine = isolated_db_manager.open_user_database(username, password)+ assert engine is not None++ # Verify data persists+ with engine.connect() as conn:+ result = conn.execute(+ text("SELECT value FROM test_data WHERE id = 1")+ )+ row = result.fetchone()+ assert row is not None+ assert row[0] == "test_value"++ def test_thread_safe_session_reuse(self, isolated_db_manager):+ """Test that thread-safe sessions can be created multiple times."""+ username = "testuser"+ password = "SecurePassword123!"++ # Create database+ isolated_db_manager.create_user_database(username, password)++ # Create multiple thread-safe sessions+ from sqlalchemy import text++ for i in range(3):+ session = (+ isolated_db_manager.create_thread_safe_session_for_metrics(+ username, password+ )+ )+ assert session is not None, (+ f"Failed to create session on iteration {i}"+ )++ # Verify session works+ result = session.execute(text("SELECT 1"))+ assert result.fetchone()[0] == 1+ session.close()++ def test_concurrent_access_same_user(self, isolated_db_manager):+ """Test concurrent access to the same user's database."""+ import threading++ username = "testuser"+ password = "SecurePassword123!"++ # Create database+ isolated_db_manager.create_user_database(username, password)++ errors = []+ success_count = [0]++ def worker():+ try:+ session = (+ isolated_db_manager.create_thread_safe_session_for_metrics(+ username, password+ )+ )+ from sqlalchemy import text++ result = session.execute(text("SELECT 1"))+ assert result.fetchone()[0] == 1+ session.close()+ success_count[0] += 1+ except Exception as e:+ errors.append(str(e))++ # Run multiple threads+ threads = [threading.Thread(target=worker) for _ in range(5)]+ for t in threads:+ t.start()+ for t in threads:+ t.join(timeout=10)++ assert len(errors) == 0, f"Errors during concurrent access: {errors}"+ assert success_count[0] == 5, (+ f"Only {success_count[0]}/5 threads succeeded"+ )diff --git a/tests/database/test_sqlcipher_utils.py b/tests/database/test_sqlcipher_utils.pyindex c282e10b99..8f30743c85 100644--- a/tests/database/test_sqlcipher_utils.py+++ b/tests/database/test_sqlcipher_utils.py@@ -117,6 +117,7 @@ class TestApplySqlcipherPragmas:]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):@@ -335,3 +336,161 @@ 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."""+ 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"+ )+ 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"+ )+ 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."""+ 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]++ required_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}"+ )++ def test_pragma_order_in_apply_sqlcipher_pragmas(self):+ """Verify pragmas are applied in correct order within apply_sqlcipher_pragmas."""+ 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+ )++ # 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"++ 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"+ )