~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 additional SQLCipher integration tests and fix rekey bug
LearningCircuite41ee71a0321
diff --git a/.gitleaks.toml b/.gitleaks.tomlindex d00f468518..1e0e9bb706 100644--- a/.gitleaks.toml+++ b/.gitleaks.toml@@ -115,7 +115,9 @@ paths = ['''src/local_deep_research/database/session_context\.py$''',# RAG routes and services use db_password variable names (not actual secrets)'''src/local_deep_research/research_library/routes/rag_routes\.py$''',- '''src/local_deep_research/research_library/services/library_rag_service\.py$'''+ '''src/local_deep_research/research_library/services/library_rag_service\.py$''',+ # SQLCipher utilities use key derivation functions (not actual secrets)+ '''src/local_deep_research/database/sqlcipher_utils\.py$''']files = ["\\.env\\.example$",diff --git a/src/local_deep_research/database/sqlcipher_utils.py b/src/local_deep_research/database/sqlcipher_utils.pyindex c8b36876ba..c06b15b218 100644--- a/src/local_deep_research/database/sqlcipher_utils.py+++ b/src/local_deep_research/database/sqlcipher_utils.py@@ -62,11 +62,15 @@ def set_sqlcipher_rekey(cursor_or_conn: Any, new_password: str) -> None:"""Change the SQLCipher encryption key using hexadecimal encoding.+ Uses the same PBKDF2 key derivation as set_sqlcipher_key to ensure+ consistency between key setting and rekeying operations.+Args:cursor_or_conn: SQLCipher cursor or connection objectnew_password: The new password to use for encryption"""- hex_password = new_password.encode("utf-8").hex()+ # Use the same key derivation as set_sqlcipher_key for consistency+ key = _get_key_from_password(new_password)# Handle SQLAlchemy connections that need text()if hasattr(cursor_or_conn, "execute") and hasattr(@@ -77,12 +81,12 @@ def set_sqlcipher_rekey(cursor_or_conn: Any, new_password: str) -> None:# 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_password}'\""+ safe_sql = f"PRAGMA rekey = \"x'{key.hex()}'\""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_password}'\""+ safe_sql = f"PRAGMA rekey = \"x'{key.hex()}'\""cursor_or_conn.execute(safe_sql)diff --git a/tests/database/test_sqlcipher_integration.py b/tests/database/test_sqlcipher_integration.pyindex 61f789db84..db0cb646f5 100644--- a/tests/database/test_sqlcipher_integration.py+++ b/tests/database/test_sqlcipher_integration.py@@ -268,3 +268,175 @@ class TestSQLCipherIntegration:assert success_count[0] == 5, (f"Only {success_count[0]}/5 threads succeeded")++ def test_change_password_works(self, isolated_db_manager):+ """Test changing password and reopening with new password."""+ username = "testuser"+ old_password = "OldPassword123!"+ new_password = "NewPassword456!"++ # Create database with old password+ isolated_db_manager.create_user_database(username, old_password)++ # Insert some data to verify it persists after password change+ 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, 'secret_data')")+ )+ conn.commit()++ # Change password+ result = isolated_db_manager.change_password(+ username, old_password, new_password+ )+ assert result is True, "Password change should succeed"++ # Old password should no longer work+ engine = isolated_db_manager.open_user_database(username, old_password)+ assert engine is None, "Old password should not work after change"++ # New password should work+ engine = isolated_db_manager.open_user_database(username, new_password)+ assert engine is not None, "New password should work after change"++ # Verify data persists after password change+ 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] == "secret_data"++ def test_check_database_integrity(self, isolated_db_manager):+ """Test check_database_integrity() returns True for valid DB."""+ username = "testuser"+ password = "SecurePassword123!"++ # Create database+ isolated_db_manager.create_user_database(username, password)++ # Check integrity - should pass for fresh database+ result = isolated_db_manager.check_database_integrity(username)+ assert result is True, "Integrity check should pass for valid database"++ def test_special_characters_in_password(self, isolated_db_manager):+ """Test passwords with quotes, backslashes, and special chars."""+ username = "testuser"+ # Password with quotes, backslashes, and special characters+ password = "P@ss'w\"ord\\123!#$%^&*()"++ # Create database with special character password+ engine = isolated_db_manager.create_user_database(username, password)+ assert engine is not None++ # Close and reopen+ isolated_db_manager.close_user_database(username)++ # Should be able to reopen with same password+ engine = isolated_db_manager.open_user_database(username, password)+ assert engine is not None, "Should open with special character password"++ # 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_unicode_in_password(self, isolated_db_manager):+ """Test passwords with unicode characters."""+ username = "testuser"+ # Password with unicode characters+ password = "密码Пароль🔐Senha123!"++ # Create database+ engine = isolated_db_manager.create_user_database(username, password)+ assert engine is not None++ # Close and reopen+ isolated_db_manager.close_user_database(username)++ # Should be able to reopen with same unicode password+ engine = isolated_db_manager.open_user_database(username, password)+ assert engine is not None, "Should open with unicode password"++ def test_empty_password_rejected(self, isolated_db_manager):+ """Test that empty password raises ValueError."""+ username = "testuser"++ with pytest.raises(+ ValueError, match="password cannot be None or empty"+ ):+ isolated_db_manager.create_user_database(username, "")++ def test_none_password_rejected(self, isolated_db_manager):+ """Test that None password raises ValueError."""+ username = "testuser"++ with pytest.raises(+ ValueError, match="password cannot be None or empty"+ ):+ isolated_db_manager.create_user_database(username, None)++ def test_empty_password_rejected_on_open(self, isolated_db_manager):+ """Test that empty password raises ValueError on open."""+ username = "testuser"+ password = "SecurePassword123!"++ # Create database first+ isolated_db_manager.create_user_database(username, password)+ isolated_db_manager.close_user_database(username)++ # Attempt to open with empty password+ with pytest.raises(+ ValueError, match="password cannot be None or empty"+ ):+ isolated_db_manager.open_user_database(username, "")++ def test_corrupted_database_returns_none(self, isolated_db_manager):+ """Test opening corrupted DB file returns None gracefully."""+ username = "testuser"+ password = "SecurePassword123!"++ # Create database+ isolated_db_manager.create_user_database(username, password)+ isolated_db_manager.close_user_database(username)++ # Corrupt the database file by overwriting with garbage+ db_path = isolated_db_manager._get_user_db_path(username)+ with open(db_path, "wb") as f:+ f.write(b"THIS IS NOT A VALID SQLITE DATABASE FILE" * 100)++ # Attempt to open - should return None, not crash+ engine = isolated_db_manager.open_user_database(username, password)+ assert engine is None, "Should return None for corrupted database"++ def test_nonexistent_user_returns_none(self, isolated_db_manager):+ """Test opening nonexistent user database returns None."""+ engine = isolated_db_manager.open_user_database(+ "nonexistent_user", "password"+ )+ assert engine is None, "Should return None for nonexistent user"++ def test_duplicate_user_rejected(self, isolated_db_manager):+ """Test creating duplicate user raises ValueError."""+ username = "testuser"+ password = "SecurePassword123!"++ # Create first user+ isolated_db_manager.create_user_database(username, password)++ # Attempt to create same user again+ with pytest.raises(ValueError, match="Database already exists"):+ isolated_db_manager.create_user_database(+ username, "DifferentPassword!"+ )