fix(archive): close partial files before cleanup on every failure

This commit is contained in:
Bingxi Zhao (Frank)
2026-10-31 17:17:26 +08:00
parent 77addee410
commit 0fb3d74495
2 changed files with 60 additions and 3 deletions

View File

@@ -210,9 +210,11 @@ def _extract_member(
returned still exceeds the limit so the caller can detect the overflow.
"""
written = 0
with archive.open(info) as source, open(destination, "xb") as sink:
# Register cleanup only after exclusive creation succeeds.
with _remove_on_error([destination]):
with archive.open(info) as source:
# Acquire exclusively before registering cleanup, then close before
# unlinking (required by Windows and by buffered flush failures).
sink = open(destination, "xb")
with _remove_on_error([destination]), sink:
while True:
chunk = source.read(chunk_size)
if not chunk:

View File

@@ -226,3 +226,58 @@ def test_existing_file_is_never_overwritten_or_cleaned_up(tmp_path, readonly):
assert not (out / "new.txt").exists()
finally:
existing.chmod(0o644)
@pytest.mark.parametrize("failure", ["read", "close"])
def test_failed_member_closes_before_cleanup(tmp_path, monkeypatch, failure):
"""Simulate Windows deny-delete sharing and buffered flush/close failure."""
import io
import deeptutor.utils.archive_extractor as extractor
destination = tmp_path / "partial.txt"
real_open = open
real_unlink = Path.unlink
sinks = []
class Sink:
def __init__(self, handle):
self.handle = handle
def __enter__(self):
return self
def write(self, data):
return self.handle.write(data)
def __exit__(self, *args):
self.handle.close()
if failure == "close":
raise OSError("flush failed")
class Source(io.BytesIO):
def read(self, size=-1):
if failure == "read" and self.tell():
raise zipfile.BadZipFile("CRC mismatch")
return super().read(size)
class Archive:
def open(self, _info):
return Source(b"partial contents")
def tracked_open(*args, **kwargs):
sink = Sink(real_open(*args, **kwargs))
sinks.append(sink)
return sink
def windows_unlink(path, *args, **kwargs):
if path == destination and any(not sink.handle.closed for sink in sinks):
raise PermissionError("cannot delete an open file")
return real_unlink(path, *args, **kwargs)
monkeypatch.setattr(extractor, "open", tracked_open, raising=False)
monkeypatch.setattr(Path, "unlink", windows_unlink)
with pytest.raises((zipfile.BadZipFile, OSError)):
extractor._extract_member(Archive(), object(), destination, 100)
assert sinks and all(sink.handle.closed for sink in sinks)
assert not destination.exists()