From 1f876f19b7edb2796ec3697b76e75b2c6b50abd9 Mon Sep 17 00:00:00 2001 From: 1cbyc Date: Tue, 17 Nov 2026 06:30:39 +0000 Subject: [PATCH] gh-162129: Validate ZIP member comment length Co-authored-by: insisong --- Lib/test/test_zipfile/test_core.py | 22 +++++++++++++++++++ Lib/zipfile/__init__.py | 5 +++++ ...7-06-00-00.gh-issue-162129.zip-comment.rst | 3 +++ 3 files changed, 30 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2026-11-17-06-00-00.gh-issue-162129.zip-comment.rst diff --git a/Lib/test/test_zipfile/test_core.py b/Lib/test/test_zipfile/test_core.py index 69203142f61589f..fe79575e8fa423c 100644 --- a/Lib/test/test_zipfile/test_core.py +++ b/Lib/test/test_zipfile/test_core.py @@ -4498,6 +4498,28 @@ def test_comments(self): with zipfile.ZipFile(TESTFN,mode="r") as zipf: self.assertEqual(zipf.comment, b"shorter comment") + def test_member_comment_too_long(self): + stream = io.BytesIO() + with zipfile.ZipFile(stream, mode="w") as zipf: + zinfo = zipfile.ZipInfo("accepted.txt") + zinfo.comment = b"x" * zipfile.ZIP_MAX_COMMENT + zipf.writestr(zinfo, b"content") + + zinfo = zipfile.ZipInfo("rejected.txt") + zinfo.comment = b"x" * (zipfile.ZIP_MAX_COMMENT + 1) + with self.assertRaisesRegex( + ValueError, + r"ZipInfo\.comment exceeds the maximum length of 65535 bytes", + ): + zipf.writestr(zinfo, b"content") + + with zipfile.ZipFile(stream) as zipf: + self.assertEqual(zipf.namelist(), ["accepted.txt"]) + self.assertEqual( + zipf.getinfo("accepted.txt").comment, + b"x" * zipfile.ZIP_MAX_COMMENT, + ) + def test_unicode_comment(self): with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf: zipf.writestr("foo.txt", "O, for a Muse of Fire!") diff --git a/Lib/zipfile/__init__.py b/Lib/zipfile/__init__.py index 87b2d2e5b8f9917..f77718709088ad6 100644 --- a/Lib/zipfile/__init__.py +++ b/Lib/zipfile/__init__.py @@ -2528,6 +2528,11 @@ def _extract_member(self, member, targetpath, pwd): def _writecheck(self, zinfo): """Check for errors before writing a file to the archive.""" + if len(zinfo.comment) > ZIP_MAX_COMMENT: + raise ValueError( + f"ZipInfo.comment exceeds the maximum length of " + f"{ZIP_MAX_COMMENT} bytes" + ) if zinfo.filename in self.NameToInfo: warnings.warn('Duplicate name: %r' % zinfo.filename, stacklevel=3) if self.mode not in ('w', 'x', 'a'): diff --git a/Misc/NEWS.d/next/Library/2026-11-17-06-00-00.gh-issue-162129.zip-comment.rst b/Misc/NEWS.d/next/Library/2026-11-17-06-00-00.gh-issue-162129.zip-comment.rst new file mode 100644 index 000000000000000..d35562fbde79b8c --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-17-06-00-00.gh-issue-162129.zip-comment.rst @@ -0,0 +1,3 @@ +Raise :exc:`ValueError` before writing a ZIP member whose +:attr:`~zipfile.ZipInfo.comment` is too long for the ZIP format. This avoids +an opaque :exc:`struct.error` while closing the archive.