From 668f4db44d2965d9009308d96e13776069d050db Mon Sep 17 00:00:00 2001 From: Nicholas Serra Date: Thu, 12 Nov 2020 08:22:33 -0500 Subject: [PATCH] 712 Handle EOFErrror with malformed file (#714) * Handle EOFError on package upload * Linting --- tests/fixtures/malformed.tar.gz | Bin 0 -> 10 bytes tests/test_package.py | 10 ++++++++++ twine/package.py | 10 ++++++++-- 3 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 tests/fixtures/malformed.tar.gz diff --git a/tests/fixtures/malformed.tar.gz b/tests/fixtures/malformed.tar.gz new file mode 100644 index 0000000000000000000000000000000000000000..5105e8bffba55252e59dd361d3906d03eb845364 GIT binary patch literal 10 Ncmb2|=3oGW{{RPK0kQx9 literal 0 HcmV?d00001 diff --git a/tests/test_package.py b/tests/test_package.py index 208c0a2a..b9ea4335 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -254,3 +254,13 @@ def EmptyDist(filename): package_file.PackageFile.from_filename(filename, comment=None) assert "Invalid distribution metadata" in err.value.args[0] + + +def test_malformed_from_file(monkeypatch): + """Raise an exception when malformed package file triggers EOFError.""" + filename = "tests/fixtures/malformed.tar.gz" + + with pytest.raises(exceptions.InvalidDistribution) as err: + package_file.PackageFile.from_filename(filename, comment=None) + + assert "Invalid distribution file" in err.value.args[0] diff --git a/twine/package.py b/twine/package.py index a7003da2..045ad81d 100644 --- a/twine/package.py +++ b/twine/package.py @@ -76,8 +76,14 @@ def from_filename(cls, filename: str, comment: Optional[str]) -> "PackageFile": # Extract the metadata from the package for ext, dtype in DIST_EXTENSIONS.items(): if filename.endswith(ext): - meta = DIST_TYPES[dtype](filename) - break + try: + meta = DIST_TYPES[dtype](filename) + except EOFError: + raise exceptions.InvalidDistribution( + "Invalid distribution file: '%s'" % os.path.basename(filename) + ) + else: + break else: raise exceptions.InvalidDistribution( "Unknown distribution format: '%s'" % os.path.basename(filename)