Skip to content

Threat model chapter 5 - #13098

Open
Dreamsorcerer wants to merge 7 commits into
masterfrom
threat-model5
Open

Dreamsorcerer wants to merge 7 commits into
masterfrom
threat-model5

Conversation

@Dreamsorcerer

Copy link
Copy Markdown
Member

No description provided.

@Dreamsorcerer Dreamsorcerer added bot:chronographer:skip This PR does not need to include a change note backport-3.15 Trigger automatic backporting to the 3.15 release branch by Patchback robot labels Jul 8, 2026
@codecov

codecov Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.13%. Comparing base (b5acd43) to head (832c9f3).
✅ All tests successful. No failed tests found.

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           
Flag Coverage Δ
Autobahn 21.53% <ø> (ø)
CI-GHA 99.06% <ø> (ø)
OS-Linux 98.75% <ø> (ø)
OS-Windows 97.53% <ø> (+<0.01%) ⬆️
OS-macOS 98.38% <ø> (+0.01%) ⬆️
Py-3.11 98.31% <ø> (ø)
Py-3.12 98.40% <ø> (+<0.01%) ⬆️
Py-3.13 98.39% <ø> (ø)
Py-3.14 98.45% <ø> (+<0.01%) ⬆️
Py-3.15 98.45% <ø> (ø)
Py-3.15t 98.30% <ø> (+<0.01%) ⬆️
Py-pypy-3.12 97.00% <ø> (+<0.01%) ⬆️
VM-macos-latest 98.38% <ø> (+0.01%) ⬆️
VM-ubuntu-latest 98.75% <ø> (ø)
VM-windows-latest 97.53% <ø> (+<0.01%) ⬆️
cython-coverage 84.04% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

@codspeed

codspeed Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

1 warning

⚠️ 49 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 102 untouched benchmarks
⏩ 83 skipped benchmarks1


Comparing threat-model5 (832c9f3) with master (b5acd43)

Open in CodSpeed

Footnotes

  1. 83 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@Dreamsorcerer

Copy link
Copy Markdown
Member Author

@aiolibsbot review

@aiolibsbot

aiolibsbot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

Comment thread THREAT_MODEL.md Resolved
@aiolibsbot

This comment was marked as resolved.

@aiolibsbot

aiolibsbot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@Dreamsorcerer

Copy link
Copy Markdown
Member Author

@aiolibsbot review

@greptile-apps

greptile-apps Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 Tier: apexRetriggerView in Greptile

[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

Comment thread THREAT_MODEL.md Resolved
Comment thread THREAT_MODEL.md Outdated
| 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. |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Member limit resets mid-step

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.

View artifacts

T-Rex Ran code and verified through T-Rex

Comment thread THREAT_MODEL.md Resolved
@aiolibsbot

This comment was marked as resolved.

Comment thread THREAT_MODEL.md Resolved
Comment thread THREAT_MODEL.md Resolved
@greptile-apps

greptile-apps Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

security Security Review

This PR appears safe to merge from a security standpoint.

What was checked
  • This PR only adds documentation to THREAT_MODEL.md and does not change any code, config, or dependency, so nothing that affects who can access what is touched.
  • The new chapter mentions only public CVE and GHSA advisory identifiers and internal function names; it contains no secrets, credentials, or internal endpoints.

Comment thread THREAT_MODEL.md Resolved
Comment thread THREAT_MODEL.md
| :--- | :--- | :--- | :--- |
| 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. |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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

Comment thread THREAT_MODEL.md
| 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. |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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:

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport-3.15 Trigger automatic backporting to the 3.15 release branch by Patchback robot bot:chronographer:skip This PR does not need to include a change note

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants