| 1 | import argparse |
| 2 | import hashlib |
| 3 | import io |
| 4 | import json |
| 5 | from pathlib import Path |
| 6 | import struct |
| 7 | import unittest |
| 8 | import zipfile |
| 9 | import zlib |
| 10 | |
| 11 | from generate import ROOT, SOURCES, corpus |
| 12 | |
| 13 | |
| 14 | MANIFEST = json.loads((ROOT / "expectations.json").read_text(encoding="utf-8")) |
| 15 | ENTRIES = {entry["name"]: entry for entry in MANIFEST["source_entries"]} |
| 16 | SAMPLES = {sample["file"]: sample for sample in MANIFEST["samples"]} |
| 17 | |
| 18 | |
| 19 | def digest(data): |
| 20 | return hashlib.sha256(data).hexdigest() |
| 21 | |
| 22 | |
| 23 | def reference_restore_local_signature(data): |
| 24 | with zipfile.ZipFile(io.BytesIO(data)) as archive: |
| 25 | offset = archive.getinfo("한글/자료.txt").header_offset |
| 26 | if data[offset:offset + 4] != b"BAD!": |
| 27 | raise ValueError("표본의 로컬 서명 손상 위치 불일치") |
| 28 | return data[:offset] + b"PK\x03\x04" + data[offset + 4:] |
| 29 | |
| 30 | |
| 31 | def local_payload(data, entry): |
| 32 | offset = entry["local_offset"] |
| 33 | if data[offset:offset + 4] != b"PK\x03\x04" or len(data) < offset + 30: |
| 34 | raise ValueError("완전한 로컬 헤더 없음") |
| 35 | header = struct.unpack_from("<4s5H3I2H", data, offset) |
| 36 | method, crc, packed, size, name_size, extra_size = ( |
| 37 | header[3], header[6], header[7], header[8], header[9], header[10] |
| 38 | ) |
| 39 | start = offset + 30 + name_size + extra_size |
| 40 | end = start + packed |
| 41 | if end > len(data): |
| 42 | raise ValueError("본문 절단") |
| 43 | payload = data[start:end] |
| 44 | if method == zipfile.ZIP_DEFLATED: |
| 45 | decoder = zlib.decompressobj(-15) |
| 46 | payload = decoder.decompress(payload) + decoder.flush() |
| 47 | if not decoder.eof or decoder.unused_data or decoder.unconsumed_tail: |
| 48 | raise ValueError("DEFLATE 경계 불일치") |
| 49 | elif method != zipfile.ZIP_STORED: |
| 50 | raise ValueError("표본에 없는 압축 방법") |
| 51 | if len(payload) != size or zlib.crc32(payload) != crc: |
| 52 | raise ValueError("본문 크기 또는 CRC 불일치") |
| 53 | return payload |
| 54 | |
| 55 | |
| 56 | def verify_recovered(sample_name, recovered): |
| 57 | sample = SAMPLES[sample_name] |
| 58 | if not sample["expected"]["publish_archive"]: |
| 59 | raise ValueError("이 표본은 복구본을 게시하면 안 됨") |
| 60 | source = (ROOT / sample_name).read_bytes() |
| 61 | if digest(source) != sample["sha256"]: |
| 62 | raise ValueError("손상 원본이 변경됨") |
| 63 | with zipfile.ZipFile(recovered) as archive: |
| 64 | names = archive.namelist() |
| 65 | expected = sample["expected"]["verified_entries"] |
| 66 | if len(names) != len(set(names)) or set(names) != set(expected): |
| 67 | raise ValueError("복구 항목 집합 불일치") |
| 68 | for info in archive.infolist(): |
| 69 | reference = ENTRIES[info.filename] |
| 70 | if info.file_size != reference["bytes"]: |
| 71 | raise ValueError("복구 내용 크기 불일치") |
| 72 | with archive.open(info) as member: |
| 73 | payload = member.read(reference["bytes"] + 1) |
| 74 | if info.is_dir() != (reference["kind"] == "directory"): |
| 75 | raise ValueError("파일과 폴더 종류 불일치") |
| 76 | if len(payload) != reference["bytes"] or digest(payload) != reference["sha256"]: |
| 77 | raise ValueError("복구 내용 해시 불일치") |
| 78 | |
| 79 | |
| 80 | class CorpusTests(unittest.TestCase): |
| 81 | def test_fixture_hashes_and_categories(self): |
| 82 | self.assertEqual({sample["category"] for sample in SAMPLES.values()}, { |
| 83 | "control", "header_damage", "middle_truncation", "payload_corruption", "unrecoverable" |
| 84 | }) |
| 85 | for name, sample in SAMPLES.items(): |
| 86 | with self.subTest(name=name): |
| 87 | data = (ROOT / name).read_bytes() |
| 88 | self.assertEqual(len(data), sample["bytes"]) |
| 89 | self.assertEqual(digest(data), sample["sha256"]) |
| 90 | self.assertEqual(digest(data), sample["expected"]["must_preserve_source_sha256"]) |
| 91 | |
| 92 | def test_regeneration_matches_committed_bytes(self): |
| 93 | for name, data in corpus().items(): |
| 94 | self.assertEqual((ROOT / name).read_bytes(), data, name) |
| 95 | |
| 96 | def test_control_with_independent_zipfile_reader(self): |
| 97 | with zipfile.ZipFile(ROOT / "control.zip") as archive: |
| 98 | self.assertIsNone(archive.testzip()) |
| 99 | self.assertEqual(archive.namelist(), list(ENTRIES)) |
| 100 | for name, expected, _ in SOURCES: |
| 101 | self.assertEqual(archive.read(name), expected) |
| 102 | self.assertEqual(digest(expected), ENTRIES[name]["sha256"]) |
| 103 | |
| 104 | def test_exact_damage_operations(self): |
| 105 | original = (ROOT / "control.zip").read_bytes() |
| 106 | for name, sample in SAMPLES.items(): |
| 107 | damaged = bytearray(original) |
| 108 | for operation in sample["mutations_from_control"]: |
| 109 | offset = operation["offset"] |
| 110 | if operation["operation"] == "truncate": |
| 111 | del damaged[offset:] |
| 112 | elif operation["operation"] == "replace": |
| 113 | replacement = bytes.fromhex(operation["hex"]) |
| 114 | damaged[offset:offset + len(replacement)] = replacement |
| 115 | elif operation["operation"] == "xor": |
| 116 | damaged[offset] ^= operation["value"] |
| 117 | else: |
| 118 | self.fail("알 수 없는 손상 연산") |
| 119 | self.assertEqual(bytes(damaged), (ROOT / name).read_bytes(), name) |
| 120 | |
| 121 | def test_damage_requires_recovery(self): |
| 122 | for name, sample in SAMPLES.items(): |
| 123 | if sample["category"] == "control": |
| 124 | continue |
| 125 | with self.subTest(name=name), self.assertRaises(zipfile.BadZipFile): |
| 126 | with zipfile.ZipFile(ROOT / name) as archive: |
| 127 | for info in archive.infolist(): |
| 128 | archive.read(info) |
| 129 | |
| 130 | def test_complete_inventory_with_only_local_signature_damage(self): |
| 131 | original = (ROOT / "control.zip").read_bytes() |
| 132 | damaged = (ROOT / "broken-local-header.zip").read_bytes() |
| 133 | with zipfile.ZipFile(io.BytesIO(damaged)) as archive: |
| 134 | self.assertEqual(archive.namelist(), list(ENTRIES)) |
| 135 | self.assertEqual(damaged[archive.start_dir:], original[archive.start_dir:]) |
| 136 | offset = 0 |
| 137 | for info in archive.infolist(): |
| 138 | self.assertEqual(info.header_offset, offset) |
| 139 | name_size, extra_size = struct.unpack_from("<HH", damaged, offset + 26) |
| 140 | offset += 30 + name_size + extra_size + info.compress_size |
| 141 | self.assertEqual(offset, archive.start_dir) |
| 142 | with self.assertRaises(zipfile.BadZipFile): |
| 143 | archive.read("한글/자료.txt") |
| 144 | repaired = reference_restore_local_signature(damaged) |
| 145 | self.assertEqual(repaired, original) |
| 146 | with zipfile.ZipFile(io.BytesIO(repaired)) as archive: |
| 147 | self.assertIsNone(archive.testzip()) |
| 148 | for info in archive.infolist(): |
| 149 | self.assertEqual(digest(archive.read(info)), ENTRIES[info.filename]["sha256"]) |
| 150 | self.assertEqual((ROOT / "broken-local-header.zip").read_bytes(), damaged) |
| 151 | expected = SAMPLES["broken-local-header.zip"]["expected"] |
| 152 | self.assertEqual(expected["recovery_summary"], { |
| 153 | "mode": "CentralDirectory", "known_entries": 6, "verified_entries": 6, |
| 154 | "lost_entries": 0, "unverified_entries": 0, "unknown_loss": False, |
| 155 | }) |
| 156 | self.assertFalse(expected["must_not_claim_complete_original"]) |
| 157 | self.assertFalse(expected["warning_required"]) |
| 158 | self.assertEqual(expected["terminal_after_successful_publication"], { |
| 159 | "outcome": "Completed", "error": "None", "publication": "Complete", "created_count": 1, |
| 160 | }) |
| 161 | |
| 162 | def test_verified_entries_have_intact_local_payloads(self): |
| 163 | for name, sample in SAMPLES.items(): |
| 164 | data = (ROOT / name).read_bytes() |
| 165 | if name == "broken-local-header.zip": |
| 166 | data = reference_restore_local_signature(data) |
| 167 | for entry_name in sample["expected"]["verified_entries"]: |
| 168 | with self.subTest(sample=name, entry=entry_name): |
| 169 | payload = local_payload(data, ENTRIES[entry_name]) |
| 170 | self.assertEqual(digest(payload), ENTRIES[entry_name]["sha256"]) |
| 171 | |
| 172 | def test_excluded_entries_are_not_verified(self): |
| 173 | for name, sample in SAMPLES.items(): |
| 174 | data = (ROOT / name).read_bytes() |
| 175 | for entry_name in sample["expected"]["excluded_entries"]: |
| 176 | with self.subTest(sample=name, entry=entry_name), self.assertRaises(ValueError): |
| 177 | local_payload(data, ENTRIES[entry_name]) |
| 178 | counts = [len(sample["expected"]["verified_entries"]) for sample in SAMPLES.values()] |
| 179 | self.assertEqual(counts, [6, 6, 6, 4, 5, 0, 6]) |
| 180 | self.assertEqual(SAMPLES["middle-truncated.zip"]["expected"]["oracle_states"]["after.txt"], |
| 181 | "not_observable") |
| 182 | |
| 183 | def test_reference_recovered_output_checker(self): |
| 184 | for name, sample in SAMPLES.items(): |
| 185 | if not sample["expected"]["publish_archive"]: |
| 186 | continue |
| 187 | stream = io.BytesIO() |
| 188 | with zipfile.ZipFile(stream, "w") as archive: |
| 189 | for entry_name, payload, _ in SOURCES: |
| 190 | if entry_name in sample["expected"]["verified_entries"]: |
| 191 | archive.writestr(entry_name, payload) |
| 192 | stream.seek(0) |
| 193 | verify_recovered(name, stream) |
| 194 | |
| 195 | def test_checker_rejects_missing_wrong_and_extra_entries(self): |
| 196 | for mutation in ("missing", "wrong", "extra"): |
| 197 | stream = io.BytesIO() |
| 198 | with zipfile.ZipFile(stream, "w") as archive: |
| 199 | for index, (name, payload, _) in enumerate(SOURCES): |
| 200 | if mutation == "missing" and index == 0: |
| 201 | continue |
| 202 | archive.writestr(name, b"wrong" if mutation == "wrong" and index == 0 else payload) |
| 203 | if mutation == "extra": |
| 204 | archive.writestr("unexpected.txt", b"extra") |
| 205 | stream.seek(0) |
| 206 | with self.subTest(mutation=mutation), self.assertRaises(ValueError): |
| 207 | verify_recovered("missing-directory.zip", stream) |
| 208 | with self.assertRaises(ValueError): |
| 209 | verify_recovered("unrecoverable.zip", io.BytesIO()) |
| 210 | |
| 211 | |
| 212 | if __name__ == "__main__": |
| 213 | parser = argparse.ArgumentParser() |
| 214 | parser.add_argument("--recovered", nargs=2, metavar=("SAMPLE", "OUTPUT_ZIP")) |
| 215 | args = parser.parse_args() |
| 216 | if args.recovered: |
| 217 | verify_recovered(args.recovered[0], Path(args.recovered[1])) |
| 218 | print("복구본 항목과 해시 일치") |
| 219 | else: |
| 220 | unittest.main(argv=[__file__], verbosity=2) |