From 4989d502c2179f0dbcd513d95eb9eb445077c559 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?B=C3=A9n=C3=A9dikt=20Tran?= <10796600+picnixz@users.noreply.github.com> Date: Mon, 29 Jul 2024 15:12:50 +0200 Subject: [PATCH 1/3] Ensure that `zipfile.is_zipfile` does not modify a file object. --- Lib/zipfile/__init__.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Lib/zipfile/__init__.py b/Lib/zipfile/__init__.py index e2aaf8bab4913d..bad3bc2d5bf24a 100644 --- a/Lib/zipfile/__init__.py +++ b/Lib/zipfile/__init__.py @@ -241,7 +241,9 @@ def is_zipfile(filename): result = False try: if hasattr(filename, "read"): + pos = filename.tell() result = _check_zipfile(fp=filename) + filename.seek(pos) else: with open(filename, "rb") as fp: result = _check_zipfile(fp) From 76a8e4a53ad06dd2e723aa79843ddd2822099bb0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?B=C3=A9n=C3=A9dikt=20Tran?= <10796600+picnixz@users.noreply.github.com> Date: Mon, 29 Jul 2024 15:15:28 +0200 Subject: [PATCH 2/3] add tests --- Lib/test/test_zipfile/test_core.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Lib/test/test_zipfile/test_core.py b/Lib/test/test_zipfile/test_core.py index 423974aada4ac1..52e656bb33248c 100644 --- a/Lib/test/test_zipfile/test_core.py +++ b/Lib/test/test_zipfile/test_core.py @@ -1969,10 +1969,16 @@ def test_is_zip_valid_file(self): zip_contents = fp.read() # - passing a file-like object fp = io.BytesIO() - fp.write(zip_contents) + end = fp.write(zip_contents) + self.assertEqual(fp.tell(), end) + mid = end // 2 + fp.seek(mid, 0) self.assertTrue(zipfile.is_zipfile(fp)) - fp.seek(0, 0) + # check that the position is left unchanged after the call + # see: https://github.com/python/cpython/issues/122356 + self.assertEqual(fp.tell(), mid) self.assertTrue(zipfile.is_zipfile(fp)) + self.assertEqual(fp.tell(), mid) def test_non_existent_file_raises_OSError(self): # make sure we don't raise an AttributeError when a partially-constructed From ca77c4d9f4450cd62041279d684bd2fa8c5d671c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?B=C3=A9n=C3=A9dikt=20Tran?= <10796600+picnixz@users.noreply.github.com> Date: Mon, 29 Jul 2024 15:20:34 +0200 Subject: [PATCH 3/3] blurb --- .../Library/2024-07-29-15-20-30.gh-issue-122356.wKCmFx.rst | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2024-07-29-15-20-30.gh-issue-122356.wKCmFx.rst diff --git a/Misc/NEWS.d/next/Library/2024-07-29-15-20-30.gh-issue-122356.wKCmFx.rst b/Misc/NEWS.d/next/Library/2024-07-29-15-20-30.gh-issue-122356.wKCmFx.rst new file mode 100644 index 00000000000000..0a4632ca975f6b --- /dev/null +++ b/Misc/NEWS.d/next/Library/2024-07-29-15-20-30.gh-issue-122356.wKCmFx.rst @@ -0,0 +1,3 @@ +Guarantee that the position of a file-like object passed to +:func:`zipfile.is_zipfile` is left untouched after the call. +Patch by Bénédikt Tran.