#!/usr/bin/env python3 """Bounded ZIP validation experiment; creates only tiny synthetic archives. No external archive is accepted or extracted. Run with --output NEW.json. The duplicate-member bug was reported upstream as CPython issue 156539; this experiment independently exercises controls and CLI status propagation. """ import argparse from datetime import datetime, timezone import hashlib import inspect import io import json from pathlib import Path import platform import struct import subprocess import sys import tempfile import warnings import zipfile PAYLOADS = (b"generation=A\n", b"generation=B\n") CASES = ( ("unique-clean", ("first.txt", "second.txt"), (0, 1), None), ("unique-first-damaged", ("first.txt", "second.txt"), (0, 1), 0), ("duplicate-clean", ("record.txt", "record.txt"), (0, 1), None), ("duplicate-first-damaged", ("record.txt", "record.txt"), (0, 1), 0), ("duplicate-last-damaged", ("record.txt", "record.txt"), (0, 1), 1), ("duplicate-reversed", ("record.txt", "record.txt"), (1, 0), None), ) def require(condition, message): if not condition: raise ValueError(message) def digest(data): return hashlib.sha256(data).hexdigest() def fixture(names, order, damaged): stream = io.BytesIO() with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="Duplicate name:", category=UserWarning) with zipfile.ZipFile(stream, "w") as archive: for name, value in zip(names, order, strict=True): entry = zipfile.ZipInfo(name, date_time=(2020, 1, 1, 0, 0, 0)) entry.compress_type = zipfile.ZIP_STORED entry.create_system = 3 entry.external_attr = 0o100600 << 16 archive.writestr(entry, PAYLOADS[value]) original = stream.getvalue() changed = bytearray(original) offset = None if damaged is not None: with zipfile.ZipFile(io.BytesIO(original)) as archive: entry = archive.infolist()[damaged] start = entry.header_offset # APPNOTE 4.3.7: fixed local header, then filename and extra bytes. local = struct.unpack_from("<4s5H3I2H", original, start) require(local[0] == b"PK\x03\x04", "Unexpected local header") require(local[3] == zipfile.ZIP_STORED and local[2] == 0, "Unsupported fixture") offset = start + 30 + local[-2] + local[-1] require(original[offset:offset + entry.file_size] == PAYLOADS[order[damaged]], "Mutation must address the selected payload") changed[offset] ^= 1 require(sum(a != b for a, b in zip(original, changed, strict=True)) == 1, "Mutation must change exactly one byte") return original, bytes(changed), offset def read_entry(archive, selector): try: with archive.open(selector) as stream: payload = stream.read() return {"ok": True, "text": payload.decode("ascii"), "bytes": len(payload), "sha256": digest(payload), "error": None} except zipfile.BadZipFile as error: return {"ok": False, "text": None, "bytes": None, "sha256": None, "error": str(error)} def observe(case, directory): key, names, order, damaged = case original, data, offset = fixture(names, order, damaged) with zipfile.ZipFile(io.BytesIO(data)) as archive: entries = archive.infolist() inventory = [{"index": i, "name": entry.filename, "headerOffset": entry.header_offset, "bytes": entry.file_size, "crc32": f"{entry.CRC:08x}"} for i, entry in enumerate(entries)] by_entry = [read_entry(archive, entry) for entry in entries] by_name = [read_entry(archive, entry.filename) for entry in entries] helper_result = archive.testzip() path = directory / (key + ".zip") path.write_bytes(data) run = subprocess.run([sys.executable, "-I", "-m", "zipfile", "-t", str(path)], capture_output=True, text=True, timeout=10, check=False) return { "id": key, "archiveBytes": len(data), "archiveSha256": digest(data), "originalSha256": digest(original), "damagedIndex": damaged, "mutationOffset": offset, "expectedTexts": [PAYLOADS[i].decode() for i in order], "inventory": inventory, "byEntry": by_entry, "byName": by_name, "testzip": helper_result, "cli": {"returncode": run.returncode, "stdout": run.stdout, "stderr": run.stderr}, } def validate(report): require(report.get("schemaVersion") == 1, "Unsupported schema") rows = report.get("cases", []) require([row.get("id") for row in rows] == [case[0] for case in CASES], "Missing, reordered or duplicated cases") for row, case in zip(rows, CASES, strict=True): key, names, order, damaged = case require(row["damagedIndex"] == damaged, key + ": incorrect damage index") require(len(row["inventory"]) == 2, key + ": inventory length") require([e["name"] for e in row["inventory"]] == list(names), key + ": names") require(row["expectedTexts"] == [PAYLOADS[i].decode() for i in order], key + ": independent expected bytes changed") require(type(row["cli"]["returncode"]) is int, key + ": status type") require(all(isinstance(row["cli"][k], str) for k in ("stdout", "stderr")), key + ": missing CLI diagnostics") for mode in ("byEntry", "byName"): require(len(row[mode]) == 2, key + ": result count") for i, observation in enumerate(row[mode]): selected = i if mode == "byEntry" else max(j for j, name in enumerate(names) if name == names[i]) expected_ok = selected != damaged require(type(observation["ok"]) is bool and observation["ok"] == expected_ok, key + ": entry CRC outcome") expected = PAYLOADS[order[selected]] if expected_ok: require(observation["text"] == expected.decode() and observation["bytes"] == len(expected) and observation["sha256"] == digest(expected) and observation["error"] is None, key + ": payload mismatch") else: require(observation["text"] is None and observation["bytes"] is None and observation["sha256"] is None and isinstance(observation["error"], str) and "CRC" in observation["error"], key + ": expected CRC error") # Do not require the known bug on future interpreters that may fix it. require(row["testzip"] is None or row["testzip"] in names, key + ": helper result") if damaged is None: require(row["testzip"] is None, key + ": clean control rejected") elif names[0] != names[1] or damaged == 1: require(row["testzip"] == names[damaged], key + ": positive control missed") if damaged is None: require(row["archiveSha256"] == row["originalSha256"] and row["mutationOffset"] is None, key + ": clean object changed") else: require(row["archiveSha256"] != row["originalSha256"] and type(row["mutationOffset"]) is int, key + ": mutation missing") return report def collect(): with tempfile.TemporaryDirectory(prefix="hesela-zip-validation-") as folder: rows = [observe(case, Path(folder)) for case in CASES] return validate({ "schemaVersion": 1, "generatedAt": datetime.now(timezone.utc).isoformat(), "contribution": "Controlled reproduction of known duplicate-member behavior and CLI status controls", "environment": { "python": platform.python_version(), "implementation": platform.python_implementation(), "platform": platform.platform(), "zipfileSha256": digest(Path(zipfile.__file__).read_bytes()), "testzipSourceSha256": digest(inspect.getsource(zipfile.ZipFile.testzip).encode()), "harnessSha256": digest(Path(__file__).read_bytes()), }, "method": "Six deterministic two-entry ZIP_STORED fixtures; 13 bytes per payload; one payload-bit mutation where specified; unchanged CRC fields; fresh isolated CLI process per fixture.", "limits": "Designed software observations, not failure rates or a general hostile-archive verifier. No compression, encryption, ZIP64, extraction, aliases or concurrent modification.", "cases": rows, }) def main(): parser = argparse.ArgumentParser(description=__doc__) group = parser.add_mutually_exclusive_group(required=True) group.add_argument("--output", type=Path) group.add_argument("--check", type=Path) args = parser.parse_args() if args.check: saved = validate(json.loads(args.check.read_text())) fresh = collect() require(fresh["cases"] == saved["cases"], "Replay differs; inspect runtime version and source hashes") print("Six fixtures replayed exactly; entry checks and CLI diagnostics match.") else: require(not args.output.exists(), "Refusing to overwrite an existing result") result = collect() with args.output.open("x") as stream: json.dump(result, stream, indent=2) stream.write("\n") print("Recorded six ZIP fixtures.") if __name__ == "__main__": main()