~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
fix: improve @cache key derivation and add debug logging for CI
LearningCircuit067553304866
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex 5a82100945..aded55ecbe 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -378,6 +378,9 @@ class DatabaseManager:def create_sqlcipher_connection():"""Create a properly initialized SQLCipher connection."""+ logger.debug(+ f"[SQLCIPHER DEBUG] open_user_database: Opening database at {db_path}"+ )conn = sqlcipher3.connect(str(db_path),isolation_level="IMMEDIATE",@@ -386,19 +389,49 @@ class DatabaseManager:cursor = conn.cursor()# IMPORTANT: For SQLCipher 4.x, cipher settings MUST be set BEFORE the key- apply_cipher_settings_before_key(cursor)+ logger.debug(+ "[SQLCIPHER DEBUG] open_user_database: Calling apply_cipher_settings_before_key"+ )+ try:+ apply_cipher_settings_before_key(cursor)+ except Exception as e:+ logger.exception(+ f"[SQLCIPHER DEBUG] open_user_database: apply_cipher_settings_before_key failed: {e}"+ )+ raise# Use centralized SQLCipher setup- set_sqlcipher_key(cursor, password)+ logger.debug(+ "[SQLCIPHER DEBUG] open_user_database: Calling set_sqlcipher_key"+ )+ try:+ set_sqlcipher_key(cursor, password)+ except Exception as e:+ logger.exception(+ f"[SQLCIPHER DEBUG] open_user_database: set_sqlcipher_key failed: {e}"+ )+ raise# Verify connection works+ logger.debug(+ "[SQLCIPHER DEBUG] open_user_database: Verifying connection"+ )if not verify_sqlcipher_connection(cursor):+ logger.error(+ "[SQLCIPHER DEBUG] open_user_database: verify_sqlcipher_connection returned False!"+ )raise ValueError("Failed to verify database key")# Apply SQLCipher and performance settings (those that go after the key)+ logger.debug(+ "[SQLCIPHER DEBUG] open_user_database: Calling apply_sqlcipher_pragmas"+ )apply_sqlcipher_pragmas(cursor, creation_mode=False)apply_performance_pragmas(cursor, username)+ logger.debug(+ "[SQLCIPHER DEBUG] open_user_database: Connection created successfully"+ )cursor.close()return conndiff --git a/src/local_deep_research/database/sqlcipher_utils.py b/src/local_deep_research/database/sqlcipher_utils.pyindex b07c0d54ec..b68d5758d7 100644--- a/src/local_deep_research/database/sqlcipher_utils.py+++ b/src/local_deep_research/database/sqlcipher_utils.py@@ -13,20 +13,23 @@ from loguru import logger@cache-def _get_key_from_password(password: str) -> bytes:+def _get_key_from_password(password: str, kdf_iterations: int) -> bytes:"""Generates an encryption key from the user's password.Args:password: The password.+ kdf_iterations: Number of PBKDF2 iterations (must be passed explicitly+ to ensure cache key includes this value).Returns:The generated key."""# Generate a secure key based on the password.- settings = get_sqlcipher_settings()- logger.info("Generating DB encryption key...")+ logger.info(+ f"Generating DB encryption key with {kdf_iterations} iterations..."+ )# Use PBKDF2 to stretch the password into a hex key.# Note: SQLCipher handles per-database salting internally, so this@@ -35,7 +38,7 @@ def _get_key_from_password(password: str) -> bytes:"sha512",password.encode(),PBKDF2_PLACEHOLDER_SALT,- settings["kdf_iterations"],+ kdf_iterations,)logger.info("Generated DB encryption key.")@@ -43,6 +46,18 @@ def _get_key_from_password(password: str) -> bytes:return key+def get_key_from_password(password: str) -> bytes:+ """+ Wrapper that gets settings and calls the cached key derivation.++ This ensures the cache key includes kdf_iterations, so changing+ the LDR_DB_KDF_ITERATIONS environment variable will generate+ a different key (not return a stale cached value).+ """+ settings = get_sqlcipher_settings()+ return _get_key_from_password(password, settings["kdf_iterations"])++def set_sqlcipher_key(cursor_or_conn: Any, password: str) -> None:"""Set the SQLCipher encryption key using hexadecimal encoding.@@ -54,7 +69,7 @@ def set_sqlcipher_key(cursor_or_conn: Any, password: str) -> None:password: The password to use for encryption"""- key = _get_key_from_password(password)+ key = get_key_from_password(password) # gitleaks:allowcursor_or_conn.execute(f"PRAGMA key = \"x'{key.hex()}'\"")@@ -70,7 +85,7 @@ def set_sqlcipher_rekey(cursor_or_conn: Any, new_password: str) -> None:new_password: The new password to use for encryption"""# Use the same key derivation as set_sqlcipher_key for consistency- key = _get_key_from_password(new_password) # gitleaks:allow+ key = get_key_from_password(new_password) # gitleaks:allow# Try SQLAlchemy text() first, fall back to raw string# The hex encoding already prevents injection since it only contains [0-9a-f]@@ -153,17 +168,33 @@ def apply_cipher_settings_before_key("""settings = get_sqlcipher_settings(username)+ logger.debug(+ f"[SQLCIPHER DEBUG] apply_cipher_settings (pre-pragma): settings={settings}"+ )+# These MUST be set BEFORE the key for SQLCipher 4.x compatibility# Use cipher_default_* pragmas for SQLCipher 4.6+ Community Edition+ logger.debug(+ f"[SQLCIPHER DEBUG] Setting cipher_default_page_size = {settings['page_size']}"+ )cursor_or_conn.execute(f"PRAGMA cipher_default_page_size = {settings['page_size']}")+ logger.debug(+ f"[SQLCIPHER DEBUG] Setting cipher_default_hmac_algorithm = {settings['hmac_algorithm']}"+ )cursor_or_conn.execute(f"PRAGMA cipher_default_hmac_algorithm = {settings['hmac_algorithm']}")+ logger.debug(+ f"[SQLCIPHER DEBUG] Setting cipher_default_kdf_algorithm = {settings['kdf_algorithm']}"+ )cursor_or_conn.execute(f"PRAGMA cipher_default_kdf_algorithm = {settings['kdf_algorithm']}")+ logger.debug(+ "[SQLCIPHER DEBUG] apply_cipher_settings (pre-pragma): completed successfully"+ )def apply_sqlcipher_pragmas(@@ -239,6 +270,9 @@ def verify_sqlcipher_connection(cursor_or_conn: Any) -> bool:True if the connection is valid, False otherwise"""try:+ logger.debug(+ "[SQLCIPHER DEBUG] verify_sqlcipher_connection: Executing SELECT 1"+ )# Force key derivation with test querycursor_or_conn.execute("SELECT 1")result = (@@ -246,9 +280,19 @@ def verify_sqlcipher_connection(cursor_or_conn: Any) -> bool:if hasattr(cursor_or_conn, "fetchone")else cursor_or_conn.execute("SELECT 1").fetchone())- return result == (1,)- except Exception:- logger.exception("SQLCipher verification failed")+ logger.debug(+ f"[SQLCIPHER DEBUG] verify_sqlcipher_connection: result={result}, expected=(1,)"+ )+ is_valid = result == (1,)+ if not is_valid:+ logger.error(+ f"[SQLCIPHER DEBUG] verify_sqlcipher_connection: FAILED - result {result} != (1,)"+ )+ return is_valid+ except Exception as e:+ logger.exception(+ f"[SQLCIPHER DEBUG] SQLCipher verification failed with exception: {e}"+ )return False