Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/backup-verification.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ can download a consistent snapshot. The verifier below works **offline** and
- Row counts for those tables
- SHA-256 fingerprint; optionally match a digest supplied through a separately
trusted channel
- Whether the file changed during verification (size and modification time)
- Whether the file changed during verification (size, modification time, and a
second SHA-256 after SQLite reads). The second digest detects same-size
replacements even when modification time is restored; verification still
requires an offline, immutable snapshot and cannot eliminate all file races.

A missing required table, broken reference, failed integrity check, unexpected
version, or mismatched digest returns a nonzero process exit code.
Expand Down
4 changes: 4 additions & 0 deletions scripts/verify_sqlite_backup.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,10 @@ def verify(
after = path.stat()
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
raise ValueError("Backup changed during verification; use an offline snapshot.")
# Metadata alone cannot detect same-size replacements or restored timestamps.
# Rehash after SQLite reads so the reported digest describes verified bytes.
if not hmac.compare_digest(digest, _file_sha256(path)):
raise ValueError("Backup content changed during verification; use an offline snapshot.")

return {
"path": str(path.resolve()),
Expand Down
19 changes: 19 additions & 0 deletions tests/test_backup_verify.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,22 @@ def test_backup_verification_rejects_non_sqlite_data(tmp_path):

with pytest.raises(sqlite3.DatabaseError):
verify(path)


def test_backup_verification_detects_content_change_without_metadata_change(
tmp_path, monkeypatch
):
"""A replaced same-size snapshot can retain size and mtime."""
path = tmp_path / "backup.sqlite3"
_backup(path)
original_hash = hashlib.sha256(path.read_bytes()).hexdigest()
calls = []

def changing_digest(_path):
calls.append(_path)
return original_hash if len(calls) == 1 else "f" * 64

monkeypatch.setattr("scripts.verify_sqlite_backup._file_sha256", changing_digest)
with pytest.raises(ValueError, match="content changed during verification"):
verify(path, expected_sha256=original_hash)
assert calls == [path, path]
Loading