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

GZIP content length mismatch fix #1579

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 23 additions & 15 deletions starlette/middleware/gzip.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,7 @@ async def send_with_gzip(self, message: Message) -> None:
await self.send(message)
elif not more_body:
# Standard GZip response.
self.gzip_file.write(body)
self.gzip_file.close()
body = self.gzip_buffer.getvalue()
body = self._set_response_body(body, more_body)

headers = MutableHeaders(raw=self.initial_message["headers"])
headers["Content-Encoding"] = "gzip"
Expand All @@ -77,11 +75,7 @@ async def send_with_gzip(self, message: Message) -> None:
headers.add_vary_header("Accept-Encoding")
del headers["Content-Length"]

self.gzip_file.write(body)
message["body"] = self.gzip_buffer.getvalue()
self.gzip_buffer.seek(0)
self.gzip_buffer.truncate()

message["body"] = self._set_response_body(body, more_body)
await self.send(self.initial_message)
await self.send(message)

Expand All @@ -90,16 +84,30 @@ async def send_with_gzip(self, message: Message) -> None:
body = message.get("body", b"")
more_body = message.get("more_body", False)

self.gzip_file.write(body)
if not more_body:
self.gzip_file.close()

message["body"] = self.gzip_buffer.getvalue()
self.gzip_buffer.seek(0)
self.gzip_buffer.truncate()
message["body"] = self._set_response_body(body, more_body)

await self.send(message)

def _set_response_body(self, body, more_body: bool = True) -> bytes:
"""Null byte fix

If the response body is null and we try to get the buffervalue, a null byte is produced.
This causes a content length mismatch.

This issues exists in the upstream Gzip middleware in starlette.
- https://github.com/tiangolo/fastapi/issues/4050
- https://github.com/tiangolo/fastapi/issues/2818

"""
if body and body not in {b"", b"null"}:
self.gzip_file.write(body)
if not more_body:
self.gzip_file.close()
value = self.gzip_buffer.getvalue()
self.gzip_buffer.seek(0)
self.gzip_buffer.truncate()
return value


async def unattached_send(message: Message) -> typing.NoReturn:
raise RuntimeError("send awaitable not set") # pragma: no cover