"""Standalone reader-archive contract: every limit, boundary, message and ordering.""" import io import re import unittest import zipfile from dataclasses import dataclass, field from unittest.mock import patch from backend import reader_archive from backend.reader_archive import ReaderArchiveInvalidError, ReaderArchiveLimitError MEMBER_RE = re.compile(r"^[^/\x00]+(?:/[^/\x00]+)*(?:/)?$") ARCHIVE = b"\0" * 1000 @dataclass class Limits: READER_RESOURCE_MAX_ARCHIVE_BYTES: int = 512 * 1024 * 1024 READER_ARCHIVE_MAX_ENTRIES: int = 20_000 READER_ARCHIVE_MAX_EXPANDED_BYTES: int = 1536 * 1024 * 1024 READER_ARCHIVE_MAX_COMPRESSION_RATIO: int = 200 READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES: int = 8 * 1024 * 1024 READER_ARCHIVE_MAX_METADATA_BYTES: int = 16 * 1024 * 1024 READER_ARCHIVE_MEMBER_RE: re.Pattern = field(default=MEMBER_RE) class FalsyInt(int): """An int that is non-zero but falsy, reaching the aggregate-only checks.""" def __bool__(self): return False class Info: def __init__(self, orig_filename="a", extra=b"", comment=b"", file_size=1, compress_size=1, header_offset=0): self.orig_filename, self.extra, self.comment = orig_filename, extra, comment self.file_size, self.compress_size, self.header_offset = file_size, compress_size, header_offset class Directory: def __init__(self, infos, start_dir=900, comment=b""): self.infos, self.start_dir, self.comment = infos, start_dir, comment def __enter__(self): return self def __exit__(self, *_): return False def infolist(self): return self.infos def end_record(entries=1, size=10, offset=900, signature=zipfile.stringEndArchive, disk=0, start=0, this_disk=None, comment=b"", comment_size=None): record = [None] * 10 for name, value in (("_ECD_SIGNATURE", signature), ("_ECD_DISK_NUMBER", disk), ("_ECD_DISK_START", start), ("_ECD_ENTRIES_THIS_DISK", entries if this_disk is None else this_disk), ("_ECD_ENTRIES_TOTAL", entries), ("_ECD_SIZE", size), ("_ECD_OFFSET", offset), ("_ECD_COMMENT_SIZE", len(comment) if comment_size is None else comment_size), ("_ECD_COMMENT", comment), ("_ECD_LOCATION", 990)): record[getattr(zipfile, name)] = value return record def make_zip(files=None, comment=b"", zip64=False): buffer = io.BytesIO() with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED, allowZip64=True) as book_zip: for name, content in (files if files is not None else {"image.svg": b""}).items(): info = zipfile.ZipInfo(name) info.compress_type = zipfile.ZIP_DEFLATED with book_zip.open(info, "w", force_zip64=zip64) as member: member.write(content) book_zip.comment = comment raw = buffer.getvalue() if zip64: # Force the ZIP64 end record so the 64-bit signature path is exercised. with zipfile.ZipFile(io.BytesIO(raw)) as source, io.BytesIO() as out: with zipfile.ZipFile(out, "w", allowZip64=True) as target: target.comment = source.comment for info in source.infolist(): target.writestr(info, source.read(info)) target._didModify = True target.start_dir = target.fp.tell() with patch.object(zipfile, "ZIP64_LIMIT", 0), patch.object(zipfile, "ZIP_FILECOUNT_LIMIT", 0): target._write_end_record() target.fp.seek(0, io.SEEK_END) target._didModify = False raw = out.getvalue() return raw class ReaderArchiveMutationContractTests(unittest.TestCase): def check(self, archive=ARCHIVE, limits=None, record=None, directory=None): limits = limits or Limits() patches = [] if record is not None: patches.append(patch.object(zipfile, "_EndRecData", return_value=record)) if directory is not None: patches.append(patch.object(zipfile, "ZipFile", return_value=directory)) for item in patches: item.start() try: return reader_archive.validate_reader_archive(archive, limits) finally: for item in reversed(patches): item.stop() def fails(self, error, message, **kwargs): with self.assertRaises(error) as raised: self.check(**kwargs) self.assertIs(type(raised.exception), error) self.assertEqual(raised.exception.args, (message,)) return raised.exception def test_error_types_are_distinct_value_errors(self): for error in (ReaderArchiveLimitError, ReaderArchiveInvalidError, reader_archive.ReaderDocumentLimitError): self.assertTrue(issubclass(error, ValueError)) self.assertFalse(issubclass(ReaderArchiveLimitError, ReaderArchiveInvalidError)) self.assertFalse(issubclass(ReaderArchiveInvalidError, ReaderArchiveLimitError)) self.assertFalse(issubclass(reader_archive.ReaderDocumentLimitError, (ReaderArchiveLimitError, ReaderArchiveInvalidError))) def test_real_archives_are_accepted(self): for zip64 in (False, True): for comment in (b"", b"archive comment"): for prefix in (b"", b"self-extracting prefix"): with self.subTest(zip64=zip64, comment=comment, prefix=prefix): raw = prefix + make_zip(comment=comment, zip64=zip64) self.assertIsNone(self.check(raw)) self.assertIsNone(self.check(make_zip(files={}))) self.assertIsNone(self.check(make_zip(files={"dir/": b"", "dir/a.txt": b"text", "名": b"x"}))) def test_archive_size_is_checked_before_parsing(self): raw = make_zip() self.assertIsNone(self.check(raw, Limits(READER_RESOURCE_MAX_ARCHIVE_BYTES=len(raw)))) with patch.object(zipfile, "_EndRecData") as eocd, patch.object(zipfile, "ZipFile") as parser: self.fails(ReaderArchiveLimitError, "阅读文件过大", archive=raw, limits=Limits(READER_RESOURCE_MAX_ARCHIVE_BYTES=len(raw) - 1)) eocd.assert_not_called() parser.assert_not_called() def test_missing_end_record_and_parser_failures(self): for archive in (b"", b"PKnot-a-zip", make_zip()[:-1]): with self.subTest(archive=archive[:12]): error = self.fails(ReaderArchiveInvalidError, "阅读文件不是有效 ZIP", archive=archive) self.assertIsNone(error.__cause__) for record in (None, []): with self.subTest(record=record), patch.object(zipfile, "ZipFile") as parser: self.fails(ReaderArchiveInvalidError, "阅读文件不是有效 ZIP", record=record) parser.assert_not_called() failure = zipfile.BadZipFile("synthetic") with patch.object(zipfile, "ZipFile", side_effect=failure): error = self.fails(ReaderArchiveInvalidError, "阅读文件不是有效 ZIP", record=end_record()) self.assertIs(error.__cause__, failure) def test_limit_and_invalid_errors_propagate_unwrapped(self): for error in (ReaderArchiveLimitError("custom limit"), ReaderArchiveInvalidError("custom invalid")): with self.subTest(error=error), patch.object(zipfile, "ZipFile", side_effect=error): with self.assertRaises(type(error)) as raised: self.check(record=end_record()) self.assertIs(raised.exception, error) def test_each_end_record_inconsistency_is_invalid_metadata(self): for name, record in ( ("disk", end_record(disk=1)), ("start", end_record(start=1)), ("this disk", end_record(this_disk=2)), ("comment size", end_record(comment=b"ab", comment_size=1)), ("size sentinel", end_record(size=0xffffffff)), # The entry count would otherwise fail as a limit, proving the sentinel check runs first. ("offset sentinel", end_record(offset=0xffffffff, entries=20_001))): with self.subTest(name=name), patch.object(zipfile, "ZipFile") as parser: self.fails(ReaderArchiveInvalidError, "阅读文件元数据无效", record=record) parser.assert_not_called() zip64 = end_record(size=10, offset=900, signature=zipfile.stringEndArchive64) self.assertIsNone(self.check(record=zip64, directory=Directory([Info()]))) sentinel64 = end_record(size=0xffffffff, offset=0, signature=zipfile.stringEndArchive64) self.fails(ReaderArchiveLimitError, "阅读文件元数据过大", record=sentinel64) def test_directory_limits_precede_zipfile_construction(self): directory = Directory([Info()]) self.assertIsNone(self.check(limits=Limits(READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES=10), record=end_record(size=10), directory=directory)) with patch.object(zipfile, "ZipFile") as parser: self.fails(ReaderArchiveLimitError, "阅读文件元数据过大", limits=Limits(READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES=9), record=end_record(size=10)) self.fails(ReaderArchiveLimitError, "阅读文件条目过多", limits=Limits(READER_ARCHIVE_MAX_ENTRIES=0), record=end_record(entries=1)) parser.assert_not_called() self.assertIsNone(self.check(limits=Limits(READER_ARCHIVE_MAX_ENTRIES=1), record=end_record(entries=1), directory=directory)) def test_directory_must_fit_inside_the_archive(self): self.assertIsNone(self.check(record=end_record(size=100, offset=900), directory=Directory([Info()]))) with patch.object(zipfile, "ZipFile") as parser: self.fails(ReaderArchiveInvalidError, "阅读文件元数据无效", record=end_record(size=101, offset=900)) parser.assert_not_called() def test_parsed_entry_count_limit_and_mismatch(self): self.fails(ReaderArchiveLimitError, "阅读文件条目过多", limits=Limits(READER_ARCHIVE_MAX_ENTRIES=1), record=end_record(entries=1), directory=Directory([Info(), Info()])) self.fails(ReaderArchiveInvalidError, "阅读文件条目数无效", record=end_record(entries=2), directory=Directory([Info()])) self.fails(ReaderArchiveInvalidError, "阅读文件条目数无效", record=end_record(entries=1), directory=Directory([])) self.assertIsNone(self.check(record=end_record(entries=0), directory=Directory([]))) def test_parsed_directory_geometry_is_validated(self): limit = Limits(READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES=10) invalid = ( ("float size", {"size": 10.0}, {}, limit), ("bool size", {"size": True}, {}, limit), ("negative size", {"size": -1}, {}, limit), ("float offset", {}, {"start_dir": 900.0}, limit), ("bool offset", {}, {"start_dir": True}, limit), ("negative offset", {}, {"start_dir": -1}, limit), ("offset past end", {}, {"start_dir": 1001}, limit), ("size past end", {"size": 10}, {"start_dir": 991}, limit), ("text comment", {}, {"comment": "comment"}, limit), ) for name, record_args, directory_args, limits in invalid: with self.subTest(name=name): args = {"start_dir": 900, "comment": b"", **directory_args} infos = [Info(header_offset=0)] self.fails(ReaderArchiveInvalidError, "阅读文件元数据无效", limits=limits, record=end_record(**{"size": 10, "offset": 0, **record_args}), directory=Directory(infos, **args)) for start_dir in (990, 1000): with self.subTest(start_dir=start_dir): size = 1000 - start_dir self.assertIsNone(self.check(limits=Limits(READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES=size), record=end_record(size=size, offset=0), directory=Directory([Info()], start_dir=start_dir))) self.assertIsNone(self.check(record=end_record(size=0, offset=0), directory=Directory([Info()], start_dir=1))) def test_member_metadata_types(self): for name, info in (("filename", Info(orig_filename=b"a")), ("extra", Info(extra="x")), ("comment", Info(comment="x"))): with self.subTest(name=name): self.fails(ReaderArchiveInvalidError, "阅读文件元数据无效", record=end_record(), directory=Directory([info])) def test_unsafe_member_paths(self): for name in ("", "/absolute", "a\x00b", ".", "..", "a/./b", "a/../b", "../escape", "a//b", "a//", "a\\..\\escape", "\\absolute", "a\\\\b"): with self.subTest(name=name): self.fails(ReaderArchiveInvalidError, "阅读文件包含不安全路径", record=end_record(), directory=Directory([Info(orig_filename=name)])) for name in ("a", "dir/", "dir/a.txt", "a.b/c..d/...", "a\\b"): with self.subTest(name=name): self.assertIsNone(self.check(record=end_record(), directory=Directory([Info(orig_filename=name)]))) strict = Limits(READER_ARCHIVE_MEMBER_RE=re.compile("safe")) self.assertIsNone(self.check(limits=strict, record=end_record(), directory=Directory([Info(orig_filename="safe")]))) self.fails(ReaderArchiveInvalidError, "阅读文件包含不安全路径", limits=strict, record=end_record(), directory=Directory([Info(orig_filename="safer")])) def test_each_unsafe_path_rule_rejects_without_the_member_pattern(self): # The default member pattern rejects most of these names by itself, so a # permissive pattern is needed to exercise every explicit rule. anything = Limits(READER_ARCHIVE_MEMBER_RE=re.compile("(?s).*")) nul = chr(0) for name in ("", "a" + nul + "b", nul, ".", "..", "a/./b", "a/../b", "a//b", "a//", "//", "/"): with self.subTest(name=name): self.fails(ReaderArchiveInvalidError, "阅读文件包含不安全路径", limits=anything, record=end_record(), directory=Directory([Info(orig_filename=name)])) for name in ("a", "dir/", "a/b/", "a..b", "a.b/c..d/...", "XX/XXa"): with self.subTest(name=name): self.assertIsNone(self.check(limits=anything, record=end_record(), directory=Directory([Info(orig_filename=name)]))) def test_member_ratio_is_enforced_even_when_the_aggregate_ratio_passes(self): # A second, poorly compressed member keeps the aggregate under the limit. padding = Info(file_size=0, compress_size=500) self.fails(ReaderArchiveLimitError, "阅读文件压缩比过高", record=end_record(entries=2), directory=Directory([Info(file_size=201, compress_size=1), padding])) self.assertIsNone(self.check(record=end_record(entries=2), directory=Directory([Info(file_size=200, compress_size=1), padding]))) def test_filename_encoding_failures(self): for failure in (UnicodeEncodeError("utf-8", "a", 0, 1, "synthetic"), AttributeError("synthetic")): class Name(str): def encode(self, *_args, **_kwargs): raise failure with self.subTest(failure=type(failure).__name__): error = self.fails(ReaderArchiveInvalidError, "阅读文件元数据无效", record=end_record(), directory=Directory([Info(orig_filename=Name("a"))])) self.assertIs(error.__cause__, failure) calls = [] class Recorded(str): def encode(self, *args, **kwargs): calls.append((args, kwargs)) return super().encode(*args, **kwargs) self.assertIsNone(self.check(record=end_record(), directory=Directory([Info(orig_filename=Recorded("a"))]))) self.assertEqual(calls, [(("utf-8", "surrogatepass"), {})]) def test_metadata_budget_counts_every_component(self): surrogate = "\ud800" infos = [Info(orig_filename="名" + surrogate, extra=b"ex", comment=b"cmt"), Info(orig_filename="b")] # 4-byte archive comment, then 46 + 6 + 2 + 3 and 46 + 1 + 0 + 0. exact = 4 + 46 + 6 + 2 + 3 + 46 + 1 for budget, accepted in ((exact, True), (exact - 1, False)): with self.subTest(budget=budget): kwargs = {"limits": Limits(READER_ARCHIVE_MAX_METADATA_BYTES=budget), "record": end_record(entries=2), "directory": Directory(infos, comment=b"note")} if accepted: self.assertIsNone(self.check(**kwargs)) else: self.fails(ReaderArchiveLimitError, "阅读文件元数据过大", **kwargs) def test_member_sizes_and_offsets(self): invalid = ( ("float size", {"file_size": 1.0}), ("bool size", {"file_size": True}), ("negative size", {"file_size": -1}), ("float compressed", {"compress_size": 1.0}), ("bool compressed", {"compress_size": True}), ("negative compressed", {"compress_size": -1}), ("compressed past end", {"compress_size": 1001}), ("float offset", {"header_offset": 0.0}), ("bool offset", {"header_offset": False}), ("negative offset", {"header_offset": -1}), ("offset at end", {"header_offset": 1000}), ("offset at directory", {"header_offset": 900}), ) for name, values in invalid: with self.subTest(name=name): self.fails(ReaderArchiveInvalidError, "阅读文件条目无效", record=end_record(), directory=Directory([Info(**values)])) for values in ({"compress_size": 1000, "file_size": 1000}, {"header_offset": 899}, {"file_size": 0, "compress_size": 0}): with self.subTest(values=values): self.assertIsNone(self.check(record=end_record(), directory=Directory([Info(**values)]))) self.assertIsNone(self.check(record=end_record(size=1, offset=0), directory=Directory([Info(header_offset=998)], start_dir=999))) def test_expanded_size_is_cumulative(self): infos = [Info(file_size=3, compress_size=1), Info(file_size=3, compress_size=1)] self.assertIsNone(self.check(limits=Limits(READER_ARCHIVE_MAX_EXPANDED_BYTES=6), record=end_record(entries=2), directory=Directory(infos))) self.fails(ReaderArchiveLimitError, "阅读文件展开后过大", limits=Limits(READER_ARCHIVE_MAX_EXPANDED_BYTES=5), record=end_record(entries=2), directory=Directory(infos)) def test_member_compression_ratio(self): self.fails(ReaderArchiveLimitError, "阅读文件压缩比过高", record=end_record(), directory=Directory([Info(file_size=1, compress_size=0)])) self.assertIsNone(self.check(record=end_record(), directory=Directory([Info(file_size=200, compress_size=1)]))) self.fails(ReaderArchiveLimitError, "阅读文件压缩比过高", record=end_record(), directory=Directory([Info(file_size=201, compress_size=1)])) self.assertIsNone(self.check(limits=Limits(READER_ARCHIVE_MAX_COMPRESSION_RATIO=3), record=end_record(), directory=Directory([Info(file_size=6, compress_size=2)]))) self.fails(ReaderArchiveLimitError, "阅读文件压缩比过高", limits=Limits(READER_ARCHIVE_MAX_COMPRESSION_RATIO=3), record=end_record(), directory=Directory([Info(file_size=7, compress_size=2)])) def test_aggregate_checks_after_members(self): self.fails(ReaderArchiveLimitError, "阅读文件压缩比过高", record=end_record(), directory=Directory([Info(file_size=FalsyInt(1), compress_size=0)])) self.assertIsNone(self.check(record=end_record(), directory=Directory([Info(file_size=FalsyInt(0), compress_size=0)]))) for ratio, size, accepted in ((3, 6, True), (3, 7, False)): with self.subTest(ratio=ratio, size=size): kwargs = {"limits": Limits(READER_ARCHIVE_MAX_COMPRESSION_RATIO=ratio), "record": end_record(), "directory": Directory([Info(file_size=FalsyInt(size), compress_size=2)])} if accepted: self.assertIsNone(self.check(**kwargs)) else: self.fails(ReaderArchiveLimitError, "阅读文件压缩比过高", **kwargs) infos = [Info(file_size=1, compress_size=500), Info(file_size=1, compress_size=500)] self.assertIsNone(self.check(record=end_record(entries=2), directory=Directory(infos))) infos.append(Info(file_size=0, compress_size=1)) self.fails(ReaderArchiveInvalidError, "阅读文件条目无效", record=end_record(entries=3), directory=Directory(infos)) def test_limits_are_read_at_each_use(self): class Live(Limits): reads: list live = Live() live.reads = [] class Directory2(Directory): def infolist(self): live.READER_ARCHIVE_MAX_ENTRIES = 0 return self.infos self.fails(ReaderArchiveLimitError, "阅读文件条目过多", limits=live, record=end_record(), directory=Directory2([Info()])) if __name__ == "__main__": unittest.main()