~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 comprehensive SQLCipher 4.6 compatibility tests
LearningCircuit9e1cf136d66a
diff --git a/src/local_deep_research/database/sqlcipher_utils.py b/src/local_deep_research/database/sqlcipher_utils.pyindex 497303615a..b07c0d54ec 100644--- a/src/local_deep_research/database/sqlcipher_utils.py+++ b/src/local_deep_research/database/sqlcipher_utils.py@@ -71,23 +71,18 @@ def set_sqlcipher_rekey(cursor_or_conn: Any, new_password: str) -> None:"""# Use the same key derivation as set_sqlcipher_key for consistencykey = _get_key_from_password(new_password) # gitleaks:allow- hex_key = key.hex()- # Handle SQLAlchemy connections that need text()- if hasattr(cursor_or_conn, "execute") and hasattr(- cursor_or_conn.execute, "__self__"- ):- # This is likely a SQLAlchemy connection+ # Try SQLAlchemy text() first, fall back to raw string+ # The hex encoding already prevents injection since it only contains [0-9a-f]+ safe_sql = f"PRAGMA rekey = \"x'{key.hex()}'\""++ try:+ # Try SQLAlchemy connection (needs text() wrapper)from sqlalchemy import text- # SQLAlchemy doesn't support parameterized PRAGMA, so we use the safe hex encoding- # The hex encoding already prevents injection since it only contains [0-9a-f]- safe_sql = f"PRAGMA rekey = \"x'{hex_key}'\""cursor_or_conn.execute(text(safe_sql))- else:- # Raw SQLCipher connection - also doesn't support parameterized PRAGMA- # The hex encoding already prevents injection since it only contains [0-9a-f]- safe_sql = f"PRAGMA rekey = \"x'{hex_key}'\""+ except TypeError:+ # Raw SQLCipher connection - use string directlycursor_or_conn.execute(safe_sql)diff --git a/tests/auth_tests/test_encrypted_db.py b/tests/auth_tests/test_encrypted_db.pyindex 5f567e3da3..65cc6639d1 100644--- a/tests/auth_tests/test_encrypted_db.py+++ b/tests/auth_tests/test_encrypted_db.py@@ -234,3 +234,162 @@ class TestDatabaseManager:result = conn.execute(text("PRAGMA cipher_page_size"))# Default page size is 16384 (16KB)assert result.scalar() == "16384"+++class TestConnectionVerification:+ """Tests for connection verification functionality."""++ def test_verify_connection_correct_password(self, db_manager, auth_user):+ """Verify connection verification returns True with correct password."""+ from src.local_deep_research.database.sqlcipher_utils import (+ apply_cipher_settings_before_key,+ set_sqlcipher_key,+ verify_sqlcipher_connection,+ )+ from src.local_deep_research.database.sqlcipher_compat import (+ get_sqlcipher_module,+ )++ # Create database+ db_manager.create_user_database("testuser", "testpassword123")+ db_path = db_manager._get_user_db_path("testuser")+ db_manager.close_user_database("testuser")++ # Verify connection with correct password+ sqlcipher = get_sqlcipher_module()+ conn = sqlcipher.connect(str(db_path))+ cursor = conn.cursor()+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "testpassword123")++ assert verify_sqlcipher_connection(cursor) is True+ cursor.close()+ conn.close()++ def test_verify_connection_wrong_password(self, db_manager, auth_user):+ """Verify accessing encrypted data with wrong password fails."""+ from src.local_deep_research.database.sqlcipher_utils import (+ apply_cipher_settings_before_key,+ set_sqlcipher_key,+ )+ from src.local_deep_research.database.sqlcipher_compat import (+ get_sqlcipher_module,+ )++ # Create database+ db_manager.create_user_database("testuser", "correctpassword")+ db_path = db_manager._get_user_db_path("testuser")+ db_manager.close_user_database("testuser")++ # Try to access encrypted data with wrong password+ sqlcipher = get_sqlcipher_module()+ conn = sqlcipher.connect(str(db_path))+ cursor = conn.cursor()+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "wrongpassword")+ cursor.close()++ # Accessing actual encrypted data should fail+ with pytest.raises(Exception):+ # Try to read from an actual table - this will fail with wrong key+ conn.execute(+ "SELECT name FROM sqlite_master WHERE type='table'"+ ).fetchall()++ conn.close()++ def test_all_pragmas_applied_comprehensive(self, db_manager, auth_user):+ """Comprehensive test verifying ALL SQLCipher pragmas are applied."""+ from src.local_deep_research.database.sqlcipher_utils import (+ get_sqlcipher_settings,+ )++ settings = get_sqlcipher_settings()+ engine = db_manager.create_user_database("testuser", "testpassword123")++ with engine.connect() as conn:+ # Cipher settings (must be set before key)+ page_size = conn.execute(text("PRAGMA cipher_page_size")).scalar()+ assert str(page_size) == str(settings["page_size"]), (+ f"cipher_page_size mismatch: expected {settings['page_size']}, got {page_size}"+ )++ hmac_algo = conn.execute(+ text("PRAGMA cipher_hmac_algorithm")+ ).scalar()+ assert hmac_algo == settings["hmac_algorithm"], (+ f"cipher_hmac_algorithm mismatch: expected {settings['hmac_algorithm']}, got {hmac_algo}"+ )++ kdf_algo = conn.execute(+ text("PRAGMA cipher_kdf_algorithm")+ ).scalar()+ assert kdf_algo == settings["kdf_algorithm"], (+ f"cipher_kdf_algorithm mismatch: expected {settings['kdf_algorithm']}, got {kdf_algo}"+ )++ # Settings that go after key+ kdf_iter = conn.execute(text("PRAGMA kdf_iter")).scalar()+ assert str(kdf_iter) == str(settings["kdf_iterations"]), (+ f"kdf_iter mismatch: expected {settings['kdf_iterations']}, got {kdf_iter}"+ )++ # Performance settings+ journal_mode = conn.execute(text("PRAGMA journal_mode")).scalar()+ assert journal_mode.lower() == "wal", (+ f"journal_mode should be WAL, got {journal_mode}"+ )++ temp_store = conn.execute(text("PRAGMA temp_store")).scalar()+ assert temp_store == 2, (+ f"temp_store should be 2 (MEMORY), got {temp_store}"+ )++ busy_timeout = conn.execute(text("PRAGMA busy_timeout")).scalar()+ assert busy_timeout == 10000, (+ f"busy_timeout should be 10000, got {busy_timeout}"+ )++ synchronous = conn.execute(text("PRAGMA synchronous")).scalar()+ assert synchronous == 1, (+ f"synchronous should be 1 (NORMAL), got {synchronous}"+ )++ def test_create_sqlcipher_connection_helper(self, db_manager, auth_user):+ """Test the create_sqlcipher_connection helper function."""+ from src.local_deep_research.database.sqlcipher_utils import (+ create_sqlcipher_connection,+ )++ # Create database first+ db_manager.create_user_database("testuser", "testpassword123")+ db_path = db_manager._get_user_db_path("testuser")+ db_manager.close_user_database("testuser")++ # Use helper function to open+ conn = create_sqlcipher_connection(str(db_path), "testpassword123")+ assert conn is not None++ # Verify connection works+ result = conn.execute("SELECT 1").fetchone()+ assert result == (1,)++ conn.close()++ def test_create_sqlcipher_connection_wrong_password(+ self, db_manager, auth_user+ ):+ """Test create_sqlcipher_connection fails with wrong password."""+ from src.local_deep_research.database.sqlcipher_utils import (+ create_sqlcipher_connection,+ )++ # Create database first+ db_manager.create_user_database("testuser", "correctpassword")+ db_path = db_manager._get_user_db_path("testuser")+ db_manager.close_user_database("testuser")++ # Wrong password should raise an error (DatabaseError from SQLCipher)+ # when trying to execute pragmas on encrypted database+ with pytest.raises(Exception):+ create_sqlcipher_connection(str(db_path), "wrongpassword")diff --git a/tests/auth_tests/test_sqlcipher_backwards_compat.py b/tests/auth_tests/test_sqlcipher_backwards_compat.pynew file mode 100644index 0000000000..71d97a1f03--- /dev/null+++ b/tests/auth_tests/test_sqlcipher_backwards_compat.py@@ -0,0 +1,350 @@+"""+Tests for SQLCipher backwards compatibility.++These tests verify that databases can be created, closed, and reopened+correctly across multiple sessions, ensuring data persistence and+settings consistency.+"""++import shutil+import tempfile+from pathlib import Path++import pytest++from src.local_deep_research.database.sqlcipher_utils import (+ apply_cipher_settings_before_key,+ apply_performance_pragmas,+ apply_sqlcipher_pragmas,+ set_sqlcipher_key,+)+from src.local_deep_research.database.sqlcipher_compat import (+ get_sqlcipher_module,+)+++def temp_db_path():+ """Create a temporary database path."""+ temp_dir = tempfile.mkdtemp()+ db_path = Path(temp_dir) / "test_compat.db"+ yield db_path+ shutil.rmtree(temp_dir)+++def sqlcipher_module():+ """Get the SQLCipher module."""+ return get_sqlcipher_module()+++def create_configured_connection(sqlcipher_module, db_path, password):+ """Helper to create a properly configured connection."""+ conn = sqlcipher_module.connect(str(db_path))+ cursor = conn.cursor()+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, password)+ apply_sqlcipher_pragmas(cursor)+ apply_performance_pragmas(cursor)+ cursor.close()+ return conn+++class TestCreateCloseReopen:+ """Tests for create → close → reopen cycles."""++ def test_create_and_reopen_same_session(+ self, sqlcipher_module, temp_db_path+ ):+ """Verify database can be created and reopened within same test."""+ password = "test_password_123"++ # Create database+ conn1 = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ conn1.execute("CREATE TABLE test (id INTEGER PRIMARY KEY, data TEXT)")+ conn1.execute("INSERT INTO test VALUES (1, 'test_data')")+ conn1.commit()+ conn1.close()++ # Reopen database+ conn2 = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ result = conn2.execute("SELECT data FROM test WHERE id = 1").fetchone()+ assert result[0] == "test_data", (+ "Data should persist after close/reopen"+ )+ conn2.close()++ def test_create_reopen_multiple_times(self, sqlcipher_module, temp_db_path):+ """Verify database can be opened and closed multiple times."""+ password = "test_password_456"++ # Create database+ conn = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ conn.execute(+ "CREATE TABLE counter (id INTEGER PRIMARY KEY, count INTEGER)"+ )+ conn.execute("INSERT INTO counter VALUES (1, 0)")+ conn.commit()+ conn.close()++ # Open and close 5 times, incrementing counter each time+ for i in range(5):+ conn = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ conn.execute("UPDATE counter SET count = count + 1 WHERE id = 1")+ conn.commit()+ conn.close()++ # Final open to verify counter+ conn = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ result = conn.execute(+ "SELECT count FROM counter WHERE id = 1"+ ).fetchone()+ assert result[0] == 5, (+ f"Counter should be 5 after 5 increments, got {result[0]}"+ )+ conn.close()++ def test_data_persists_across_sessions(+ self, sqlcipher_module, temp_db_path+ ):+ """Verify complex data persists correctly across sessions."""+ password = "persistence_test"++ # Session 1: Create database with multiple tables and data+ conn1 = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ conn1.execute("""+ CREATE TABLE users (+ id INTEGER PRIMARY KEY,+ username TEXT UNIQUE,+ email TEXT+ )+ """)+ conn1.execute("""+ CREATE TABLE settings (+ user_id INTEGER,+ key TEXT,+ value TEXT,+ FOREIGN KEY(user_id) REFERENCES users(id)+ )+ """)++ # Insert test data+ conn1.execute(+ "INSERT INTO users VALUES (1, 'alice', '[email protected]')"+ )+ conn1.execute("INSERT INTO users VALUES (2, 'bob', '[email protected]')")+ conn1.execute("INSERT INTO settings VALUES (1, 'theme', 'dark')")+ conn1.execute("INSERT INTO settings VALUES (1, 'language', 'en')")+ conn1.execute("INSERT INTO settings VALUES (2, 'theme', 'light')")+ conn1.commit()+ conn1.close()++ # Session 2: Verify all data persists+ conn2 = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )++ # Check users+ users = conn2.execute(+ "SELECT username, email FROM users ORDER BY id"+ ).fetchall()+ assert users == [+ ("alice", "[email protected]"),+ ("bob", "[email protected]"),+ ]++ # Check settings+ alice_settings = conn2.execute(+ "SELECT key, value FROM settings WHERE user_id = 1 ORDER BY key"+ ).fetchall()+ assert alice_settings == [("language", "en"), ("theme", "dark")]++ bob_settings = conn2.execute(+ "SELECT key, value FROM settings WHERE user_id = 2"+ ).fetchall()+ assert bob_settings == [("theme", "light")]++ conn2.close()++ def test_settings_match_after_reopen(self, sqlcipher_module, temp_db_path):+ """Verify SQLCipher settings remain consistent after reopen."""+ password = "settings_test"++ # Create database+ conn1 = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ conn1.execute("CREATE TABLE test (id INTEGER)")+ conn1.commit()++ # Capture settings from first connection+ original_page_size = conn1.execute(+ "PRAGMA cipher_page_size"+ ).fetchone()[0]+ original_hmac = conn1.execute(+ "PRAGMA cipher_hmac_algorithm"+ ).fetchone()[0]+ original_kdf = conn1.execute("PRAGMA cipher_kdf_algorithm").fetchone()[+ 0+ ]+ conn1.close()++ # Reopen and verify settings+ conn2 = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )++ new_page_size = conn2.execute("PRAGMA cipher_page_size").fetchone()[0]+ new_hmac = conn2.execute("PRAGMA cipher_hmac_algorithm").fetchone()[0]+ new_kdf = conn2.execute("PRAGMA cipher_kdf_algorithm").fetchone()[0]++ assert str(new_page_size) == str(original_page_size), (+ f"Page size changed: {original_page_size} -> {new_page_size}"+ )+ assert new_hmac == original_hmac, (+ f"HMAC algorithm changed: {original_hmac} -> {new_hmac}"+ )+ assert new_kdf == original_kdf, (+ f"KDF algorithm changed: {original_kdf} -> {new_kdf}"+ )++ conn2.close()+++class TestDatabaseMigration:+ """Tests for database schema changes across sessions."""++ def test_schema_migration(self, sqlcipher_module, temp_db_path):+ """Verify schema can be modified across sessions."""+ password = "migration_test"++ # Session 1: Create initial schema+ conn1 = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ conn1.execute("CREATE TABLE data (id INTEGER PRIMARY KEY, value TEXT)")+ conn1.execute("INSERT INTO data VALUES (1, 'initial')")+ conn1.commit()+ conn1.close()++ # Session 2: Modify schema (add column)+ conn2 = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ conn2.execute("ALTER TABLE data ADD COLUMN created_at TEXT")+ conn2.execute("UPDATE data SET created_at = '2024-01-01' WHERE id = 1")+ conn2.commit()+ conn2.close()++ # Session 3: Verify modified schema+ conn3 = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ result = conn3.execute(+ "SELECT value, created_at FROM data WHERE id = 1"+ ).fetchone()+ assert result == ("initial", "2024-01-01")+ conn3.close()++ def test_create_index_persists(self, sqlcipher_module, temp_db_path):+ """Verify indexes persist across sessions."""+ password = "index_test"++ # Session 1: Create table and index+ conn1 = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ conn1.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT)")+ conn1.execute("CREATE INDEX idx_email ON users(email)")+ conn1.commit()+ conn1.close()++ # Session 2: Verify index exists+ conn2 = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ indexes = conn2.execute(+ "SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='users'"+ ).fetchall()++ index_names = [idx[0] for idx in indexes]+ assert "idx_email" in index_names, (+ f"Index not found. Indexes: {index_names}"+ )+ conn2.close()+++class TestLargeDataPersistence:+ """Tests for large data persistence."""++ def test_large_blob_persists(self, sqlcipher_module, temp_db_path):+ """Verify large binary data persists correctly."""+ password = "blob_test"+ import os++ # Create 1MB of random data+ large_data = os.urandom(1024 * 1024)++ # Session 1: Store large blob+ conn1 = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ conn1.execute("CREATE TABLE blobs (id INTEGER PRIMARY KEY, data BLOB)")+ conn1.execute("INSERT INTO blobs VALUES (1, ?)", (large_data,))+ conn1.commit()+ conn1.close()++ # Session 2: Retrieve and verify+ conn2 = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ result = conn2.execute("SELECT data FROM blobs WHERE id = 1").fetchone()+ assert result[0] == large_data, "Large blob data corrupted or changed"+ conn2.close()++ def test_many_rows_persist(self, sqlcipher_module, temp_db_path):+ """Verify many rows persist correctly."""+ password = "many_rows_test"++ # Session 1: Insert 1000 rows+ conn1 = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ conn1.execute(+ "CREATE TABLE numbers (id INTEGER PRIMARY KEY, value INTEGER)"+ )++ for i in range(1000):+ conn1.execute("INSERT INTO numbers VALUES (?, ?)", (i, i * 2))+ conn1.commit()+ conn1.close()++ # Session 2: Verify all rows+ conn2 = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ count = conn2.execute("SELECT COUNT(*) FROM numbers").fetchone()[0]+ assert count == 1000, f"Expected 1000 rows, got {count}"++ # Verify some specific values+ for test_id in [0, 499, 999]:+ result = conn2.execute(+ "SELECT value FROM numbers WHERE id = ?", (test_id,)+ ).fetchone()+ assert result[0] == test_id * 2, (+ f"Row {test_id} has wrong value: {result[0]} != {test_id * 2}"+ )++ conn2.close()diff --git a/tests/auth_tests/test_sqlcipher_compatibility.py b/tests/auth_tests/test_sqlcipher_compatibility.pynew file mode 100644index 0000000000..826b1e29cf--- /dev/null+++ b/tests/auth_tests/test_sqlcipher_compatibility.py@@ -0,0 +1,371 @@+"""+Tests for SQLCipher 4.6+ Community Edition compatibility.++These tests verify that the cipher_default_* pragmas are used correctly+and that the PRAGMA ordering (before/after key) is correct.+"""++import shutil+import tempfile+from pathlib import Path++import pytest++from src.local_deep_research.database.encrypted_db import DatabaseManager+from src.local_deep_research.database.sqlcipher_compat import (+ get_sqlcipher_module,+)+from src.local_deep_research.database.sqlcipher_utils import (+ apply_cipher_settings_before_key,+ apply_sqlcipher_pragmas,+ get_sqlcipher_settings,+ set_sqlcipher_key,+)+++def temp_data_dir():+ """Create a temporary data directory for testing."""+ temp_dir = tempfile.mkdtemp()+ yield Path(temp_dir)+ shutil.rmtree(temp_dir)+++def temp_db_path(temp_data_dir):+ """Create a temporary database path."""+ return temp_data_dir / "test_cipher.db"+++def sqlcipher_module():+ """Get the SQLCipher module."""+ return get_sqlcipher_module()+++def db_manager(temp_data_dir, monkeypatch):+ """Create a DatabaseManager with test configuration."""+ monkeypatch.setenv("LDR_DATA_DIR", str(temp_data_dir))+ manager = DatabaseManager()+ manager.data_dir = temp_data_dir / "encrypted_databases"+ manager.data_dir.mkdir(parents=True, exist_ok=True)+ return manager+++def auth_user(temp_data_dir, monkeypatch):+ """Create a test user in auth database."""+ monkeypatch.setenv("LDR_DATA_DIR", str(temp_data_dir))++ from src.local_deep_research.database.auth_db import (+ get_auth_db_session,+ init_auth_database,+ )+ from src.local_deep_research.database.models.auth import User++ init_auth_database()+ auth_db = get_auth_db_session()+ user = User(username="testuser")+ auth_db.add(user)+ auth_db.commit()+ auth_db.close()+ return user+++class TestSQLCipher46Compatibility:+ """Tests for SQLCipher 4.6+ compatibility with cipher_default_* pragmas."""++ def test_cipher_default_page_size_applied(+ self, sqlcipher_module, temp_db_path+ ):+ """Verify cipher_default_page_size pragma is applied correctly."""+ settings = get_sqlcipher_settings()+ expected_page_size = settings["page_size"]++ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()++ # Apply cipher settings BEFORE key (SQLCipher 4.6+ requirement)+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "testpassword")+ cursor.close()++ # Verify the page size is applied+ result = conn.execute("PRAGMA cipher_page_size").fetchone()+ assert result is not None+ assert str(result[0]) == str(expected_page_size), (+ f"Expected cipher_page_size={expected_page_size}, got {result[0]}"+ )++ conn.close()++ def test_cipher_default_hmac_algorithm_applied(+ self, sqlcipher_module, temp_db_path+ ):+ """Verify cipher_default_hmac_algorithm pragma is applied correctly."""+ settings = get_sqlcipher_settings()+ expected_hmac = settings["hmac_algorithm"]++ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()++ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "testpassword")+ cursor.close()++ result = conn.execute("PRAGMA cipher_hmac_algorithm").fetchone()+ assert result is not None+ assert result[0] == expected_hmac, (+ f"Expected cipher_hmac_algorithm={expected_hmac}, got {result[0]}"+ )++ conn.close()++ def test_cipher_default_kdf_algorithm_applied(+ self, sqlcipher_module, temp_db_path+ ):+ """Verify cipher_default_kdf_algorithm pragma is applied correctly."""+ settings = get_sqlcipher_settings()+ expected_kdf = settings["kdf_algorithm"]++ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()++ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "testpassword")+ cursor.close()++ result = conn.execute("PRAGMA cipher_kdf_algorithm").fetchone()+ assert result is not None+ assert result[0] == expected_kdf, (+ f"Expected cipher_kdf_algorithm={expected_kdf}, got {result[0]}"+ )++ conn.close()++ def test_pragma_order_cipher_settings_before_key(+ self, sqlcipher_module, temp_db_path+ ):+ """Verify that cipher_default_* pragmas work when applied BEFORE key."""+ settings = get_sqlcipher_settings()++ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()++ # Correct order: cipher settings BEFORE key+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "testpassword")++ # Should be able to create tables and query+ conn.execute("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)")+ conn.execute("INSERT INTO test VALUES (1, 'hello')")+ result = conn.execute("SELECT * FROM test").fetchone()++ assert result == (1, "hello"), (+ "Database should be accessible with correct order"+ )++ # Verify settings were applied+ page_size = conn.execute("PRAGMA cipher_page_size").fetchone()[0]+ assert str(page_size) == str(settings["page_size"])++ cursor.close()+ conn.close()++ def test_pragma_order_kdf_iter_after_key(+ self, sqlcipher_module, temp_db_path+ ):+ """Verify that kdf_iter pragma works when applied AFTER key."""+ settings = get_sqlcipher_settings()++ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()++ # Correct order+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "testpassword")+ apply_sqlcipher_pragmas(cursor, creation_mode=True)+ cursor.close()++ # Verify kdf_iter was applied+ result = conn.execute("PRAGMA kdf_iter").fetchone()+ assert result is not None+ assert str(result[0]) == str(settings["kdf_iterations"]), (+ f"Expected kdf_iter={settings['kdf_iterations']}, got {result[0]}"+ )++ conn.close()++ def test_cipher_default_pragmas_set_correct_defaults(+ self, sqlcipher_module, temp_db_path+ ):+ """+ Verify that cipher_default_* pragmas properly configure the database.++ This test confirms that using cipher_default_page_size (not cipher_page_size)+ correctly sets the page size for new databases in SQLCipher 4.6+.+ """+ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()++ # Use cipher_default_page_size (the correct way for SQLCipher 4.6+)+ cursor.execute("PRAGMA cipher_default_page_size = 16384")+ cursor.execute("PRAGMA key = 'testpassword'")+ cursor.close()++ # The page size should be 16384 as we set it+ result = conn.execute("PRAGMA cipher_page_size").fetchone()+ assert result[0] == "16384", (+ f"cipher_default_page_size should set page size to 16384, got {result[0]}"+ )++ # Create a table to ensure database is usable+ conn.execute("CREATE TABLE test (id INTEGER PRIMARY KEY)")+ conn.execute("INSERT INTO test VALUES (1)")+ result = conn.execute("SELECT * FROM test").fetchone()+ assert result == (1,), "Database should be functional"++ conn.close()++ def test_database_created_with_correct_settings(+ self, db_manager, auth_user+ ):+ """Verify database is created with all correct SQLCipher settings."""+ from sqlalchemy import text++ settings = get_sqlcipher_settings()+ engine = db_manager.create_user_database("testuser", "testpassword123")++ with engine.connect() as conn:+ # Check all cipher settings+ page_size = conn.execute(text("PRAGMA cipher_page_size")).scalar()+ hmac_algo = conn.execute(+ text("PRAGMA cipher_hmac_algorithm")+ ).scalar()+ kdf_algo = conn.execute(+ text("PRAGMA cipher_kdf_algorithm")+ ).scalar()+ kdf_iter = conn.execute(text("PRAGMA kdf_iter")).scalar()++ assert str(page_size) == str(settings["page_size"]), (+ f"cipher_page_size mismatch: expected {settings['page_size']}, got {page_size}"+ )+ assert hmac_algo == settings["hmac_algorithm"], (+ f"cipher_hmac_algorithm mismatch: expected {settings['hmac_algorithm']}, got {hmac_algo}"+ )+ assert kdf_algo == settings["kdf_algorithm"], (+ f"cipher_kdf_algorithm mismatch: expected {settings['kdf_algorithm']}, got {kdf_algo}"+ )+ assert str(kdf_iter) == str(settings["kdf_iterations"]), (+ f"kdf_iter mismatch: expected {settings['kdf_iterations']}, got {kdf_iter}"+ )++ def test_database_reopened_with_matching_settings(+ self, db_manager, auth_user+ ):+ """Verify database can be reopened and settings remain consistent."""+ from sqlalchemy import text++ settings = get_sqlcipher_settings()++ # Create database+ engine = db_manager.create_user_database("testuser", "testpassword123")++ # Create a test table and write some data+ with engine.connect() as conn:+ conn.execute(+ text(+ "CREATE TABLE IF NOT EXISTS test_data (id INTEGER PRIMARY KEY, value TEXT)"+ )+ )+ conn.execute(+ text(+ "INSERT INTO test_data (id, value) VALUES (1, 'test_value')"+ )+ )+ conn.commit()++ # Close the database+ db_manager.close_user_database("testuser")+ assert "testuser" not in db_manager.connections++ # Reopen the database+ engine2 = db_manager.open_user_database("testuser", "testpassword123")+ assert engine2 is not None++ with engine2.connect() as conn:+ # Verify settings are still correct+ page_size = conn.execute(text("PRAGMA cipher_page_size")).scalar()+ hmac_algo = conn.execute(+ text("PRAGMA cipher_hmac_algorithm")+ ).scalar()+ kdf_algo = conn.execute(+ text("PRAGMA cipher_kdf_algorithm")+ ).scalar()++ assert str(page_size) == str(settings["page_size"])+ assert hmac_algo == settings["hmac_algorithm"]+ assert kdf_algo == settings["kdf_algorithm"]++ # Verify data is still there+ result = conn.execute(+ text("SELECT value FROM test_data WHERE id = 1")+ ).scalar()+ assert result == "test_value", "Data should persist after reopen"+++class TestSQLCipherVersionDetection:+ """Tests for SQLCipher version detection and compatibility."""++ def test_sqlcipher_version_is_4x(self, sqlcipher_module, temp_db_path):+ """Verify we're testing against SQLCipher 4.x."""+ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()++ # Set key first (required to query version in some setups)+ cursor.execute("PRAGMA key = 'test'")++ result = conn.execute("PRAGMA cipher_version").fetchone()+ assert result is not None++ version = result[0]+ # Should be 4.x.x (e.g., "4.6.1 community")+ assert version.startswith("4."), (+ f"Expected SQLCipher 4.x, got {version}"+ )++ cursor.close()+ conn.close()++ def test_cipher_settings_function_returns_valid_settings(self):+ """Verify get_sqlcipher_settings returns all required keys."""+ settings = get_sqlcipher_settings()++ required_keys = [+ "kdf_iterations",+ "page_size",+ "hmac_algorithm",+ "kdf_algorithm",+ ]+ for key in required_keys:+ assert key in settings, f"Missing required setting: {key}"++ # Verify types+ assert isinstance(settings["kdf_iterations"], int)+ assert isinstance(settings["page_size"], int)+ assert isinstance(settings["hmac_algorithm"], str)+ assert isinstance(settings["kdf_algorithm"], str)++ # Verify reasonable values+ assert settings["kdf_iterations"] >= 100000, (+ "KDF iterations should be >= 100000"+ )+ assert settings["page_size"] in [+ 1024,+ 4096,+ 8192,+ 16384,+ 32768,+ 65536,+ ], "Page size should be a valid SQLite page size"diff --git a/tests/auth_tests/test_sqlcipher_key_derivation.py b/tests/auth_tests/test_sqlcipher_key_derivation.pynew file mode 100644index 0000000000..8ae0abd29c--- /dev/null+++ b/tests/auth_tests/test_sqlcipher_key_derivation.py@@ -0,0 +1,307 @@+"""+Tests for SQLCipher key derivation functions.++These tests verify that password-to-key derivation is consistent,+deterministic, and secure.+"""++import shutil+import tempfile+from pathlib import Path++import pytest++from src.local_deep_research.database.sqlcipher_utils import (+ _get_key_from_password,+ get_sqlcipher_settings,+ set_sqlcipher_key,+ set_sqlcipher_rekey,+)+from src.local_deep_research.database.sqlcipher_compat import (+ get_sqlcipher_module,+)+++def temp_db_path():+ """Create a temporary database path."""+ temp_dir = tempfile.mkdtemp()+ db_path = Path(temp_dir) / "test_key.db"+ yield db_path+ shutil.rmtree(temp_dir)+++def sqlcipher_module():+ """Get the SQLCipher module."""+ return get_sqlcipher_module()+++class TestKeyDerivation:+ """Tests for password-to-key derivation."""++ def test_key_derivation_deterministic(self):+ """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)+ key2 = _get_key_from_password(password)++ assert key1 == key2, "Same password should always produce same key"++ 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")+ key2 = _get_key_from_password("password2")++ 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)++ # 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)+ 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")+ hex_string = key.hex()++ # Verify only hex characters+ valid_hex_chars = set("0123456789abcdef")+ assert all(c in valid_hex_chars for c in hex_string), (+ "Key hex encoding should only contain [0-9a-f]"+ )++ 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",+ 'password"with"double"quotes',+ "password\\with\\backslashes",+ "password\nwith\nnewlines",+ "password\twith\ttabs",+ "unicode: 日本語 emoji: 🔐🔑",+ "sql_injection: '; DROP TABLE users; --",+ "null_byte: \x00test",+ ]++ keys = []+ for password in special_passwords:+ try:+ key = _get_key_from_password(password)+ keys.append(key)+ # Verify key is valid bytes+ assert isinstance(key, bytes), (+ f"Key should be bytes for: {password}"+ )+ assert len(key) > 0, f"Key should not be empty for: {password}"+ except Exception as e:+ pytest.fail(f"Password '{password}' caused error: {e}")++ # All keys should be unique+ assert len(set(keys)) == len(keys), (+ "All special passwords should produce unique keys"+ )++ 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")++ # SHA512-based PBKDF2 produces 64-byte key (512 bits)+ assert len(key) == 64, f"Key should be 64 bytes, got {len(key)}"++ 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 input+ key = _get_key_from_password("")+ assert isinstance(key, bytes), (+ "Empty password should still produce bytes"+ )+ assert len(key) == 64, (+ "Key length should be consistent (64 bytes for SHA512)"+ )+++class TestKeyDerivationWithDatabase:+ """Tests for key derivation in actual database operations."""++ def test_derived_key_opens_database(self, sqlcipher_module, temp_db_path):+ """Verify derived key can create and open a database."""+ from src.local_deep_research.database.sqlcipher_utils import (+ apply_cipher_settings_before_key,+ )++ password = "test_database_password"++ # Create database+ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, password)+ cursor.close()++ conn.execute("CREATE TABLE test (id INTEGER PRIMARY KEY)")+ conn.execute("INSERT INTO test VALUES (1)")+ conn.commit() # Important: commit before closing+ conn.close()++ # Reopen with same password+ conn2 = sqlcipher_module.connect(str(temp_db_path))+ cursor2 = conn2.cursor()+ apply_cipher_settings_before_key(cursor2)+ set_sqlcipher_key(cursor2, password)+ cursor2.close()++ result = conn2.execute("SELECT * FROM test").fetchone()+ assert result == (1,), "Should be able to read data with same password"+ conn2.close()++ def test_wrong_password_cannot_open(self, sqlcipher_module, temp_db_path):+ """Verify wrong password cannot open database."""+ from src.local_deep_research.database.sqlcipher_utils import (+ apply_cipher_settings_before_key,+ )++ # Create database with password1+ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "password1")+ cursor.close()++ conn.execute("CREATE TABLE test (id INTEGER PRIMARY KEY)")+ conn.commit()+ conn.close()++ # Try to open with password2+ conn2 = sqlcipher_module.connect(str(temp_db_path))+ cursor2 = conn2.cursor()+ apply_cipher_settings_before_key(cursor2)+ set_sqlcipher_key(cursor2, "password2")+ cursor2.close()++ # Should fail when trying to access data+ with pytest.raises(Exception):+ conn2.execute("SELECT * FROM test").fetchone()++ conn2.close()++ def test_rekey_uses_same_derivation(self, sqlcipher_module, temp_db_path):+ """Verify rekey produces key compatible with set_sqlcipher_key."""+ from src.local_deep_research.database.sqlcipher_utils import (+ apply_cipher_settings_before_key,+ )++ # Create database+ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "original_password")+ cursor.close()++ conn.execute("CREATE TABLE test (id INTEGER, value TEXT)")+ conn.execute("INSERT INTO test VALUES (1, 'secret_data')")+ conn.commit()++ # Rekey to new password+ set_sqlcipher_rekey(conn, "new_password")+ conn.close()++ # Open with new password using set_sqlcipher_key+ conn2 = sqlcipher_module.connect(str(temp_db_path))+ cursor2 = conn2.cursor()+ apply_cipher_settings_before_key(cursor2)+ set_sqlcipher_key(cursor2, "new_password")+ cursor2.close()++ # Should be able to read data+ result = conn2.execute("SELECT value FROM test WHERE id = 1").fetchone()+ assert result[0] == "secret_data", "Data should be readable after rekey"+ conn2.close()++ # Original password should no longer work+ conn3 = sqlcipher_module.connect(str(temp_db_path))+ cursor3 = conn3.cursor()+ apply_cipher_settings_before_key(cursor3)+ set_sqlcipher_key(cursor3, "original_password")+ cursor3.close()++ with pytest.raises(Exception):+ conn3.execute("SELECT * FROM test").fetchone()+ conn3.close()+++class TestKeyDerivationSecurity:+ """Security-focused tests for key derivation."""++ def test_pbkdf2_iterations_sufficient(self):+ """Verify KDF iterations are set to a secure value."""+ settings = get_sqlcipher_settings()+ iterations = settings["kdf_iterations"]++ # OWASP recommends at least 600,000 for PBKDF2-HMAC-SHA512+ # We use 256,000 which is a reasonable balance for performance+ assert iterations >= 100000, (+ f"KDF iterations should be at least 100000, got {iterations}"+ )++ 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)++ # Key should be bytes, not string+ assert isinstance(key, bytes), "Key should be bytes"++ # Key should not contain the password+ assert password.encode() not in key, (+ "Key should not contain plaintext password"+ )++ def test_different_salts_would_produce_different_keys(self):+ """+ Document that our fixed salt means same password = same key.++ 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")+ _get_key_from_password.cache_clear()+ key2 = _get_key_from_password("test")++ assert key1 == key2, (+ "Fixed salt ensures consistent key derivation for database compatibility"+ )diff --git a/tests/auth_tests/test_sqlcipher_performance.py b/tests/auth_tests/test_sqlcipher_performance.pynew file mode 100644index 0000000000..c883cdf7e3--- /dev/null+++ b/tests/auth_tests/test_sqlcipher_performance.py@@ -0,0 +1,268 @@+"""+Tests for SQLCipher performance pragmas.++These tests verify that performance-related PRAGMA settings are+correctly applied for optimal database performance.+"""++import shutil+import tempfile+from pathlib import Path++import pytest++from src.local_deep_research.database.sqlcipher_utils import (+ apply_cipher_settings_before_key,+ apply_performance_pragmas,+ set_sqlcipher_key,+)+from src.local_deep_research.database.sqlcipher_compat import (+ get_sqlcipher_module,+)+++def temp_db_path():+ """Create a temporary database path."""+ temp_dir = tempfile.mkdtemp()+ db_path = Path(temp_dir) / "test_performance.db"+ yield db_path+ shutil.rmtree(temp_dir)+++def sqlcipher_module():+ """Get the SQLCipher module."""+ return get_sqlcipher_module()+++def configured_connection(sqlcipher_module, temp_db_path):+ """Create a fully configured database connection."""+ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "testpassword")+ apply_performance_pragmas(cursor)+ cursor.close()+ return conn+++class TestWALMode:+ """Tests for WAL (Write-Ahead Logging) mode."""++ def test_wal_mode_enabled(self, configured_connection):+ """Verify WAL journal mode is enabled by default."""+ result = configured_connection.execute("PRAGMA journal_mode").fetchone()+ assert result is not None+ assert result[0].lower() == "wal", f"Expected WAL mode, got {result[0]}"+ configured_connection.close()++ def test_wal_creates_additional_files(self, sqlcipher_module, temp_db_path):+ """Verify WAL mode creates -wal and -shm files."""+ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "testpassword")+ apply_performance_pragmas(cursor)+ cursor.close()++ # Create a table and write data to trigger WAL file creation+ conn.execute("CREATE TABLE test (id INTEGER PRIMARY KEY, data TEXT)")+ conn.execute("INSERT INTO test VALUES (1, 'test_data')")+ conn.commit()++ # Note: WAL files (-wal, -shm) may not exist immediately or may be cleaned up+ # The main verification is that WAL mode is enabled+ assert (+ conn.execute("PRAGMA journal_mode").fetchone()[0].lower() == "wal"+ )+ conn.close()++ def test_concurrent_reads_with_wal(self, sqlcipher_module, temp_db_path):+ """Verify WAL mode allows concurrent read connections."""+ # Create and populate database+ conn1 = sqlcipher_module.connect(str(temp_db_path))+ cursor1 = conn1.cursor()+ apply_cipher_settings_before_key(cursor1)+ set_sqlcipher_key(cursor1, "testpassword")+ apply_performance_pragmas(cursor1)+ cursor1.close()++ conn1.execute("CREATE TABLE test (id INTEGER PRIMARY KEY, data TEXT)")+ conn1.execute("INSERT INTO test VALUES (1, 'data1')")+ conn1.commit()++ # Open second read connection while first is open+ conn2 = sqlcipher_module.connect(str(temp_db_path))+ cursor2 = conn2.cursor()+ apply_cipher_settings_before_key(cursor2)+ set_sqlcipher_key(cursor2, "testpassword")+ apply_performance_pragmas(cursor2)+ cursor2.close()++ # Both connections should be able to read+ result1 = conn1.execute("SELECT * FROM test").fetchall()+ result2 = conn2.execute("SELECT * FROM test").fetchall()++ assert result1 == result2 == [(1, "data1")]++ conn2.close()+ conn1.close()+++class TestCacheSettings:+ """Tests for cache size settings."""++ def test_cache_size_applied(self, configured_connection):+ """Verify cache_size pragma is applied."""+ result = configured_connection.execute("PRAGMA cache_size").fetchone()+ assert result is not None+ # Default is 64MB = 65536KB, stored as negative value+ assert result[0] < 0, "Cache size should be negative (KB format)"+ configured_connection.close()++ def test_temp_store_memory(self, configured_connection):+ """Verify temp_store is set to MEMORY."""+ result = configured_connection.execute("PRAGMA temp_store").fetchone()+ assert result is not None+ # 2 = MEMORY+ assert result[0] == 2, (+ f"Expected temp_store=2 (MEMORY), got {result[0]}"+ )+ configured_connection.close()+++class TestBusyTimeout:+ """Tests for busy timeout setting."""++ def test_busy_timeout_applied(self, configured_connection):+ """Verify busy_timeout is set to prevent immediate lock failures."""+ result = configured_connection.execute("PRAGMA busy_timeout").fetchone()+ assert result is not None+ assert result[0] == 10000, (+ f"Expected busy_timeout=10000, got {result[0]}"+ )+ configured_connection.close()++ def test_busy_timeout_prevents_immediate_lock_error(+ self, sqlcipher_module, temp_db_path+ ):+ """Verify busy_timeout allows waiting for locks."""++ # Create database+ conn1 = sqlcipher_module.connect(str(temp_db_path))+ cursor1 = conn1.cursor()+ apply_cipher_settings_before_key(cursor1)+ set_sqlcipher_key(cursor1, "testpassword")+ apply_performance_pragmas(cursor1)+ cursor1.close()++ conn1.execute("CREATE TABLE test (id INTEGER PRIMARY KEY, data TEXT)")+ conn1.execute("INSERT INTO test VALUES (1, 'data1')")+ conn1.commit()++ # The busy_timeout should allow retries+ # This is a basic test that the setting is applied+ result = conn1.execute("PRAGMA busy_timeout").fetchone()+ assert result[0] == 10000++ conn1.close()+++class TestSynchronousMode:+ """Tests for synchronous mode setting."""++ def test_synchronous_mode_normal(self, configured_connection):+ """Verify synchronous mode is set to NORMAL (good balance)."""+ result = configured_connection.execute("PRAGMA synchronous").fetchone()+ assert result is not None+ # Default is NORMAL (1)+ assert result[0] == 1, (+ f"Expected synchronous=1 (NORMAL), got {result[0]}"+ )+ configured_connection.close()+++class TestPerformanceIntegration:+ """Integration tests for performance settings."""++ def test_all_performance_pragmas_applied(self, configured_connection):+ """Verify all performance pragmas are applied correctly."""+ pragmas = {+ "journal_mode": lambda x: x.lower() == "wal",+ "temp_store": lambda x: x == 2,+ "busy_timeout": lambda x: x == 10000,+ "synchronous": lambda x: x == 1,+ }++ for pragma, validator in pragmas.items():+ result = configured_connection.execute(+ f"PRAGMA {pragma}"+ ).fetchone()+ assert result is not None, f"PRAGMA {pragma} returned None"+ assert validator(result[0]), (+ f"PRAGMA {pragma} has unexpected value: {result[0]}"+ )++ configured_connection.close()++ def test_performance_after_reopen(self, sqlcipher_module, temp_db_path):+ """Verify performance settings persist across connections."""+ # Create database with performance pragmas+ conn1 = sqlcipher_module.connect(str(temp_db_path))+ cursor1 = conn1.cursor()+ apply_cipher_settings_before_key(cursor1)+ set_sqlcipher_key(cursor1, "testpassword")+ apply_performance_pragmas(cursor1)+ cursor1.close()++ conn1.execute("CREATE TABLE test (id INTEGER)")+ conn1.commit()+ conn1.close()++ # Reopen and verify+ conn2 = sqlcipher_module.connect(str(temp_db_path))+ cursor2 = conn2.cursor()+ apply_cipher_settings_before_key(cursor2)+ set_sqlcipher_key(cursor2, "testpassword")+ apply_performance_pragmas(cursor2)+ cursor2.close()++ # WAL mode persists (stored in database file)+ result = conn2.execute("PRAGMA journal_mode").fetchone()+ assert result[0].lower() == "wal"++ # Other settings are per-connection but should still be applied+ result = conn2.execute("PRAGMA busy_timeout").fetchone()+ assert result[0] == 10000++ conn2.close()++ def test_write_performance_with_settings(self, configured_connection):+ """Verify database performs well with applied settings."""+ import time++ configured_connection.execute(+ "CREATE TABLE perf_test (id INTEGER PRIMARY KEY, data TEXT)"+ )++ # Insert 100 rows and measure time+ start = time.time()+ for i in range(100):+ configured_connection.execute(+ f"INSERT INTO perf_test VALUES ({i}, 'test_data_{i}')"+ )+ configured_connection.commit()+ elapsed = time.time() - start++ # Should complete in reasonable time (< 5 seconds with WAL)+ assert elapsed < 5, f"100 inserts took {elapsed:.2f}s - too slow"++ # Verify all data was written+ count = configured_connection.execute(+ "SELECT COUNT(*) FROM perf_test"+ ).fetchone()[0]+ assert count == 100++ configured_connection.close()diff --git a/tests/auth_tests/test_sqlcipher_rekey.py b/tests/auth_tests/test_sqlcipher_rekey.pynew file mode 100644index 0000000000..9a955a3998--- /dev/null+++ b/tests/auth_tests/test_sqlcipher_rekey.py@@ -0,0 +1,353 @@+"""+Tests for SQLCipher rekey (password change) functionality.++These tests verify that password changes work correctly and use+consistent key derivation with initial key setup.+"""++import shutil+import tempfile+from pathlib import Path++import pytest++from src.local_deep_research.database.sqlcipher_utils import (+ apply_cipher_settings_before_key,+ set_sqlcipher_key,+ set_sqlcipher_rekey,+ _get_key_from_password,+)+from src.local_deep_research.database.sqlcipher_compat import (+ get_sqlcipher_module,+)+++def temp_db_path():+ """Create a temporary database path."""+ temp_dir = tempfile.mkdtemp()+ db_path = Path(temp_dir) / "test_rekey.db"+ yield db_path+ shutil.rmtree(temp_dir)+++def sqlcipher_module():+ """Get the SQLCipher module."""+ return get_sqlcipher_module()+++def encrypted_db(sqlcipher_module, temp_db_path):+ """Create an encrypted database with test data."""+ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "original_password")+ cursor.close()++ conn.execute("CREATE TABLE test_data (id INTEGER PRIMARY KEY, value TEXT)")+ conn.execute("INSERT INTO test_data VALUES (1, 'secret_value_1')")+ conn.execute("INSERT INTO test_data VALUES (2, 'secret_value_2')")+ conn.execute("INSERT INTO test_data VALUES (3, 'secret_value_3')")+ conn.commit()++ return {"conn": conn, "path": temp_db_path, "password": "original_password"}+++class TestRekeyFunctionality:+ """Tests for basic rekey operations."""++ def test_rekey_changes_password(self, encrypted_db, sqlcipher_module):+ """Verify rekey successfully changes the database password."""+ conn = encrypted_db["conn"]+ db_path = encrypted_db["path"]++ # Change password+ set_sqlcipher_rekey(conn, "new_password")+ conn.close()++ # Old password should fail+ conn_old = sqlcipher_module.connect(str(db_path))+ cursor_old = conn_old.cursor()+ apply_cipher_settings_before_key(cursor_old)+ set_sqlcipher_key(cursor_old, "original_password")+ cursor_old.close()++ with pytest.raises(Exception):+ conn_old.execute("SELECT * FROM test_data").fetchone()+ conn_old.close()++ # New password should work+ conn_new = sqlcipher_module.connect(str(db_path))+ cursor_new = conn_new.cursor()+ apply_cipher_settings_before_key(cursor_new)+ set_sqlcipher_key(cursor_new, "new_password")+ cursor_new.close()++ result = conn_new.execute("SELECT * FROM test_data").fetchall()+ assert len(result) == 3, (+ "All data should be accessible with new password"+ )+ conn_new.close()++ def test_rekey_preserves_all_data(self, encrypted_db, sqlcipher_module):+ """Verify all data is preserved after password change."""+ conn = encrypted_db["conn"]+ db_path = encrypted_db["path"]++ # Read data before rekey+ original_data = conn.execute(+ "SELECT id, value FROM test_data ORDER BY id"+ ).fetchall()++ # Change password+ set_sqlcipher_rekey(conn, "new_password")+ conn.close()++ # Read data after rekey+ conn_new = sqlcipher_module.connect(str(db_path))+ cursor_new = conn_new.cursor()+ apply_cipher_settings_before_key(cursor_new)+ set_sqlcipher_key(cursor_new, "new_password")+ cursor_new.close()++ new_data = conn_new.execute(+ "SELECT id, value FROM test_data ORDER BY id"+ ).fetchall()+ conn_new.close()++ assert original_data == new_data, "Data should be identical after rekey"++ 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 password+ password = "test_password_for_derivation"+ derived_key = _get_key_from_password(password)++ # The rekey function should use the same derivation+ # We verify by checking that both set_sqlcipher_key and set_sqlcipher_rekey+ # call _get_key_from_password with the same logic+ cache_info = _get_key_from_password.cache_info()+ assert cache_info.hits >= 0, "Function should use caching"++ # Derive again to verify same result+ derived_key_2 = _get_key_from_password(password)+ assert derived_key == derived_key_2, (+ "Key derivation must be deterministic"+ )++ def test_rekey_multiple_times(self, encrypted_db, sqlcipher_module):+ """Verify password can be changed multiple times."""+ conn = encrypted_db["conn"]+ db_path = encrypted_db["path"]++ passwords = ["password_1", "password_2", "password_3", "final_password"]++ for new_password in passwords:+ set_sqlcipher_rekey(conn, new_password)++ conn.close()++ # Only the final password should work+ for wrong_password in passwords[:-1]:+ conn_wrong = sqlcipher_module.connect(str(db_path))+ cursor_wrong = conn_wrong.cursor()+ apply_cipher_settings_before_key(cursor_wrong)+ set_sqlcipher_key(cursor_wrong, wrong_password)+ cursor_wrong.close()++ with pytest.raises(Exception):+ conn_wrong.execute("SELECT * FROM test_data").fetchone()+ conn_wrong.close()++ # Final password works+ conn_final = sqlcipher_module.connect(str(db_path))+ cursor_final = conn_final.cursor()+ apply_cipher_settings_before_key(cursor_final)+ set_sqlcipher_key(cursor_final, "final_password")+ cursor_final.close()++ result = conn_final.execute("SELECT * FROM test_data").fetchall()+ assert len(result) == 3+ conn_final.close()+++class TestRekeySpecialPasswords:+ """Tests for rekey with special characters in passwords."""++ def test_rekey_with_quotes(self, encrypted_db, sqlcipher_module):+ """Verify rekey works with quotes in password."""+ conn = encrypted_db["conn"]+ db_path = encrypted_db["path"]++ # Password with single and double quotes+ new_password = "pass'word\"with'quotes\""++ set_sqlcipher_rekey(conn, new_password)+ conn.close()++ # Verify new password works+ conn_new = sqlcipher_module.connect(str(db_path))+ cursor_new = conn_new.cursor()+ apply_cipher_settings_before_key(cursor_new)+ set_sqlcipher_key(cursor_new, new_password)+ cursor_new.close()++ result = conn_new.execute("SELECT * FROM test_data").fetchone()+ assert result is not None, (+ "Database should be accessible with quoted password"+ )+ conn_new.close()++ def test_rekey_with_unicode(self, encrypted_db, sqlcipher_module):+ """Verify rekey works with unicode characters."""+ conn = encrypted_db["conn"]+ db_path = encrypted_db["path"]++ # Password with unicode and emoji+ new_password = "パスワード🔐安全🔑"++ set_sqlcipher_rekey(conn, new_password)+ conn.close()++ # Verify new password works+ conn_new = sqlcipher_module.connect(str(db_path))+ cursor_new = conn_new.cursor()+ apply_cipher_settings_before_key(cursor_new)+ set_sqlcipher_key(cursor_new, new_password)+ cursor_new.close()++ result = conn_new.execute("SELECT * FROM test_data").fetchone()+ assert result is not None, (+ "Database should be accessible with unicode password"+ )+ conn_new.close()++ def test_rekey_with_backslashes(self, encrypted_db, sqlcipher_module):+ """Verify rekey works with backslashes in password."""+ conn = encrypted_db["conn"]+ db_path = encrypted_db["path"]++ # Password with backslashes+ new_password = "pass\\word\\with\\backslashes"++ set_sqlcipher_rekey(conn, new_password)+ conn.close()++ # Verify new password works+ conn_new = sqlcipher_module.connect(str(db_path))+ cursor_new = conn_new.cursor()+ apply_cipher_settings_before_key(cursor_new)+ set_sqlcipher_key(cursor_new, new_password)+ cursor_new.close()++ result = conn_new.execute("SELECT * FROM test_data").fetchone()+ assert result is not None, (+ "Database should be accessible with backslash password"+ )+ conn_new.close()++ def test_rekey_with_sql_injection_attempt(+ self, encrypted_db, sqlcipher_module+ ):+ """Verify rekey is safe against SQL injection attempts."""+ conn = encrypted_db["conn"]+ db_path = encrypted_db["path"]++ # Password that looks like SQL injection+ new_password = "'; DROP TABLE test_data; --"++ set_sqlcipher_rekey(conn, new_password)+ conn.close()++ # Verify new password works and table still exists+ conn_new = sqlcipher_module.connect(str(db_path))+ cursor_new = conn_new.cursor()+ apply_cipher_settings_before_key(cursor_new)+ set_sqlcipher_key(cursor_new, new_password)+ cursor_new.close()++ # Table should still exist and have data+ result = conn_new.execute("SELECT COUNT(*) FROM test_data").fetchone()+ assert result[0] == 3, (+ "Table should exist and have all data after 'injection' password"+ )+ conn_new.close()+++class TestRekeyWithSQLAlchemy:+ """Tests for rekey via SQLAlchemy connections."""++ def test_rekey_via_sqlalchemy(self, temp_db_path):+ """Verify rekey works through SQLAlchemy connection."""+ from sqlalchemy import create_engine, event, text++ from src.local_deep_research.database.sqlcipher_utils import (+ apply_cipher_settings_before_key,+ apply_sqlcipher_pragmas,+ set_sqlcipher_key,+ set_sqlcipher_rekey,+ )+ from src.local_deep_research.database.sqlcipher_compat import (+ get_sqlcipher_module,+ )++ sqlcipher_module = get_sqlcipher_module()++ # Create database with raw connection first+ raw_conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = raw_conn.cursor()+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "original_password")+ cursor.close()+ raw_conn.execute(+ "CREATE TABLE test (id INTEGER PRIMARY KEY, data TEXT)"+ )+ raw_conn.execute("INSERT INTO test VALUES (1, 'test_data')")+ raw_conn.commit()+ raw_conn.close()++ # Open with SQLAlchemy and rekey+ engine = create_engine(+ f"sqlite:///{temp_db_path}",+ module=sqlcipher_module,+ )++ @event.listens_for(engine, "connect")+ def set_cipher(dbapi_conn, connection_record):+ cursor = dbapi_conn.cursor()+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "original_password")+ apply_sqlcipher_pragmas(cursor)+ cursor.close()++ with engine.connect() as conn:+ # Verify data is accessible+ result = conn.execute(+ text("SELECT data FROM test WHERE id = 1")+ ).scalar()+ assert result == "test_data"++ # Rekey via SQLAlchemy connection+ set_sqlcipher_rekey(conn, "new_password")+ conn.commit()++ engine.dispose()++ # Verify new password works with raw connection+ raw_conn2 = sqlcipher_module.connect(str(temp_db_path))+ cursor2 = raw_conn2.cursor()+ apply_cipher_settings_before_key(cursor2)+ set_sqlcipher_key(cursor2, "new_password")+ cursor2.close()++ result = raw_conn2.execute(+ "SELECT data FROM test WHERE id = 1"+ ).fetchone()+ assert result[0] == "test_data", (+ "Data should be accessible with new password"+ )+ raw_conn2.close()diff --git a/tests/auth_tests/test_sqlcipher_settings.py b/tests/auth_tests/test_sqlcipher_settings.pynew file mode 100644index 0000000000..c32e86707b--- /dev/null+++ b/tests/auth_tests/test_sqlcipher_settings.py@@ -0,0 +1,304 @@+"""+Tests for SQLCipher settings and environment variable overrides.++These tests verify that default settings are correct and that+environment variables properly override them.+"""++import shutil+import tempfile+from pathlib import Path++import pytest++from src.local_deep_research.database.sqlcipher_utils import (+ DEFAULT_KDF_ITERATIONS,+ DEFAULT_PAGE_SIZE,+ DEFAULT_HMAC_ALGORITHM,+ DEFAULT_KDF_ALGORITHM,+ get_sqlcipher_settings,+ apply_cipher_settings_before_key,+ apply_performance_pragmas,+ set_sqlcipher_key,+)+from src.local_deep_research.database.sqlcipher_compat import (+ get_sqlcipher_module,+)+++def temp_db_path():+ """Create a temporary database path."""+ temp_dir = tempfile.mkdtemp()+ db_path = Path(temp_dir) / "test_settings.db"+ yield db_path+ shutil.rmtree(temp_dir)+++def sqlcipher_module():+ """Get the SQLCipher module."""+ return get_sqlcipher_module()+++def clean_env(monkeypatch):+ """Remove all LDR_DB_* environment variables."""+ env_vars = [+ "LDR_DB_KDF_ITERATIONS",+ "LDR_DB_PAGE_SIZE",+ "LDR_DB_HMAC_ALGORITHM",+ "LDR_DB_KDF_ALGORITHM",+ "LDR_DB_CACHE_SIZE_MB",+ "LDR_DB_JOURNAL_MODE",+ "LDR_DB_SYNCHRONOUS",+ ]+ for var in env_vars:+ monkeypatch.delenv(var, raising=False)+ return monkeypatch+++class TestDefaultSettings:+ """Tests for default SQLCipher settings."""++ def test_default_kdf_iterations(self, clean_env):+ """Verify default KDF iterations value."""+ settings = get_sqlcipher_settings()+ assert settings["kdf_iterations"] == DEFAULT_KDF_ITERATIONS+ assert settings["kdf_iterations"] == 256000, "Default should be 256000"++ def test_default_page_size(self, clean_env):+ """Verify default page size value."""+ settings = get_sqlcipher_settings()+ assert settings["page_size"] == DEFAULT_PAGE_SIZE+ assert settings["page_size"] == 16384, "Default should be 16384 (16KB)"++ def test_default_hmac_algorithm(self, clean_env):+ """Verify default HMAC algorithm value."""+ settings = get_sqlcipher_settings()+ assert settings["hmac_algorithm"] == DEFAULT_HMAC_ALGORITHM+ assert settings["hmac_algorithm"] == "HMAC_SHA512"++ def test_default_kdf_algorithm(self, clean_env):+ """Verify default KDF algorithm value."""+ settings = get_sqlcipher_settings()+ assert settings["kdf_algorithm"] == DEFAULT_KDF_ALGORITHM+ assert settings["kdf_algorithm"] == "PBKDF2_HMAC_SHA512"++ def test_settings_returns_all_required_keys(self, clean_env):+ """Verify settings dictionary has all required keys."""+ settings = get_sqlcipher_settings()+ required_keys = [+ "kdf_iterations",+ "page_size",+ "hmac_algorithm",+ "kdf_algorithm",+ ]+ for key in required_keys:+ assert key in settings, f"Missing key: {key}"++ def test_settings_values_are_correct_types(self, clean_env):+ """Verify settings values have correct types."""+ settings = get_sqlcipher_settings()+ assert isinstance(settings["kdf_iterations"], int)+ assert isinstance(settings["page_size"], int)+ assert isinstance(settings["hmac_algorithm"], str)+ assert isinstance(settings["kdf_algorithm"], str)+++class TestEnvironmentOverrides:+ """Tests for environment variable overrides."""++ def test_kdf_iterations_override(self, monkeypatch):+ """Verify LDR_DB_KDF_ITERATIONS environment variable works."""+ monkeypatch.setenv("LDR_DB_KDF_ITERATIONS", "500000")+ settings = get_sqlcipher_settings()+ assert settings["kdf_iterations"] == 500000++ def test_page_size_override(self, monkeypatch):+ """Verify LDR_DB_PAGE_SIZE environment variable works."""+ monkeypatch.setenv("LDR_DB_PAGE_SIZE", "8192")+ settings = get_sqlcipher_settings()+ assert settings["page_size"] == 8192++ def test_hmac_algorithm_override(self, monkeypatch):+ """Verify LDR_DB_HMAC_ALGORITHM environment variable works."""+ monkeypatch.setenv("LDR_DB_HMAC_ALGORITHM", "HMAC_SHA256")+ settings = get_sqlcipher_settings()+ assert settings["hmac_algorithm"] == "HMAC_SHA256"++ def test_kdf_algorithm_override(self, monkeypatch):+ """Verify LDR_DB_KDF_ALGORITHM environment variable works."""+ monkeypatch.setenv("LDR_DB_KDF_ALGORITHM", "PBKDF2_HMAC_SHA256")+ settings = get_sqlcipher_settings()+ assert settings["kdf_algorithm"] == "PBKDF2_HMAC_SHA256"+++class TestPerformancePragmaSettings:+ """Tests for performance pragma environment variable overrides."""++ def test_cache_size_override(+ self, sqlcipher_module, temp_db_path, monkeypatch+ ):+ """Verify LDR_DB_CACHE_SIZE_MB environment variable works."""+ monkeypatch.setenv("LDR_DB_CACHE_SIZE_MB", "128")++ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "testpassword")+ apply_performance_pragmas(cursor)+ cursor.close()++ # cache_size in KB (negative means KB)+ # 128 MB = 131072 KB, stored as -131072+ result = conn.execute("PRAGMA cache_size").fetchone()+ assert result is not None+ assert result[0] == -131072, (+ f"Expected -131072 (-128*1024), got {result[0]}"+ )+ conn.close()++ def test_journal_mode_override(+ self, sqlcipher_module, temp_db_path, monkeypatch+ ):+ """Verify LDR_DB_JOURNAL_MODE environment variable works."""+ monkeypatch.setenv("LDR_DB_JOURNAL_MODE", "DELETE")++ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "testpassword")+ apply_performance_pragmas(cursor)+ cursor.close()++ result = conn.execute("PRAGMA journal_mode").fetchone()+ assert result is not None+ assert result[0].lower() == "delete"+ conn.close()++ def test_synchronous_override(+ self, sqlcipher_module, temp_db_path, monkeypatch+ ):+ """Verify LDR_DB_SYNCHRONOUS environment variable works."""+ monkeypatch.setenv("LDR_DB_SYNCHRONOUS", "FULL")++ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "testpassword")+ apply_performance_pragmas(cursor)+ cursor.close()++ result = conn.execute("PRAGMA synchronous").fetchone()+ assert result is not None+ # SQLite returns synchronous as integer: 0=OFF, 1=NORMAL, 2=FULL, 3=EXTRA+ assert result[0] == 2, f"Expected 2 (FULL), got {result[0]}"+ conn.close()++ def test_default_journal_mode_is_wal(+ self, sqlcipher_module, temp_db_path, clean_env+ ):+ """Verify default journal mode is WAL."""+ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "testpassword")+ apply_performance_pragmas(cursor)+ cursor.close()++ result = conn.execute("PRAGMA journal_mode").fetchone()+ assert result is not None+ assert result[0].lower() == "wal", f"Expected WAL, got {result[0]}"+ conn.close()++ def test_default_temp_store_is_memory(+ self, sqlcipher_module, temp_db_path, clean_env+ ):+ """Verify temp_store is always set to MEMORY."""+ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "testpassword")+ apply_performance_pragmas(cursor)+ cursor.close()++ result = conn.execute("PRAGMA temp_store").fetchone()+ assert result is not None+ # temp_store: 0=DEFAULT, 1=FILE, 2=MEMORY+ assert result[0] == 2, f"Expected 2 (MEMORY), got {result[0]}"+ conn.close()++ def test_default_busy_timeout(+ self, sqlcipher_module, temp_db_path, clean_env+ ):+ """Verify busy_timeout is set to 10000ms."""+ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "testpassword")+ apply_performance_pragmas(cursor)+ cursor.close()++ result = conn.execute("PRAGMA busy_timeout").fetchone()+ assert result is not None+ assert result[0] == 10000, f"Expected 10000, got {result[0]}"+ conn.close()+++class TestSettingsAppliedToDatabase:+ """Tests verifying settings are actually applied to databases."""++ def test_cipher_settings_applied_before_key(+ self, sqlcipher_module, temp_db_path, clean_env+ ):+ """Verify cipher_default_* settings are applied before key."""+ settings = get_sqlcipher_settings()++ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()++ # Apply settings before key+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "testpassword")+ cursor.close()++ # Verify all cipher settings+ page_size = conn.execute("PRAGMA cipher_page_size").fetchone()[0]+ hmac_algo = conn.execute("PRAGMA cipher_hmac_algorithm").fetchone()[0]+ kdf_algo = conn.execute("PRAGMA cipher_kdf_algorithm").fetchone()[0]++ assert str(page_size) == str(settings["page_size"])+ assert hmac_algo == settings["hmac_algorithm"]+ assert kdf_algo == settings["kdf_algorithm"]++ conn.close()++ def test_multiple_env_overrides_work_together(+ self, sqlcipher_module, temp_db_path, monkeypatch+ ):+ """Verify multiple environment variable overrides work together."""+ monkeypatch.setenv("LDR_DB_PAGE_SIZE", "8192")+ monkeypatch.setenv("LDR_DB_KDF_ITERATIONS", "100000")+ monkeypatch.setenv("LDR_DB_CACHE_SIZE_MB", "32")++ settings = get_sqlcipher_settings()+ assert settings["page_size"] == 8192+ assert settings["kdf_iterations"] == 100000++ conn = sqlcipher_module.connect(str(temp_db_path))+ cursor = conn.cursor()+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, "testpassword")+ apply_performance_pragmas(cursor)+ cursor.close()++ # Verify page size+ page_size = conn.execute("PRAGMA cipher_page_size").fetchone()[0]+ assert str(page_size) == "8192"++ # Verify cache size (32MB = 32768KB = -32768)+ cache_size = conn.execute("PRAGMA cache_size").fetchone()[0]+ assert cache_size == -32768++ conn.close()diff --git a/tests/auth_tests/test_sqlcipher_threads.py b/tests/auth_tests/test_sqlcipher_threads.pynew file mode 100644index 0000000000..3e34838a81--- /dev/null+++ b/tests/auth_tests/test_sqlcipher_threads.py@@ -0,0 +1,382 @@+"""+Tests for SQLCipher thread safety.++These tests verify that SQLCipher connections work correctly when+accessed from multiple threads.+"""++import shutil+import tempfile+import threading+import time+from concurrent.futures import ThreadPoolExecutor, as_completed+from pathlib import Path++import pytest++from src.local_deep_research.database.sqlcipher_utils import (+ apply_cipher_settings_before_key,+ apply_performance_pragmas,+ apply_sqlcipher_pragmas,+ set_sqlcipher_key,+)+from src.local_deep_research.database.sqlcipher_compat import (+ get_sqlcipher_module,+)+++def temp_db_path():+ """Create a temporary database path."""+ temp_dir = tempfile.mkdtemp()+ db_path = Path(temp_dir) / "test_threads.db"+ yield db_path+ shutil.rmtree(temp_dir)+++def sqlcipher_module():+ """Get the SQLCipher module."""+ return get_sqlcipher_module()+++def create_configured_connection(sqlcipher_module, db_path, password):+ """Helper to create a properly configured connection."""+ conn = sqlcipher_module.connect(str(db_path), check_same_thread=False)+ cursor = conn.cursor()+ apply_cipher_settings_before_key(cursor)+ set_sqlcipher_key(cursor, password)+ apply_sqlcipher_pragmas(cursor)+ apply_performance_pragmas(cursor)+ cursor.close()+ return conn+++class TestThreadSafety:+ """Tests for basic thread safety."""++ def test_connection_per_thread(self, sqlcipher_module, temp_db_path):+ """Verify each thread can create its own connection."""+ password = "thread_test"++ # Create initial database+ conn = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ conn.execute("CREATE TABLE thread_data (thread_id INTEGER, value TEXT)")+ conn.commit()+ conn.close()++ results = []+ errors = []++ def thread_work(thread_id):+ try:+ # Each thread creates its own connection+ thread_conn = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ thread_conn.execute(+ "INSERT INTO thread_data VALUES (?, ?)",+ (thread_id, f"data_from_{thread_id}"),+ )+ thread_conn.commit()+ thread_conn.close()+ results.append(thread_id)+ except Exception as e:+ errors.append((thread_id, str(e)))++ # Run 5 threads concurrently+ threads = []+ for i in range(5):+ t = threading.Thread(target=thread_work, args=(i,))+ threads.append(t)+ t.start()++ for t in threads:+ t.join()++ # Verify no errors+ assert not errors, f"Thread errors: {errors}"++ # Verify all data was written+ conn = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ count = conn.execute("SELECT COUNT(*) FROM thread_data").fetchone()[0]+ assert count == 5, f"Expected 5 rows, got {count}"+ conn.close()++ def test_concurrent_reads_different_connections(+ self, sqlcipher_module, temp_db_path+ ):+ """Verify concurrent reads work from different connections."""+ password = "concurrent_read_test"++ # Create and populate database+ conn = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ conn.execute("CREATE TABLE test (id INTEGER PRIMARY KEY, data TEXT)")+ for i in range(100):+ conn.execute("INSERT INTO test VALUES (?, ?)", (i, f"data_{i}"))+ conn.commit()+ conn.close()++ results = []+ errors = []++ def read_work(reader_id):+ try:+ reader_conn = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ # Read random rows+ data = reader_conn.execute(+ "SELECT COUNT(*) FROM test"+ ).fetchone()[0]+ results.append((reader_id, data))+ reader_conn.close()+ except Exception as e:+ errors.append((reader_id, str(e)))++ # Run 10 concurrent readers+ with ThreadPoolExecutor(max_workers=10) as executor:+ futures = [executor.submit(read_work, i) for i in range(10)]+ for future in as_completed(futures):+ pass # Just wait for completion++ assert not errors, f"Read errors: {errors}"+ assert len(results) == 10+ # All readers should see 100 rows+ assert all(count == 100 for _, count in results)++ def test_write_serialization(self, sqlcipher_module, temp_db_path):+ """Verify concurrent writes are properly serialized."""+ password = "write_serial_test"++ # Create database+ conn = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ conn.execute(+ "CREATE TABLE counter (id INTEGER PRIMARY KEY, count INTEGER)"+ )+ conn.execute("INSERT INTO counter VALUES (1, 0)")+ conn.commit()+ conn.close()++ errors = []++ def increment_work(worker_id, increments):+ try:+ worker_conn = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ for _ in range(increments):+ # SQLite handles serialization with busy_timeout+ worker_conn.execute(+ "UPDATE counter SET count = count + 1 WHERE id = 1"+ )+ worker_conn.commit()+ worker_conn.close()+ except Exception as e:+ errors.append((worker_id, str(e)))++ # 5 workers each doing 10 increments = 50 total+ threads = []+ for i in range(5):+ t = threading.Thread(target=increment_work, args=(i, 10))+ threads.append(t)+ t.start()++ for t in threads:+ t.join()++ assert not errors, f"Write errors: {errors}"++ # Verify final count+ conn = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ count = conn.execute(+ "SELECT count FROM counter WHERE id = 1"+ ).fetchone()[0]+ assert count == 50, f"Expected 50, got {count}"+ conn.close()+++class TestConnectionPooling:+ """Tests for connection pooling behavior."""++ def test_multiple_connections_same_database(+ self, sqlcipher_module, temp_db_path+ ):+ """Verify multiple simultaneous connections to same database."""+ password = "pool_test"++ # Create database+ conn0 = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ conn0.execute(+ "CREATE TABLE shared (id INTEGER PRIMARY KEY, owner TEXT)"+ )+ conn0.commit()++ # Create additional connections+ conns = [conn0]+ for i in range(4):+ c = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ conns.append(c)++ # Each connection writes to shared table+ for i, conn in enumerate(conns):+ conn.execute("INSERT INTO shared VALUES (?, ?)", (i, f"conn_{i}"))+ conn.commit()++ # All connections should see all data+ for conn in conns:+ count = conn.execute("SELECT COUNT(*) FROM shared").fetchone()[0]+ assert count == 5, f"Connection should see 5 rows, got {count}"++ # Close all connections+ for conn in conns:+ conn.close()++ def test_connection_reuse_safe(self, sqlcipher_module, temp_db_path):+ """Verify connections can be safely reused across operations."""+ password = "reuse_test"++ conn = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ conn.execute(+ "CREATE TABLE reuse_test (id INTEGER PRIMARY KEY, data TEXT)"+ )+ conn.commit()++ # Perform many operations on same connection+ for i in range(100):+ conn.execute(+ "INSERT INTO reuse_test VALUES (?, ?)", (i, f"data_{i}")+ )+ if i % 10 == 0:+ conn.commit()++ conn.commit()++ # Verify all data+ count = conn.execute("SELECT COUNT(*) FROM reuse_test").fetchone()[0]+ assert count == 100++ conn.close()+++class TestBackgroundThreads:+ """Tests for background thread database access."""++ def test_background_thread_writes(self, sqlcipher_module, temp_db_path):+ """Verify background thread can write to database."""+ password = "bg_write_test"++ # Create database in main thread+ main_conn = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ main_conn.execute(+ "CREATE TABLE bg_data (id INTEGER PRIMARY KEY, source TEXT)"+ )+ main_conn.commit()+ main_conn.close()++ background_done = threading.Event()+ background_error = []++ def background_work():+ try:+ bg_conn = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ bg_conn.execute(+ "INSERT INTO bg_data VALUES (1, 'background_thread')"+ )+ bg_conn.commit()+ bg_conn.close()+ except Exception as e:+ background_error.append(str(e))+ finally:+ background_done.set()++ # Start background thread+ bg_thread = threading.Thread(target=background_work, daemon=True)+ bg_thread.start()++ # Wait for completion+ background_done.wait(timeout=10)++ assert not background_error, (+ f"Background thread error: {background_error}"+ )++ # Verify data in main thread+ main_conn = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ result = main_conn.execute(+ "SELECT source FROM bg_data WHERE id = 1"+ ).fetchone()+ assert result[0] == "background_thread"+ main_conn.close()++ def test_main_thread_reads_background_writes(+ self, sqlcipher_module, temp_db_path+ ):+ """Verify main thread can read data written by background thread."""+ password = "main_bg_test"++ # Create database+ conn = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ conn.execute(+ "CREATE TABLE bg_writes (id INTEGER PRIMARY KEY, timestamp REAL)"+ )+ conn.commit()+ conn.close()++ write_count = 20+ writes_done = threading.Event()++ def writer_thread():+ writer_conn = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ for i in range(write_count):+ writer_conn.execute(+ "INSERT INTO bg_writes VALUES (?, ?)",+ (i, time.time()),+ )+ writer_conn.commit()+ time.sleep(0.01) # Small delay between writes+ writer_conn.close()+ writes_done.set()++ # Start writer thread+ writer = threading.Thread(target=writer_thread, daemon=True)+ writer.start()++ # Wait for writes to complete+ writes_done.wait(timeout=30)++ # Read from main thread+ reader_conn = create_configured_connection(+ sqlcipher_module, temp_db_path, password+ )+ count = reader_conn.execute(+ "SELECT COUNT(*) FROM bg_writes"+ ).fetchone()[0]+ assert count == write_count, f"Expected {write_count} rows, got {count}"+ reader_conn.close()