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.

fix(db): validate both passwords in change_password before rekeying (#6375)

Lukas Buckf99562270aed
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.py
index a7adc4c237..e7c450bb03 100644
--- a/src/local_deep_research/database/encrypted_db.py
+++ b/src/local_deep_research/database/encrypted_db.py
@@ -1416,6 +1416,28 @@ class DatabaseManager:
)
return False
+ # Validate BOTH keys before anything touches the database, mirroring
+ # the guards on create_user_database / open_user_database. Rekeying to
+ # an empty or whitespace-only password used to succeed and return
+ # True, after which the open-path guard rejected that same password
+ # and the database was permanently unopenable (#6353).
+ if not self._is_valid_encryption_key(old_password):
+ logger.error(
+ f"Invalid encryption key when changing password for user {username}: "
+ "old password is None or empty"
+ )
+ raise ValueError(
+ "Invalid encryption key: old password cannot be None or empty"
+ )
+ if not self._is_valid_encryption_key(new_password):
+ logger.error(
+ f"Invalid encryption key when changing password for user {username}: "
+ "new password is None or empty"
+ )
+ raise ValueError(
+ "Invalid encryption key: new password cannot be None or empty"
+ )
+
db_path = self._get_user_db_path(username)
if not db_path.exists():
diff --git a/src/local_deep_research/web/routers/auth.py b/src/local_deep_research/web/routers/auth.py
index 1a7eb1aa83..c9416faa8f 100644
--- a/src/local_deep_research/web/routers/auth.py
+++ b/src/local_deep_research/web/routers/auth.py
@@ -1018,7 +1018,12 @@ def change_password(
# Validation
errors = []
- if not current_password:
+ # ``strip()``: a whitespace-only current password is not empty, so it
+ # passed this check and reached ``change_password``'s own key validation,
+ # which raises ValueError -- a 500 where the form should simply say the
+ # field is required (#6375). The new password needs no equivalent: every
+ # whitespace-only value fails validate_strength below.
+ if not current_password.strip():
errors.append("Current password is required")
if not new_password:
@@ -1107,9 +1112,41 @@ def change_password(
)
# Attempt password change (the rekey) — holds only this user's gate.
- success = db_manager.change_password(
- username, current_password, new_password
- )
+ try:
+ success = db_manager.change_password(
+ username, current_password, new_password
+ )
+ except ValueError:
+ # change_password validates both keys before it rekeys and
+ # raises on an invalid one. The form checks above should have
+ # caught anything a browser can send, so this is the backstop
+ # that keeps a missed shape a 400 rather than a 500 with a
+ # traceback. Nothing has been rekeyed on this path.
+ #
+ # The exception is not logged: its message is built from the
+ # password fields this handler holds in plaintext, and the
+ # repository's logging guard rejects an exception variable here
+ # for exactly that reason. The fact and the user are what an
+ # operator needs; the reason is one of the two guards in
+ # change_password.
+ logger.warning(
+ f"Password change rejected for {username}: the rekey path "
+ "refused one of the submitted password fields"
+ )
+ flash(
+ request,
+ "Password change rejected: check the current and new password "
+ "fields and try again.",
+ "error",
+ )
+ return render_template(
+ request,
+ "auth/change_password.html",
+ {
+ "password_requirements": PasswordValidator.get_requirements(),
+ },
+ status_code=400,
+ )
if success:
# The rekey is the ONLY step needed. The auth database stores no
diff --git a/tests/database/test_change_password_validation.py b/tests/database/test_change_password_validation.py
new file mode 100644
index 0000000000..9a90a42a37
--- /dev/null
+++ b/tests/database/test_change_password_validation.py
@@ -0,0 +1,72 @@
+"""``change_password`` must reject an invalid password BEFORE it rekeys.
+
+``create_user_database`` and ``open_user_database`` guard the password with
+``_is_valid_encryption_key``, but the rekey path did not: rekeying to an empty
+or whitespace-only password succeeded and returned ``True``, after which the
+open-path guard rejected that same password and the database was permanently
+unopenable (#6353).
+"""
+
+import pytest
+
+from local_deep_research.database.encrypted_db import DatabaseManager
+
+OLD_PASSWORD = "OldCorrectHorse1!"
+
+
+def manager(tmp_path, monkeypatch):
+ """A DatabaseManager writing to an isolated data directory."""
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ mgr = DatabaseManager()
+ mgr.data_dir = tmp_path
+ if not mgr.has_encryption:
+ pytest.skip("SQLCipher not available; rekey path is a no-op")
+ yield mgr
+ mgr.close_all_databases()
+
+
+def user(manager):
+ username = "rekey_guard_user"
+ manager.create_user_database(username, OLD_PASSWORD)
+ manager.close_user_database(username)
+ return username
+
+
[email protected]("bad_password", ["", " ", None])
+def test_invalid_new_password_is_rejected_before_rekey(
+ manager, user, bad_password
+):
+ with pytest.raises(
+ ValueError, match="new password cannot be None or empty"
+ ):
+ manager.change_password(user, OLD_PASSWORD, bad_password)
+
+ # Nothing was rekeyed: the old password still opens the database.
+ engine = manager.open_user_database(user, OLD_PASSWORD)
+ assert engine is not None
+ manager.close_user_database(user)
+
+
[email protected]("bad_password", ["", " ", None])
+def test_invalid_old_password_is_rejected(manager, user, bad_password):
+ with pytest.raises(
+ ValueError, match="old password cannot be None or empty"
+ ):
+ manager.change_password(user, bad_password, "NewCorrectHorse2!")
+
+ engine = manager.open_user_database(user, OLD_PASSWORD)
+ assert engine is not None
+ manager.close_user_database(user)
+
+
+def test_valid_new_password_still_rekeys(manager, user):
+ assert (
+ manager.change_password(user, OLD_PASSWORD, "NewCorrectHorse2!") is True
+ )
+
+ assert manager.open_user_database(user, OLD_PASSWORD) is None
+ engine = manager.open_user_database(user, "NewCorrectHorse2!")
+ assert engine is not None
+ manager.close_user_database(user)
diff --git a/tests/web/routers/test_auth_flow_gaps.py b/tests/web/routers/test_auth_flow_gaps.py
index 8b6282a87c..fa42db4db8 100644
--- a/tests/web/routers/test_auth_flow_gaps.py
+++ b/tests/web/routers/test_auth_flow_gaps.py
@@ -16,6 +16,9 @@ Covers (audit parity list):
- Temp-auth token single use at the HTTP layer: the token stored in the
session at login is consumed by the first request that needs it and is
removed from the cookie session, so it cannot be replayed.
+- Change-password with a whitespace-only current password is a form
+ validation error, not a 500: the field check reads the stripped value, so
+ the request never reaches the rekey path's own key validation.
(Store-level single-use semantics are already covered by
tests/database/test_temp_auth.py::test_retrieve_auth_removes_entry.)
@@ -426,3 +429,47 @@ class TestTempAuthTokenSingleUse:
assert (
session_password_store.get_session_password(user, sid) is not None
)
+
+
+# ----------------------------------------------------------------------------
+# Change-password input validation
+# ----------------------------------------------------------------------------
+
+
+class TestChangePasswordWhitespaceCurrent:
+ """A whitespace-only current password must be refused by the form.
+
+ ``" "`` is not empty, so the handler's ``if not current_password``
+ check passed it through to ``DatabaseManager.change_password``, whose
+ key validation raises ``ValueError`` — a 500 with a traceback where the
+ user should see "Current password is required" (#6375).
+ """
+
+ def test_whitespace_only_current_password_is_a_validation_error(
+ self, app, registered_user
+ ):
+ user, pw = registered_user
+ client = _new_client(app)
+ assert _login(client, user, pw).status_code == 302
+
+ new_password = "ReplacementPass123" # noqa: S105
+ resp = client.post(
+ "/auth/change-password",
+ data={
+ "current_password": " ",
+ "new_password": new_password,
+ "confirm_password": new_password,
+ "csrf_token": _csrf(client),
+ },
+ follow_redirects=False,
+ )
+
+ assert resp.status_code == 400, (
+ "a whitespace-only current password must come back as a form "
+ f"validation error, got {resp.status_code}: {resp.text[:300]}"
+ )
+ assert "Current password is required" in resp.text
+
+ # Nothing was rekeyed: the real password still opens the database.
+ assert _login(_new_client(app), user, pw).status_code == 302
+ assert _login(_new_client(app), user, new_password).status_code == 401