diff --git a/CHANGES/14479.bugfix.rst b/CHANGES/14479.bugfix.rst new file mode 100644 index 00000000000..ed9a5404d03 --- /dev/null +++ b/CHANGES/14479.bugfix.rst @@ -0,0 +1,2 @@ +Fixed a compressed body being corrupted when a write was cancelled during +compression and the caller continued writing -- by :user:`Dreamsorcerer`. diff --git a/aiohttp/http_writer.py b/aiohttp/http_writer.py index bd59217a452..9941b6911c8 100644 --- a/aiohttp/http_writer.py +++ b/aiohttp/http_writer.py @@ -4,7 +4,7 @@ import re import sys from collections.abc import Awaitable, Callable, Iterable -from typing import TYPE_CHECKING, NamedTuple +from typing import TYPE_CHECKING, NamedTuple, NoReturn from multidict import CIMultiDict @@ -53,6 +53,7 @@ class StreamWriter(AbstractStreamWriter): chunked: bool = False _eof: bool = False _compress: ZLibCompressor | None = None + _compress_cancelled: bool = False def __init__( self, @@ -85,6 +86,19 @@ def enable_compression( ) -> None: self._compress = ZLibCompressor(encoding=encoding, strategy=strategy) + def _raise_compress_cancelled(self) -> NoReturn: + # The executor can't be interrupted, so the compressor may have + # consumed a chunk whose output was dropped. Nothing written after + # that would decompress, so the message can't be completed. Callers + # that let the cancellation propagate close the connection themselves; + # this is only reached by one that carried on. + transport = self._protocol.transport + if transport is not None: + transport.close() + raise ClientConnectionResetError( + "Cannot write after a compressed write was cancelled" + ) + def _write( self, chunk: "bytes | bytearray | memoryview[int] | memoryview[bytes]" ) -> None: @@ -183,7 +197,13 @@ async def write( body_size = len(chunk) if notify is not None else 0 if self._compress is not None: - chunk = await self._compress.compress(chunk) + if self._compress_cancelled: + self._raise_compress_cancelled() + try: + chunk = await self._compress.compress(chunk) + except asyncio.CancelledError: + self._compress_cancelled = True + raise if not chunk: if notify is not None and body_size: notify(body_size, self.output_size) @@ -280,11 +300,19 @@ async def write_eof(self, chunk: bytes = b"") -> None: # Handle body/compression if self._compress: + if self._compress_cancelled: + self._raise_compress_cancelled() chunks: list[bytes] = [] chunks_len = 0 - if chunk and (compressed_chunk := await self._compress.compress(chunk)): - chunks_len = len(compressed_chunk) - chunks.append(compressed_chunk) + if chunk: + try: + compressed_chunk = await self._compress.compress(chunk) + except asyncio.CancelledError: + self._compress_cancelled = True + raise + if compressed_chunk: + chunks_len = len(compressed_chunk) + chunks.append(compressed_chunk) flush_chunk = self._compress.flush() chunks_len += len(flush_chunk) diff --git a/tests/test_http_writer.py b/tests/test_http_writer.py index fb7b85ab415..e4380e43e84 100644 --- a/tests/test_http_writer.py +++ b/tests/test_http_writer.py @@ -3,6 +3,7 @@ import asyncio import zlib from collections.abc import Callable, Generator, Iterable +from concurrent.futures import ThreadPoolExecutor from typing import Any from unittest import mock @@ -709,6 +710,60 @@ async def test_write_payload_deflate_compression_chunked_connection_lost_all_zli await msg.write_eof(b"end") +@pytest.mark.parametrize("cancelled", ("write", "write_eof")) +@pytest.mark.parametrize("retried", ("write", "write_eof")) +async def test_compressed_write_cancelled( + cancelled: str, + retried: str, + buf: bytearray, + protocol: BaseProtocol, + transport: asyncio.Transport, + slow_executor: ThreadPoolExecutor, +) -> None: + """Cancelling compress() loses its output, so the message must not continue.""" + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) + msg.enable_compression("deflate") + msg.enable_chunking() + assert msg._compress is not None + msg._compress._executor = slow_executor + + with pytest.raises(TimeoutError): + async with asyncio.timeout(0): + await getattr(msg, cancelled)(b"data" * 4096) + + assert not transport.close.called # type: ignore[attr-defined] + with pytest.raises( + ClientConnectionResetError, match="compressed write was cancelled" + ): + await getattr(msg, retried)(b"data") + transport.close.assert_called_once_with() # type: ignore[attr-defined] + assert not buf + + +async def test_compressed_write_cancelled_connection_lost( + buf: bytearray, + protocol: BaseProtocol, + transport: asyncio.Transport, + slow_executor: ThreadPoolExecutor, +) -> None: + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) + msg.enable_compression("deflate") + assert msg._compress is not None + msg._compress._executor = slow_executor + + with pytest.raises(TimeoutError): + async with asyncio.timeout(0): + await msg.write(b"data" * 4096) + + protocol.transport = None + with pytest.raises( + ClientConnectionResetError, match="compressed write was cancelled" + ): + await msg.write_eof() + assert not transport.close.called # type: ignore[attr-defined] + assert not buf + + async def test_write_payload_bytes_memoryview( buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: diff --git a/tests/test_web_server.py b/tests/test_web_server.py index 06efc6e5c05..2be1dc0dfe9 100644 --- a/tests/test_web_server.py +++ b/tests/test_web_server.py @@ -1,6 +1,8 @@ import asyncio import gc +import os import socket +from concurrent.futures import ThreadPoolExecutor from contextlib import suppress from typing import Any, NoReturn from unittest import mock @@ -9,6 +11,7 @@ from pytest_aiohttp import AiohttpClient, AiohttpRawServer, AiohttpServer from aiohttp import client, web +from aiohttp.http import StreamWriter from aiohttp.http_exceptions import BadStatusLine @@ -208,6 +211,51 @@ async def handler(request: web.BaseRequest) -> MyResponse: logger.debug.assert_called_with("Ignored premature client disconnection") +@pytest.mark.parametrize("keeps_writing", (True, False)) +async def test_compressed_write_cancelled_in_handler( + keeps_writing: bool, + aiohttp_client: AiohttpClient, + slow_executor: ThreadPoolExecutor, +) -> None: + transports: list[asyncio.Transport | None] = [] + + async def handler(request: web.Request) -> web.StreamResponse: + transports.append(request.transport) + resp = web.StreamResponse() + resp.enable_compression(web.ContentCoding.gzip) + writer = await resp.prepare(request) + assert isinstance(writer, StreamWriter) + assert writer._compress is not None + writer._compress._executor = slow_executor + with suppress(TimeoutError): + async with asyncio.timeout(0): + await resp.write(os.urandom(65536)) + if keeps_writing: + with suppress(ConnectionResetError): + await resp.write(b"more") + return resp + + async def ping(request: web.Request) -> web.Response: + transports.append(request.transport) + return web.Response() + + app = web.Application() + app.router.add_get("/", handler) + app.router.add_get("/ping", ping) + # Without decompression a corrupt body would be read without complaint. + cli = await aiohttp_client(app, auto_decompress=False) + + async with cli.get("/") as resp: + assert resp.status == 200 + with pytest.raises(client.ClientPayloadError): + await resp.read() + async with cli.get("/ping") as resp: + assert resp.status == 200 + + cancelled, reconnected = transports + assert cancelled is not reconnected + + async def test_raw_server_not_http_exception_debug( aiohttp_raw_server: AiohttpRawServer, aiohttp_client: AiohttpClient ) -> None: