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: preserve salts for recoverable database backups (#7032)

LearningCircuit7f8364aee9bb
diff --git a/changelog.d/+backup-salt-recovery.bugfix.md b/changelog.d/+backup-salt-recovery.bugfix.md
new file mode 100644
index 0000000000..659dabdb03
--- /dev/null
+++ b/changelog.d/+backup-salt-recovery.bugfix.md
@@ -0,0 +1 @@
+Preserve the matching salt alongside encrypted database backups and verify backups independently of the original database. Keep salt files with their backups during retention and password-change cleanup, use unique export filenames, and document offline recovery into an empty directory. The once-a-day login backup now counts only a backup that passed this verification, so a backup missing its salt no longer prevents a complete replacement. Until the application restarts or the password changes, verification results are remembered while the backup and salt files keep the same file identity, size and modification time: later logins reuse a remembered pass without checking any backup again, and do not repeat a remembered failure. A backup without a salt file, of a database that has its own salt, is rejected without deriving a key, and a backup whose database or salt file is removed or changed while it is being verified does not count. A new backup is removed, and no older backup is deleted, when its database or salt file is removed or changed while it is being verified, or when, by the end of its publication, either file has gone missing or differs in size from the verified one, or a salt file has appeared beside a backup verified without one. A backup that v1.10.7 made of a database with its own salt has no salt file, so it never counts as that day's backup: if the pre-migration backup fails, the first sign-in after the upgrade still makes a login backup, which with the default `backup.max_count` of 1 removes the user's older backups.
diff --git a/docs/deployment/upgrading.md b/docs/deployment/upgrading.md
index a679d72a5a..ea3a36d0de 100644
--- a/docs/deployment/upgrading.md
+++ b/docs/deployment/upgrading.md
@@ -176,15 +176,26 @@ Treat a user with no `Pre-migration backup created` line for that sign-in
as having no pre-migration backup, and rely on the offline backup for that
user's rollback.
+If the pre-migration backup fails, that first sign-in can still remove the
+user's backups made before the upgrade. A backup that v1.10.7 made of a
+database with its own salt has no salt file, so it never passes
+verification and does not count as that day's backup: the sign-in's login
+backup runs even if v1.10.7 made a backup earlier the same UTC day. If that
+login backup succeeds, it is a copy of the upgraded database, and with the
+default `backup.max_count` of `1` it removes all of the user's older
+backups. To keep them, raise `backup.max_count`, or copy them out of the
+backup directory, before upgrading.
+
This pre-migration backup is not durable. Writing it applies the user's
`backup.max_count` and `backup.max_age_days` to their older automatic
backups, so with the default `backup.max_count` of `1` it removes all of
them; if those settings cannot be read before the migration, or are not
whole numbers within the settings' ranges (1 to 30 backups, 1 to 90 days),
it removes none. Later events replace or delete the pre-migration backup
-itself. A sign-in adds a login backup only when the user has no backup dated
-the current UTC day, so only the first sign-in on each later UTC day adds
-one; further sign-ins that day add nothing.
+itself. A sign-in adds a login backup only when none of the user's backups
+dated the current UTC day passes verification, so only the first sign-in on
+each later UTC day adds one; further sign-ins that day add nothing while
+that day's backup still passes.
- With the default `backup.max_count` of `1`, the first login backup made on
a later UTC day replaces it with a copy of the upgraded database. A
diff --git a/docs/security/database-backup.md b/docs/security/database-backup.md
index 6a7800504c..a14cdc296b 100644
--- a/docs/security/database-backup.md
+++ b/docs/security/database-backup.md
@@ -6,16 +6,17 @@ Local Deep Research includes an automatic database backup system that creates en
- **Automatic**: Backups run in the background after login without blocking the UI
- **Encrypted**: Backups use the same encryption as your main database
-- **Safe**: Uses SQLCipher's `sqlcipher_export()` for atomic backups that work correctly with WAL mode
+- **WAL-aware**: Uses SQLCipher's `sqlcipher_export()` to copy committed data, including data still in the source WAL
+- **Salt preservation**: New backups include the original matching `.salt` file when the source uses a per-database salt
- **Configurable**: Enable/disable and configure retention via settings
- **Pre-migration**: A backup is automatically attempted before any database schema migration
## How It Works
1. When you log in successfully, a background backup is scheduled
-2. Only one backup per calendar day is created — subsequent logins the same day are skipped to prevent a corrupted database from overwriting all good backups
+2. Only one verified backup per calendar day is normally created — subsequent logins the same day reuse it. The verification in step 4 runs when a backup is created. The application then remembers each verification result, passing or failing, for as long as the backup and its salt keep the same file identity, size and modification time; an application restart or a password change forgets them. A later login reuses a remembered pass without verifying any backup. Only when none of the day's backups has one does it verify the backups that have no remembered result, newest first, stopping at the first that passes. A backup whose database or salt file is removed or changed during that check does not count. An older backup missing its required salt does not prevent creation of a complete replacement, and when the database has its own salt, such a backup is rejected without deriving a key
3. The backup runs in a separate thread (non-blocking)
-4. Uses `sqlcipher_export()` to create an encrypted copy preserving all cipher settings
+4. Uses `sqlcipher_export()` to create an encrypted copy, preserves the matching salt, and verifies the copy using the backup's own salt. A copy is removed, and no older backup is deleted, when its database or salt file is removed or changed while it is being verified, or when, by the end of its publication, either file has gone missing or differs in size from the verified one, or a salt file has appeared beside a copy verified without one. A change made after the verification that keeps each file's size is not detected at publication
5. Old backups are automatically cleaned up based on your retention settings
6. Before database migrations, a backup is always attempted regardless of the daily limit. If it fails, the log shows `Pre-migration backup failed` and the migration runs anyway. A pre-migration backup that was made is not kept: with the default **Max Backups** of `1`, the login backup on a later UTC day replaces it with a copy of the migrated database, and a password change deletes it. Copy it out of the backup directory if you may need to roll back; see the [upgrade and rollback guide](../deployment/upgrading.md#automatic-pre-migration-backups)
@@ -28,11 +29,24 @@ Backups are stored in:
Where `{user_hash}` is the first 16 hex characters of the SHA-256 hash of your username.
-Each backup file is named with a timestamp:
+Each new backup has a timestamp and a unique suffix, so forced backups in the
+same second cannot overwrite one another:
+
```
-ldr_backup_20250125_143022.db
+ldr_backup_20250125_143022_ab12cd34.db
+ldr_backup_20250125_143022_ab12cd34.db.salt
```
+**Preserve both files together.** The salt is required to derive the database
+key from the password. It is not a replacement for the password, and generating
+a new salt will not recover an existing database. Retention and password-change
+cleanup remove each backup together with its salt.
+
+Legacy databases that use LDR's built-in shared salt have no `.salt` sidecar.
+New backups of those databases remain readable through the legacy derivation
+path. Do not assume a missing salt means a backup is legacy: verify it with the
+matching application version and cipher configuration before relying on it.
+
## Settings
Configure backup behavior in Settings > Backup:
@@ -51,20 +65,95 @@ We use SQLCipher's `sqlcipher_export()` instead of `VACUUM INTO` or simple file
1. **Encryption Preservation**: `VACUUM INTO` does not preserve SQLCipher encryption settings. `sqlcipher_export()` correctly copies data while maintaining the same encryption key and cipher configuration
2. **WAL Safety**: Regular file copy can corrupt databases using WAL (Write-Ahead Logging) mode
-3. **Atomic Operation**: The backup uses ATTACH + export + DETACH, and is written to a temporary file then atomically renamed
-4. **Integrity Verification**: Each backup is verified with `PRAGMA quick_check` before being finalized
-
-## Restoring from Backup
-
-To restore from a backup:
-
-1. Stop the application
-2. Locate your backup in the backup directory
-3. Copy it to replace your current database file (keep the `.salt` file alongside it)
-4. Restart the application
+3. **Publication**: The export uses a unique temporary database. After verification, its salt is renamed first and the database is renamed last. A process interruption between those steps leaves an orphan salt, rather than a listed database with a missing salt. The two files are not a single atomic filesystem transaction; copy completed pairs together to external storage
+4. **Integrity Verification**: Each backup is verified with `PRAGMA quick_check` and its own recovery inputs before being finalized
+
+## Backup scope
+
+These are **per-user database snapshots**, not full instance backups. They do
+not include the account registry (`ldr_auth.db`), deployment configuration, or files
+stored outside the user database, such as filesystem-backed library content.
+Preserve those separately when backing up an entire deployment. A cleanly
+stopped copy of the full data directory and deployment configuration is the
+appropriate starting point for an instance recovery rehearsal.
+
+Keep the application version and any custom `LDR_DB_CONFIG_*` cipher settings
+with the backup inventory. The database and salt do not encode all settings
+used for key derivation. Use the same configuration to verify and recover a
+backup; changing it can prevent a correct password from opening the database.
+
+## Offline recovery rehearsal
+
+The procedure below recovers a user database into a **new, empty directory**.
+It does not replace a live database or recreate a missing account registry.
+An in-application restore with coordinated session shutdown is tracked in
+[#5327](https://github.com/LearningCircuit/local-deep-research/issues/5327).
+
+1. Copy the completed backup and its matching `.salt` to storage outside the
+ original data directory. For backups made before salt preservation was
+ added, preserve the original database's matching salt as well. This change
+ cannot reconstruct a salt already lost from an older backup.
+2. Use the matching LDR version and cipher configuration in an isolated
+ environment. Keep it stopped; do not point a running instance at the
+ recovery directory.
+3. Create an empty recovery directory. Copy the backup database there using
+ the original user's filename, `ldr_user_<user_hash>.db`, and copy its salt
+ as `ldr_user_<user_hash>.db.salt`. The user hash is the first 16 hexadecimal
+ characters of SHA-256 of the exact username. Restrict the directory to the
+ operator and the recovered files to the application account.
+4. Verify the recovered copy without access to the original data directory.
+ Run the following with the matching LDR installation. It prompts for the
+ password instead of putting it in shell history:
+
+ ```python
+ from getpass import getpass
+ from pathlib import Path
+ from local_deep_research.database.sqlcipher_utils import create_sqlcipher_connection
+
+ recovered = Path(input("Recovered database path: ")).expanduser()
+ if not recovered.is_file() or recovered.is_symlink():
+ raise ValueError("Select the recovered database file")
+ connection = create_sqlcipher_connection(recovered, getpass("Backup password: "))
+ try:
+ result = connection.execute("PRAGMA quick_check").fetchall()
+ if result != [("ok",)]:
+ raise ValueError("Recovered database failed its integrity check")
+ tables = connection.execute(
+ "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"
+ ).fetchall()
+ print("Integrity check passed. Recovered tables:", tables)
+ finally:
+ connection.close()
+ ```
+
+5. In a separate instance recovery rehearsal, restore the corresponding account
+ registry, configuration, and required external files, then check login and
+ representative research/library data through the UI. A database integrity
+ check alone does not establish that the whole instance has been recovered.
+
+Before any eventual replacement of a production database, stop every process
+using it and preserve the current database, salt, and any WAL/SHM files as a
+rollback set. Do not copy a backup over a live database or discard a WAL that
+may contain uncheckpointed writes. Keep recovery and rollback sets separate;
+never combine an old WAL with a recovered database.
**Important**: The backup uses the same password as when it was created. If you've changed your password since the backup, you'll need to use the old password to access it.
+The automated recovery tests exercise real SQLCipher exports with committed
+WAL data, remove the original data directory, recover using the archived
+database/salt pair, check the recovered data, and verify that new writes persist.
+They also cover legacy databases, a wrong password, missing or damaged backup
+salts, failed publication, publishing the salt before the database, retention
+of matching file pairs, and reusing a verified backup on later logins until
+its database or salt file is replaced or its modification time changes. They
+check that later logins derive no key when a failing backup is kept beside a
+verified one, that a backup without a salt file, of a database that has its
+own salt, is rejected before any key derivation, and that a backup or export
+whose database or salt file is removed during its check, or an export whose
+salt is removed before or during publication, is neither reused nor
+published. They do not exercise live in-application replacement or full
+account-registry recovery.
+
## Troubleshooting
### Backups not being created
@@ -88,5 +177,10 @@ If you see "Backup verification failed" in logs, the backup may be corrupted. Th
1. The disk ran out of space during backup
2. There was a system crash during backup
3. The source database is corrupted
+4. The backup's `.salt` file is missing or damaged (backups made before salts were kept alongside them have none)
-In this case, the corrupted backup file is automatically deleted.
+A new backup that fails verification is deleted automatically. An existing
+backup that fails the check at a later login no longer counts as that day's
+backup and is kept until retention removes it. The failure is remembered, so
+that backup is not checked again until the application restarts, the password
+changes, or its database or salt file changes.
diff --git a/src/local_deep_research/database/backup/backup_service.py b/src/local_deep_research/database/backup/backup_service.py
index 649b514df3..670cbb6ab9 100644
--- a/src/local_deep_research/database/backup/backup_service.py
+++ b/src/local_deep_research/database/backup/backup_service.py
@@ -6,6 +6,7 @@ and work correctly with WAL mode.
import os
import shutil
+import tempfile
import threading
import time
from dataclasses import dataclass
@@ -23,11 +24,15 @@ from ...config.paths import (
get_user_database_filename,
)
from ..sqlcipher_utils import (
+ LEGACY_PBKDF2_SALT,
apply_performance_pragmas,
apply_sqlcipher_pragmas,
create_sqlcipher_connection,
get_key_from_password,
+ get_salt_file_path,
+ get_salt_for_database,
get_sqlcipher_settings,
+ has_per_database_salt,
set_sqlcipher_key,
verify_sqlcipher_connection,
)
@@ -40,6 +45,21 @@ from ..sqlcipher_utils import (
_user_locks: dict[str, threading.Lock] = {}
_user_locks_lock = threading.Lock()
+# Device, inode, size and modification time of one file.
+_FileIdentity = tuple[int, int, int, int]
+# Identity of a backup database and of its salt file (None when it has none).
+_BackupIdentity = tuple[_FileIdentity, Optional[_FileIdentity]]
+
+# Full backup verifications run in this process, per user: {username: {backup
+# path: (identity of the database and salt files verified, whether they
+# passed)}}. _verify_backup costs a full key derivation and a PRAGMA
+# quick_check over the whole backup, so the daily limit reuses a remembered
+# pass, and skips a remembered failure, only while both files keep that
+# identity. A restart forgets every result; a password change forgets that
+# user's. A user's entries are read and written only while holding that user's
+# backup lock. They contain file metadata, no key material.
+_backup_verifications: dict[str, dict[Path, tuple[_BackupIdentity, bool]]] = {}
+
# Characters that must never appear in the validated backup path string.
# ATTACH DATABASE takes a string literal and cannot be parameterized in
# SQLite/SQLCipher, so the path is interpolated into SQL. A single quote IS
@@ -48,11 +68,31 @@ _user_locks_lock = threading.Lock()
# break backups. Double-quote, NUL and control chars are rejected outright. A
# backslash is in the set, but never appears in the validated string in a real
# backup path: it is the Windows separator, normalised to "/" before this check
-# (see _create_backup_impl); on POSIX a real separator is always "/", so a
+# (see _validate_backup_path); on POSIX a real separator is always "/", so a
# literal backslash there is conservatively rejected.
_UNSAFE_BACKUP_PATH_CHARS = frozenset('"\\\0\n\r\t')
+def _validate_backup_path(path: Path) -> str:
+ """Normalize host separators and validate the path used in ATTACH.
+
+ Use this before reserving files and again for the exported temporary path.
+ Filesystem operations keep their native Path; a literal POSIX backslash
+ remains invalid instead of being redirected to another directory.
+ """
+ path_string = str(path)
+ if os.sep == "\\":
+ path_string = path_string.replace("\\", "/")
+ bad_chars = _UNSAFE_BACKUP_PATH_CHARS & set(path_string)
+ if bad_chars:
+ raise ValueError(
+ "Backup path contains characters not allowed in a "
+ "SQLCipher ATTACH statement: "
+ + ", ".join(sorted(repr(c) for c in bad_chars))
+ )
+ return path_string
+
+
def _get_user_lock(username: str) -> threading.Lock:
"""Get or create a lock for a specific user.
@@ -70,6 +110,64 @@ def _get_user_lock(username: str) -> threading.Lock:
return _user_locks[username]
+def _get_backup_verifications(
+ username: str,
+) -> dict[Path, tuple[_BackupIdentity, bool]]:
+ """Return the user's remembered verification results.
+
+ Read or change the returned mapping only while holding the user's lock.
+ """
+ with _user_locks_lock:
+ return _backup_verifications.setdefault(username, {})
+
+
+def _file_identity(path: Path) -> _FileIdentity:
+ """Return the device, inode, size and mtime of ``path`` itself."""
+ status = path.lstat()
+ return status.st_dev, status.st_ino, status.st_size, status.st_mtime_ns
+
+
+def _backup_identity(backup_path: Path) -> Optional[_BackupIdentity]:
+ """Identify the exact database and salt files a verification reads.
+
+ ``lstat`` gives a replaced file, including one replaced by a symlink, a
+ different identity. A legacy backup has no salt file. None means the
+ files could not be identified, so no result for them is reused.
+ """
+ try:
+ database = _file_identity(backup_path)
+ except OSError:
+ return None
+ try:
+ salt = _file_identity(get_salt_file_path(backup_path))
+ except FileNotFoundError:
+ salt = None
+ except OSError:
+ return None
+ return database, salt
+
+
+def _is_published_pair(
+ published: Optional[_BackupIdentity], verified: _BackupIdentity
+) -> bool:
+ """Whether the published files are the complete pair that was verified.
+
+ The database, and the salt if one was verified, must be there with the
+ size they had when verified, and a salt must be absent if none was. A
+ rename keeps a file's size. Device, inode and modification time are not
+ compared: should a filesystem change them on rename, that only means a
+ later login verifies the backup again.
+ """
+ if published is None:
+ return False
+ (database, salt), (verified_database, verified_salt) = published, verified
+ if database[2] != verified_database[2]:
+ return False
+ if salt is None or verified_salt is None:
+ return salt is verified_salt
+ return salt[2] == verified_salt[2]
+
+
def is_safe_glob_result(path: Path, base_dir: Path) -> bool:
"""Validate that a glob result is safe to use.
@@ -164,12 +262,21 @@ class BackupService:
"""Create an encrypted backup of the user's database.
Uses sqlcipher_export() to create a safe, atomic backup that inherits
- the encryption key from the source database. The backup is created
- with a .tmp suffix and atomically renamed to prevent race conditions
- with cleanup operations.
+ the encryption key from the source database. The matching salt is
+ copied alongside it. The database is published only after its salt,
+ so a completed .db file never depends on the source's salt file.
+ If either file is removed or changed while the copy is verified, or
+ a file of the pair is missing, or no longer the size verified, when
+ it is published, the new backup fails and is removed, and no older
+ backup is deleted.
By default, only one backup per calendar day is created to prevent
a corrupted database from rapidly overwriting all good backups.
+ Only a backup that passed the full verification counts. That runs
+ when a backup is created. An existing backup is verified again only
+ when none of today's backups has a pass this process remembers for
+ its current database and salt files, and only if no failure is
+ remembered for those files either (see _find_verified_backup).
Use force=True to bypass this check (used by pre-migration backups).
This method is protected by a per-user lock to prevent concurrent
@@ -193,23 +300,22 @@ class BackupService:
if not force:
today = datetime.now(UTC).strftime("%Y%m%d")
# After globbing, verify each result is a direct child of backup_dir
- existing_today = [
+ todays_backups = [
f
for f in self.backup_dir.glob(f"ldr_backup_{today}_*.db")
if is_safe_glob_result(f, self.backup_dir)
]
- if existing_today:
- latest = max(existing_today, key=lambda p: p.name)
+ existing = self._find_verified_backup(todays_backups)
+ if existing is not None:
+ existing_path, existing_size = existing
logger.debug(
- f"Backup already exists for today ({latest.name}), "
- "skipping"
+ "Backup already exists for today "
+ f"({existing_path.name}), skipping"
)
return BackupResult(
success=True,
- backup_path=latest,
- size_bytes=latest.stat().st_size
- if latest.exists()
- else 0,
+ backup_path=existing_path,
+ size_bytes=existing_size,
)
start = time.perf_counter()
@@ -258,14 +364,38 @@ class BackupService:
error=f"Could not verify disk space: {e}",
)
- # Generate backup filename with timestamp
- # Use .tmp suffix during creation to prevent cleanup race conditions
+ # Reserve a unique, owner-only temporary file. Forced backups can run
+ # within the same second; neither a new export nor failed cleanup may
+ # overwrite a previous successful backup.
timestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")
- backup_filename = f"ldr_backup_{timestamp}.db"
- backup_path = self.backup_dir / backup_filename
- temp_path = self.backup_dir / f"ldr_backup_{timestamp}.db.tmp"
+ temp_path = None
+ backup_path = None
try:
+ _validate_backup_path(self.backup_dir)
+ fd, temp_name = (
+ tempfile.mkstemp( # Safe: empty owner-only file; SQLCipher writes ciphertext
+ prefix=f"ldr_backup_{timestamp}_",
+ suffix=".db.tmp",
+ dir=self.backup_dir,
+ )
+ )
+ os.close(fd)
+ temp_path = Path(temp_name)
+ destination = temp_path.with_suffix("")
+ destination_salt = get_salt_file_path(destination)
+ if (
+ destination.exists()
+ or destination.is_symlink()
+ or destination_salt.exists()
+ or destination_salt.is_symlink()
+ ):
+ raise FileExistsError( # noqa: TRY301 - outer handler removes our reserved temp file
+ "Backup destination already exists"
+ )
+ backup_path = destination
+ salt_copied = self._copy_source_salt(temp_path)
+
# Create connection to source database
conn = create_sqlcipher_connection(str(self.db_path), self.password)
cursor = conn.cursor()
@@ -287,28 +417,13 @@ class BackupService:
# VACUUM INTO doesn't preserve encryption in SQLCipher
# Security: the ATTACH path below is interpolated (not
# parameterizable). Single quotes are escaped (see below); any
- # other unsafe char is rejected. Don't log the full path — it can
- # contain a username — only the offending characters.
- # Windows paths carry backslashes, which the ATTACH literal
- # rejects (see _UNSAFE_BACKUP_PATH_CHARS) - so automatic
- # backups failed on every Windows install. SQLite/SQLCipher
- # accept forward slashes on every platform, so normalise the
- # string used in the SQL statement only; ``temp_path`` (a
- # Path) keeps the real separators for filesystem work.
- temp_path_str = str(temp_path)
- if os.sep == "\\":
- temp_path_str = temp_path_str.replace("\\", "/")
- bad_chars = _UNSAFE_BACKUP_PATH_CHARS & set(temp_path_str)
- if bad_chars:
- raise ValueError(
- "Backup path contains characters not allowed in a "
- "SQLCipher ATTACH statement: "
- + ", ".join(sorted(repr(c) for c in bad_chars))
- )
+ # other unsafe chars were rejected before file creation.
+ # Use the same normalization for the reserved temporary path.
+ temp_path_str = _validate_backup_path(temp_path)
# Get the hex key for ATTACH (same key derivation as source)
hex_key = get_key_from_password(
- self.password, db_path=self.db_path
+ self.password, db_path=temp_path
).hex()
# Defensive: ensure hex_key is strictly hexadecimal
@@ -366,10 +481,10 @@ class BackupService:
safe_close(conn, "backup connection")
# Verify the backup is valid (still using temp path)
- if not self._verify_backup(temp_path):
+ passed, verified_identity = self._verify_and_identify(temp_path)
+ if not passed or verified_identity is None:
# Delete corrupted backup
- if temp_path.exists():
- temp_path.unlink()
+ self._remove_backup_files(temp_path)
return BackupResult(
success=False,
error="Backup verification failed - backup was corrupted",
@@ -382,10 +497,46 @@ class BackupService:
# Get backup size before rename
backup_size = temp_path.stat().st_size
- # Atomic rename from .tmp to final .db
- # This ensures cleanup won't see/delete partially created backups
+ # Renaming keeps both identities, so later logins today reuse
+ # this verification while the published files stay unchanged.
+ # Record it before publishing: an error after the renames would
+ # make the handler below delete the new backup. If publication
+ # fails, the entry matches no file.
+ _get_backup_verifications(self.username)[
+ self.backup_dir / backup_path.name
+ ] = (verified_identity, True)
+
+ # Publish the salt first, then the database as the completion
+ # marker. A crash between renames leaves only an orphan salt,
+ # which retention cleanup can remove after the stale-file delay.
+ # The salt rename does not depend on the salt still existing:
+ # if it has gone since the verification, the rename raises and
+ # the handler below removes the partial pair before any older
+ # backup is deleted.
+ if salt_copied:
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: The source is the fixed .salt sidecar of this call's mkstemp file in the server-owned sha256-named per-user backup directory
+ get_salt_file_path(temp_path).rename(
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: The target is the fixed .salt sidecar of the same mkstemp name without .tmp in that directory
+ get_salt_file_path(backup_path)
+ )
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: temp_path is this call's mkstemp file in the server-owned sha256-named per-user backup directory and backup_path is that name without .tmp
temp_path.rename(backup_path)
+ # Delete older backups only while the complete pair that was
+ # verified is in place under its final names.
+ if not _is_published_pair(
+ _backup_identity(backup_path), verified_identity
+ ):
+ logger.warning(
+ f"Backup {backup_path.name} changed during "
+ "publication; removing it"
+ )
+ self._remove_backup_files(backup_path)
+ return BackupResult(
+ success=False,
+ error="Backup files changed during publication",
+ )
+
logger.info(
f"Created backup for user: {backup_path.name} ({backup_size} bytes)"
)
@@ -413,15 +564,15 @@ class BackupService:
except Exception as e:
logger.exception("Backup creation failed")
# Clean up any partial backup (temp file)
- if temp_path.exists():
+ if temp_path is not None:
try:
- temp_path.unlink()
+ self._remove_backup_files(temp_path)
except OSError:
pass
# Also clean up final path in case rename partially succeeded
- if backup_path.exists():
+ if backup_path is not None:
try:
- backup_path.unlink()
+ self._remove_backup_files(backup_path)
except OSError:
pass
return BackupResult(
@@ -429,6 +580,125 @@ class BackupService:
error=str(e),
)
+ def _verify_and_identify(
+ self, backup_path: Path
+ ) -> tuple[bool, Optional[_BackupIdentity]]:
+ """Run the full verification and identify the files it covered.
+
+ A backup passes only if its database file, and its salt file or the
+ absence of one, are the same before and after the verification: a
+ file that is removed, replaced or written to during the check fails
+ it, whatever the check found. Opening a path that was removed during
+ the check makes SQLite create an empty database there, which the
+ checks accept, and a salt removed after the key was derived would
+ otherwise let the database be published without it. An empty
+ database never passes. The identity is returned only for files that
+ were the same before and after, and is None otherwise, so a result
+ is never remembered for files it did not read.
+ """
+ identity = _backup_identity(backup_path)
+ passed = self._verify_backup(backup_path)
+ after = _backup_identity(backup_path)
+ if after is None or after != identity:
+ return False, None
+ if after[0][2] == 0:
+ passed = False
+ return passed, identity
+
+ def _find_verified_backup(
+ self, backups: list[Path]
+ ) -> Optional[tuple[Path, int]]:
+ """Return one of ``backups`` that passes the full verification.
+
+ Returns that backup and its size, or None when none passes. Results
+ remembered in this process come first and cost no key derivation: a
+ pass is reused, and a failure skipped, while the backup's database
+ and salt files keep the device, inode, size and modification time
+ they had when verified. If any backup has a remembered pass, the
+ newest of those is returned and nothing is verified. Otherwise the
+ backups without a remembered result, such as after a restart or once
+ either file is replaced, removed or written to, are verified newest
+ first until one passes, and each result is remembered. A change that
+ preserves all four values is not detected. A backup that has been
+ removed counts as absent, and one whose database or salt file is
+ removed or changed during its verification does not pass, with no
+ result remembered. Must be called with the user's backup lock held.
+ """
+ results = _get_backup_verifications(self.username)
+ # Forget results for files that are not candidates any more.
+ for path in results.keys() - set(backups):
+ del results[path]
+
+ passes: list[tuple[Path, _BackupIdentity]] = []
+ unknown: list[tuple[Path, _BackupIdentity]] = []
+ for path in backups:
+ identity = _backup_identity(path)
+ remembered = results.get(path)
+ if identity is None:
+ # Removed since the glob, or its files cannot be identified:
+ # there is no backup to count.
+ results.pop(path, None)
+ elif remembered is not None and remembered[0] == identity:
+ if remembered[1]:
+ passes.append((path, identity))
+ else:
+ results.pop(path, None)
+ unknown.append((path, identity))
+
+ def modified_ns(candidate: tuple[Path, _BackupIdentity]) -> int:
+ return candidate[1][0][3]
+
+ if passes:
+ newest, newest_identity = max(passes, key=modified_ns)
+ return newest, newest_identity[0][2]
+ for candidate, scanned in sorted(
+ unknown, key=modified_ns, reverse=True
+ ):
+ passed, verified = self._verify_and_identify(candidate)
+ if verified is not None:
+ results[candidate] = (verified, passed)
+ if passed:
+ return candidate, (verified or scanned)[0][2]
+ return None
+
+ def _copy_source_salt(self, temp_path: Path) -> bool:
+ """Preserve the original salt, never generate a replacement.
+
+ Legacy databases use a fixed salt built into the key derivation and
+ need no sidecar. Opening the source still verifies that this is
+ actually a legacy database, rather than a database with a lost salt.
+
+ Returns:
+ True if a salt file was written for ``temp_path``, False for a
+ legacy database.
+ """
+ source_salt = get_salt_file_path(self.db_path)
+ if source_salt.is_symlink():
+ raise ValueError("Database salt must not be a symlink")
+ salt = get_salt_for_database(self.db_path)
+ if salt == LEGACY_PBKDF2_SALT:
+ return False
+ fd = os.open(
+ get_salt_file_path(temp_path),
+ os.O_WRONLY | os.O_CREAT | os.O_EXCL,
+ 0o600,
+ )
+ # The "wb" wrapper (io.FileIO) sets the descriptor to binary mode on
+ # Windows, so no salt byte is translated as a line ending.
+ with os.fdopen(
+ fd, "wb"
+ ) as salt_file: # Safe: non-secret salt for encrypted backup recovery
+ salt_file.write(salt)
+ salt_file.flush()
+ os.fsync(salt_file.fileno())
+ return True
+
+ @staticmethod
+ def _remove_backup_files(backup_path: Path) -> None:
+ """Remove a database and its salt without following salt symlinks."""
+ backup_path.unlink(missing_ok=True)
+ get_salt_file_path(backup_path).unlink(missing_ok=True)
+
def _verify_backup(self, backup_path: Path) -> bool:
"""Verify that a backup file is valid and readable.
@@ -438,13 +708,38 @@ class BackupService:
Returns:
True if backup is valid, False otherwise
"""
- if not backup_path.exists():
+ backup_salt = get_salt_file_path(backup_path)
+ if (
+ not backup_path.is_file()
+ or backup_path.is_symlink()
+ or backup_salt.is_symlink()
+ ):
return False
- if backup_path.stat().st_size == 0:
+ try:
+ backup_size = backup_path.stat().st_size
+ except OSError:
+ # Removed since the check above: there is no backup to verify.
+ return False
+ if backup_size == 0:
logger.warning("Backup file is empty (0 bytes)")
return False
+ # _copy_source_salt gives every new backup of a database that has its
+ # own salt a copy of it, and the application never adds a salt to a
+ # legacy database. A backup without a salt, of a database with one,
+ # is therefore incomplete (made before salts were copied, or damaged)
+ # or belongs to an earlier database: reject it before any key
+ # derivation, and before the legacy-salt warning that deriving its
+ # key would log. Only the presence of the source's salt is checked,
+ # so it can make this check stricter, never weaker.
+ if not backup_salt.exists() and has_per_database_salt(self.db_path):
+ logger.warning(
+ f"Backup {backup_path.name} has no salt file, but its "
+ "database has one"
+ )
+ return False
+
try:
# Import SQLCipher module
from ..sqlcipher_compat import (
@@ -459,9 +754,10 @@ class BackupService:
cursor = conn.cursor()
try:
- # Set encryption key using the SOURCE database's salt
- # (backup was encrypted with the source DB's per-database salt)
- set_sqlcipher_key(cursor, self.password, db_path=self.db_path)
+ # Verify using only recovery inputs next to the backup.
+ # Never fall back to the source's salt: doing so would hide
+ # an incomplete backup until the original data is lost.
+ set_sqlcipher_key(cursor, self.password, db_path=backup_path)
apply_sqlcipher_pragmas(cursor, creation_mode=False)
# Run quick integrity check
@@ -580,13 +876,31 @@ class BackupService:
tmp_file.stat().st_mtime, tz=UTC
)
if mtime < stale_tmp_cutoff:
- tmp_file.unlink()
+ self._remove_backup_files(tmp_file)
logger.info(
f"Cleaned up stale temp file: {tmp_file.name}"
)
except (OSError, FileNotFoundError):
pass
+ # Interrupted publication can leave a salt without a database.
+ # Keep recent files alone; they may belong to an active export.
+ for pattern in ("ldr_backup_*.db.salt", "ldr_backup_*.db.tmp.salt"):
+ for salt_file in self.backup_dir.glob(pattern):
+ if not is_safe_glob_result(salt_file, self.backup_dir):
+ continue
+ try:
+ if (
+ not salt_file.with_suffix("").exists()
+ and datetime.fromtimestamp(
+ salt_file.stat().st_mtime, tz=UTC
+ )
+ < stale_tmp_cutoff
+ ):
+ salt_file.unlink()
+ except OSError:
+ pass
+
# Get all backup files sorted by modification time (newest first)
def _safe_mtime(p: Path) -> float:
try:
@@ -636,8 +950,7 @@ class BackupService:
if should_delete:
try:
- # nosemgrep: semgrep.rules.path-traversal-risk, reason: Retention unlinks only fixed-pattern backup glob results checked by is_safe_glob_result under the server-owned per-user backup directory
- backup.unlink()
+ self._remove_backup_files(backup)
deleted_count += 1
logger.debug(
f"Deleted old backup {backup.name}: {reason}"
@@ -714,10 +1027,14 @@ class BackupService:
# prevent a concurrent backup from writing an old-key backup
# between the purge and the fresh backup creation.
with _get_user_lock(self.username):
+ # Forget results obtained with the old password, so a backup the
+ # purge cannot delete is checked again with the new one.
+ _get_backup_verifications(self.username).clear()
+
# Delete all existing backup files
for info in self.list_backups():
try:
- (self.backup_dir / info["path"]).unlink()
+ self._remove_backup_files(self.backup_dir / info["path"])
logger.debug(f"Purged old-key backup: {info['filename']}")
except OSError:
logger.warning(
@@ -731,7 +1048,7 @@ class BackupService:
if is_safe_glob_result(f, self.backup_dir)
]:
try:
- tmp_file.unlink()
+ self._remove_backup_files(tmp_file)
except OSError:
logger.warning(
f"Could not delete stale tmp file {tmp_file.name}"
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.py
index d546be40cf..89efd897ba 100644
--- a/src/local_deep_research/database/encrypted_db.py
+++ b/src/local_deep_research/database/encrypted_db.py
@@ -871,7 +871,7 @@ class DatabaseManager:
# Create per-database salt for new databases (v2 security improvement).
#
- # A pre-existing salt here is an ORPHAN, not live data: the
+ # A pre-existing salt here is orphaned from its primary DB: the
# ``db_path.exists()`` guard above already established that no
# database file exists, and a valid encrypted DB always has BOTH
# the ``.db`` and its ``.salt``. Such an orphan is left by a create
@@ -880,15 +880,14 @@ class DatabaseManager:
# removed only the ``.db``. Without recovery, ``create_database_salt``
# raises ``FileExistsError`` (it refuses to overwrite to protect
# live data) on every retry, so the username stays permanently
- # un-registerable. Remove the stale artifacts and create fresh —
- # safe precisely because no database depends on this salt.
+ # un-registerable. Remove the stale artifacts and create fresh;
+ # no live primary database at this path depends on the salt.
#
- # Note: backups are keyed off the *source* DB's salt (they store no
- # salt copy — see backup_service), so deleting a salt also strands
- # any backups for it. That is not reachable here: this only fires
- # when db_path is absent, and the app never removes a live .db while
- # keeping its .salt (there is no in-app restore). Only out-of-band
- # manual deletion of the .db could turn this into backup loss.
+ # New backups retain their own matching salt. Backups created
+ # before that change can still depend on this source salt, so an
+ # operator recovering an older backup must preserve it if the
+ # source .db was removed out of band. The app does not remove a
+ # live .db while retaining its salt (there is no in-app restore).
#
# SAFETY INVARIANT: this deletion is safe only while a salt-without-
# a-.db always means garbage. That holds today because create_user_
diff --git a/tests/ci/standalone/test_native_database_backups.py b/tests/ci/standalone/test_native_database_backups.py
new file mode 100644
index 0000000000..a956bdaa0c
--- /dev/null
+++ b/tests/ci/standalone/test_native_database_backups.py
@@ -0,0 +1,163 @@
+"""Recover real encrypted backups after losing the complete source directory.
+
+This also runs natively on Windows. Existing salts are seeded with binary
+file I/O so backup qualification is independent of the salt-creation fix.
+No filesystem, SQLCipher, export, verification or recovery operation is mocked.
+"""
+
+from contextlib import closing
+import os
+from pathlib import Path
+import shutil
+import tempfile
+import unittest
+from unittest.mock import patch
+from uuid import uuid4
+
+from local_deep_research.database.backup.backup_service import BackupService
+from local_deep_research.database.sqlcipher_compat import get_sqlcipher_module
+from local_deep_research.database.sqlcipher_utils import (
+ create_sqlcipher_connection,
+ get_salt_file_path,
+ get_sqlcipher_settings,
+)
+
+
+class NativeBackupTests(unittest.TestCase):
+ def test_backup_pair_survives_source_loss_and_accepts_durable_writes(self):
+ salts = (
+ b"\x00\x1a\xff\r\n\r\r\n" + bytes(range(24)),
+ b"\n" * 32,
+ b"\r\n" * 16,
+ )
+ sqlcipher = get_sqlcipher_module()
+ for index, salt in enumerate(salts):
+ with self.subTest(salt=index):
+ with tempfile.TemporaryDirectory(
+ prefix="ldr-native-backup-"
+ ) as temporary:
+ root = Path(temporary)
+ source = root / "original's café data"
+ with patch.dict(
+ os.environ,
+ {
+ "LDR_DATA_DIR": str(source),
+ "LDR_TEST_MODE": "false",
+ "LDR_DB_CONFIG_KDF_ITERATIONS": "256000",
+ },
+ ):
+ self.assertEqual(
+ get_sqlcipher_settings()["kdf_iterations"], 256000
+ )
+ service = BackupService(
+ f"native-backup-{uuid4().hex}",
+ "native-backup-test-password",
+ )
+ service.db_path.parent.mkdir(
+ parents=True, exist_ok=True
+ )
+ source_salt = get_salt_file_path(service.db_path)
+ source_salt.write_bytes(salt)
+ with closing(
+ create_sqlcipher_connection(
+ service.db_path,
+ service.password,
+ creation_mode=True,
+ )
+ ) as connection:
+ self.assertTrue(
+ connection.execute(
+ "PRAGMA cipher_version"
+ ).fetchone()[0]
+ )
+ self.assertEqual(
+ connection.execute(
+ "PRAGMA journal_mode=WAL"
+ ).fetchone()[0],
+ "wal",
+ )
+ connection.execute("PRAGMA wal_autocheckpoint=0")
+ connection.execute(
+ "CREATE TABLE canary (value TEXT NOT NULL)"
+ )
+ connection.execute(
+ "INSERT INTO canary VALUES (?)", ("WAL data",)
+ )
+ connection.commit()
+ self.assertGreater(
+ Path(str(service.db_path) + "-wal")
+ .stat()
+ .st_size,
+ 0,
+ )
+ backup = service.create_backup(force=True)
+ self.assertTrue(backup.success, backup.error)
+ self.assertEqual(source_salt.read_bytes(), salt)
+ self.assertEqual(
+ get_salt_file_path(
+ backup.backup_path
+ ).read_bytes(),
+ salt,
+ )
+
+ archive = root / "archive's café"
+ archive.mkdir()
+ recovered = archive / "recovered.db"
+ shutil.copy2(backup.backup_path, recovered)
+ shutil.copy2(
+ get_salt_file_path(backup.backup_path),
+ get_salt_file_path(recovered),
+ )
+ shutil.rmtree(source)
+ self.assertFalse(source.exists())
+ self.assertTrue(service._verify_backup(recovered))
+ self.assertNotEqual(
+ recovered.read_bytes()[:16], b"SQLite format 3\0"
+ )
+ with closing(
+ create_sqlcipher_connection(
+ recovered, service.password
+ )
+ ) as connection:
+ self.assertEqual(
+ connection.execute(
+ "PRAGMA quick_check"
+ ).fetchall(),
+ [("ok",)],
+ )
+ self.assertEqual(
+ connection.execute(
+ "SELECT value FROM canary"
+ ).fetchall(),
+ [("WAL data",)],
+ )
+ connection.execute(
+ "INSERT INTO canary VALUES (?)",
+ ("durable write",),
+ )
+ connection.commit()
+ with closing(
+ create_sqlcipher_connection(
+ recovered, service.password
+ )
+ ) as connection:
+ self.assertEqual(
+ connection.execute(
+ "SELECT COUNT(*) FROM canary"
+ ).fetchone(),
+ (2,),
+ )
+ with self.assertRaises(
+ (ValueError, sqlcipher.DatabaseError)
+ ):
+ with closing(
+ create_sqlcipher_connection(
+ recovered, "wrong-password"
+ )
+ ):
+ pass
+ self.assertFalse(source.exists())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/database/backup/test_backup_crash_recovery_ci.py b/tests/database/backup/test_backup_crash_recovery_ci.py
index d590de8a0f..147cb4d684 100644
--- a/tests/database/backup/test_backup_crash_recovery_ci.py
+++ b/tests/database/backup/test_backup_crash_recovery_ci.py
@@ -50,9 +50,11 @@ def _create_test_database(db_path: Path, password: str):
apply_cipher_defaults_before_key → set_sqlcipher_key → apply_sqlcipher_pragmas
"""
from local_deep_research.database.sqlcipher_utils import (
+ create_database_salt,
create_sqlcipher_connection,
)
+ create_database_salt(db_path)
conn = create_sqlcipher_connection(
str(db_path), password, creation_mode=True
)
@@ -212,16 +214,16 @@ class TestFullCrashRecoveryCycle:
"Backup has plaintext SQLite header — encryption failed!"
)
- # ── Step 4: Simulate crash — destroy original database ──
- db_path.unlink()
- for suffix in ["-wal", "-shm"]:
- wal_path = db_path.parent / (db_path.name + suffix)
- if wal_path.exists():
- wal_path.unlink()
+ # ── Step 4: Lose the entire source directory, including its salt ──
+ shutil.rmtree(db_dir)
assert not db_path.exists()
- # ── Step 5: Restore from backup — copy to original path ──
+ # ── Step 5: Restore using only the backup directory ──
+ db_dir.mkdir()
shutil.copy2(str(backup_result.backup_path), str(db_path))
+ shutil.copy2(
+ str(backup_result.backup_path) + ".salt", str(db_path) + ".salt"
+ )
os.chmod(db_path, 0o600)
# ── Step 6: Verify restored database works ──
@@ -488,7 +490,7 @@ class TestBackupDataIntegrity:
shutil.copy2(str(result.backup_path), str(restored_path))
# Copy salt file too (needed for key derivation)
- salt_src = Path(str(db_path) + ".salt")
+ salt_src = Path(str(result.backup_path) + ".salt")
if salt_src.exists():
shutil.copy2(str(salt_src), str(restored_path) + ".salt")
diff --git a/tests/database/backup/test_backup_salt_recovery.py b/tests/database/backup/test_backup_salt_recovery.py
new file mode 100644
index 0000000000..d8ee6aaeb6
--- /dev/null
+++ b/tests/database/backup/test_backup_salt_recovery.py
@@ -0,0 +1,754 @@
+"""Real SQLCipher recovery with no access to the original data directory."""
+
+import hashlib
+import os
+import shutil
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+from unittest.mock import MagicMock, call, patch
+
+import pytest
+
+from local_deep_research.database import sqlcipher_compat, sqlcipher_utils
+from local_deep_research.database.backup import backup_service
+from local_deep_research.database.backup.backup_service import BackupService
+from local_deep_research.database.sqlcipher_utils import (
+ create_database_salt,
+ create_sqlcipher_connection,
+ get_salt_file_path,
+ set_sqlcipher_rekey,
+)
+
+pytest.importorskip("sqlcipher3")
+
+PASSWORD = "recovery-test-password"
+NEW_PASSWORD = "recovery-test-new-password"
+
+
+def source(tmp_path, monkeypatch):
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path / "live"))
+ service = BackupService("family-member", PASSWORD, max_backups=3)
+ return service
+
+
+def count_key_derivations():
+ """Count PBKDF2 key derivations; every full verification needs one."""
+ return patch.object(
+ sqlcipher_utils,
+ "_get_key_from_password",
+ wraps=sqlcipher_utils._get_key_from_password,
+ )
+
+
+def shift_mtime(path, seconds):
+ """Move a file's modification time, which also changes its identity."""
+ status = path.stat()
+ os.utime(
+ path,
+ ns=(status.st_atime_ns, status.st_mtime_ns + seconds * 1_000_000_000),
+ )
+
+
+def create_source(service, *, legacy=False):
+ if not legacy:
+ create_database_salt(service.db_path)
+ conn = create_sqlcipher_connection(
+ service.db_path, PASSWORD, creation_mode=True
+ )
+ conn.execute("PRAGMA journal_mode=WAL")
+ conn.execute("PRAGMA wal_autocheckpoint=0")
+ conn.execute("CREATE TABLE research (id INTEGER PRIMARY KEY, report TEXT)")
+ conn.execute("INSERT INTO research VALUES (1, 'family research report')")
+ conn.commit()
+ return conn
+
+
+ "legacy", [False, True], ids=["per-user-salt", "legacy"]
+)
+def test_recovery_uses_only_archived_backup_and_password(
+ source, tmp_path, legacy
+):
+ """Export committed WAL data, destroy the source, restore and write again."""
+ conn = create_source(source, legacy=legacy)
+ try:
+ assert Path(str(source.db_path) + "-wal").stat().st_size > 0
+ result = source.create_backup()
+ assert result.success, result.error
+ finally:
+ conn.close()
+
+ archive = tmp_path / "archive"
+ shutil.copytree(source.backup_dir, archive)
+ backup = archive / result.backup_path.name
+ salt = get_salt_file_path(backup)
+ assert salt.exists() is not legacy
+ if not legacy:
+ assert (
+ salt.read_bytes() == get_salt_file_path(source.db_path).read_bytes()
+ )
+ assert salt.stat().st_mode & 0o777 == 0o600
+ assert backup.read_bytes()[:16] != b"SQLite format 3\x00"
+
+ shutil.rmtree(tmp_path / "live")
+ assert not source.db_path.parent.exists()
+ assert source._verify_backup(backup)
+
+ # Follow the documented offline restore procedure into an empty directory.
+ destination = tmp_path / "restored" / source.db_filename
+ destination.parent.mkdir()
+ shutil.copy2(backup, destination)
+ if salt.exists():
+ shutil.copy2(salt, get_salt_file_path(destination))
+ restored = create_sqlcipher_connection(destination, PASSWORD)
+ try:
+ assert restored.execute("SELECT * FROM research").fetchall() == [
+ (1, "family research report")
+ ]
+ assert restored.execute("PRAGMA quick_check").fetchone() == ("ok",)
+ restored.execute("INSERT INTO research VALUES (2, 'new report')")
+ restored.commit()
+ finally:
+ restored.close()
+ reopened = create_sqlcipher_connection(destination, PASSWORD)
+ try:
+ assert reopened.execute("SELECT COUNT(*) FROM research").fetchone() == (
+ 2,
+ )
+ finally:
+ reopened.close()
+ with pytest.raises(Exception):
+ create_sqlcipher_connection(destination, "wrong-password")
+
+
+ "damage", ["missing", "mismatched", "truncated", "symlink"]
+)
+def test_backup_verification_never_uses_source_salt(source, tmp_path, damage):
+ conn = create_source(source)
+ conn.close()
+ result = source.create_backup()
+ assert result.success, result.error
+ backup = result.backup_path
+ salt = get_salt_file_path(backup)
+ original = backup.read_bytes()
+ if damage == "missing":
+ salt.unlink()
+ elif damage == "mismatched":
+ salt.write_bytes(b"x" * 32)
+ elif damage == "truncated":
+ salt.write_bytes(b"x")
+ else:
+ external = tmp_path / "external.salt"
+ external.write_bytes(salt.read_bytes())
+ salt.unlink()
+ salt.symlink_to(external)
+ assert get_salt_file_path(source.db_path).exists()
+ assert not source._verify_backup(backup)
+ assert backup.read_bytes() == original
+
+
+def test_daily_limit_replaces_old_backup_without_its_salt(source):
+ conn = create_source(source)
+ conn.close()
+ first = source.create_backup()
+ assert first.success, first.error
+ get_salt_file_path(first.backup_path).unlink()
+ second = source.create_backup()
+ assert second.success, second.error
+ assert second.backup_path != first.backup_path
+ assert source._verify_backup(second.backup_path)
+ # A complete backup still enforces the once-per-day rule.
+ assert source.create_backup().backup_path == second.backup_path
+
+
+def test_daily_limit_reuses_a_verified_backup_without_verifying_again(
+ source, monkeypatch
+):
+ conn = create_source(source)
+ conn.close()
+ first = source.create_backup()
+ assert first.success, first.error
+ with patch.object(
+ source, "_verify_backup", wraps=source._verify_backup
+ ) as verify:
+ # Creation ran the full verification; unchanged files need no repeat.
+ assert source.create_backup().backup_path == first.backup_path
+ assert verify.call_count == 0
+ # A restarted process has no record, so it verifies the backup once.
+ monkeypatch.setattr(backup_service, "_backup_verifications", {})
+ assert source.create_backup().backup_path == first.backup_path
+ assert source.create_backup().backup_path == first.backup_path
+ verify.assert_called_once_with(first.backup_path)
+
+
[email protected]("change", ["replaced", "touched"])
[email protected]("changed", ["database", "salt"])
+def test_daily_limit_verifies_a_changed_backup_again(source, changed, change):
+ conn = create_source(source)
+ conn.close()
+ first = source.create_backup()
+ assert first.success, first.error
+ target = first.backup_path
+ if changed == "salt":
+ target = get_salt_file_path(target)
+ status = target.stat()
+ if change == "replaced":
+ # Same bytes, size and timestamps in a new file, as copying the
+ # backup back from external storage would leave it.
+ copy = target.with_name(target.name + ".copy")
+ shutil.copy2(target, copy)
+ os.replace(copy, target)
+ assert target.stat().st_ino != status.st_ino
+ else:
+ os.utime(
+ target,
+ ns=(status.st_atime_ns, status.st_mtime_ns + 1_000_000_000),
+ )
+ with patch.object(
+ source, "_verify_backup", wraps=source._verify_backup
+ ) as verify:
+ assert source.create_backup().backup_path == first.backup_path
+ assert source.create_backup().backup_path == first.backup_path
+ # Verified once after the change, then reused while unchanged again.
+ verify.assert_called_once_with(first.backup_path)
+
+
[email protected]("damage", ["salt-missing", "salt-mismatched"])
+def test_later_sign_ins_derive_no_key_beside_a_failing_backup(source, damage):
+ """A failing same-day backup kept by retention costs later sign-ins nothing.
+
+ On upgrade day, for example, an earlier backup made without its salt
+ fails, a replacement is created, and retention keeps both.
+ """
+ conn = create_source(source)
+ conn.close()
+ earlier = source.create_backup()
+ assert earlier.success, earlier.error
+ shift_mtime(earlier.backup_path, -60)
+ salt = get_salt_file_path(earlier.backup_path)
+ if damage == "salt-missing":
+ salt.unlink()
+ else:
+ salt.write_bytes(b"x" * 32)
+ replacement = source.create_backup()
+ assert replacement.success, replacement.error
+ assert replacement.backup_path != earlier.backup_path
+ assert earlier.backup_path.exists()
+ with count_key_derivations() as derive:
+ for _ in range(2):
+ later = source.create_backup()
+ assert later.backup_path == replacement.backup_path
+ assert derive.call_count == 0
+
+
+def test_unremembered_backups_are_verified_newest_first_until_one_passes(
+ source,
+):
+ conn = create_source(source)
+ conn.close()
+ oldest, middle, newest = [
+ source.create_backup(force=True) for _ in range(3)
+ ]
+ assert all(r.success for r in (oldest, middle, newest))
+ get_salt_file_path(newest.backup_path).write_bytes(b"x" * 32)
+ # New timestamps, in creation order, leave no result remembered.
+ for minutes, result in enumerate((newest, middle, oldest), start=1):
+ shift_mtime(result.backup_path, -60 * minutes)
+ with patch.object(
+ source, "_verify_backup", wraps=source._verify_backup
+ ) as verify:
+ assert source.create_backup().backup_path == middle.backup_path
+ # The oldest is never verified: the middle backup already passed.
+ assert verify.call_args_list == [
+ call(newest.backup_path),
+ call(middle.backup_path),
+ ]
+ # Both results are remembered, so the next sign-in verifies nothing.
+ assert source.create_backup().backup_path == middle.backup_path
+ # A remembered pass also comes before a newer backup that has no
+ # remembered result.
+ shift_mtime(newest.backup_path, 1)
+ assert source.create_backup().backup_path == middle.backup_path
+ assert verify.call_count == 2
+
+
[email protected]("changed", ["database", "salt"])
+def test_a_known_failing_backup_is_checked_again_only_once_changed(
+ source, changed
+):
+ conn = create_source(source)
+ conn.close()
+ first = source.create_backup()
+ assert first.success, first.error
+ salt = get_salt_file_path(first.backup_path)
+ salt.write_bytes(b"x" * 32)
+ target = first.backup_path if changed == "database" else salt
+ # No room for a replacement, so the failing backup stays the only one.
+ with (
+ patch("shutil.disk_usage", return_value=MagicMock(free=0)),
+ patch.object(
+ source, "_verify_backup", wraps=source._verify_backup
+ ) as verify,
+ count_key_derivations() as derive,
+ ):
+ for _ in range(2):
+ assert not source.create_backup().success
+ # Checked once; the unchanged failure is remembered.
+ assert (verify.call_count, derive.call_count) == (1, 1)
+ shift_mtime(target, 1)
+ assert not source.create_backup().success
+ assert (verify.call_count, derive.call_count) == (2, 2)
+
+
+def test_backup_without_salt_of_a_salted_database_derives_no_key(
+ source, loguru_caplog
+):
+ conn = create_source(source)
+ conn.close()
+ result = source.create_backup()
+ assert result.success, result.error
+ get_salt_file_path(result.backup_path).unlink()
+ with (
+ count_key_derivations() as derive,
+ loguru_caplog.at_level("WARNING"),
+ ):
+ assert not source._verify_backup(result.backup_path)
+ assert derive.call_count == 0
+ assert "has no salt file, but its database has one" in loguru_caplog.text
+ assert "legacy shared salt" not in loguru_caplog.text
+
+
+def test_legacy_backup_without_salt_still_verifies(source):
+ conn = create_source(source, legacy=True)
+ conn.close()
+ result = source.create_backup()
+ assert result.success, result.error
+ assert not get_salt_file_path(source.db_path).exists()
+ assert not get_salt_file_path(result.backup_path).exists()
+ with count_key_derivations() as derive:
+ assert source._verify_backup(result.backup_path)
+ # A database without its own salt still uses the legacy derivation.
+ assert derive.call_count == 1
+
+
+ "moment", ["before-size-check", "before-open", "while-open"]
+)
+def test_backup_removed_during_its_check_counts_as_absent(
+ source, monkeypatch, moment
+):
+ conn = create_source(source)
+ conn.close()
+ first = source.create_backup()
+ assert first.success, first.error
+ target = first.backup_path
+ # A new timestamp, so the daily check verifies the backup again.
+ shift_mtime(target, 1)
+ removed = []
+
+ def remove_once(path):
+ # As another process deleting the backup would.
+ if Path(path) == target and not removed:
+ removed.append(path)
+ BackupService._remove_backup_files(target)
+
+ if moment == "before-size-check":
+ is_file = Path.is_file
+
+ def checked_then_removed(path, *args, **kwargs):
+ found = is_file(path, *args, **kwargs)
+ remove_once(path)
+ return found
+
+ monkeypatch.setattr(Path, "is_file", checked_then_removed)
+ elif moment == "before-open":
+ # SQLite then creates an empty database at the removed path.
+ get_module = sqlcipher_compat.get_sqlcipher_module
+
+ def removed_then_opened():
+ remove_once(target)
+ return get_module()
+
+ monkeypatch.setattr(
+ sqlcipher_compat, "get_sqlcipher_module", removed_then_opened
+ )
+ else:
+ set_key = backup_service.set_sqlcipher_key
+
+ def keyed_then_removed(cursor, password, db_path=None):
+ set_key(cursor, password, db_path=db_path)
+ remove_once(db_path)
+
+ monkeypatch.setattr(
+ backup_service, "set_sqlcipher_key", keyed_then_removed
+ )
+
+ result = source.create_backup()
+ assert removed
+ assert result.success, result.error
+ assert result.backup_path != target
+ assert source._verify_backup(result.backup_path)
+
+
+def test_backup_whose_salt_is_removed_during_its_check_does_not_count(
+ source, monkeypatch
+):
+ conn = create_source(source)
+ conn.close()
+ first = source.create_backup()
+ assert first.success, first.error
+ target = first.backup_path
+ # A new timestamp, so the daily check verifies the backup again.
+ shift_mtime(target, 1)
+ set_key = backup_service.set_sqlcipher_key
+ removed = []
+
+ def keyed_then_salt_removed(cursor, password, db_path=None):
+ set_key(cursor, password, db_path=db_path)
+ # As another process deleting the salt once the key is derived:
+ # the check still passes, but the backup is no longer complete.
+ if Path(db_path) == target and not removed:
+ removed.append(db_path)
+ get_salt_file_path(target).unlink()
+
+ monkeypatch.setattr(
+ backup_service, "set_sqlcipher_key", keyed_then_salt_removed
+ )
+ result = source.create_backup()
+ assert removed
+ assert result.success, result.error
+ assert result.backup_path != target
+ assert source._verify_backup(result.backup_path)
+
+
+def test_export_removed_during_its_verification_is_never_published(
+ source, monkeypatch
+):
+ conn = create_source(source)
+ conn.close()
+ first = source.create_backup()
+ assert first.success, first.error
+ source.max_backups = 1
+ before = {p.name: p.read_bytes() for p in source.backup_dir.iterdir()}
+ get_module = sqlcipher_compat.get_sqlcipher_module
+ removed = []
+
+ def remove_finished_export():
+ # Runs before each SQLCipher open. Once the export holds data, the
+ # next open is its verification: remove it first, as another
+ # process would, so SQLite opens an empty database in its place.
+ for export in source.backup_dir.glob("ldr_backup_*.db.tmp"):
+ if export.stat().st_size and not removed:
+ removed.append(export)
+ BackupService._remove_backup_files(export)
+ return get_module()
+
+ monkeypatch.setattr(
+ sqlcipher_compat, "get_sqlcipher_module", remove_finished_export
+ )
+ result = source.create_backup(force=True)
+ assert removed
+ assert not result.success
+ # No empty backup was published, so retention kept the earlier one.
+ assert {
+ p.name: p.read_bytes() for p in source.backup_dir.iterdir()
+ } == before
+
+
+ "moment", ["during-verification", "before-publication", "between-renames"]
+)
+def test_export_whose_salt_disappears_is_never_published(
+ source, monkeypatch, moment
+):
+ conn = create_source(source)
+ conn.close()
+ first = source.create_backup()
+ assert first.success, first.error
+ source.max_backups = 1
+ before = {p.name: p.read_bytes() for p in source.backup_dir.iterdir()}
+ removed = []
+
+ def remove_salt(database):
+ # As another process deleting the new backup's salt would.
+ salt = get_salt_file_path(database)
+ if not removed and salt.exists():
+ removed.append(salt.name)
+ salt.unlink()
+
+ if moment == "during-verification":
+ set_key = backup_service.set_sqlcipher_key
+
+ def keyed_then_removed(cursor, password, db_path=None):
+ set_key(cursor, password, db_path=db_path)
+ remove_salt(Path(db_path))
+
+ monkeypatch.setattr(
+ backup_service, "set_sqlcipher_key", keyed_then_removed
+ )
+ elif moment == "before-publication":
+ verify = BackupService._verify_and_identify
+
+ def verified_then_removed(self, path):
+ outcome = verify(self, path)
+ remove_salt(path)
+ return outcome
+
+ monkeypatch.setattr(
+ BackupService, "_verify_and_identify", verified_then_removed
+ )
+ rename = Path.rename
+ renamed = []
+
+ def recorded_rename(path, target):
+ renamed.append(path.name)
+ if moment == "between-renames" and path.name.endswith(".db.tmp"):
+ # The salt is published first: remove it from its final name
+ # just before the database follows.
+ remove_salt(Path(target))
+ return rename(path, target)
+
+ monkeypatch.setattr(Path, "rename", recorded_rename)
+ result = source.create_backup(force=True)
+ assert removed
+ assert not result.success
+ # A missing salt stops publication before the database is renamed; a
+ # salt that goes after its own rename gets the database removed again.
+ database_renames = [n for n in renamed if n.endswith(".db.tmp")]
+ expected = 1 if moment == "between-renames" else 0
+ assert len(database_renames) == expected, renamed
+ # No incomplete backup is left, so retention kept the earlier pair.
+ assert {
+ p.name: p.read_bytes() for p in source.backup_dir.iterdir()
+ } == before
+ assert source._verify_backup(first.backup_path)
+
+
+def file_digests(directory):
+ """Each file's name and SHA-256 digest; a failed comparison of these
+ shows no database or salt bytes."""
+ return {
+ path.name: hashlib.sha256(path.read_bytes()).hexdigest()
+ for path in directory.iterdir()
+ }
+
+
+ "change", ["database-grows", "salt-grows", "salt-appears-beside-legacy"]
+)
+def test_export_whose_files_change_size_before_publication_is_removed(
+ source, monkeypatch, change
+):
+ """After its verification and before its publication, the new backup's
+ database grows, its salt grows, or a salt file appears beside a legacy
+ backup, which was verified without one. Publication checks that each
+ file is there with the size it had when verified, and that a backup
+ verified without a salt still has none, so the new backup is removed,
+ and retention keeps the earlier one."""
+ legacy = change == "salt-appears-beside-legacy"
+ conn = create_source(source, legacy=legacy)
+ conn.close()
+ first = source.create_backup()
+ assert first.success, first.error
+ assert get_salt_file_path(first.backup_path).exists() is not legacy
+ source.max_backups = 1
+ before = file_digests(source.backup_dir)
+ verify = BackupService._verify_and_identify
+ changed = []
+
+ def verified_then_changed(self, path):
+ outcome = verify(self, path)
+ if change == "database-grows":
+ target = path
+ elif change == "salt-grows":
+ target = get_salt_file_path(path)
+ else:
+ # Where the salt of the published backup would be.
+ target = get_salt_file_path(path.with_suffix(""))
+ with target.open("ab") as handle:
+ handle.write(b"\0")
+ changed.append(target.name)
+ return outcome
+
+ monkeypatch.setattr(
+ BackupService, "_verify_and_identify", verified_then_changed
+ )
+ result = source.create_backup(force=True)
+
+ assert changed
+ assert not result.success
+ assert result.error == "Backup files changed during publication"
+ assert file_digests(source.backup_dir) == before
+ assert source._verify_backup(first.backup_path)
+
+
+def test_password_change_forgets_passes_verified_with_the_old_password(
+ source,
+):
+ conn = create_source(source)
+ conn.close()
+ old = source.create_backup()
+ assert old.success, old.error
+ conn = create_sqlcipher_connection(source.db_path, PASSWORD)
+ try:
+ set_sqlcipher_rekey(conn, NEW_PASSWORD, db_path=source.db_path)
+ finally:
+ conn.close()
+ changed = BackupService(source.username, NEW_PASSWORD, max_backups=3)
+ # The purge deletes nothing and has no room for a new-password backup.
+ with (
+ patch.object(
+ BackupService,
+ "_remove_backup_files",
+ side_effect=OSError("in use"),
+ ),
+ patch("shutil.disk_usage", return_value=MagicMock(free=0)),
+ ):
+ refreshed = changed.purge_and_refresh()
+ assert not refreshed.success
+ assert old.backup_path.exists()
+ # The old-password backup must not stand in for today's backup.
+ replacement = changed.create_backup()
+ assert replacement.success, replacement.error
+ assert replacement.backup_path != old.backup_path
+ assert changed._verify_backup(replacement.backup_path)
+ assert not changed._verify_backup(old.backup_path)
+
+
+def test_failed_publication_keeps_prior_backup_and_removes_partial_pair(source):
+ conn = create_source(source)
+ conn.close()
+ first = source.create_backup()
+ assert first.success, first.error
+ before = {p.name: p.read_bytes() for p in source.backup_dir.iterdir()}
+ rename = Path.rename
+ renames = []
+
+ def fail_database_publish(path, target):
+ # Only record here. _create_backup_impl turns any exception, an
+ # AssertionError included, into success=False, which this test
+ # expects anyway, so an assert at this point could never fail it.
+ target = Path(target)
+ renames.append((path, target, get_salt_file_path(target).exists()))
+ if path.name.endswith(".db.tmp"):
+ raise OSError("simulated publication failure")
+ return rename(path, target)
+
+ with patch.object(Path, "rename", fail_database_publish):
+ failed = source.create_backup(force=True)
+ assert not failed.success
+ assert failed.error == "simulated publication failure"
+ # The salt was renamed first and was in place when the database rename
+ # ran; reversing the two renames fails here.
+ assert len(renames) == 2, renames
+ (salt_from, salt_to, _), (db_from, db_to, salt_published) = renames
+ assert db_from.name.endswith(".db.tmp")
+ assert db_to == db_from.with_suffix("")
+ assert (salt_from, salt_to) == (
+ get_salt_file_path(db_from),
+ get_salt_file_path(db_to),
+ )
+ assert salt_published
+ assert {
+ p.name: p.read_bytes() for p in source.backup_dir.iterdir()
+ } == before
+ assert source._verify_backup(first.backup_path)
+
+
+def test_salt_write_failure_keeps_prior_backup(source):
+ conn = create_source(source)
+ conn.close()
+ first = source.create_backup()
+ assert first.success, first.error
+ before = sorted(p.name for p in source.backup_dir.iterdir())
+ with patch(
+ "local_deep_research.database.backup.backup_service.os.fsync",
+ side_effect=OSError("disk full"),
+ ):
+ failed = source.create_backup(force=True)
+ assert not failed.success
+ assert sorted(p.name for p in source.backup_dir.iterdir()) == before
+ assert source._verify_backup(first.backup_path)
+
+
+def test_destination_collision_never_removes_existing_backup(source):
+ conn = create_source(source)
+ conn.close()
+ first = source.create_backup()
+ assert first.success, first.error
+ before = {p.name: p.read_bytes() for p in source.backup_dir.iterdir()}
+ temporary = first.backup_path.with_suffix(".db.tmp")
+ fd = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ with patch(
+ "local_deep_research.database.backup.backup_service.tempfile.mkstemp",
+ return_value=(fd, str(temporary)),
+ ):
+ result = source.create_backup(force=True)
+ assert not result.success
+ assert {
+ p.name: p.read_bytes() for p in source.backup_dir.iterdir()
+ } == before
+
+
+def test_forced_backups_are_unique_and_retention_removes_salts(source):
+ conn = create_source(source)
+ conn.close()
+ source.max_backups = 2
+ with patch(
+ "local_deep_research.database.backup.backup_service.datetime"
+ ) as clock:
+ clock.now.return_value = datetime.now(UTC)
+ clock.fromtimestamp.side_effect = datetime.fromtimestamp
+ results = [source.create_backup(force=True) for _ in range(3)]
+ assert all(r.success for r in results)
+ assert len({r.backup_path for r in results}) == 3
+ assert not results[0].backup_path.exists()
+ assert not get_salt_file_path(results[0].backup_path).exists()
+ for result in results[1:]:
+ assert source._verify_backup(result.backup_path)
+ # Random suffixes do not determine which same-second backup is newest.
+ # Both passes are remembered, so the newer one is reported unverified.
+ with patch.object(
+ source, "_verify_backup", wraps=source._verify_backup
+ ) as verify:
+ assert source.create_backup().backup_path == results[-1].backup_path
+ verify.assert_not_called()
+ # New timestamps on both leave neither with a remembered result, so the
+ # daily check verifies them newest first.
+ newest_time = datetime.now(UTC).timestamp() + 1
+ os.utime(results[1].backup_path, (newest_time - 60, newest_time - 60))
+ os.utime(results[-1].backup_path, (newest_time, newest_time))
+ assert source.create_backup().backup_path == results[-1].backup_path
+ assert len(list(source.backup_dir.iterdir())) == 4
+
+
+def test_cleanup_removes_stale_interrupted_pairs_and_orphan_salts(source):
+ stale = (datetime.now(UTC) - timedelta(hours=2)).timestamp()
+ names = [
+ "ldr_backup_20200101_000000.db.tmp",
+ "ldr_backup_20200101_000000.db.tmp.salt",
+ "ldr_backup_20200101_000001.db.salt",
+ "ldr_backup_20200101_000002.db.tmp.salt",
+ ]
+ for name in names:
+ path = source.backup_dir / name
+ path.write_bytes(b"incomplete")
+ os.utime(path, (stale, stale))
+ active_salt = source.backup_dir / "ldr_backup_20200101_000003.db.salt"
+ active_salt.write_bytes(b"recent publication")
+ source._cleanup_old_backups()
+ assert list(source.backup_dir.iterdir()) == [active_salt]
+
+
+def test_purge_removes_database_and_salt_together(source):
+ conn = create_source(source)
+ conn.close()
+ first = source.create_backup()
+ assert first.success, first.error
+ refreshed = source.purge_and_refresh()
+ assert refreshed.success, refreshed.error
+ assert not first.backup_path.exists()
+ assert not get_salt_file_path(first.backup_path).exists()
+ assert source._verify_backup(refreshed.backup_path)
diff --git a/tests/database/backup/test_backup_service.py b/tests/database/backup/test_backup_service.py
index e2db70fa86..7e9dd894da 100644
--- a/tests/database/backup/test_backup_service.py
+++ b/tests/database/backup/test_backup_service.py
@@ -4889,7 +4889,7 @@ class TestPasswordChangeBackupSecurity:
set_sqlcipher_rekey(cursor, info["new_pw"], db_path=info["db_path"])
conn.close()
- timestamp = info["backup_path"].stem.removeprefix("ldr_backup_")
+ timestamp = "_".join(info["backup_path"].stem.split("_")[2:4])
refresh_time = datetime.strptime(timestamp, "%Y%m%d_%H%M%S").replace(
tzinfo=UTC
)
@@ -4925,9 +4925,11 @@ class TestPasswordChangeBackupSecurity:
)
result = svc.purge_and_refresh()
- # Then the replacement reuses the path and only accepts the new password
+ # The replacement has a distinct path even at the same timestamp,
+ # the old backup is gone, and only the new password works.
assert result.success
- assert result.backup_path == info["backup_path"]
+ assert result.backup_path != info["backup_path"]
+ assert not info["backup_path"].exists()
assert result.backup_path.exists()
conn = info["sqlcipher"].connect(str(result.backup_path))
@@ -5886,7 +5888,8 @@ class TestDailyBackupLimit:
),
):
svc = BackupService(username="daily", password="pw")
- result = svc.create_backup(force=False)
+ with patch.object(svc, "_verify_backup", return_value=True):
+ result = svc.create_backup(force=False)
# Should succeed without creating a new file
assert result.success is True
diff --git a/tests/database/backup/test_backup_windows_attach_path.py b/tests/database/backup/test_backup_windows_attach_path.py
index e31588ed3a..2fe9e04284 100644
--- a/tests/database/backup/test_backup_windows_attach_path.py
+++ b/tests/database/backup/test_backup_windows_attach_path.py
@@ -32,15 +32,18 @@ def windows_host(monkeypatch):
monkeypatch.setattr(os, "sep", "\\")
-def test_attach_statement_accepts_a_windows_backup_path(tmp_path, windows_host):
[email protected]("path_suffix", ["", "'quoted"])
+def test_attach_statement_accepts_a_windows_backup_path(
+ tmp_path, windows_host, path_suffix
+):
db_dir = tmp_path / "encrypted_databases"
db_dir.mkdir()
db_file = db_dir / "ldr_user_win.db"
db_file.write_bytes(b"x" * 1000)
if os.name == "nt":
- backup_dir = tmp_path / "backups"
+ backup_dir = tmp_path / f"backups{path_suffix}"
else:
- backup_dir = tmp_path / "back\\ups"
+ backup_dir = tmp_path / f"back\\ups{path_suffix}"
backup_dir.mkdir()
attach_paths: list[str] = []
@@ -98,11 +101,14 @@ def test_attach_statement_accepts_a_windows_backup_path(tmp_path, windows_host):
# The literal must be the real temp path with separators normalised to
# "/", not merely backslash-free: a corrupted normalisation (an injected
# "/../", say) would pass a weaker "no backslash" check on its own.
- expected_prefix = str(backup_dir).replace("\\", "/") + "/"
- assert literal.startswith(expected_prefix), literal
- assert re.fullmatch(
- r"ldr_backup_\d{8}_\d{6}\.db\.tmp", literal[len(expected_prefix) :]
- ), literal
+ assert result.backup_path is not None
+ assert result.backup_path.parent == backup_dir
+ expected = (
+ str(result.backup_path.with_suffix(".db.tmp"))
+ .replace("\\", "/")
+ .replace("'", "''")
+ )
+ assert literal == expected
def test_attach_statement_still_rejects_a_quote_unsafe_path(
diff --git a/tests/database/test_encrypted_db_manager_contracts.py b/tests/database/test_encrypted_db_manager_contracts.py
index 7ee36d63a1..817d81515e 100644
--- a/tests/database/test_encrypted_db_manager_contracts.py
+++ b/tests/database/test_encrypted_db_manager_contracts.py
@@ -506,16 +506,8 @@ def test_data_dir_override_does_not_redirect_the_backup_service(tmp_path):
# ===========================================================================
-def test_verify_backup_keys_off_the_source_database_salt(tmp_path):
- """``_verify_backup`` derives its key with the SOURCE db's ``.salt``.
-
- The backup file stores no salt of its own, so a backup is decryptable only
- while the source ``.salt`` still exists. ``create_user_database``'s
- orphan-recovery branch deletes a ``.salt`` when no ``.db`` sits beside it
- (via ``_remove_partial_user_db_files``), which strands every backup taken
- from that database -- permanently, since SQLCipher keys are
- unrecoverable.
- """
+def test_verify_backup_keys_off_its_own_salt(tmp_path):
+ """Verification must not conceal a backup's missing recovery inputs."""
import local_deep_research.database.backup.backup_service as bs
db_dir = tmp_path / "encrypted_databases"
@@ -567,10 +559,8 @@ def test_verify_backup_keys_off_the_source_database_salt(tmp_path):
mod.return_value.connect.return_value = _Conn()
assert service._verify_backup(backup_file) is True
- assert captured["db_path"] == service.db_path
- assert captured["db_path"] != backup_file
- # The salt sidecar the verification depends on belongs to the SOURCE.
- assert Path(captured["db_path"]).parent == db_dir
+ assert captured["db_path"] == backup_file
+ assert captured["db_path"] != service.db_path
def test_backup_service_exposes_no_restore_path():
diff --git a/tests/security/test_db_adjacent_backup_posture.py b/tests/security/test_db_adjacent_backup_posture.py
index 57dc96fe6e..4f4e6895c8 100644
--- a/tests/security/test_db_adjacent_backup_posture.py
+++ b/tests/security/test_db_adjacent_backup_posture.py
@@ -1,49 +1,14 @@
-"""Backup artifact permission posture and salt-stranding (round-9, C2+C5).
-
-C2 attack class: sensitive-file permission window during atomic-replace
-writes. ``BackupService._create_backup_impl`` exports into a ``.tmp``
-sibling (``backup_service.py:245-347``) that is chmod'd 0600 only AFTER
-export+verify (line 340) and then atomically renamed. Between ATTACH and
-chmod, the ``.tmp`` carries umask-default permissions (0644 under the
-realistic umasks probed here) -- a window in which a LOCAL same-host
-reader can observe the file. These tests pin, with a real SQLCipher
-engine, that the window is ciphertext-only and bounded:
-
-* every mid-flight ``.tmp`` sample is group/world read-only at worst
- (never writable) under realistic umasks 022/002;
-* no mid-flight sample ever carries the plaintext SQLite magic header --
- the content observable in the window is SQLCipher ciphertext under the
- same derived key as the final artifact (a metadata window: existence,
- size and mode leak; content does not);
-* the FINAL artifact is exactly 0600, the per-user backups directory is
- exactly 0700 (enforced by ``get_user_backup_directory``, paths.py:214-
- 221), and no ``.tmp`` survives the operation.
-
-This is a HOLD-with-documentation classification: ciphertext-only content
-plus local-reader tier. The exposure would only escalate if plaintext
-ever appeared in the ``.tmp`` -- pinned against here by the header check.
-
-C5 attack class: key-material stranding (availability, not disclosure).
-Backups store no salt of their own; verification explicitly re-derives
-the key via the SOURCE database's ``.salt`` (``backup_service.py:408-
-410``, ``set_sqlcipher_key(..., db_path=self.db_path)``). Deleting the
-source ``.salt`` strands every backup. The pinned property is that
-stranding fails CLEANLY: verification returns False (never a false
-success), the backup file is left byte-identical, and no partial
-artifacts appear. (A direct reopen of the backup file -- not going
-through ``_verify_backup`` -- fails the same way regardless of the
-source salt: the backup has no ``.salt`` file next to it, so key
-derivation always falls back to the legacy shared salt, which
-SQLCipher reports as "file is not a database".)
-
-Real engines throughout; whole module ``serial`` (mutates the
-process-global umask) and ``nonroot`` (permission-bit assertions no-op
-under root), same conventions as
-``tests/security/test_db_connection_umask_perms.py``.
+"""Real SQLCipher backup permissions and recovery-input independence.
+
+Temporary and completed database files use owner-only permissions. Salt
+sidecars travel with backups, so removing the original salt cannot strand
+an independently verified backup. This module is serial/nonroot because
+its permission probes temporarily change the process-global umask.
"""
import hashlib
import os
+import shutil
import stat
import threading
import time
@@ -219,64 +184,50 @@ class TestBackupTmpPermissionWindow:
class TestBackupSaltStranding:
- """C5: deleting the source ``.salt`` strands backups -- cleanly."""
+ """Deleting the source salt must not strand a completed backup."""
- def test_missing_source_salt_fails_verification_cleanly(self, hunt_env):
- """With a valid backup present, deleting the source ``.salt``
- makes verification fail (no false success), leaves the backup
- byte-identical, creates no partial artifacts, and reopening the
- stranded backup raises instead of silently succeeding."""
+ def test_missing_source_salt_does_not_strand_backup(self, hunt_env):
+ """Verify and reopen a real backup after losing the source salt."""
from local_deep_research.database.backup.backup_service import (
BackupService,
)
from local_deep_research.database.sqlcipher_utils import (
create_sqlcipher_connection,
+ get_salt_file_path,
)
username = "c5strand"
- password = "C5Strand-Pw-1!" # noqa: S105
+ password = "C5Strand-Pw-1!"
db_path = _create_source_db(username, password)
- salt_path = db_path.with_name(db_path.name + ".salt")
- assert salt_path.exists(), "fixture: source DB must be salted (v2)"
-
+ salt_path = get_salt_file_path(db_path)
service = BackupService(username=username, password=password)
result = service.create_backup(force=True)
- assert result.success, f"backup failed: {result.error}"
+ assert result.success, result.error
backup_path = result.backup_path
assert backup_path is not None
-
- # Positive control: the backup verifies while the salt exists.
- assert service._verify_backup(backup_path) is True
-
+ assert (
+ get_salt_file_path(backup_path).read_bytes()
+ == salt_path.read_bytes()
+ )
before_digest = _digest(backup_path)
artifacts_before = sorted(p.name for p in service.backup_dir.iterdir())
salt_path.unlink()
-
- # Stranded verification fails -- never a false success.
- assert service._verify_backup(backup_path) is False, (
- "verification succeeded after the source salt was deleted -- "
- "false success on a stranded backup"
- )
-
- # Clean failure: backup untouched, no partial artifacts.
- assert backup_path.exists()
- assert _digest(backup_path) == before_digest, (
- "failed verification mutated the backup file"
+ assert service._verify_backup(backup_path)
+ recovered = hunt_env / "recovered.db"
+ shutil.copy2(backup_path, recovered)
+ shutil.copy2(
+ get_salt_file_path(backup_path), get_salt_file_path(recovered)
)
+ conn = create_sqlcipher_connection(recovered, password)
+ try:
+ assert conn.execute("SELECT COUNT(*) FROM blob").fetchone() == (
+ _SOURCE_ROWS,
+ )
+ finally:
+ conn.close()
+ assert _digest(backup_path) == before_digest
assert (
sorted(p.name for p in service.backup_dir.iterdir())
== artifacts_before
- ), "failed verification left partial artifacts"
-
- # Reopening the stranded backup fails loudly -- but this is
- # independent of the source salt being deleted: create_sqlcipher_
- # connection derives the salt from backup_path itself, and the
- # backup never had a .salt file next to it, so it always falls
- # back to the legacy shared salt, deriving a wrong key. SQLCipher
- # reports that as a database-format error rather than a silent
- # success. (The assertion that actually depends on the deleted
- # source salt is the `_verify_backup(...) is False` check above,
- # which explicitly re-derives the key via self.db_path.)
- with pytest.raises(Exception, match="file is not a database"):
- create_sqlcipher_connection(str(backup_path), password)
+ )