diff --git a/docs/backup-verification.md b/docs/backup-verification.md index 587a1f0..559b990 100644 --- a/docs/backup-verification.md +++ b/docs/backup-verification.md @@ -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. diff --git a/scripts/verify_sqlite_backup.py b/scripts/verify_sqlite_backup.py index 0236606..09b1d82 100644 --- a/scripts/verify_sqlite_backup.py +++ b/scripts/verify_sqlite_backup.py @@ -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()), diff --git a/tests/test_backup_verify.py b/tests/test_backup_verify.py index c1166bc..3293df3 100644 --- a/tests/test_backup_verify.py +++ b/tests/test_backup_verify.py @@ -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]