~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(backup): re-check containment in every backup purge loop (#8014)
LearningCircuit981458080dd9
diff --git a/changelog.d/7853.security.md b/changelog.d/7853.security.mdnew file mode 100644index 0000000000..f2596beb85--- /dev/null+++ b/changelog.d/7853.security.md@@ -0,0 +1 @@+The backup purges that run after a password change now skip any listed backup entry that does not name a file directly inside the user's backup directory, such as a relative `..` name, an absolute path, or the directory itself. Symlinked entries were already skipped. An entry that cannot be inspected is skipped instead of aborting the purge, and a skipped entry is logged without its name. The check is a snapshot and does not protect against concurrent filesystem changes.diff --git a/src/local_deep_research/database/backup/backup_service.py b/src/local_deep_research/database/backup/backup_service.pyindex 56ae49c776..4dbe6d8e85 100644--- a/src/local_deep_research/database/backup/backup_service.py+++ b/src/local_deep_research/database/backup/backup_service.py@@ -1269,10 +1269,46 @@ class BackupService:]def _managed_backup_paths(self) -> list[Path]:- """Include quarantined copies without exposing them for restore."""- return [+ """Include quarantined copies without exposing them for restore.++ The superseded-key purge deletes what this returns, so each joined+ path is re-checked here (purge_and_refresh enumerates with+ list_backup_files instead and re-checks each entry itself).+ list_backups() reports only bare names from a filtered glob, but an+ entry that is not a bare in-root name (a poisoned listing or a+ future caller) must not redirect a purge outside backup_dir. is_safe_glob_result drops a symlink entry and+ an entry that resolves outside backup_dir. The resolved entry must+ also be a direct child of backup_dir: an entry of "." or "" joins+ to backup_dir itself, which is_relative_to() accepts, and its salt+ path would then name a sibling outside the directory. An entry+ that cannot be inspected (an OSError, or a ValueError such as an+ embedded NUL byte) is dropped too. The check is a snapshot, not+ atomic with the caller's unlink. A refused entry is logged without+ its name.+ """+ # Lazy import, as in is_safe_glob_result.+ from ...security.path_validator import resolve_allow_missing++ candidates = [self.backup_dir / info["path"] for info in self.list_backups()] + self._quarantined_backup_paths()+ contained = []+ for path in candidates:+ try:+ safe = is_safe_glob_result(path, self.backup_dir) and (+ resolve_allow_missing(path).parent+ == resolve_allow_missing(self.backup_dir)+ )+ except (OSError, ValueError):+ safe = False+ if safe:+ contained.append(path)+ else:+ logger.warning(+ "Skipping a backup entry that is a symlink or is not "+ "directly inside the backup directory"+ )+ return containeddef purge_and_refresh(self) -> "BackupResult":"""Remove old-key backup files and create a current-password backup.@@ -1408,6 +1444,10 @@ class BackupService:``OSError``, so in a directory that can be listed but not searchedevery old backup would look absent and the purge would be recordedas verified clean.++ A ``ValueError`` (such as an embedded NUL byte) means the entry+ cannot name a file on disk at all, so it is neither deleted nor+ counted; the entry is skipped and the purge carries on."""try:info = os.lstat(entry)@@ -1415,6 +1455,12 @@ class BackupService:return Falseexcept OSError:return True+ except ValueError:+ logger.warning(+ "Ignoring an entry that is not a valid path during a "+ "password-change purge"+ )+ return Falseif S_ISLNK(info.st_mode):logger.warning("Ignoring a symlink with a backup name during a "@@ -1440,6 +1486,8 @@ class BackupService:)except OSError:return True+ except ValueError:+ inside = Falseif not inside:logger.warning("Ignoring an entry outside the backup directory during a "diff --git a/tests/security/test_identity_paths_and_host_effects.py b/tests/security/test_identity_paths_and_host_effects.pyindex ebf8e7a4fe..89ee76f505 100644--- a/tests/security/test_identity_paths_and_host_effects.py+++ b/tests/security/test_identity_paths_and_host_effects.py@@ -335,3 +335,116 @@ def test_purge_does_not_follow_forged_backup_symlink(# The purge never deletes a symlink's target, so the link itself is not a# remaining old-password backup and cannot keep the warning up (#7443 R2).service._create_backup_impl.assert_called_once_with(purge_incomplete=False)+++# Issue #7853: every purge loop skips a forged listing entry and still+# deletes ordinary backups. The superseded-key purge consumes+# _managed_backup_paths (which re-checks list_backups entries); purge_and_refresh+# enumerates with list_backup_files and re-checks each entry itself, so the+# forged listing is injected through both.++_ORDINARY_BACKUP = "ldr_backup_20260101_000000.db"+++def _forge_listing(service, monkeypatch, tmp_path, kind):+ """Plant an outside canary and a listing that also names a real backup.++ Returns (canary, ordinary_backup). ``kind`` picks how the forged entry+ reaches the canary: a relative ``..`` name, an absolute path, or an+ in-root symlink with a backup name. ``dot`` names backup_dir itself,+ whose salt path is a sibling outside it, and ``nul`` is a name with an+ embedded NUL byte that cannot be resolved at all.+ """+ canary = tmp_path / "outside.db"+ canary.write_bytes(b"do not delete")+ ordinary = service.backup_dir / _ORDINARY_BACKUP+ ordinary.write_bytes(b"old-key backup")+ if kind == "relative":+ forged = "../outside.db"+ elif kind == "absolute":+ forged = str(canary)+ elif kind == "dot":+ forged = "."+ elif kind == "nul":+ forged = "ldr_backup_20260101_000002.db\x00"+ else:+ if __import__("sys").platform == "win32":+ pytest.skip("Unix-specific test")+ link = service.backup_dir / "ldr_backup_20260101_000001.db"+ try:+ link.symlink_to(canary)+ except OSError:+ pytest.skip("Cannot create symlinks in this environment")+ forged = link.name+ monkeypatch.setattr(+ service,+ "list_backups",+ lambda: [+ {"filename": "forged.db", "path": forged},+ {"filename": _ORDINARY_BACKUP, "path": _ORDINARY_BACKUP},+ ],+ )+ monkeypatch.setattr(+ backup_service,+ "list_backup_files",+ lambda directory, *, include_auxiliary=False: [+ directory / forged,+ directory / _ORDINARY_BACKUP,+ ],+ )+ return canary, ordinary+++_FORGED_KINDS = ["relative", "absolute", "symlink", "dot", "nul"]++[email protected]("kind", _FORGED_KINDS)+def test_managed_backup_paths_drops_forged_entries(+ tmp_path, monkeypatch, backup_service_in_tmpdir, loguru_caplog, kind+):+ service = backup_service_in_tmpdir+ _canary, ordinary = _forge_listing(service, monkeypatch, tmp_path, kind)++ with loguru_caplog.at_level("WARNING"):+ paths = service._managed_backup_paths()++ assert paths == [ordinary]+ assert "directly inside the backup directory" in loguru_caplog.text+ # The refusal is logged without the entry's name.+ assert "outside.db" not in loguru_caplog.text+ assert "ldr_backup_20260101_000001" not in loguru_caplog.text+ assert "ldr_backup_20260101_000002" not in loguru_caplog.text+++def _run_superseded_purge(service, monkeypatch):+ # Every backup counts as superseded and no salt is required, so the+ # only thing that can keep a forged entry alive is the containment check.+ monkeypatch.setattr(+ backup_service, "has_per_database_salt", lambda _p: False+ )+ monkeypatch.setattr(+ service, "_classify_backup_key", lambda _p: "superseded"+ )+ return service.purge_backups_under_superseded_key()++[email protected]("kind", _FORGED_KINDS)[email protected]("loop", ["purge_and_refresh", "superseded_key"])+def test_every_purge_loop_skips_forged_entries(+ tmp_path, monkeypatch, backup_service_in_tmpdir, loop, kind+):+ if loop == "purge_and_refresh" and kind == "nul":+ pytest.skip(+ "list_backup_files enumerates with iterdir(), which cannot "+ "yield a name with a NUL byte"+ )+ service = backup_service_in_tmpdir+ canary, ordinary = _forge_listing(service, monkeypatch, tmp_path, kind)++ if loop == "purge_and_refresh":+ service.purge_and_refresh()+ else:+ assert _run_superseded_purge(service, monkeypatch) == 1++ assert canary.read_bytes() == b"do not delete"+ assert not ordinary.exists()