Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

feat(security): warn at startup on weak SQLCipher KDF with existing user DBs (#4816)

LearningCircuit4103670e957a
diff --git a/changelog.d/+warn-weak-kdf-existing-dbs.security.md b/changelog.d/+warn-weak-kdf-existing-dbs.security.md
new file mode 100644
index 0000000000..8293881ee8
--- /dev/null
+++ b/changelog.d/+warn-weak-kdf-existing-dbs.security.md
@@ -0,0 +1 @@
+The server now logs a loud warning at startup when the SQLCipher KDF is weakened below the production floor (reached only in test mode, e.g. ``LDR_TEST_MODE``) while user databases already exist. New databases would be created with this weak at-rest work factor, and — separately — any existing database created at a higher KDF can no longer be opened: its on-disk key is unchanged, but the server now derives a different, weaker key, so decryption fails and login returns a generic "Invalid username or password" 401 for every affected user (the KDF-mismatch symptom class behind PR #4775). Silent on fresh deployments and when the effective KDF is at/above the floor.
diff --git a/src/local_deep_research/database/sqlcipher_utils.py b/src/local_deep_research/database/sqlcipher_utils.py
index 9447f2a358..2c53183dc2 100644
--- a/src/local_deep_research/database/sqlcipher_utils.py
+++ b/src/local_deep_research/database/sqlcipher_utils.py
@@ -364,6 +364,63 @@ def get_sqlcipher_settings() -> dict:
}
+def warn_if_weak_kdf_with_existing_databases(
+ data_dir: Union[str, Path],
+) -> bool:
+ """Warn loudly when the effective SQLCipher KDF is below the production
+ floor *and* user databases already exist in ``data_dir``.
+
+ The KDF iteration count is derived from the environment at open time
+ (see :func:`get_sqlcipher_settings`) and is NOT stored with the
+ database. So if the floor is relaxed (test mode) on a deployment that
+ already holds real data, newly created databases get a weak at-rest work
+ factor, and — separately — any existing database that was created at a
+ *higher* KDF can no longer be opened: its on-disk key is unchanged, but
+ the server now derives a different, weaker key, so decryption fails and
+ login returns a generic "Invalid username or password" 401 that is
+ indistinguishable from a wrong password (the KDF-mismatch symptom class
+ behind PR #4775).
+
+ Scope: this only catches the "server is now weak" direction, and only a
+ *sub-floor* effective KDF. It cannot detect the inverse (a production-KDF
+ server opening databases created weak) or general in-range KDF drift,
+ because the creation-time KDF is not persisted to compare against — only
+ a sub-floor effective KDF is observable from the environment alone.
+
+ Intentionally silent on a fresh deployment (no pre-existing databases →
+ nothing to mismatch) and when the effective KDF is at/above the floor
+ (e.g. the 256000 default) — that is harmless.
+
+ Returns ``True`` if a warning was emitted (used by tests).
+ """
+ effective_kdf = get_sqlcipher_settings()["kdf_iterations"]
+ if effective_kdf >= MIN_KDF_ITERATIONS_PRODUCTION:
+ return False
+
+ # Only count + truthiness are used, so no need to sort the glob result.
+ existing = list(Path(data_dir).glob("ldr_user_*.db"))
+ if not existing:
+ return False
+
+ logger.warning(
+ "SQLCipher KDF is configured to {} iterations — below the production "
+ "floor of {} (reached only in test mode, e.g. LDR_TEST_MODE) — while "
+ "{} user database(s) already exist in {}. New databases created now "
+ "get this weak at-rest work factor. Separately, any of those existing "
+ "databases that was created at a higher KDF can no longer be opened: "
+ "its on-disk key is unchanged, but the server now derives a different, "
+ "weaker key, so decryption fails and login returns a generic 'Invalid "
+ "username or password' 401 for every affected user (the KDF-mismatch "
+ "symptom class behind PR #4775). If this is a production deployment, "
+ "unset LDR_TEST_MODE (and any low LDR_DB_CONFIG_KDF_ITERATIONS).",
+ effective_kdf,
+ MIN_KDF_ITERATIONS_PRODUCTION,
+ len(existing),
+ data_dir,
+ )
+ return True
+
+
def apply_cipher_defaults_before_key(
cursor_or_conn: Any,
) -> None:
diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.py
index 3a681a6971..997e1548ef 100644
--- a/src/local_deep_research/web/app.py
+++ b/src/local_deep_research/web/app.py
@@ -73,6 +73,22 @@ def main():
# Create the Flask app and SocketIO instance
app, socket_service = create_app()
+ # Surface a cipher misconfiguration that otherwise only shows up as
+ # affected users getting "Invalid username or password": a relaxed
+ # SQLCipher KDF (test mode) on a deployment that already holds real user
+ # databases. No-op on fresh installs and when the effective KDF is at the
+ # production floor. Wrapped so a check failure can never block server boot.
+ try:
+ from ..database.encrypted_db import db_manager
+ from ..database.sqlcipher_utils import (
+ warn_if_weak_kdf_with_existing_databases,
+ )
+
+ if db_manager.has_encryption:
+ warn_if_weak_kdf_with_existing_databases(db_manager.data_dir)
+ except Exception:
+ logger.exception("Weak-KDF startup configuration check failed")
+
# Start the background log-queue processor. With no ``before_request``
# handler pulling from the queue, this daemon is the only drain path
# during normal operation; a final drain runs at atexit.
diff --git a/tests/database/test_sqlcipher_utils.py b/tests/database/test_sqlcipher_utils.py
index f930ef48bd..52259810db 100644
--- a/tests/database/test_sqlcipher_utils.py
+++ b/tests/database/test_sqlcipher_utils.py
@@ -1324,3 +1324,116 @@ class TestCipherMemorySecurityEnvVar:
]
assert len(mem_calls) == 1, f"Failed for creation_mode={mode}"
assert "OFF" in mem_calls[0], f"Failed for creation_mode={mode}"
+
+
+class TestWeakKdfStartupWarning:
+ """warn_if_weak_kdf_with_existing_databases() — fire only when the
+ effective KDF is below the production floor AND user DBs already exist."""
+
+ @staticmethod
+ def _make_user_db(data_dir, username="alice"):
+ # Generate the filename via the REAL generator so this fixture tracks
+ # production naming (ldr_user_<hash>.db) instead of a brittle literal.
+ from local_deep_research.config.paths import (
+ get_user_database_filename,
+ )
+
+ (data_dir / get_user_database_filename(username)).write_bytes(b"")
+
+ def test_warns_when_weak_kdf_and_databases_exist(self, tmp_path):
+ from local_deep_research.database.sqlcipher_utils import (
+ warn_if_weak_kdf_with_existing_databases,
+ )
+
+ self._make_user_db(tmp_path)
+ with patch.dict(
+ os.environ,
+ {
+ "LDR_TEST_MODE": "1",
+ "LDR_DB_CONFIG_KDF_ITERATIONS": "1000",
+ },
+ clear=True,
+ ):
+ assert warn_if_weak_kdf_with_existing_databases(tmp_path) is True
+
+ def test_silent_when_no_databases_exist(self, tmp_path):
+ """Fresh deployment: nothing to mismatch, even with a weak KDF."""
+ from local_deep_research.database.sqlcipher_utils import (
+ warn_if_weak_kdf_with_existing_databases,
+ )
+
+ with patch.dict(
+ os.environ,
+ {
+ "LDR_TEST_MODE": "1",
+ "LDR_DB_CONFIG_KDF_ITERATIONS": "1000",
+ },
+ clear=True,
+ ):
+ assert warn_if_weak_kdf_with_existing_databases(tmp_path) is False
+
+ def test_silent_at_production_floor(self, tmp_path):
+ """Effective KDF at/above the floor is safe even with DBs present."""
+ from local_deep_research.database.sqlcipher_utils import (
+ warn_if_weak_kdf_with_existing_databases,
+ )
+
+ self._make_user_db(tmp_path)
+ # No test mode → effective KDF is the 256000 default → not weak.
+ with patch.dict(os.environ, {}, clear=True):
+ assert warn_if_weak_kdf_with_existing_databases(tmp_path) is False
+
+ def test_silent_when_test_mode_but_default_kdf(self, tmp_path):
+ """LDR_TEST_MODE merely *set* (no low iterations requested) keeps the
+ 256000 default, which is not weak — must not warn."""
+ from local_deep_research.database.sqlcipher_utils import (
+ warn_if_weak_kdf_with_existing_databases,
+ )
+
+ self._make_user_db(tmp_path)
+ with patch.dict(os.environ, {"LDR_TEST_MODE": "1"}, clear=True):
+ assert warn_if_weak_kdf_with_existing_databases(tmp_path) is False
+
+ def test_warning_message_is_rendered_with_count(
+ self, tmp_path, loguru_caplog
+ ):
+ """Force the message to render (loguru is lazy — only then is the
+ {}-placeholder/arg count exercised) and assert the actual content,
+ including the user-DB count. Without this, a broken format string
+ ships green and is then swallowed by the boot-time try/except."""
+ from local_deep_research.database.sqlcipher_utils import (
+ warn_if_weak_kdf_with_existing_databases,
+ )
+
+ self._make_user_db(tmp_path, "alice")
+ self._make_user_db(tmp_path, "bob")
+
+ loguru_caplog.set_level("WARNING")
+ with patch.dict(
+ os.environ,
+ {"LDR_TEST_MODE": "1", "LDR_DB_CONFIG_KDF_ITERATIONS": "1000"},
+ clear=True,
+ ):
+ assert warn_if_weak_kdf_with_existing_databases(tmp_path) is True
+
+ text = loguru_caplog.text
+ # "1000 iterations", not bare "1000" — "1000" is a substring of the
+ # "100000" floor, so the bare check would pass without proving the
+ # effective KDF actually rendered.
+ assert "1000 iterations" in text # effective KDF
+ assert "100000" in text # production floor
+ assert "2 user database" in text # count rendered for 2 DBs
+ assert "PR #4775" in text
+
+ def test_silent_case_logs_nothing(self, tmp_path, loguru_caplog):
+ """A non-firing call must emit NO warning, not merely return False."""
+ from local_deep_research.database.sqlcipher_utils import (
+ warn_if_weak_kdf_with_existing_databases,
+ )
+
+ self._make_user_db(tmp_path)
+ loguru_caplog.set_level("WARNING")
+ with patch.dict(os.environ, {}, clear=True): # production floor
+ assert warn_if_weak_kdf_with_existing_databases(tmp_path) is False
+
+ assert "SQLCipher KDF" not in loguru_caplog.text