fix: 加固备份引擎,修复多次备份导致备份数据损坏/丢失的缺陷

- 复制后 SHA-256 回读校验,失败保留旧文件并报错
- 写入后 fsync + FlushFileBuffers,成功才提示可安全弹出
- 预检拦截脏卷(FAT32 走 fsutil dirty query)、目标在源内、空间不足、FAT32 4GiB 上限
- 清理阶段要求扫描完整且无失败,否则一个文件都不删
- 默认把多余条目移入 .udbak-quarantine 隔离区(保留 7 天),彻底删除需显式勾选
- 路径比较改为 Windows 大小写无关,修正仅大小写不同的文件名
- 临时文件改到 .udbak-tmp/<随机>/,不再用 <名>~bak 覆盖真实文件
- 扫描/清理/删除全程长路径支持
- 新增 legacy/usb_backup_v1.py 对照、tests 复现脚本与 18 项回归测试、ANALYSIS.md 取证报告
This commit is contained in:
admin committed 2026-10-29 14:14:46 +08:00
1 parent 3909f100d0
commit 9d8ce0c23e
6 files changed
+2225 -430

No files matched your search

+224
View File
@@ -0,0 +1,224 @@
# -*- coding: utf-8 -*-
"""复现 legacy/usb_backup_v1.py 中会把"备份数据打坏/打丢"的确定性缺陷。
这些缺陷与具体文件系统无关(NTFS 上即可稳定复现),在 FAT32 U 盘上危害更大:
FAT32 目录条目是"创建顺序",遍历顺序不固定,会让 ~bak 临时名冲突更容易命中;
FAT32 无日志,一次掉线/拔盘就会进入"脏卷",后续每次备份都在损坏的 FAT 上继续写。
运行: python tests/repro_v1_defects.py
退出码 0 = 全部缺陷按预期复现(诊断成立)。
"""
import os
import shutil
import sys
import tempfile
import time
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
sys.path.insert(0, os.path.join(ROOT, "legacy"))
import usb_backup_v1 as v1 # noqa: E402
RESULTS = []
def check(name, reproduced, detail):
RESULTS.append((name, reproduced, detail))
print((" [已复现] " if reproduced else " [未复现] ") + name)
print(" " + detail)
def fresh(prefix):
return tempfile.mkdtemp(prefix=prefix)
def write(path, data, mtime=None):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "wb") as f:
f.write(data)
if mtime is not None:
os.utime(path, (mtime, mtime))
def run_full(src, dst):
eng = v1.BackupEngine(src, dst)
return eng.full_backup()
# --------------------------------------------------------------------------
# 1. 大小写不一致 → 清理阶段把源里仍在的文件从备份中删掉
# --------------------------------------------------------------------------
def defect_case_mismatch():
base = fresh("v1-case-")
src = os.path.join(base, "src")
dst = os.path.join(base, "dst")
write(os.path.join(src, "Spec.TXT"), b"important payload " * 100)
run_full(src, dst)
os.rename(os.path.join(src, "Spec.TXT"), os.path.join(src, "spec.txt"))
ok, stats = run_full(src, dst)
left = os.listdir(dst)
check(
"① 大小写不一致 → 备份文件被误删",
left == [],
"源中仍有 spec.txt(内容 1800 字节),全量备份后目标目录 = {},deleted={}".format(
left, stats.get("deleted")
),
)
shutil.rmtree(base, ignore_errors=True)
# --------------------------------------------------------------------------
# 2. 临时文件 <目标名>~bak 会覆盖源中同名真实文件(与遍历顺序相关)
# --------------------------------------------------------------------------
def defect_tmp_name_collision():
base = fresh("v1-tmpname-")
src = os.path.join(base, "src")
dst = os.path.join(base, "dst")
t = 1700000000
write(os.path.join(src, "X"), b"A" * 4096, t)
write(os.path.join(src, "X~bak"), b"B" * 4096, t) # 用户真实的文件
# FAT32 的目录项是创建顺序,~bak 文件完全可能先被遍历到;此处按该顺序注入
real_scan = v1.BackupEngine._scan
def fat_order_scan(self):
files = [os.path.join(self.source, n) for n in ("X~bak", "X")]
return files
def peek(path):
if not os.path.exists(path):
return "<备份中已丢失>"
return repr(open(path, "rb").read()[:1])
v1.BackupEngine._scan = fat_order_scan
try:
run_full(src, dst)
first = peek(os.path.join(dst, "X~bak"))
ok, stats2 = run_full(src, dst) # 再跑一次
second = peek(os.path.join(dst, "X~bak"))
finally:
v1.BackupEngine._scan = real_scan
check(
"② 临时名 <名>~bak 吞掉同名真实文件(本次备份中丢失)",
first == "<备份中已丢失>",
"源 X~bak 内容应为 b'B';第 1 次备份后 = {},第 2 次备份后 = {}(copied={} skipped={})".format(
first, second, stats2.get("copied"), stats2.get("skipped")
),
)
shutil.rmtree(base, ignore_errors=True)
# --------------------------------------------------------------------------
# 3. 扫描不完整(U 盘瞬时掉线/权限/杀软占用)→ 清理阶段删掉备份里的整棵子树
# --------------------------------------------------------------------------
def defect_scan_error_deletes_backup():
base = fresh("v1-scan-")
src = os.path.join(base, "src")
dst = os.path.join(base, "dst")
write(os.path.join(src, "keep.txt"), b"keep")
write(os.path.join(src, "photos", "a.jpg"), b"a" * 1024)
write(os.path.join(src, "photos", "b.jpg"), b"b" * 1024)
run_full(src, dst)
before = sorted(os.listdir(os.path.join(dst, "photos")))
real_scan = v1.BackupEngine._scan
def partial_scan(self): # 模拟 os.walk 在 photos/ 上失败(onerror 只打了一行警告)
return [os.path.join(self.source, "keep.txt")]
v1.BackupEngine._scan = partial_scan
try:
ok, stats = run_full(src, dst)
finally:
v1.BackupEngine._scan = real_scan
after = sorted(os.listdir(os.path.join(dst, "photos"))) if os.path.isdir(os.path.join(dst, "photos")) else []
check(
"③ 源目录瞬时读不到 → 备份里的文件被删除",
before == ["a.jpg", "b.jpg"] and after == [],
"源 photos/ 仍有 2 个文件;备份里 photos/ 由 {} 变成 {}(deleted={})".format(
before, after, stats.get("deleted")
),
)
shutil.rmtree(base, ignore_errors=True)
# --------------------------------------------------------------------------
# 4. 备份目标位于源内部:无任何保护,每次都多套一层目录(指数级嵌套)
# --------------------------------------------------------------------------
def defect_dest_inside_source():
base = fresh("v1-nest-")
src = os.path.join(base, "src")
dst = os.path.join(src, "backup")
write(os.path.join(src, "data.bin"), b"x" * 2048)
depths = []
for _ in range(3):
run_full(src, dst)
depth = 0
cur = dst
while os.path.isdir(os.path.join(cur, "backup")):
depth += 1
cur = os.path.join(cur, "backup")
depths.append(depth)
check(
"④ 目标在源内部 → 自我嵌套(backup/backup/backup…)",
depths == [0, 1, 2],
"连续 3 次全量备份后 backup 下嵌套层数 = {}".format(depths),
)
shutil.rmtree(base, ignore_errors=True)
# --------------------------------------------------------------------------
# 5. 只比 大小+mtime(±2s):内容变了但大小和 mtime 相同 → 永远跳过,备份是旧数据
# --------------------------------------------------------------------------
def defect_stale_content_skipped():
base = fresh("v1-stale-")
src = os.path.join(base, "src")
dst = os.path.join(base, "dst")
t = 1700000000
f = os.path.join(src, "db.bin")
write(f, b"V1" + b"\x00" * 1022, t)
run_full(src, dst)
# 源文件内容变了(同样 1024 字节),mtime 被应用层改写回原值(拷贝/同步工具常见)
write(f, b"V2" + b"\x00" * 1022, t)
ok, stats = run_full(src, dst)
got = open(os.path.join(dst, "db.bin"), "rb").read(2)
check(
"⑤ 大小+mtime 相同但内容不同 → 静默跳过,备份内容过期",
got == b"V1",
"源文件已变为 V2,备份内容仍是 {!r}(copied={} skipped={},README 宣称的 SHA-256 比对未生效)".format(
got, stats.get("copied"), stats.get("skipped")
),
)
shutil.rmtree(base, ignore_errors=True)
def main():
if os.name != "nt":
print("仅支持 Windows")
return 2
print("legacy/usb_backup_v1.py 缺陷复现")
print("=" * 78)
defect_case_mismatch()
defect_tmp_name_collision()
defect_scan_error_deletes_backup()
defect_dest_inside_source()
defect_stale_content_skipped()
print("=" * 78)
bad = [n for n, r, _ in RESULTS if not r]
print("复现成功 {}/{}".format(len(RESULTS) - len(bad), len(RESULTS)))
if bad:
print("未复现: " + ", ".join(bad))
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+288
View File
@@ -0,0 +1,288 @@
# -*- coding: utf-8 -*-
"""usb_backup.py(加固版 v2)备份引擎回归测试。
运行: python -m unittest discover -s tests -v
"""
import os
import shutil
import stat
import sys
import tempfile
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
sys.path.insert(0, ROOT)
import usb_backup as ub # noqa: E402
def write(path, data=b"", mtime=None):
os.makedirs(ub._long(os.path.dirname(path)), exist_ok=True)
with open(ub._long(path), "wb") as f:
f.write(data)
if mtime is not None:
os.utime(ub._long(path), (mtime, mtime))
def read(path):
with open(ub._long(path), "rb") as f:
return f.read()
class EngineTestBase(unittest.TestCase):
def setUp(self):
self.base = tempfile.mkdtemp(prefix="v2test-")
self.src = os.path.join(self.base, "src")
self.dst = os.path.join(self.base, "dst")
os.makedirs(self.src)
os.makedirs(self.dst)
def tearDown(self):
shutil.rmtree(self.base, ignore_errors=True)
def engine(self, **kw):
kw.setdefault("log_callback", lambda m: None)
return ub.BackupEngine(self.src, self.dst, **kw)
def run_engine(self, **kw):
return self.engine(**kw).run()
def tree(self, root):
out = {}
for dp, _dn, fns in os.walk(root):
for fn in fns:
p = os.path.join(dp, fn)
out[os.path.relpath(p, root)] = read(p)
return out
class TestBasic(EngineTestBase):
def test_copies_tree_files_dirs_unicode_empty(self):
write(os.path.join(self.src, "a.txt"), b"alpha")
write(os.path.join(self.src, "sub", "b.bin"), b"B" * 1000)
write(os.path.join(self.src, "中文目录", "规格书.doc"), b"doc")
write(os.path.join(self.src, "empty.txt"), b"")
os.makedirs(os.path.join(self.src, "空目录"))
ok, stats = self.run_engine()
self.assertTrue(ok, stats)
self.assertEqual(self.tree(self.dst), self.tree(self.src))
self.assertTrue(os.path.isdir(os.path.join(self.dst, "空目录")))
self.assertEqual(stats["copied"], 4)
self.assertEqual(stats["failed"], 0)
def test_second_run_skips_everything(self):
write(os.path.join(self.src, "a.txt"), b"alpha")
write(os.path.join(self.src, "sub", "b.bin"), b"B" * 10000)
self.run_engine()
ok, stats = self.run_engine()
self.assertTrue(ok)
self.assertEqual(stats["copied"], 0)
self.assertEqual(stats["skipped"], 2)
def test_no_temp_leftovers(self):
write(os.path.join(self.src, "a.txt"), b"alpha")
self.run_engine()
tmp_root = os.path.join(self.dst, ub.TMP_DIR)
leftovers = []
for dp, _dn, fns in os.walk(tmp_root):
leftovers += fns
self.assertEqual(leftovers, [])
def test_mtime_preserved(self):
t = 1600000000
write(os.path.join(self.src, "a.txt"), b"x", t)
self.run_engine()
self.assertAlmostEqual(os.stat(os.path.join(self.dst, "a.txt")).st_mtime, t, delta=2)
def test_missing_dest_is_created(self):
shutil.rmtree(self.dst)
write(os.path.join(self.src, "a.txt"), b"alpha")
ok, _stats = self.run_engine()
self.assertTrue(ok)
self.assertEqual(read(os.path.join(self.dst, "a.txt")), b"alpha")
def test_five_runs_are_stable(self):
for i in range(30):
write(os.path.join(self.src, "d%d" % (i % 5), "f%02d.bin" % i),
bytes([i]) * (100 + i))
self.run_engine()
baseline = self.tree(self.dst)
for _ in range(4):
ok, stats = self.run_engine()
self.assertTrue(ok)
self.assertEqual(stats["copied"], 0)
self.assertEqual(stats["quarantined"], 0)
self.assertEqual(self.tree(self.dst), baseline)
class TestSafety(EngineTestBase):
def test_case_only_change_keeps_file(self):
write(os.path.join(self.src, "Spec.TXT"), b"payload" * 100)
self.run_engine()
os.rename(os.path.join(self.src, "Spec.TXT"), os.path.join(self.src, "spec.txt"))
ok, stats = self.run_engine()
self.assertTrue(ok)
self.assertEqual(stats["quarantined"], 0)
self.assertEqual(stats["deleted"], 0)
self.assertEqual(sorted(os.listdir(self.dst)), ["spec.txt"])
def test_scan_incomplete_never_deletes(self):
write(os.path.join(self.src, "keep.txt"), b"keep")
write(os.path.join(self.src, "photos", "a.jpg"), b"a")
self.run_engine()
eng = self.engine()
real_scan = eng._scan
def partial():
files, dirs = real_scan()
eng.scan_complete = False # 模拟某个目录读不到
return [f for f in files if f[1] == "keep.txt"], dirs
eng._scan = partial
ok, stats = eng.run()
self.assertTrue(ok)
self.assertEqual(stats["quarantined"], 0)
self.assertTrue(os.path.isfile(os.path.join(self.dst, "photos", "a.jpg")))
def test_copy_failure_never_deletes(self):
write(os.path.join(self.src, "keep.txt"), b"keep")
write(os.path.join(self.src, "gone.txt"), b"gone")
self.run_engine()
os.remove(os.path.join(self.src, "gone.txt"))
eng = self.engine()
real_scan = eng._scan
def scan_with_ghost():
files, dirs = real_scan()
files.append((os.path.join(self.src, "ghost.bin"), "ghost.bin", 1, 0))
return files, dirs
eng._scan = scan_with_ghost
ok, stats = eng.run()
self.assertFalse(ok) # 有失败项
self.assertEqual(stats["quarantined"], 0) # 但不删任何东西
self.assertTrue(os.path.isfile(os.path.join(self.dst, "gone.txt")))
def test_dest_inside_source_rejected(self):
inner = os.path.join(self.src, "backup")
os.makedirs(inner)
eng = ub.BackupEngine(self.src, inner, log_callback=lambda m: None)
with self.assertRaises(ub.BackupError):
eng.run()
def test_source_inside_dest_rejected(self):
eng = ub.BackupEngine(os.path.join(self.dst, "sub"), self.dst,
log_callback=lambda m: None)
os.makedirs(os.path.join(self.dst, "sub"))
with self.assertRaises(ub.BackupError):
eng.run()
class TestCleanup(EngineTestBase):
def test_removed_source_file_is_quarantined_not_destroyed(self):
write(os.path.join(self.src, "a.txt"), b"alpha")
write(os.path.join(self.src, "old", "gone.txt"), b"gone-content")
self.run_engine()
os.remove(os.path.join(self.src, "old", "gone.txt"))
ok, stats = self.run_engine()
self.assertTrue(ok)
self.assertFalse(os.path.exists(os.path.join(self.dst, "old", "gone.txt")))
qroot = os.path.join(self.dst, ub.QUARANTINE_DIR)
found = []
for dp, _dn, fns in os.walk(qroot):
for fn in fns:
found.append(os.path.join(dp, fn))
self.assertEqual(len(found), 1)
self.assertTrue(found[0].endswith(os.path.join("old", "gone.txt")))
self.assertEqual(read(found[0]), b"gone-content")
def test_hard_delete_option(self):
write(os.path.join(self.src, "a.txt"), b"alpha")
write(os.path.join(self.src, "extra.txt"), b"extra")
self.run_engine()
os.remove(os.path.join(self.src, "extra.txt"))
ok, stats = self.run_engine(hard_delete=True)
self.assertTrue(ok)
self.assertEqual(stats["deleted"], 1)
self.assertFalse(os.path.exists(os.path.join(self.dst, "extra.txt")))
self.assertFalse(os.path.isdir(os.path.join(self.dst, ub.QUARANTINE_DIR)))
def test_extra_directory_moved_whole(self):
write(os.path.join(self.src, "a.txt"), b"alpha")
write(os.path.join(self.dst, "leftover", "x.txt"), b"x")
write(os.path.join(self.dst, "leftover", "sub", "y.txt"), b"y")
ok, stats = self.run_engine()
self.assertTrue(ok)
self.assertFalse(os.path.isdir(os.path.join(self.dst, "leftover")))
qroot = os.path.join(self.dst, ub.QUARANTINE_DIR)
names = []
for dp, _dn, fns in os.walk(qroot):
names += fns
self.assertEqual(sorted(names), ["x.txt", "y.txt"])
def test_type_conflict_file_over_directory(self):
write(os.path.join(self.src, "node"), b"i am a file")
write(os.path.join(self.dst, "node", "child.txt"), b"old")
ok, stats = self.run_engine()
self.assertTrue(ok)
self.assertEqual(read(os.path.join(self.dst, "node")), b"i am a file")
class TestIntegrity(EngineTestBase):
def test_stale_content_detected_with_deep_verify(self):
t = 1600000000
f = os.path.join(self.src, "db.bin")
write(f, b"V1" + b"\x00" * 1022, t)
self.run_engine()
write(f, b"V2" + b"\x00" * 1022, t) # 内容变了,大小/mtime 不变
ok, stats = self.run_engine(deep_verify=True)
self.assertTrue(ok)
self.assertEqual(read(os.path.join(self.dst, "db.bin")), b"V2" + b"\x00" * 1022)
def test_corrupt_write_detected_and_old_file_kept(self):
write(os.path.join(self.src, "a.txt"), b"good-content")
self.run_engine()
write(os.path.join(self.src, "a.txt"), b"new-content!!")
real_hash = ub._hash_file
state = {"armed": True}
def flaky_hash(path, buf=ub.HASH_BUF):
# 只对临时文件"返回"错误的哈希,模拟落盘内容被破坏
if state["armed"] and ub.TMP_DIR in str(path):
state["armed"] = False
return "0" * 64
return real_hash(path, buf)
ub._hash_file = flaky_hash
try:
ok, stats = self.run_engine()
finally:
ub._hash_file = real_hash
self.assertFalse(ok)
self.assertEqual(stats["failed"], 1)
self.assertEqual(read(os.path.join(self.dst, "a.txt")), b"good-content")
class TestLongPath(EngineTestBase):
def test_copies_path_over_260(self):
deep = os.path.join(self.src, *(["d" * 40] * 7))
target = os.path.join(deep, "deep.bin")
self.assertGreater(len(target), 280)
write(target, b"deep-data")
ok, stats = self.run_engine()
self.assertTrue(ok, stats)
self.assertEqual(stats["copied"], 1)
self.assertEqual(read(os.path.join(self.dst, *(["d" * 40] * 7), "deep.bin")),
b"deep-data")
if __name__ == "__main__":
unittest.main(verbosity=2)