Repository navigation
Threat model chapter 5 - #13098
Threat model chapter 5#13098Dreamsorcerer wants to merge 7 commits into
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #13098 +/- ##
=======================================
Coverage 99.13% 99.13%
=======================================
Files 135 135
Lines 54630 54630
Branches 2808 2808
=======================================
Hits 54158 54158
Misses 357 357
Partials 115 115
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
Merging this PR will not alter performance1 warning
Comparing Footnotes
|
|
@aiolibsbot review |
|
|
This comment was marked as resolved.
This comment was marked as resolved.
|
|
|
@aiolibsbot review |
Confidence Score: 5/5
[Low impact] This docs-only PR appears safe to merge, but its descriptions of compression safeguards need correction. Reviews (2) · Last reviewed commit: "Merge branch 'master' into threat-model5" · Reviewed by Greptile |
| | 5.3 | Cancellation hazard | Comments in `compress()` (`compression_utils.py:ZLibCompressor.compress`) note that cancelling mid-call corrupts compressor state. For WebSocket (`WebSocketWriter.send_frame`), where the compressor persists across frames for context takeover, small frames compress synchronously under `_send_lock` with no await before the write; large frames run compress + flush + write in `_send_compressed_frame_async_locked` as a task under `asyncio.shield`, taking the lock inside it, so a cancelled caller cannot interrupt the sequence. For HTTP (`StreamWriter.write` / `write_eof`, `MultipartPayloadWriter.write`, `Response._do_start_compression`), where there is no lock, the compressor is per message (`StreamWriter` is built per request in `RequestHandler.start` and `ClientRequest._create_writer`, `MultipartPayloadWriter` per part, `_do_start_compression` uses a local single-use object), `StreamWriter` itself does not await between `compress()` returning and the transport write (`drain()` comes after), and both cancellation exits close the connection (`ClientRequest.write_bytes` → `conn.close()`, `RequestHandler.start` → `force_close()`), so a corrupted compressor is never seen by a later message on the same keep-alive connection. | **User**: do not cancel an in-flight `StreamResponse.write()` on a compressed response (e.g. under `asyncio.wait_for`) and then keep writing to it — the executor-side `compress()` cannot be un-run, so the stream is missing that chunk; close the response instead. | | ||
| | 5.4 | Trailing data | Members after the first are handed to a fresh decompressor (`ConcatDecompressionHandler._decompress_members`), which is the RFC 1952 §2.2 / RFC 8878 §3.1.1 reading of the stream. Bytes that cannot start a member, and a CRC / length mismatch on any member, raise in the backend and surface as `ContentEncodingError` (`DeflateBuffer.feed_data`). Stream completion is only verified for `deflate`: `DeflateBuffer.feed_eof` raises there when the stream is not at `eof`, but a gzip member truncated before its trailer, a trailing partial member / zstd frame, or a truncated brotli / zstd stream is accepted silently (brotli and zstd withhold output until a block completes, so a truncated stream can arrive as an empty body), and `BodyPartReader._decode_content` has no completion check for any encoding. The short-tail edge cases are backend-dependent (5.2). Brotli has no member concatenation; any trailing byte after a complete stream raises. | **Verify stream completion at EOF for every codec, not just `deflate`: `DeflateBuffer.feed_eof` and `BodyPartReader._decode_content` should raise `ContentEncodingError` when the input ends mid-member. The codecs need a "complete" property that survives the gzip / zstd boundary reset (a fresh decompressor that has been fed nothing is complete; one that has been fed is not until `eof`).** **User**: an intermediary that inspects compressed bodies in front of aiohttp must decode every member, not just the first. | | ||
| | 5.5 | Error disclosure | Generic message; no internal state. | None. | | ||
| | 5.6 | Member flood | `ConcatDecompressionHandler._decompress_members` feeds each member through a window that starts at `MEMBER_WINDOW_MIN` (64 B) and doubles up to `MEMBER_WINDOW_MAX` (64 KiB), so a boundary doesn't copy the whole remaining input into `unused_data`, and raises `TooManyMembersError` past `MAX_DECOMPRESS_MEMBERS` (1024) members in one call. The per-call `max_length` budget spans members, with the unread remainder carried to the next call in `_pending_unused_data`. The cap is per `decompress_sync` call, i.e. per input chunk, which is what bounds one event-loop step; it is not a per-stream total. | None. | |
There was a problem hiding this comment.
The 1,024-member limit applies to each decompression call, not each event-loop step. The HTTP parser can call the decompressor again with empty input without yielding: one parser call decoded 3,000 concatenated members through seven decompression calls. Please remove the claim that this limit bounds one step; it could lead maintainers to overlook work that keeps other connections waiting.
Knowledge Base Used: Cookies, compression, and utility primitives
Artifacts
Authored parser reproduction script
- The executed script feeds identical concatenated gzip input through the repository parser under two output budgets, making the synchronous retry behavior observable.
Parser run with unlimited output budget
- The captured command, working directory, exit code, and output show the 3000-member input rejected on its first decompressor call.
Parser run with default output budget
- The captured command, working directory, exit code, and output show one parser call completing all 3000 members through seven decompressor calls.
This comment was marked as resolved.
This comment was marked as resolved.
| | :--- | :--- | :--- | :--- | | ||
| | 5.1 | Decompression bomb | All decompressors accept a `max_length` parameter and refuse to produce more than that many bytes per call. Per-stream caps are applied by callers (`HttpPayloadParser` in [§5.6](#56-streams--payloads), `BodyPartReader` in [§5.4](#54-multipart-parsing--encoding), `WebSocketReader` in [§5.3](#53-websocket-framing--per-message-deflate)), each with their own bound. Some backends (notably `isal_zlib`) can overshoot `max_length` by a single zlib block before the next call rejects further data. | Maintain regression tests for every backend. The post-decompress per-stream cap (caller-side) is the load-bearing defence; codec-level `max_length` is best-effort. | | ||
| | 5.2 | Backend swap | `ZLibDecompressor.data_available` and its `_last_empty` flag work around isal's lack of "no further data" detection. The wrapper's signatures (`ZLibCompressObjProtocol` / `ZLibDecompressObjProtocol` in `compression_utils.py`) define the protocol any alternative backend must satisfy. `tests/test_compression_utils.py` runs the compress / decompress round trips under `zlib`, `zlib_ng` and `isal_zlib`, but not the multi-member tests, and `isal_zlib` already diverges there: it rejects a bad gzip header only once all 10 header bytes have arrived, where `zlib` rejects at the 2-byte magic, and it swallows up to six trailing bytes after a raw-deflate member, so a second member that short is silently dropped. | **Expand the docstrings on `ZLibBackendProtocol` / `ZLibCompressObjProtocol` / `ZLibDecompressObjProtocol` to spell out (a) the strict `max_length` output contract, (b) the "no further data" detection convention aiohttp relies on to terminate the decompress loop, (c) the `eof` / `unused_data` member-boundary contract `ConcatDecompressionHandler` relies on, and (d) that new backends must be gated behind the same regression suite as `zlib` / `isal_zlib`. Parametrise the multi-member tests over `parametrize_zlib_backend`.** | | ||
| | 5.3 | Cancellation hazard | Comments in `compress()` (`compression_utils.py:ZLibCompressor.compress`) note that cancelling mid-call corrupts compressor state. For WebSocket (`WebSocketWriter.send_frame`), where the compressor persists across frames for context takeover, small frames compress synchronously under `_send_lock` with no await before the write; large frames run compress + flush + write in `_send_compressed_frame_async_locked` as a task under `asyncio.shield`, taking the lock inside it, so a cancelled caller cannot interrupt the sequence. For HTTP (`StreamWriter.write` / `write_eof`, `MultipartPayloadWriter.write`, `Response._do_start_compression`), where there is no lock, the compressor is per message (`StreamWriter` is built per request in `RequestHandler.start` and `ClientRequest._create_writer`, `MultipartPayloadWriter` per part, `_do_start_compression` uses a local single-use object), `StreamWriter` itself does not await between `compress()` returning and the transport write (`drain()` comes after), and a writer that loses compressed output to cancellation refuses every later write (StreamWriter also closes the transport), so nothing from a corrupted compressor gets sent. | None. | |
There was a problem hiding this comment.
Cancelled multipart writes can continue
The HTTP cancellation safeguard described here does not cover MultipartPayloadWriter. If a custom part catches a timeout during a compressed write and keeps writing, the compressor may have advanced without sending its output. MultipartPayloadWriter does not reject later writes or close the transport, and it can flush a corrupt part. Qualify this path rather than saying every writer refuses later writes.
Knowledge Base Used: Cookies, compression, and utility primitives
| | 5.1 | Decompression bomb | All decompressors accept a `max_length` parameter and refuse to produce more than that many bytes per call. Per-stream caps are applied by callers (`HttpPayloadParser` in [§5.6](#56-streams--payloads), `BodyPartReader` in [§5.4](#54-multipart-parsing--encoding), `WebSocketReader` in [§5.3](#53-websocket-framing--per-message-deflate)), each with their own bound. Some backends (notably `isal_zlib`) can overshoot `max_length` by a single zlib block before the next call rejects further data. | Maintain regression tests for every backend. The post-decompress per-stream cap (caller-side) is the load-bearing defence; codec-level `max_length` is best-effort. | | ||
| | 5.2 | Backend swap | `ZLibDecompressor.data_available` and its `_last_empty` flag work around isal's lack of "no further data" detection. The wrapper's signatures (`ZLibCompressObjProtocol` / `ZLibDecompressObjProtocol` in `compression_utils.py`) define the protocol any alternative backend must satisfy. `tests/test_compression_utils.py` runs the compress / decompress round trips under `zlib`, `zlib_ng` and `isal_zlib`, but not the multi-member tests, and `isal_zlib` already diverges there: it rejects a bad gzip header only once all 10 header bytes have arrived, where `zlib` rejects at the 2-byte magic, and it swallows up to six trailing bytes after a raw-deflate member, so a second member that short is silently dropped. | **Expand the docstrings on `ZLibBackendProtocol` / `ZLibCompressObjProtocol` / `ZLibDecompressObjProtocol` to spell out (a) the strict `max_length` output contract, (b) the "no further data" detection convention aiohttp relies on to terminate the decompress loop, (c) the `eof` / `unused_data` member-boundary contract `ConcatDecompressionHandler` relies on, and (d) that new backends must be gated behind the same regression suite as `zlib` / `isal_zlib`. Parametrise the multi-member tests over `parametrize_zlib_backend`.** | | ||
| | 5.3 | Cancellation hazard | Comments in `compress()` (`compression_utils.py:ZLibCompressor.compress`) note that cancelling mid-call corrupts compressor state. For WebSocket (`WebSocketWriter.send_frame`), where the compressor persists across frames for context takeover, small frames compress synchronously under `_send_lock` with no await before the write; large frames run compress + flush + write in `_send_compressed_frame_async_locked` as a task under `asyncio.shield`, taking the lock inside it, so a cancelled caller cannot interrupt the sequence. For HTTP (`StreamWriter.write` / `write_eof`, `MultipartPayloadWriter.write`, `Response._do_start_compression`), where there is no lock, the compressor is per message (`StreamWriter` is built per request in `RequestHandler.start` and `ClientRequest._create_writer`, `MultipartPayloadWriter` per part, `_do_start_compression` uses a local single-use object), `StreamWriter` itself does not await between `compress()` returning and the transport write (`drain()` comes after), and a writer that loses compressed output to cancellation refuses every later write (StreamWriter also closes the transport), so nothing from a corrupted compressor gets sent. | None. | | ||
| | 5.4 | Trailing data | Members after the first are handed to a fresh decompressor (`ConcatDecompressionHandler._decompress_members`), which is the RFC 1952 §2.2 / RFC 8878 §3.1.1 reading of the stream. Bytes that cannot start a member, and a CRC / length mismatch on any member, raise in the backend and surface as `ContentEncodingError` (`DeflateBuffer.feed_data`). Stream completion is only verified for `deflate`: `DeflateBuffer.feed_eof` raises there when the stream is not at `eof`, but a gzip member truncated before its trailer, a trailing partial member / zstd frame, or a truncated brotli / zstd stream is accepted silently (brotli and zstd withhold output until a block completes, so a truncated stream can arrive as an empty body), and `BodyPartReader._decode_content` has no completion check for any encoding. The short-tail edge cases are backend-dependent (5.2). Brotli has no member concatenation; any trailing byte after a complete stream raises. | **Verify stream completion at EOF for every codec, not just `deflate`: `DeflateBuffer.feed_eof` and `BodyPartReader._decode_content` should raise `ContentEncodingError` when the input ends mid-member. The codecs need a "complete" property that survives the gzip / zstd boundary reset (a fresh decompressor that has been fed nothing is complete; one that has been fed is not until `eof`).** **User**: an intermediary that inspects compressed bodies in front of aiohttp must decode every member, not just the first. | |
There was a problem hiding this comment.
Truncated HTTP streams already fail
The chapter says only deflate is checked at the end of an HTTP body. DeflateBuffer.feed_eof() already checks stream_complete for every decoding stage, including gzip, Brotli, and zstd, and tests expect truncated streams to raise an error. Remove the claim that HTTP accepts these bodies and the recommendation to add that check. The separate multipart limitation can remain.
Knowledge Base Used:
No description provided.