~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(auth): fence the post-change_password backup refresh on the rekey epoch (#7755)
Imaduddin Bhaisahebe18b3cd51c7d
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex a28fbeca37..d4737cec3d 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -183,6 +183,13 @@ class DatabaseInitializationError(Exception):# enough that a genuine cross-process rekey owner still fails promptly._REKEY_CONTENTION_RETRY_SECONDS = 1.0+# The epoch the calling thread's most recent successful ``change_password``+# committed, as ``(db_path, epoch)``. ``refresh_backups_after_password_change``+# reads it to fence the post-change backup refresh on that exact change.+# Thread-local because ``change_password`` and the refresh run back to back on+# the request's thread; another thread's change must never be mistaken for it.+_last_password_change = threading.local()+# Ceiling on each wait a request-path caller makes for the user's rekey# sidecar: a cache claim (lifecycle lock, sidecar gate and flock together),# a cold open and the epoch initialization at registration. A holder keeps@@ -3288,6 +3295,9 @@ class DatabaseManager:lock_path = db_path.with_name(f"{db_path.name}.rekey.lock")raise RekeyLockContentionError(lock_path)+ # Forget an earlier change on this thread: only a change that+ # commits below may vouch for a backup refresh.+ _last_password_change.value = Nonestage = RekeyStage.PREPARATIONpending_may_exist = Falsecommitted = False@@ -3422,6 +3432,7 @@ class DatabaseManager:)committed = True+ _last_password_change.value = (db_path, pending_epoch)if epoch_published:self._clear_committed_rekey_pending(db_path, pending_epoch, username@@ -3486,6 +3497,67 @@ class DatabaseManager:finally:rekey_lock.release()+ def refresh_backups_after_password_change(+ self, username: str, new_password: str+ ):+ """Replace old-key backups after this thread's ``change_password``.++ ``change_password`` released the rekey sidecar before returning, so+ another process may have changed the password again, and minted a+ backup under its newer key, before this runs. Purging by this+ password's view would then delete that fresh backup. Reacquire the+ sidecar and require the exact stable epoch this change committed+ before touching any file, and keep the sidecar through the purge and+ the new backup (the same order as ``_purge_superseded_key_backups``,+ which fences the login recovery path).++ Returns the ``BackupResult`` of the fresh backup, or ``None`` when+ the refresh was skipped because this change no longer owns the+ epoch: a later change purges and refreshes for itself, and a change+ whose epoch was never published is resolved by the next successful+ open, which purges the superseded backups. Raises+ ``RekeyLockContentionError`` if the sidecar stays held, so the+ caller can report that old-key backups may remain.+ """+ from .backup.backup_service import BackupService++ db_path = self._get_user_db_path(username)+ recorded = getattr(_last_password_change, "value", None)+ _last_password_change.value = None+ if recorded is None or recorded[0] != db_path:+ logger.warning(+ f"Backup refresh skipped for {username}: no committed "+ "password change on this thread to fence it against"+ )+ return None+ expected_epoch = recorded[1]++ with acquire_rekey_lock(+ db_path,+ local_wait=10.0,+ contention_retry=_REKEY_CONTENTION_RETRY_SECONDS,+ ):+ state = read_rekey_epoch_state(db_path)+ if state != RekeyEpochState(expected_epoch, None):+ logger.info(+ f"Backup refresh skipped for {username}: the rekey "+ "epoch moved or is unresolved since this change"+ )+ return None+ backup_service = BackupService(+ username=username, password=new_password+ )+ # A pinned manager data_dir can differ from the backup+ # service's configured directory. The fence must vouch for the+ # database whose backups would actually be deleted.+ if backup_service.db_path != db_path:+ logger.warning(+ f"Backup refresh skipped for {username}: backup "+ "service targets a different database"+ )+ return None+ return backup_service.purge_and_refresh()+def user_exists(self, username: str) -> bool:"""Check if a user exists in the auth database."""from .auth_db import auth_db_sessiondiff --git a/src/local_deep_research/web/routers/auth.py b/src/local_deep_research/web/routers/auth.pyindex 461e263aa2..e3d844a4ae 100644--- a/src/local_deep_research/web/routers/auth.py+++ b/src/local_deep_research/web/routers/auth.py@@ -1490,12 +1490,21 @@ def change_password(# a fresh backup with the new key. Old-key backups are a# security risk per NIST SP 800-57 / OWASP A02 — they remain# decryptable with the compromised password.+ #+ # The manager reacquires the rekey sidecar and requires the epoch+ # this change committed before deleting anything, so a concurrent+ # (cross-process) change's fresh backup is never classified against+ # a stale epoch. It returns None when a later change owns the epoch.try:- from ...database.backup.backup_service import BackupService-- svc = BackupService(username=username, password=new_password)- result = svc.purge_and_refresh()- if result.success:+ result = db_manager.refresh_backups_after_password_change(+ username, new_password+ )+ if result is None:+ logger.info(+ f"Backup refresh after password change skipped for "+ f"{_log_value_preview(username)}: a later rekey owns it"+ )+ elif result.success:logger.info(f"Backups refreshed after password change for {_log_value_preview(username)}")@@ -1504,6 +1513,12 @@ def change_password(f"Post-password-change backup failed for {_log_value_preview(username)}: "f"{result.error}. Old backups were purged.")+ except RekeyLockContentionError:+ logger.exception(+ f"Backup refresh after password change for "+ f"{_log_value_preview(username)} could not take the rekey "+ "lock; backups under the old key may remain"+ )except Exception:logger.exception(f"Could not refresh backups after password change "diff --git a/tests/database/backup/test_superseded_key_purge.py b/tests/database/backup/test_superseded_key_purge.pyindex 1935796653..496f30f639 100644--- a/tests/database/backup/test_superseded_key_purge.py+++ b/tests/database/backup/test_superseded_key_purge.py@@ -12,6 +12,7 @@ import multiprocessingimport osimport sqlite3import stat+import threadingimport timeimport uuidfrom unittest.mock import patch@@ -767,3 +768,144 @@ def test_quarantine_cleanup_does_not_follow_links_or_match_unrelated_files(assert linked.is_symlink()assert directory.is_dir()assert unrelated.exists()+++# --- Route-side refresh after a completed password change (#7677) ----------+++def test_refresh_after_change_replaces_old_key_backups(manager):+ # Given an old-key backup and a completed, published password change+ username, db_path = _user(manager)+ old_backup = _backup(username, OLD)+ assert manager.change_password(username, OLD, NEW) is True++ # When the route refreshes backups for that change+ result = manager.refresh_backups_after_password_change(username, NEW)++ # Then the old-key backup is gone and a new-key backup exists+ assert result is not None and result.success, result+ assert not old_backup.exists()+ assert result.backup_path.exists()+ assert (+ BackupService(username=username, password=NEW)._classify_backup_key(+ result.backup_path+ )+ == "current"+ )+++def test_refresh_after_change_keeps_a_later_changes_fresh_backup(manager):+ # Given the first change completed and released the sidecar+ username, db_path = _user(manager)+ _backup(username, OLD)+ assert manager.change_password(username, OLD, NEW) is True+ later_backup = []++ def later_change_from_another_request():+ # A second change lands in between, then mints its fresh backup.+ # It runs on its own thread, so it cannot overwrite the first+ # change's record on this thread.+ assert manager.change_password(username, NEW, LATEST) is True+ later_backup.append(_backup(username, LATEST))++ worker = threading.Thread(target=later_change_from_another_request)+ worker.start()+ worker.join(timeout=60)+ assert len(later_backup) == 1, "the second password change never ran"++ # When the first change's route refresh finally runs+ result = manager.refresh_backups_after_password_change(username, NEW)++ # Then it stands down and the later change's backup survives+ assert result is None+ backup = later_backup[0]+ assert backup.exists(), "stale route refresh deleted the fresh backup"+ assert get_salt_file_path(backup).exists()+ assert (+ BackupService(username=username, password=LATEST)._classify_backup_key(+ backup+ )+ == "current"+ )+++def test_refresh_after_change_skips_when_the_epoch_was_never_published(+ manager,+):+ # Given a proven change whose epoch commit failed (pending left behind)+ username, db_path = _user(manager)+ old_backup = _backup(username, OLD)+ with patch.object(+ encrypted_db,+ "commit_rekey_epoch",+ side_effect=OSError(28, "No space left on device"),+ ):+ assert manager.change_password(username, OLD, NEW) is True++ # When the route refreshes+ result = manager.refresh_backups_after_password_change(username, NEW)++ # Then nothing is deleted now; the next open resolves it and purges+ assert result is None+ assert old_backup.exists()+ manager.close_all_databases()+ assert manager.open_user_database(username, NEW) is not None+ assert not old_backup.exists()+++def test_refresh_without_a_change_on_this_thread_does_nothing(manager):+ username, db_path = _user(manager)+ backup = _backup(username, OLD)++ with patch.object(BackupService, "purge_and_refresh") as refresh:+ assert (+ manager.refresh_backups_after_password_change(username, OLD) is None+ )+ refresh.assert_not_called()+ assert backup.exists()+++def test_refresh_is_single_use_per_change(manager):+ username, db_path = _user(manager)+ assert manager.change_password(username, OLD, NEW) is True+ assert manager.refresh_backups_after_password_change(username, NEW)++ with patch.object(BackupService, "purge_and_refresh") as refresh:+ assert (+ manager.refresh_backups_after_password_change(username, NEW) is None+ )+ refresh.assert_not_called()+++def test_refresh_holds_cross_process_rekey_lock_through_the_purge(manager):+ username, db_path = _user(manager)+ _backup(username, OLD)+ assert manager.change_password(username, OLD, NEW) is True+ original_remove = BackupService._remove_backup_files+ observed = []++ def remove_while_another_process_attempts_rekey(backup):+ context = multiprocessing.get_context("spawn")+ outcomes = context.Queue()+ contender = context.Process(+ target=_try_rekey_lock_in_child,+ args=(str(db_path), outcomes),+ )+ contender.start()+ try:+ observed.append(outcomes.get(timeout=20))+ contender.join(timeout=10)+ assert contender.exitcode == 0+ finally:+ if contender.is_alive():+ contender.terminate()+ original_remove(backup)++ with patch.object(+ BackupService,+ "_remove_backup_files",+ side_effect=remove_while_another_process_attempts_rekey,+ ):+ assert manager.refresh_backups_after_password_change(username, NEW)++ assert observed and set(observed) == {"contended"}