Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Send a clearer error message if response is truncated before a chunk #2860

Merged
merged 4 commits into from
Jan 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/2860.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Use ProtocolError instead of InvalidChunkLength if response terminates before the chunk length is sent.
8 changes: 6 additions & 2 deletions src/urllib3/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -1100,9 +1100,13 @@ def _update_chunk_length(self) -> None:
try:
self.chunk_left = int(line, 16)
except ValueError:
# Invalid chunked protocol response, abort.
self.close()
raise InvalidChunkLength(self, line) from None
if line:
# Invalid chunked protocol response, abort.
raise InvalidChunkLength(self, line) from None
else:
# Truncated at start of next chunk
raise ProtocolError("Response ended prematurely") from None

def _handle_chunk(self, amt: int | None) -> bytes:
returned_chunk = None
Expand Down
20 changes: 20 additions & 0 deletions test/test_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -1333,6 +1333,21 @@ def test_invalid_chunk_length(self) -> None:
assert isinstance(orig_ex, InvalidChunkLength)
assert orig_ex.length == fp.BAD_LENGTH_LINE.encode()

def test_truncated_before_chunk(self) -> None:
stream = [b"foooo", b"bbbbaaaaar"]
fp = MockChunkedNoChunks(stream)
r = httplib.HTTPResponse(MockSock) # type: ignore[arg-type]
r.fp = fp # type: ignore[assignment]
r.chunked = True
r.chunk_left = None
resp = HTTPResponse(
r, preload_content=False, headers={"transfer-encoding": "chunked"}
)
with pytest.raises(ProtocolError) as ctx:
next(resp.read_chunked())

assert str(ctx.value) == "Response ended prematurely"

def test_chunked_response_without_crlf_on_end(self) -> None:
stream = [b"foo", b"bar", b"baz"]
fp = MockChunkedEncodingWithoutCRLFOnEnd(stream)
Expand Down Expand Up @@ -1594,6 +1609,11 @@ def _encode_chunk(self, chunk: bytes) -> bytes:
return f"{len(chunk):X};asd=qwe\r\n{chunk.decode()}\r\n".encode()


class MockChunkedNoChunks(MockChunkedEncodingResponse):
def _encode_chunk(self, chunk: bytes) -> bytes:
return b""


class MockSock:
@classmethod
def makefile(cls, *args: typing.Any, **kwargs: typing.Any) -> None:
Expand Down