Skip to contentSkip to conversation

python3-aiohttp: fix CVEs (2026-11-25)

PATCH New Ashishkumar Parmar X (asparmar - E INFOCHIPS PRIVATE LIMITED at Cisco) 1 participant 11 messages Nov 25

lore
Share & tools
lore
#0 lore raw

cover python3-aiohttp: fix CVEs (2026-11-25)

From: Ashishkumar Parmar <[email protected]>

Backport the upstream security fixes for python3-aiohttp on Wrynose without upgrading the package or its dependencies.

The series carries the CVE-2026-123817 fragment-retention fix and the fixes for CVE-2026-128124 through CVE-2026-128129 and CVE-2026-128132. They address domain matching, cookie and form limits, multipart base64 reads, and WebSocket size limits and flow control.

The existing CVE-2026-54273_p2.patch already backports the fix that upstream identifies for CVE-2026-128130 [1]. Patch 10 adds the second CVE ID to that patch's metadata so cve-check credits the existing fix; no second source patch is needed.

CVE-2026-128131 concerns concatenated-member decompression code absent from the current sources and recipe patches. Patch 8 records this with not-applicable-config, which maps to vulnerableCodeNotPresent.

[1] https://github.com/aio-libs/aiohttp/security/advisories/GHSA-28qf-cpwq-vmc2

Ashishkumar Parmar (10):
python3-aiohttp: fix CVE-2026-123817
python3-aiohttp: fix CVE-2026-128124
python3-aiohttp: fix CVE-2026-128125
python3-aiohttp: fix CVE-2026-128126
python3-aiohttp: fix CVE-2026-128127
python3-aiohttp: fix CVE-2026-128128
python3-aiohttp: fix CVE-2026-128129
python3-aiohttp: ignore CVE-2026-128131
python3-aiohttp: fix CVE-2026-128132
python3-aiohttp: mark CVE-2026-128130 patched

 .../python3-aiohttp/CVE-2026-123817_p1.patch  |  120 +
 .../python3-aiohttp/CVE-2026-123817_p2.patch  |  317 ++
 .../python3-aiohttp/CVE-2026-128124.patch     |  118 +
 .../python3-aiohttp/CVE-2026-128125.patch     | 3115 +++++++++++++++++
 .../python3-aiohttp/CVE-2026-128126.patch     |  599 ++++
 .../python3-aiohttp/CVE-2026-128127.patch     |  291 ++
 .../python3-aiohttp/CVE-2026-128128.patch     |  206 ++
 .../python3-aiohttp/CVE-2026-128129.patch     |  677 ++++
 .../python3-aiohttp/CVE-2026-128132.patch     | 1242 +++++++
 .../python3-aiohttp/CVE-2026-54273_p2.patch   |    2 +-
 .../python/python3-aiohttp_3.13.5.bb          |   17 +
 11 files changed, 6703 insertions(+), 1 deletion(-)
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-123817_p1.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-123817_p2.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128124.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128125.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128126.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128127.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128128.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128129.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128132.patch
Signature · 1 line
2.35.6
#1 lore raw

PATCH 1/10 python3-aiohttp: fix CVE-2026-123817

From: Ashishkumar Parmar <[email protected]>

This patch applies the upstream 3.14 backport for CVE-2026-123817. The fragment cap fix [1] and its follow-up [2] bound retained read objects without pausing an incomplete WebSocket frame. The public CVE advisory is referenced in [3].

Regenerate the compiled WebSocket reader from the patched source so the accelerated implementation receives the fix as well.

[1] https://github.com/aio-libs/aiohttp/commit/09bcaa73ff084a0c539bbf16a0a78743acb7141f
[2] https://github.com/aio-libs/aiohttp/commit/6a4f6682817839313b04b8e5cea2b39c1a88ab4f
[3] https://github.com/aio-libs/aiohttp/security/advisories/GHSA-2g87-pp6c-29x5

---
 .../python3-aiohttp/CVE-2026-123817_p1.patch  | 120 +++++++
 .../python3-aiohttp/CVE-2026-123817_p2.patch  | 317 ++++++++++++++++++
 .../python/python3-aiohttp_3.13.5.bb          |   9 +
 3 files changed, 446 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-123817_p1.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-123817_p2.patch
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-123817_p1.patch new file +120 -0
new file mode 100644
index 0000000000..607bbb8312
@@ -0,0 +1,120 @@
+From 56fdb8bc54ff8882eeb6950fb5899959df4dd865 Mon Sep 17 00:00:00 2001
+From: Sam Bull <[email protected]>
+Date: Sat, 8 Aug 2026 22:39:27 +0100
+Subject: [PATCH] Limit number of queued WS fragments (#13352) (#13355)
+
+(cherry picked from commit 288cf469ba800a071fcddca61434d6ab9dcf689d)
+
+CVE: CVE-2026-123817
+Upstream-Status: Backport [https://github.com/aio-libs/aiohttp/commit/09bcaa73ff084a0c539bbf16a0a78743acb7141f]
+
+Backport Changes:
+- Omit the unavailable decode_text test-constructor argument.
+
+Signed-off-by: Ashishkumar Parmar <[email protected]>
+---
+ CHANGES/13352.bugfix.rst        |  1 +
+ aiohttp/_websocket/reader_c.pxd |  1 +
+ aiohttp/_websocket/reader_py.py |  9 +++++++
+ tests/test_websocket_parser.py  | 44 +++++++++++++++++++++++++++++++++
+ 4 files changed, 55 insertions(+)
+ create mode 100644 CHANGES/13352.bugfix.rst
+
+diff --git a/CHANGES/13352.bugfix.rst b/CHANGES/13352.bugfix.rst
+new file mode 100644
+index 0000000..a10a0d7
+--- /dev/null
++++ b/CHANGES/13352.bugfix.rst
+@@ -0,0 +1 @@
++Capped the number of per-read payload fragments the WebSocket reader retains in memory -- by :user:`Dreamsorcerer`.
+diff --git a/aiohttp/_websocket/reader_c.pxd b/aiohttp/_websocket/reader_c.pxd
+index a7620d8..7f676c9 100644
+--- a/aiohttp/_websocket/reader_c.pxd
++++ b/aiohttp/_websocket/reader_c.pxd
+@@ -69,6 +69,7 @@ cdef class WebSocketReader:
+     cdef bint _frame_fin
+     cdef int _frame_opcode
+     cdef list _payload_fragments
++    cdef Py_ssize_t _max_fragments
+     cdef Py_ssize_t _frame_payload_len
+ 
+     cdef bytes _tail
+diff --git a/aiohttp/_websocket/reader_py.py b/aiohttp/_websocket/reader_py.py
+index 16c5f3b..27f1fee 100644
+--- a/aiohttp/_websocket/reader_py.py
++++ b/aiohttp/_websocket/reader_py.py
+@@ -145,6 +145,9 @@ class WebSocketReader:
+         self._frame_fin = False
+         self._frame_opcode: int = OP_CODE_NOT_SET
+         self._payload_fragments: list[bytes] = []
++        # Limit number of fragments, so a large number of tiny fragments
++        # doesn't exceed reasonable memory usage.
++        self._max_fragments = max(1024, max_msg_size // 256) if max_msg_size else 0
+         self._frame_payload_len = 0
+ 
+         self._tail: bytes = b""
+@@ -457,6 +460,12 @@ class WebSocketReader:
+                     # If we don't have a complete frame, we need to save the
+                     # data for the next call to feed_data.
+                     self._payload_fragments.append(data_cstr[f_start_pos:f_end_pos])
++                    if (
++                        self._max_fragments
++                        and len(self._payload_fragments) > self._max_fragments
++                        and not self.queue._protocol._reading_paused
++                    ):
++                        self.queue._protocol.pause_reading()
+                     break
+ 
+                 payload: Union[bytes, bytearray]
+diff --git a/tests/test_websocket_parser.py b/tests/test_websocket_parser.py
+index 3a283e0..5589bd3 100644
+--- a/tests/test_websocket_parser.py
++++ b/tests/test_websocket_parser.py
+@@ -756,3 +756,47 @@ def test_flow_control_multi_byte_text(
+         large_payload_size,
+     )
+     assert protocol._reading_paused is True
++
++
++async def test_incomplete_frame_pauses_when_fragment_limit_exceeded(
++    protocol: BaseProtocol,
++) -> None:
++    max_msg_size = 64 * 1024
++    loop = asyncio.get_running_loop()
++    out = WebSocketDataQueue(protocol, 2**16, loop=loop)
++    parser = WebSocketReader(out, max_msg_size, compress=False)
++
++    payload_len = 32 * 1024
++    parser.feed_data(PACK_LEN2(0x80 | WSMsgType.BINARY, 126, payload_len))
++    assert protocol._reading_paused is False
++
++    # Feed the payload two bytes per read so the pause is
++    # driven purely by the fragment count, not the total byte count.
++    paused_after = None
++    for i in range(payload_len // 2 - 1):  # pragma: no branch
++        parser.feed_data(b"xx")
++        if protocol._reading_paused:
++            paused_after = i + 1  # type: ignore[unreachable]
++            break
++
++    assert paused_after is not None
++    # Paused long before the frame could complete (16384 two-byte reads).
++    assert paused_after < payload_len // 2  # type: ignore[unreachable]
++
++
++async def test_incomplete_frame_not_paused_for_normal_reads(
++    protocol: BaseProtocol,
++) -> None:
++    max_msg_size = 64 * 1024
++    loop = asyncio.get_running_loop()
++    out = WebSocketDataQueue(protocol, 2**16, loop=loop)
++    parser = WebSocketReader(out, max_msg_size, compress=False)
++
++    # Normal traffic (a frame delivered in a handful of reasonably sized reads)
++    # must never trip the fragment-limit backpressure.
++    payload_len = 32 * 1024
++    parser.feed_data(PACK_LEN2(0x80 | WSMsgType.BINARY, 126, payload_len))
++    # 32 KiB in 4 KiB reads -> 8 fragments, far below the cap.
++    for _ in range(payload_len // 4096):
++        parser.feed_data(b"x" * 4096)
++    assert protocol._reading_paused is False
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-123817_p2.patch new file +317 -0

317 lines not on this page · raw message

meta-python/recipes-devtools/python/python3-aiohttp_3.13.5.bb +9 -0
index 98fd4bdba3..619d2c6658 100644
@@ -32,6 +32,8 @@ SRC_URI += " \
     file://CVE-2026-111063_p1.patch \
     file://CVE-2026-111063_p2.patch \
     file://CVE-2026-111064.patch \
+    file://CVE-2026-123817_p1.patch \
+    file://CVE-2026-123817_p2.patch \
 "
 
 CVE_PRODUCT = "aiohttp:aiohttp"
@@ -50,6 +52,13 @@ do_configure:prepend() {
         -I ${S}/aiohttp \
         -o ${S}/aiohttp/_http_parser.c \
         ${S}/aiohttp/_http_parser.pyx
+
+    cp ${S}/aiohttp/_websocket/reader_py.py \
+        ${S}/aiohttp/_websocket/reader_c.py
+    cython3 -3 -Werror \
+        -I ${S}/aiohttp \
+        -o ${S}/aiohttp/_websocket/reader_c.c \
+        ${S}/aiohttp/_websocket/reader_c.py
 }
 
 PACKAGECONFIG ??= ""
Signature · 1 line
2.35.6
#2 lore raw

PATCH 2/10 python3-aiohttp: fix CVE-2026-128124

In reply to Ashishkumar Parmar X (asparmar - E INFOCHIPS PRIVATE LIMITED at Cisco)

From: Ashishkumar Parmar <[email protected]>

This patch applies the wildcard domain matching fix for CVE-2026-128124 from the upstream stable branch [1].

The translated domain mask avoids pathological wildcard matching while preserving the current Host matching rules.

[1] https://github.com/aio-libs/aiohttp/commit/c6ac0e44c3c573ff9616f4a6a532992538b31e43
[2] https://github.com/aio-libs/aiohttp/security/advisories/GHSA-jm3w-gw2p-xjfj

---
 .../python3-aiohttp/CVE-2026-128124.patch     | 118 ++++++++++++++++++
 .../python/python3-aiohttp_3.13.5.bb          |   1 +
 2 files changed, 119 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128124.patch
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128124.patch new file +118 -0
new file mode 100644
index 0000000000..33e2f6ba36
@@ -0,0 +1,118 @@
+From 406a4349e838b03f4c4ce4955203a0b762fa9bb3 Mon Sep 17 00:00:00 2001
+From: Sam Bull <[email protected]>
+Date: Mon, 5 Oct 2026 00:34:47 +0100
+Subject: [PATCH] Improve performance of domain matching (#13943) (#13945)
+
+(cherry picked from commit 766b882820da0651c84090e366a3b024b4a263c9)
+
+CVE: CVE-2026-128124
+Upstream-Status: Backport [https://github.com/aio-libs/aiohttp/commit/c6ac0e44c3c573ff9616f4a6a532992538b31e43]
+
+Backport Changes:
+- Apply fnmatch translation to the existing full domain mask and retain
+  the existing canonical pattern and case-sensitive Host matching.
+  The upstream change follows port-handling commit 1577756e9170, which
+  is absent here; importing that behavior is unnecessary for this fix.
+- Omit the port-dependent regression cases, retaining the wildcard
+  matching cases and benchmark. Add checks for the existing Host rules.
+
+Signed-off-by: Ashishkumar Parmar <[email protected]>
+---
+ CHANGES/13943.bugfix.rst                   |  1 +
+ aiohttp/web_urldispatcher.py               |  7 ++++---
+ tests/test_benchmarks_web_urldispatcher.py | 16 ++++++++++++++++
+ tests/test_urldispatch.py                  | 14 ++++++++++++++
+ 4 files changed, 35 insertions(+), 3 deletions(-)
+ create mode 100644 CHANGES/13943.bugfix.rst
+
+diff --git a/CHANGES/13943.bugfix.rst b/CHANGES/13943.bugfix.rst
+new file mode 100644
+index 0000000..d565849
+--- /dev/null
++++ b/CHANGES/13943.bugfix.rst
+@@ -0,0 +1 @@
++Improved performance in domain matching with ``Application.add_domain()`` -- by :user:`Dreamsorcerer`.
+diff --git a/aiohttp/web_urldispatcher.py b/aiohttp/web_urldispatcher.py
+index 48465b5..5893f59 100644
+--- a/aiohttp/web_urldispatcher.py
++++ b/aiohttp/web_urldispatcher.py
+@@ -1,6 +1,7 @@
+ import abc
+ import asyncio
+ import base64
++import fnmatch
+ import functools
+ import hashlib
+ import html
+@@ -866,12 +867,12 @@ class MaskDomain(Domain):
+ 
+     def __init__(self, domain: str) -> None:
+         super().__init__(domain)
+-        mask = self._domain.replace(".", r"\.").replace("*", ".*")
+-        self._mask = re.compile(mask)
++        self._pattern = self._domain.replace(".", r"\.").replace("*", ".*")
++        self._mask = re.compile(fnmatch.translate(self._domain))
+ 
+     @property
+     def canonical(self) -> str:
+-        return self._mask.pattern
++        return self._pattern
+ 
+     def match_domain(self, host: str) -> bool:
+         return self._mask.fullmatch(host) is not None
+diff --git a/tests/test_benchmarks_web_urldispatcher.py b/tests/test_benchmarks_web_urldispatcher.py
+index 936ed63..b4b86b1 100644
+--- a/tests/test_benchmarks_web_urldispatcher.py
++++ b/tests/test_benchmarks_web_urldispatcher.py
+@@ -17,6 +17,7 @@ from yarl import URL
+ import aiohttp
+ from aiohttp import web
+ from aiohttp.http import HttpVersion, RawRequestMessage
++from aiohttp.web_urldispatcher import MaskDomain
+ 
+ 
+ @pytest.fixture
+@@ -573,3 +574,18 @@ def test_resolve_prefix_resources_many_prefix_many_plain(
+     @benchmark
+     def _run() -> None:
+         loop.run_until_complete(run_url_dispatcher_benchmark())
++
++
++def test_match_domain_wildcards_long_host(benchmark: BenchmarkFixture) -> None:
++    """Match a two-wildcard domain rule against the longest possible Host header."""
++    rule = MaskDomain("*.*.example.com")
++    # llhttp caps a Host header at max_field_size - len("Host") bytes, and a
++    # dotted host is the worst case for a wildcard rule.
++    host = ("a." * 4093)[:8186]
++
++    assert rule.match_domain(host) is False
++
++    @benchmark
++    def _run() -> None:
++        for _ in range(100):
++            rule.match_domain(host)
+diff --git a/tests/test_urldispatch.py b/tests/test_urldispatch.py
+index e329ea2..6cf8507 100644
+--- a/tests/test_urldispatch.py
++++ b/tests/test_urldispatch.py
+@@ -1120,6 +1120,20 @@ def test_domain_valid():
+         ("*.example.com", "jpg.example.com", True),
+         ("*.example.com", "a.example.com", True),
+         ("*.example.com", "example.com", False),
++        # A wildcard spans labels.
++        ("*.example.com", "a.b.example.com", True),
++        ("*.example.com", ".example.com", True),
++        ("*", "a:b", True),
++        # Several wildcards, including adjacent and infix ones.
++        ("*.*.example.com", "a.b.example.com", True),
++        ("*.*.example.com", "a.example.com", False),
++        ("**.example.com", "a.example.com", True),
++        ("a*b.example.com", "axxb.example.com", True),
++        ("x*x.example.com", "x.example.com", False),
++        # Preserve the existing case-sensitive, full-Host matching rules.
++        ("*.example.com", "A.EXAMPLE.COM", False),
++        ("*.example.com", "a.example.com:8080", False),
++        ("*.example.com", "a:b.example.com", True),
+     ],
+ )
+ def test_match_domain(a, b, result):
meta-python/recipes-devtools/python/python3-aiohttp_3.13.5.bb +1 -0
index 619d2c6658..293d15fdaa 100644
@@ -34,6 +34,7 @@ SRC_URI += " \
     file://CVE-2026-111064.patch \
     file://CVE-2026-123817_p1.patch \
     file://CVE-2026-123817_p2.patch \
+    file://CVE-2026-128124.patch \
 "
 
 CVE_PRODUCT = "aiohttp:aiohttp"
Signature · 1 line
2.35.6
#3 lore raw

PATCH 3/10 python3-aiohttp: fix CVE-2026-128125

In reply to Ashishkumar Parmar X (asparmar - E INFOCHIPS PRIVATE LIMITED at Cisco)

From: Ashishkumar Parmar <[email protected]>

This patch applies the client cookie resource limits for CVE-2026-128125 from the upstream stable branch [1].

Limit parsed response cookies, retained cookies and outgoing Cookie headers while preserving explicit per-request cookies.

The embedded backport notes describe the required prerequisite or follow-up changes and the adaptations to the current APIs.

[1] https://github.com/aio-libs/aiohttp/commit/6963ee0befec1502b6bb7b4db6c72d044c08f4fa
[2] https://github.com/aio-libs/aiohttp/commit/f1750ba2cd59ece20932c57e6096f878c2d29aa6
[3] https://github.com/aio-libs/aiohttp/commit/f2c0280fe7d9857378add2619abd4661b1b13e1c
[4] https://github.com/aio-libs/aiohttp/security/advisories/GHSA-5pv8-vvhc-h7jv

---
 .../python3-aiohttp/CVE-2026-128125.patch     | 3115 +++++++++++++++++
 .../python/python3-aiohttp_3.13.5.bb          |    1 +
 2 files changed, 3116 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128125.patch
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128125.patch new file +3115 -0
new file mode 100644
index 0000000000..c564ba70ab
@@ -0,0 +1,3115 @@
+From 180406642ba5a1fb8db7637e7e21b3b398e117e9 Mon Sep 17 00:00:00 2001
+From: "J. Nick Koston" <[email protected]>
+Date: Sun, 4 Oct 2026 16:03:11 -0500
+Subject: [PATCH] [PR #13930/b1f6c87b backport][3.14] Add limits for client
+ cookie handling (#13942)
+
+Fixes
+#123
+
+CVE: CVE-2026-128125
+Upstream-Status: Backport [https://github.com/aio-libs/aiohttp/commit/6963ee0befec1502b6bb7b4db6c72d044c08f4fa]
+
+Backport Changes:
+- Rebase the cookie storage changes onto the current source context.
+- Fold the private update helper and defensive Morsel copying from
+  https://github.com/aio-libs/aiohttp/commit/f1750ba2cd59ece20932c57e6096f878c2d29aa6.
+  The helper carries absolute expiry and trusted-parser validation through
+  loading and insertion without changing the public API. Private copies
+  keep caller mutation from invalidating checked cookie state and cached
+  lengths used by the limits.
+- Preserve the current per-request jar constructor arguments while using
+  the unlimited jar for explicit request cookies.
+- Adapt regressions to the current ClientResponse constructor and private
+  host-only cookie metadata. Omit the cookies-view regression because that
+  public property is absent. Keep the prerequisite's ownership regressions
+  and normalized-copy expectations.
+- Use the printable-octal fixtures in tests/test_cookie_helpers.py from
+  https://github.com/aio-libs/aiohttp/commit/f2c0280fe7d9857378add2619abd4661b1b13e1c.
+  The existing fixtures expect acceptance of decoded control characters,
+  which the fixed parser rejects.
+- Omit the async conversions for
+  test_save_creates_private_cookie_file and
+  test_save_preserves_existing_cookie_file_permissions in
+  tests/test_cookiejar.py because these tests are absent.
+- Omit release notes, contributor and reference-documentation updates.
+  Retain the security regressions and temporary-jar benchmark adjustment.
+
+Co-authored-by: iamibi <[email protected]>
+Co-authored-by: Sam Bull <[email protected]>
+Signed-off-by: Ashishkumar Parmar <[email protected]>
+---
+ aiohttp/_cookie_helpers.py         |  254 ++++---
+ aiohttp/client.py                  |    4 +-
+ aiohttp/cookiejar.py               |  445 ++++++++++--
+ tests/test_benchmarks_cookiejar.py |    4 +-
+ tests/test_client_functional.py    |  127 ++++
+ tests/test_client_response.py      |   26 +
+ tests/test_cookie_helpers.py       |  524 +++++++++-----
+ tests/test_cookiejar.py            | 1042 +++++++++++++++++++++++++++-
+ 8 files changed, 2077 insertions(+), 349 deletions(-)
+
+diff --git a/aiohttp/_cookie_helpers.py b/aiohttp/_cookie_helpers.py
+index 10e2e0e..3ec0d40 100644
+--- a/aiohttp/_cookie_helpers.py
++++ b/aiohttp/_cookie_helpers.py
+@@ -6,8 +6,8 @@ These are not part of the public API and may change without notice.
+ """
+ 
+ import re
+-from http.cookies import Morsel
+-from typing import List, Optional, Sequence, Tuple, cast
++from http.cookies import CookieError, Morsel
++from typing import List, Sequence, Tuple
+ 
+ from .log import internal_logger
+ 
+@@ -43,6 +43,18 @@ _COOKIE_BOOL_ATTRS = frozenset(  # AKA Morsel._flags
+     ("secure", "httponly", "partitioned")
+ )
+ 
++# Implementation limits as permitted by RFC 6265 Section 6.1.
++_MAX_COOKIES_PER_RESPONSE = 50
++_MAX_COOKIE_PAIR_LENGTH = 4096
++_MAX_COOKIE_ATTRIBUTE_VALUE_LENGTH = 1024
++# Like Chromium's ParsedCookie::kMaxPairs, but more lenient.
++_MAX_COOKIE_ATTRIBUTES = 32
++
++# Where the next attribute can start: skips runs of ";" and whitespace.
++_ATTRIBUTE_START_RE = re.compile(r"[^;\s]", re.ASCII)
++_COOKIE_FORBIDDEN_CTL_RE = re.compile(r"[\x00-\x08\x0a-\x1f\x7f]")
++_COOKIE_CTL_RE = re.compile(r"[\x00-\x1f\x7f]")
++
+ # SimpleCookie's pattern for parsing cookies with relaxed validation
+ # Based on http.cookies pattern but extended to allow more characters in cookie names
+ # to handle real-world cookies (fixes #2683)
+@@ -100,7 +112,9 @@ def preserve_morsel_with_coded_value(cookie: Morsel[str]) -> Morsel[str]:
+         A Morsel object with preserved coded_value
+ 
+     """
+-    mrsl_val = cast("Morsel[str]", cookie.get(cookie.key, Morsel()))
++    # Don't look up cookie.key in the Morsel: it maps attribute names, so a
++    # cookie named ``path`` would return the Path attribute.
++    mrsl_val: Morsel[str] = Morsel()
+     # We use __setstate__ instead of the public set() API because it allows us to
+     # bypass validation and set already validated state. This is more stable than
+     # setting protected attributes directly and unlikely to change since it would
+@@ -164,10 +178,9 @@ def parse_cookie_header(header: str) -> List[Tuple[str, Morsel[str]]]:
+     There are no attributes in Cookie headers - even names that match
+     attribute names (like 'path' or 'secure') should be treated as cookies.
+ 
+-    This parser uses the same regex-based approach as parse_set_cookie_headers
+-    to properly handle quoted values that may contain semicolons. When the
+-    regex fails to match a malformed cookie, it falls back to simple parsing
+-    to ensure subsequent cookies are not lost
++    This parser uses _COOKIE_PATTERN to properly handle quoted values that may
++    contain semicolons. When the regex fails to match a malformed cookie, it
++    falls back to simple parsing to ensure subsequent cookies are not lost
+     https://github.com/aio-libs/aiohttp/issues/11632
+ 
+     Args:
+@@ -186,7 +199,7 @@ def parse_cookie_header(header: str) -> List[Tuple[str, Morsel[str]]]:
+ 
+     invalid_names = []
+     while i < n:
+-        # Use the same pattern as parse_set_cookie_headers to find cookies
++        # Find the next cookie-pair
+         match = _COOKIE_PATTERN.match(header, i)
+         if not match:
+             # Fallback for malformed cookies https://github.com/aio-libs/aiohttp/issues/11632
+@@ -244,95 +257,152 @@ def parse_cookie_header(header: str) -> List[Tuple[str, Morsel[str]]]:
+     return cookies
+ 
+ 
+-def parse_set_cookie_headers(headers: Sequence[str]) -> List[Tuple[str, Morsel[str]]]:
++def _encoded_length(text: str) -> int | None:
++    """Return the UTF-8 length of text, or None if it can't be encoded."""
++    if text.isascii():
++        return len(text)
++    try:
++        return len(text.encode("utf-8"))
++    except UnicodeEncodeError:
++        return None
++
++
++def _apply_cookie_attributes(morsel: Morsel[str], attributes: str) -> None:
++    """Set the recognized attributes from the text after the cookie-pair.
++
++    The field must already be free of control characters other than tab.
++    """
++    # Walk with the cookie pattern so a quoted value keeps its ";". Missing
++    # semicolons between attributes are tolerated; every match is an attribute
++    # of this cookie, never a new cookie.
++    index = 0
++    end = len(attributes)
++    for _ in range(_MAX_COOKIE_ATTRIBUTES):
++        if index >= end:
++            break
++        if (attribute_match := _COOKIE_PATTERN.match(attributes, index)) is None:
++            # Skip a malformed segment and any run of ";" or whitespace after it.
++            if (
++                not (next_index := attributes.find(";", index) + 1)
++                or (start := _ATTRIBUTE_START_RE.search(attributes, next_index)) is None
++            ):
++                break
++            index = start.start()
++            continue
++        index = attribute_match.end()
++        lower_key = attribute_match.group("key").lower()
++        if lower_key not in _COOKIE_KNOWN_ATTRS:
++            # RFC 6265 Section 5.2: ignore unknown attributes.
++            continue
++        if lower_key not in morsel._reserved:  # type: ignore[attr-defined]
++            # Python versions before 3.14 do not expose Partitioned.
++            continue
++
++        # The key and value are checked here, so skip Morsel.__setitem__'s checks.
++        if lower_key in _COOKIE_BOOL_ATTRS:
++            # Like Firefox, a flag's value is ignored.
++            dict.__setitem__(morsel, lower_key, True)
++            continue
++        attr_value = attribute_match.group("val") or ""
++        if (
++            len(attr_value) <= _MAX_COOKIE_ATTRIBUTE_VALUE_LENGTH
++            and attr_value.isascii()
++            and attr_value[:1] != '"'
++            and "\t" not in attr_value
++        ):
++            # The field has no other control characters and nothing to unquote.
++            dict.__setitem__(morsel, lower_key, attr_value)
++            continue
++        attr_value_length = _encoded_length(attr_value)
++        if (
++            attr_value_length is None
++            or attr_value_length > _MAX_COOKIE_ATTRIBUTE_VALUE_LENGTH
++        ):
++            continue
++        # Patched CPython rejects control characters, even ones produced by
++        # unquoting, so ignore such an attribute rather than raise.
++        if _COOKIE_CTL_RE.search(value := _unquote(attr_value)) is None:
++            dict.__setitem__(morsel, lower_key, value)
++
++
++def _parse_quoted_pair(header: str) -> tuple[str, str, int] | None:
++    """Parse a first pair whose quoted value contains ";".
++
++    aiohttp has always accepted these. Returns the name, the quoted value and
++    where the attributes start, or None to split at the first ";" instead.
+     """
+-    Parse cookie headers using a vendored version of SimpleCookie parsing.
+-
+-    This implementation is based on SimpleCookie.__parse_string to ensure
+-    compatibility with how SimpleCookie parses cookies, including handling
+-    of malformed cookies with missing semicolons.
+-
+-    This function is used for both Cookie and Set-Cookie headers in order to be
+-    forgiving. Ideally we would have followed RFC 6265 Section 5.2 (for Cookie
+-    headers) and RFC 6265 Section 4.2.1 (for Set-Cookie headers), but the
+-    real world data makes it impossible since we need to be a bit more forgiving.
+-
+-    NOTE: This implementation differs from SimpleCookie in handling unmatched quotes.
+-    SimpleCookie will stop parsing when it encounters a cookie value with an unmatched
+-    quote (e.g., 'cookie="value'), causing subsequent cookies to be silently dropped.
+-    This implementation handles unmatched quotes more gracefully to prevent cookie loss.
+-    See https://github.com/aio-libs/aiohttp/issues/7993
++    match = _COOKIE_PATTERN.match(header)
++    if match is None or not (value := match.group("val")):
++        return None
++    if not (value.startswith('"') and value.endswith('"') and ";" in value):
++        return None
++    tail = header[match.end("val") :].lstrip(" \t")
++    if tail and not tail.startswith(";"):
++        return None
++    return match.group("key"), value, len(header) - len(tail) + bool(tail)
++
++
++def parse_set_cookie_headers(headers: Sequence[str]) -> list[tuple[str, Morsel[str]]]:
++    """Parse Set-Cookie fields into at most one cookie per field.
++
++    Fields with control characters, oversized or nameless pairs, names outside
++    the allowlist, or tabs in the pair are skipped.
+     """
+-    parsed_cookies: List[Tuple[str, Morsel[str]]] = []
++    parsed_cookies: list[tuple[str, Morsel[str]]] = []
++    over_limit = 0
++
++    for position, header in enumerate(headers):
++        if len(parsed_cookies) >= _MAX_COOKIES_PER_RESPONSE:
++            over_limit = len(headers) - position
++            break
++        if not header or _COOKIE_FORBIDDEN_CTL_RE.search(header) is not None:
++            continue
+ 
+-    for header in headers:
+-        if not header:
++        if (pair_end := header.find(";")) == -1:
++            pair_end = attributes_start = len(header)
++        else:
++            attributes_start = pair_end + 1
++        # A quote before the first ";" may start a quoted value containing ";".
++        if header.find('"', 0, pair_end) != -1 and (
++            quoted := _parse_quoted_pair(header)
++        ):
++            key, coded_value, attributes_start = quoted
++        else:
++            key, sep, coded_value = header[:pair_end].partition("=")
++            if not sep:
++                continue
++
++        key = key.strip(" \t")
++        coded_value = coded_value.strip(" \t")
++
++        if not key:
++            continue
++        if not _COOKIE_NAME_RE.match(key):
++            internal_logger.warning("Can not load cookies: Illegal cookie name %r", key)
++            continue
++        pair_length = _encoded_length(key + coded_value)
++        if pair_length is None or pair_length > _MAX_COOKIE_PAIR_LENGTH:
+             continue
+ 
+-        # Parse cookie string using SimpleCookie's algorithm
+-        i = 0
+-        n = len(header)
+-        current_morsel: Optional[Morsel[str]] = None
+-        morsel_seen = False
+-
+-        while 0 <= i < n:
+-            # Start looking for a cookie
+-            match = _COOKIE_PATTERN.match(header, i)
+-            if not match:
+-                # No more cookies
+-                break
++        value = _unquote(coded_value)
++        if _COOKIE_CTL_RE.search(value) is not None:
++            continue
++        morsel: Morsel[str] = Morsel()
++        try:
++            morsel.__setstate__(  # type: ignore[attr-defined]
++                {"key": key, "value": value, "coded_value": coded_value}
++            )
++        except CookieError:
++            continue
+ 
+-            key, value = match.group("key"), match.group("val")
+-            i = match.end(0)
+-            lower_key = key.lower()
+-
+-            if key[0] == "$":
+-                if not morsel_seen:
+-                    # We ignore attributes which pertain to the cookie
+-                    # mechanism as a whole, such as "$Version".
+-                    continue
+-                # Process as attribute
+-                if current_morsel is not None:
+-                    attr_lower_key = lower_key[1:]
+-                    if attr_lower_key in _COOKIE_KNOWN_ATTRS:
+-                        current_morsel[attr_lower_key] = value or ""
+-            elif lower_key in _COOKIE_KNOWN_ATTRS:
+-                if not morsel_seen:
+-                    # Invalid cookie string - attribute before cookie
+-                    break
+-                if lower_key in _COOKIE_BOOL_ATTRS:
+-                    # Boolean attribute with any value should be True
+-                    if current_morsel is not None and current_morsel.isReservedKey(key):
+-                        current_morsel[lower_key] = True
+-                elif value is None:
+-                    # Invalid cookie string - non-boolean attribute without value
+-                    break
+-                elif current_morsel is not None:
+-                    # Regular attribute with value
+-                    current_morsel[lower_key] = _unquote(value)
+-            elif value is not None:
+-                # This is a cookie name=value pair
+-                # Validate the name
+-                if key in _COOKIE_KNOWN_ATTRS or not _COOKIE_NAME_RE.match(key):
+-                    internal_logger.warning(
+-                        "Can not load cookies: Illegal cookie name %r", key
+-                    )
+-                    current_morsel = None
+-                else:
+-                    # Create new morsel
+-                    current_morsel = Morsel()
+-                    # Preserve the original value as coded_value (with quotes if present)
+-                    # We use __setstate__ instead of the public set() API because it allows us to
+-                    # bypass validation and set already validated state. This is more stable than
+-                    # setting protected attributes directly and unlikely to change since it would
+-                    # break pickling.
+-                    current_morsel.__setstate__(  # type: ignore[attr-defined]
+-                        {"key": key, "value": _unquote(value), "coded_value": value}
+-                    )
+-                    parsed_cookies.append((key, current_morsel))
+-                    morsel_seen = True
+-            else:
+-                # Invalid cookie string - no value for non-attribute
+-                break
++        _apply_cookie_attributes(morsel, header[attributes_start:])
++        parsed_cookies.append((key, morsel))
+ 
++    if (invalid := len(headers) - over_limit - len(parsed_cookies)) or over_limit:
++        internal_logger.debug(
++            "Ignored %d invalid Set-Cookie field(s) and %d over the %d-cookie limit",
++            invalid,
++            over_limit,
++            _MAX_COOKIES_PER_RESPONSE,
++        )
+     return parsed_cookies
+diff --git a/aiohttp/client.py b/aiohttp/client.py
+index 1eae60a..fafc5d3 100644
+--- a/aiohttp/client.py
++++ b/aiohttp/client.py
+@@ -91,7 +91,7 @@ from .connector import (
+     TCPConnector as TCPConnector,
+     UnixConnector as UnixConnector,
+ )
+-from .cookiejar import CookieJar
++from .cookiejar import CookieJar, _UnlimitedCookieJar
+ from .helpers import (
+     _SENTINEL,
+     DEBUG,
+@@ -691,7 +691,7 @@ class ClientSession:
+                     all_cookies = self._cookie_jar.filter_cookies(url)
+ 
+                     if cookies is not None:
+-                        tmp_cookie_jar = CookieJar(
++                        tmp_cookie_jar = _UnlimitedCookieJar(
+                             quote_cookie=self._cookie_jar.quote_cookie,
+                             treat_as_secure_origin=frozenset(
+                                 self._cookie_jar.treat_as_secure_origin
+diff --git a/aiohttp/cookiejar.py b/aiohttp/cookiejar.py
+index 3b2c490..f8e89df 100644
+--- a/aiohttp/cookiejar.py
++++ b/aiohttp/cookiejar.py
+@@ -5,6 +5,7 @@ import datetime
+ import heapq
+ import itertools
+ import json
++import math
+ import os  # noqa
+ import pathlib
+ import pickle
+@@ -12,31 +13,40 @@ import re
+ import time
+ import warnings
+ from collections import defaultdict
+-from collections.abc import Mapping
++from collections.abc import Mapping, Sequence
+ from http.cookies import BaseCookie, Morsel, SimpleCookie
+ from typing import (
+-    DefaultDict,
+-    Dict,
+     Iterable,
+     Iterator,
+     List,
+     Optional,
+-    Set,
+     Tuple,
+     Union,
++    cast,
+ )
+ 
+ from yarl import URL
+ 
+-from ._cookie_helpers import preserve_morsel_with_coded_value
++from ._cookie_helpers import (
++    _COOKIE_CTL_RE,
++    _encoded_length,
++    parse_set_cookie_headers,
++    preserve_morsel_with_coded_value,
++)
+ from .abc import AbstractCookieJar, ClearCookiePredicate
+ from .helpers import is_ip_address
++from .log import internal_logger
+ from .typedefs import LooseCookies, PathLike, StrOrURL
+ 
+ __all__ = ("CookieJar", "DummyCookieJar")
+ 
+ 
+ CookieItem = Union[str, "Morsel[str]"]
++_JarKey = tuple[str, str]  # (domain, path)
++_CookieKey = tuple[str, str, str]  # (domain, path, name)
++# A built morsel, its encoded name=value length and the cookie's key.
++_MorselEntry = tuple["Morsel[str]", int, _CookieKey]
++_UNLIMITED_COOKIE_KEY: _CookieKey = ("", "", "")
+ 
+ # We cache these string methods here as their use is in performance critical code.
+ _FORMAT_PATH = "{}/{}".format
+@@ -48,6 +58,16 @@ _FORMAT_DOMAIN_REVERSED = "{1}.{0}".format
+ _MIN_SCHEDULED_COOKIE_EXPIRATION = 100
+ _SIMPLE_COOKIE = SimpleCookie()
+ 
++# Private, non-configurable limits for the built-in jar.
++# Eviction follows Firefox's CookieStorage.
++_MAX_COOKIES_PER_DOMAIN = 180
++_COOKIE_QUOTA_PER_DOMAIN = 150
++_MAX_COOKIES_TOTAL = 3300
++_COOKIE_QUOTA_TOTAL = 3000
++_MAX_COOKIES_PER_REQUEST = 150
++_MAX_COOKIE_HEADER_LENGTH = 8190
++_COOKIE_HEADER_PREFIX_LENGTH = len(b"Cookie: ")
++
+ # Not persisted; the absolute deadline is saved instead.
+ _RELATIVE_EXPIRY_ATTRS = frozenset(("max-age", "expires"))
+ 
+@@ -90,6 +110,8 @@ class _RestrictedCookieUnpickler(pickle.Unpickler):
+ class CookieJar(AbstractCookieJar):
+     """Implements cookie storage adhering to RFC 6265."""
+ 
++    _limits_enabled = True
++
+     DATE_TOKENS_RE = re.compile(
+         r"[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]*"
+         r"(?P<token>[\x00-\x08\x0A-\x1F\d:a-zA-Z\x7F-\xFF]+)"
+@@ -133,14 +155,12 @@ class CookieJar(AbstractCookieJar):
+         loop: Optional[asyncio.AbstractEventLoop] = None,
+     ) -> None:
+         super().__init__(loop=loop)
+-        self._cookies: DefaultDict[Tuple[str, str], SimpleCookie] = defaultdict(
+-            SimpleCookie
+-        )
+-        self._morsel_cache: DefaultDict[Tuple[str, str], Dict[str, Morsel[str]]] = (
+-            defaultdict(dict)
++        self._cookies: defaultdict[_JarKey, SimpleCookie] = defaultdict(SimpleCookie)
++        self._morsel_cache: defaultdict[_JarKey, dict[str, _MorselEntry]] = defaultdict(
++            dict
+         )
+         # Cookie identity is (domain, path, name).
+-        self._host_only_cookies: Set[Tuple[str, str, str]] = set()
++        self._host_only_cookies: set[_CookieKey] = set()
+         self._unsafe = unsafe
+         self._quote_cookie = quote_cookie
+         if treat_as_secure_origin is None:
+@@ -158,8 +178,12 @@ class CookieJar(AbstractCookieJar):
+                     for url in treat_as_secure_origin
+                 }
+             )
+-        self._expire_heap: List[Tuple[float, Tuple[str, str, str]]] = []
+-        self._expirations: Dict[Tuple[str, str, str], float] = {}
++        self._expire_heap: list[tuple[float, _CookieKey]] = []
++        self._expirations: dict[_CookieKey, float] = {}
++        self._access_generations: dict[_CookieKey, int] = {}
++        self._next_access_generation = 0
++        self._domain_counts: dict[str, int] = {}
++        self._cookie_count = 0
+ 
+     @property
+     def quote_cookie(self) -> bool:
+@@ -211,30 +235,69 @@ class CookieJar(AbstractCookieJar):
+         compatibility with existing cookie files.
+ 
+         Replaces the current jar contents; loaded cookies pass through the
+-        same acceptance rules as :meth:`update_cookies`.
++        same acceptance rules as :meth:`update_cookies`. A malformed file
++        raises and leaves the jar unchanged.
+ 
+         :param file_path: Path to file from where cookies will be
+             imported, :class:`str` or :class:`pathlib.Path` instance.
+         """
+         file_path = pathlib.Path(file_path)
+-        # Try JSON format first
++        # Try JSON format first; only a file that isn't JSON is a legacy pickle.
+         try:
+             with file_path.open(mode="r", encoding="utf-8") as f:
+                 data = json.load(f)
+-            self._load_json_data(data)
+         except (json.JSONDecodeError, UnicodeDecodeError, ValueError):
+-            # Fall back to legacy pickle format with restricted unpickler
+-            with file_path.open(mode="rb") as f:
+-                self._cookies = _RestrictedCookieUnpickler(f).load()
++            pass
++        else:
++            self._load_json_data(data)
++            return
++        # Fall back to legacy pickle format with restricted unpickler
++        with file_path.open(mode="rb") as f:
++            pickled = _RestrictedCookieUnpickler(f).load()
++        loaded = self._new_loading_jar()
++        for (domain, _), cookies in pickled.items():
++            response_url = URL.build(scheme="https", host=domain) if domain else URL()
++            for name, morsel in cookies.items():
++                loaded._update_cookies({name: morsel}, response_url, copy_morsels=False)
++        self._replace_contents(loaded)
++
++    def _new_loading_jar(self) -> "CookieJar":
++        return CookieJar(
++            unsafe=self._unsafe,
++            quote_cookie=self._quote_cookie,
++            treat_as_secure_origin=self._treat_as_secure_origin,
++            loop=self._loop,
++        )
++
++    def _replace_contents(self, loaded: "CookieJar") -> None:
++        # Refill the existing mapping so views from the cookies property stay live.
++        cookies = self._cookies
++        cookies.clear()
++        cookies.update(loaded._cookies)
++        self.__dict__.update(loaded.__dict__)
++        self._cookies = cookies
+ 
+     def _load_json_data(
+         self, data: dict[str, dict[str, dict[str, str | bool | float]]]
+     ) -> None:
+-        """Replace contents, routing cookies through update_cookies()."""
+-        self.clear()
++        """Replace contents, routing cookies through _update_cookies()."""
++        # Fill a new jar and adopt its state only once every record is in,
++        # so a bad file leaves this one unchanged.
++        loaded = self._new_loading_jar()
+         for compound_key, cookie_data in data.items():
+             domain, path = compound_key.split("|", 1)
+             for name, morsel_data in cookie_data.items():
++                expiration: float | None = None
++                if (raw_expiration := morsel_data.get("expires_timestamp")) is not None:
++                    try:
++                        expiration = float(raw_expiration)
++                        if not math.isfinite(expiration):
++                            raise ValueError(expiration)
++                    except (OverflowError, TypeError, ValueError) as exc:
++                        raise ValueError(
++                            f"Cookie {name!r} in {compound_key!r}: "
++                            "expiration timestamp must be a finite number"
++                        ) from exc
+                 morsel: Morsel[str] = Morsel()
+                 # Use __setstate__ to bypass validation, same pattern
+                 # used in _build_morsel and _cookie_helpers.
+@@ -259,11 +322,13 @@ class CookieJar(AbstractCookieJar):
+                 response_url = (
+                     URL.build(scheme="https", host=domain) if domain else URL()
+                 )
+-                self.update_cookies({name: morsel}, response_url)
+-                # Restore the absolute deadline; update_cookies() schedules none.
+-                if (exp := morsel_data.get("expires_timestamp")) is not None:
+-                    self._expire_cookie(float(exp), domain, path, name)
+-        self._do_expiration()
++                loaded._update_cookies(
++                    {name: morsel},
++                    response_url,
++                    copy_morsels=False,
++                    expiration=expiration,
++                )
++        self._replace_contents(loaded)
+ 
+     def clear(self, predicate: Optional[ClearCookiePredicate] = None) -> None:
+         if predicate is None:
+@@ -272,6 +337,9 @@ class CookieJar(AbstractCookieJar):
+             self._morsel_cache.clear()
+             self._host_only_cookies.clear()
+             self._expirations.clear()
++            self._access_generations.clear()
++            self._domain_counts.clear()
++            self._cookie_count = 0
+             return
+ 
+         now = time.time()
+@@ -302,7 +370,7 @@ class CookieJar(AbstractCookieJar):
+         This function does not iterate self to avoid unnecessary expiration
+         checks.
+         """
+-        return sum(len(cookie.values()) for cookie in self._cookies.values())
++        return self._cookie_count
+ 
+     def _do_expiration(self) -> None:
+         """Remove expired cookies."""
+@@ -347,12 +415,80 @@ class CookieJar(AbstractCookieJar):
+         if to_del:
+             self._delete_cookies(to_del)
+ 
+-    def _delete_cookies(self, to_del: List[Tuple[str, str, str]]) -> None:
++    def _delete_cookies(self, to_del: list[_CookieKey]) -> None:
+         for domain, path, name in to_del:
+-            self._host_only_cookies.discard((domain, path, name))
+-            self._cookies[(domain, path)].pop(name, None)
+-            self._morsel_cache[(domain, path)].pop(name, None)
+-            self._expirations.pop((domain, path, name), None)
++            cookie_key = (domain, path, name)
++            jar_key = (domain, path)
++            self._host_only_cookies.discard(cookie_key)
++            if (cookies := self._cookies.get(jar_key)) is not None:
++                if cookies.pop(name, None) is not None:
++                    self._cookie_count -= 1
++                    if domain_count := self._domain_counts[domain] - 1:
++                        self._domain_counts[domain] = domain_count
++                    else:
++                        del self._domain_counts[domain]
++                if not cookies:
++                    del self._cookies[jar_key]
++            if (morsels := self._morsel_cache.get(jar_key)) is not None:
++                morsels.pop(name, None)
++                if not morsels:
++                    del self._morsel_cache[jar_key]
++            self._expirations.pop(cookie_key, None)
++            self._access_generations.pop(cookie_key, None)
++
++    def _make_room(self, domain: str, secure: bool) -> bool:
++        """Evict for a new cookie like Firefox; False drops the new cookie.
++
++        Mirrors AddCookie and FindStaleCookies: expired, then non-secure,
++        cookies go first, least recently used first; secure cookies are only
++        evicted for another secure cookie.
++        """
++        if self._domain_counts.get(domain, 0) >= _MAX_COOKIES_PER_DOMAIN:
++            self._do_expiration()
++            count = self._domain_counts.get(domain, 0)
++            # Leave room so the domain ends at its quota.
++            if (excess := count - _COOKIE_QUOTA_PER_DOMAIN + 1) <= 0:
++                return True
++            non_secure: list[tuple[int, _CookieKey]] = []
++            secure_keys: list[tuple[int, _CookieKey]] = []
++            for (cookie_domain, path), cookies in self._cookies.items():
++                if cookie_domain != domain:
++                    continue
++                for name, cookie in cookies.items():
++                    cookie_key = (domain, path, name)
++                    entry = (self._access_generations.get(cookie_key, 0), cookie_key)
++                    (secure_keys if cookie["secure"] else non_secure).append(entry)
++            if not (candidates := non_secure):
++                if count < _MAX_COOKIES_PER_DOMAIN:  # expiry freed a slot
++                    return True
++                if not secure:
++                    return False
++                candidates = secure_keys
++            candidates.sort()
++            evicted = candidates[:excess]
++            self._delete_cookies([key for _, key in evicted])
++            internal_logger.debug(
++                "Evicted %d cookie(s) for %s over the %d-cookie domain limit",
++                len(evicted),
++                domain,
++                _MAX_COOKIES_PER_DOMAIN,
++            )
++        else:
++            self._purge_cookies()
++        return True
++
++    def _purge_cookies(self) -> None:
++        """Evict expired, then least recently used, cookies down to the total."""
++        self._do_expiration()
++        if (excess := self._cookie_count - _COOKIE_QUOTA_TOTAL) <= 0:
++            return
++        generations = self._access_generations
++        self._delete_cookies(sorted(generations, key=generations.__getitem__)[:excess])
++        internal_logger.debug(
++            "Evicted %d cookie(s) over the %d-cookie total limit",
++            excess,
++            _MAX_COOKIES_TOTAL,
++        )
+ 
+     def _expire_cookie(self, when: float, domain: str, path: str, name: str) -> None:
+         cookie_key = (domain, path, name)
+@@ -364,6 +500,36 @@ class CookieJar(AbstractCookieJar):
+ 
+     def update_cookies(self, cookies: LooseCookies, response_url: URL = URL()) -> None:
+         """Update cookies."""
++        self._update_cookies(cookies, response_url, copy_morsels=True)
++
++    def update_cookies_from_headers(
++        self, headers: Sequence[str], response_url: URL
++    ) -> None:
++        """Update cookies from raw Set-Cookie headers."""
++        hostname = response_url.raw_host
++        if not self._unsafe and is_ip_address(hostname):
++            # Reject IP-origin cookies before parsing the fields.
++            return
++        if headers and (cookies_to_update := parse_set_cookie_headers(headers)):
++            # The freshly parsed Morsels are not shared with the caller,
++            # so they can be stored and normalized without a defensive copy.
++            # The parser only produces cookies that can be sent.
++            self._update_cookies(
++                cookies_to_update,
++                response_url,
++                copy_morsels=False,
++                check_sendable=False,
++            )
++
++    def _update_cookies(
++        self,
++        cookies: LooseCookies,
++        response_url: URL,
++        *,
++        copy_morsels: bool,
++        expiration: float | None = None,
++        check_sendable: bool = True,
++    ) -> None:
+         hostname = response_url.raw_host
+ 
+         if not self._unsafe and is_ip_address(hostname):
+@@ -378,6 +544,9 @@ class CookieJar(AbstractCookieJar):
+                 tmp = SimpleCookie()
+                 tmp[name] = cookie  # type: ignore[assignment]
+                 cookie = tmp[name]
++            elif copy_morsels:
++                # TODO(https://github.com/python/typeshed/pull/16346): Remove cast
++                cookie = cast("Morsel[str]", cookie.copy())
+ 
+             domain = cookie["domain"]
+ 
+@@ -408,41 +577,90 @@ class CookieJar(AbstractCookieJar):
+             path = path.rstrip("/")
+ 
+             if not domain and hostname is not None:
+-                self._host_only_cookies.add((hostname, path, name))
+-                domain = cookie["domain"] = hostname
++                host_only = True
++                domain = hostname
+             else:
+-                # A cookie with an explicit Domain attribute replaces any
+-                # host-only cookie with the same (domain, path, name) identity.
+-                self._host_only_cookies.discard((domain, path, name))
++                host_only = False
+ 
+-            if max_age := cookie["max-age"]:
++            deadline: float | None = None
++            if expiration is not None:
++                # Saved jars pass an absolute deadline.
++                deadline = expiration
++            elif max_age := cookie["max-age"]:
+                 try:
+                     delta_seconds = int(max_age)
+                     # https://datatracker.ietf.org/doc/html/rfc6265#section-5.2.2
+                     if delta_seconds <= 0:
+-                        max_age_expiration = 0.0
++                        deadline = 0.0
+                     else:
+                         # Cap first to protect against OverflowError on next line.
+                         delta_seconds = min(delta_seconds, self.MAX_TIME)
+-                        max_age_expiration = min(
+-                            time.time() + delta_seconds, self.MAX_TIME
+-                        )
+-                    self._expire_cookie(max_age_expiration, domain, path, name)
++                        deadline = min(time.time() + delta_seconds, self.MAX_TIME)
+                 except ValueError:
+                     cookie["max-age"] = ""
+ 
+             elif expires := cookie["expires"]:
+                 if expire_time := self._parse_date(expires):
+-                    self._expire_cookie(expire_time, domain, path, name)
++                    deadline = expire_time
+                 else:
+                     cookie["expires"] = ""
+ 
++            if check_sendable and self._limits_enabled and not self._can_send(cookie):
++                internal_logger.debug(
++                    "Dropped cookie %r for %s: it can't be sent in a Cookie header",
++                    name,
++                    domain,
++                )
++                continue
++
+             key = (domain, path)
+-            if self._cookies[key].get(name) != cookie:
++            cookie_key = (domain, path, name)
++            bucket = self._cookies.get(key)
++            stored = None if bucket is None else bucket.get(name)
++            if (
++                stored is None
++                and self._limits_enabled
++                and (
++                    self._domain_counts.get(domain, 0) >= _MAX_COOKIES_PER_DOMAIN
++                    or self._cookie_count >= _MAX_COOKIES_TOTAL
++                )
++                # Like Firefox, a cookie that only deletes never evicts others.
++                and (deadline is None or deadline > time.time())
++                and not self._make_room(domain, bool(cookie["secure"]))
++            ):
++                internal_logger.debug(
++                    "Dropped cookie %r for %s: its domain is full of Secure cookies",
++                    name,
++                    domain,
++                )
++                continue
++
++            if host_only:
++                self._host_only_cookies.add(cookie_key)
++                cookie["domain"] = domain
++            else:
++                # A cookie with an explicit Domain attribute replaces any
++                # host-only cookie with the same (domain, path, name) identity.
++                self._host_only_cookies.discard(cookie_key)
++            if deadline is not None:
++                self._expire_cookie(deadline, domain, path, name)
++            elif self._expirations:
++                # RFC 6265 5.3 step 11: a replacement doesn't inherit expiry.
++                self._expirations.pop(cookie_key, None)
++
++            if stored != cookie:
+                 # Don't blow away the cache if the same
+                 # cookie gets set again
++                if stored is None:
++                    self._cookie_count += 1
++                    self._domain_counts[domain] = self._domain_counts.get(domain, 0) + 1
+                 self._cookies[key][name] = cookie
+-                self._morsel_cache[key].pop(name, None)
++                if (morsels := self._morsel_cache.get(key)) is not None:
++                    morsels.pop(name, None)
++            if self._limits_enabled:
++                # Like Firefox, each stored cookie gets its own access time.
++                self._next_access_generation += 1
++                self._access_generations[cookie_key] = self._next_access_generation
+ 
+         self._do_expiration()
+ 
+@@ -476,31 +694,29 @@ class CookieJar(AbstractCookieJar):
+                 request_origin = request_url.origin()
+             is_not_secure = request_origin not in self._treat_as_secure_origin
+ 
++        # Last (most specific) matching cookie per name wins.
++        selected: dict[str, _MorselEntry] = {}
++
+         # Send shared cookie
+         key = ("", "")
+-        for c in self._cookies[key].values():
+-            if is_not_secure and c["secure"]:
+-                continue
+-
+-            # Check cache first
+-            if c.key in self._morsel_cache[key]:
+-                filtered[c.key] = self._morsel_cache[key][c.key]
+-                continue
+-
+-            # Build and cache the morsel
+-            mrsl_val = self._build_morsel(c)
+-            self._morsel_cache[key][c.key] = mrsl_val
+-            filtered[c.key] = mrsl_val
++        if key in self._cookies:
++            morsels = self._morsel_cache[key]
++            for name, cookie in self._cookies[key].items():
++                if is_not_secure and cookie["secure"]:
++                    continue
++                if (entry := morsels.get(name)) is None:
++                    entry = morsels[name] = self._morsel_entry(key, name, cookie)
++                selected[name] = entry
+ 
+-        if is_ip_address(hostname):
+-            if not self._unsafe:
+-                return filtered
+-            domains: Iterable[str] = (hostname,)
+-        else:
++        if not is_ip_address(hostname):
+             # Get all the subdomains that might match a cookie (e.g. "foo.bar.com", "bar.com", "com")
+-            domains = itertools.accumulate(
++            domains: Iterable[str] = itertools.accumulate(
+                 reversed(hostname.split(".")), _FORMAT_DOMAIN_REVERSED
+             )
++        elif self._unsafe:
++            domains = (hostname,)
++        else:
++            domains = ()
+ 
+         # Get all the path prefixes that might match a cookie (e.g. "", "/foo", "/foo/bar")
+         paths = itertools.accumulate(request_url.path.split("/"), _FORMAT_PATH)
+@@ -510,8 +726,9 @@ class CookieJar(AbstractCookieJar):
+         path_len = len(request_url.path)
+         # Point 2: https://www.rfc-editor.org/rfc/rfc6265.html#section-5.4
+         for p in pairs:
+-            if p not in self._cookies:
++            if p == ("", "") or p not in self._cookies:
+                 continue
++            morsels = self._morsel_cache[p]
+             for name, cookie in self._cookies[p].items():
+                 domain = cookie["domain"]
+ 
+@@ -525,18 +742,80 @@ class CookieJar(AbstractCookieJar):
+                 if is_not_secure and cookie["secure"]:
+                     continue
+ 
+-                # We already built the Morsel so reuse it here
+-                if name in self._morsel_cache[p]:
+-                    filtered[name] = self._morsel_cache[p][name]
+-                    continue
++                if (entry := morsels.get(name)) is None:
++                    entry = morsels[name] = self._morsel_entry(p, name, cookie)
++                # Re-insert so the order tracks specificity, for the header and
++                # the over-limit fallback.
++                selected.pop(name, None)
++                selected[name] = entry
++
++        if self._limits_enabled:
++            # Each cookie after the first adds a "; " separator.
++            header_length = _COOKIE_HEADER_PREFIX_LENGTH - 2 + 2 * len(selected)
++            header_length += sum(entry[1] for entry in selected.values())
++            if (
++                len(selected) > _MAX_COOKIES_PER_REQUEST
++                or header_length > _MAX_COOKIE_HEADER_LENGTH
++            ):
++                return self._filter_cookies_within_limits(selected, hostname)
++            self._touch_cookies([entry[2] for entry in selected.values()])
++        # Bypass BaseCookie.__setitem__, which stores Morsel values as-is.
++        dict.update(filtered, {name: entry[0] for name, entry in selected.items()})
++        return filtered
+ 
+-                # Build and cache the morsel
+-                mrsl_val = self._build_morsel(cookie)
+-                self._morsel_cache[p][name] = mrsl_val
+-                filtered[name] = mrsl_val
++    def _filter_cookies_within_limits(
++        self, selected: dict[str, _MorselEntry], hostname: str
++    ) -> "BaseCookie[str]":
++        """Admit the most specific cookies first so a host's own cookies win."""
++        header_length = _COOKIE_HEADER_PREFIX_LENGTH - 2  # no "; " before the first
++        admitted: list[tuple[str, _MorselEntry]] = []
++        for name, entry in reversed(selected.items()):
++            if len(admitted) >= _MAX_COOKIES_PER_REQUEST:
++                break
++            if header_length + 2 + entry[1] > _MAX_COOKIE_HEADER_LENGTH:
++                continue
++            header_length += 2 + entry[1]
++            admitted.append((name, entry))
+ 
++        filtered: BaseCookie[str] = BaseCookie()
++        for name, entry in reversed(admitted):
++            dict.__setitem__(filtered, name, entry[0])
++        self._touch_cookies([entry[2] for _, entry in admitted])
++        internal_logger.debug(
++            "Omitted %d cookie(s) for %s over the %d-cookie"
++            " or %d-octet Cookie header limit",
++            len(selected) - len(admitted),
++            hostname,
++            _MAX_COOKIES_PER_REQUEST,
++            _MAX_COOKIE_HEADER_LENGTH,
++        )
+         return filtered
+ 
++    @staticmethod
++    def _can_send(cookie: Morsel[str]) -> bool:
++        """Return whether the cookie can be written to a Cookie header."""
++        # Whichever of value and coded_value is sent, CPython builds with the
++        # CVE-2026-3644 patch also reject control characters in either.
++        text = f"{cookie.key}={cookie.value}{cookie.coded_value}"
++        return _COOKIE_CTL_RE.search(text) is None and _encoded_length(text) is not None
++
++    def _morsel_entry(
++        self, jar_key: _JarKey, name: str, cookie: Morsel[str]
++    ) -> _MorselEntry:
++        """Build the morsel to send with its length in the Cookie header."""
++        morsel = self._build_morsel(cookie)
++        length = _encoded_length(f"{morsel.key}={morsel.coded_value}")
++        assert length is not None  # Checked before storing.
++        return morsel, length, jar_key + (name,)
++
++    def _touch_cookies(self, cookie_keys: Sequence[_CookieKey]) -> None:
++        """Record one access generation for cookies used together, like Firefox."""
++        self._next_access_generation += 1
++        generation = self._next_access_generation
++        generations = self._access_generations
++        for cookie_key in cookie_keys:
++            generations[cookie_key] = generation
++
+     def _build_morsel(self, cookie: Morsel[str]) -> Morsel[str]:
+         """Build a morsel for sending, respecting quote_cookie setting."""
+         if self._quote_cookie and cookie.coded_value and cookie.coded_value[0] == '"':
+@@ -634,6 +913,19 @@ class CookieJar(AbstractCookieJar):
+         return calendar.timegm((year, month, day, hour, minute, second, -1, -1, -1))
+ 
+ 
++class _UnlimitedCookieJar(CookieJar):
++    """Jar for per-request cookies, which the jar limits don't apply to."""
++
++    _limits_enabled = False
++
++    def _morsel_entry(
++        self, jar_key: _JarKey, name: str, cookie: Morsel[str]
++    ) -> _MorselEntry:
++        # The length and LRU key only serve the limits. These cookies skip the
++        # storage check, so an unencodable one is left for the writer to report.
++        return self._build_morsel(cookie), 0, _UNLIMITED_COOKIE_KEY
++
++
+ class DummyCookieJar(AbstractCookieJar):
+     """Implements a dummy cookie storage.
+ 
+@@ -664,5 +956,10 @@ class DummyCookieJar(AbstractCookieJar):
+     def update_cookies(self, cookies: LooseCookies, response_url: URL = URL()) -> None:
+         pass
+ 
++    def update_cookies_from_headers(
++        self, headers: Sequence[str], response_url: URL
++    ) -> None:
++        """Ignore raw Set-Cookie fields without parsing them."""
++
+     def filter_cookies(self, request_url: URL) -> "BaseCookie[str]":
+         return SimpleCookie()
+diff --git a/tests/test_benchmarks_cookiejar.py b/tests/test_benchmarks_cookiejar.py
+index 7856615..f95e5f0 100644
+--- a/tests/test_benchmarks_cookiejar.py
++++ b/tests/test_benchmarks_cookiejar.py
+@@ -5,7 +5,7 @@ from http.cookies import BaseCookie
+ from pytest_codspeed import BenchmarkFixture
+ from yarl import URL
+ 
+-from aiohttp.cookiejar import CookieJar
++from aiohttp.cookiejar import CookieJar, _UnlimitedCookieJar
+ 
+ 
+ async def test_load_cookies_into_temp_cookiejar(benchmark: BenchmarkFixture) -> None:
+@@ -20,7 +20,7 @@ async def test_load_cookies_into_temp_cookiejar(benchmark: BenchmarkFixture) ->
+ 
+     @benchmark
+     def _run() -> None:
+-        tmp_cookie_jar = CookieJar()
++        tmp_cookie_jar = _UnlimitedCookieJar()
+         tmp_cookie_jar.update_cookies(cookies)
+         req_cookies = tmp_cookie_jar.filter_cookies(url)
+         all_cookies.load(req_cookies)
+diff --git a/tests/test_client_functional.py b/tests/test_client_functional.py
+index 7530ada..c2b14ee 100644
+--- a/tests/test_client_functional.py
++++ b/tests/test_client_functional.py
+@@ -62,6 +62,7 @@ from aiohttp.client_exceptions import (
+ from aiohttp.client_reqrep import ClientRequest
+ from aiohttp.compression_utils import DEFAULT_MAX_DECOMPRESS_SIZE
+ from aiohttp.connector import Connection
++from aiohttp.cookiejar import _MAX_COOKIES_PER_REQUEST
+ from aiohttp.http_exceptions import DecompressSizeError
+ from aiohttp.http_writer import StreamWriter
+ from aiohttp.payload import (
+@@ -1605,6 +1606,62 @@ async def test_HTTP_302_max_redirects(aiohttp_client) -> None:
+     assert ctx.value.request_info.method == "GET"
+ 
+ 
++async def test_redirect_cookie_storage_is_bounded(
++    aiohttp_client: AiohttpClient,
++) -> None:
++    """Large Set-Cookie fields across redirects keep jar and cache state bounded."""
++    redirect_count = 10
++    fields_per_response = 20
++    ignored_attribute = "x" * 7400
++    received_cookie_headers: list[str] = []
++
++    async def handler(request: web.Request) -> web.Response:
++        received_cookie_headers.append(request.headers.get(hdrs.COOKIE, ""))
++        count = int(request.match_info["count"])
++        if count:
++            response = web.Response(
++                status=302, headers={hdrs.LOCATION: f"/redirect/{count - 1}"}
++            )
++        else:
++            response = web.Response()
++        for index in range(fields_per_response):
++            response.headers.add(
++                hdrs.SET_COOKIE,
++                f"cookie{count}_{index}=value; junk={ignored_attribute}",
++            )
++        return response
++
++    app = web.Application()
++    app.router.add_get(r"/redirect/{count:\d+}", handler)
++    jar = aiohttp.CookieJar(unsafe=True)
++    client = await aiohttp_client(app, cookie_jar=jar)
++
++    async with client.get(
++        f"/redirect/{redirect_count}", max_redirects=redirect_count + 1
++    ) as response:
++        assert response.status == 200
++        assert len(response.history) == redirect_count
++        assert len(response.cookies) == fields_per_response
++        assert len(response.headers.getall(hdrs.SET_COOKIE)) == fields_per_response
++
++    response_bytes = (
++        (redirect_count + 1)
++        * fields_per_response
++        * len(f"Set-Cookie: cookie10_15=value; junk={ignored_attribute}".encode())
++    )
++    assert response_bytes > 1024 * 1024
++    max_cookies = aiohttp.cookiejar._MAX_COOKIES_PER_DOMAIN
++    assert redirect_count * fields_per_response > max_cookies
++    assert aiohttp.cookiejar._COOKIE_QUOTA_PER_DOMAIN < len(jar) <= max_cookies
++    assert sum(map(len, jar._morsel_cache.values())) <= max_cookies
++    assert all(
++        aiohttp.cookiejar._COOKIE_HEADER_PREFIX_LENGTH + len(value.encode())
++        <= aiohttp.cookiejar._MAX_COOKIE_HEADER_LENGTH
++        for value in received_cookie_headers
++        if value
++    )
++
++
+ async def test_HTTP_200_GET_WITH_PARAMS(aiohttp_client) -> None:
+     async def handler(request):
+         return web.Response(
+@@ -2785,6 +2842,76 @@ async def test_cookies_per_request(aiohttp_client) -> None:
+         assert 200 == resp.status
+ 
+ 
++async def test_per_request_cookies_are_not_jar_limited(
++    aiohttp_client: AiohttpClient,
++) -> None:
++    cookies = {f"cookie{i}": "value" for i in range(_MAX_COOKIES_PER_REQUEST + 1)}
++
++    async def handler(request: web.Request) -> web.Response:
++        assert request.cookies.keys() == cookies.keys()
++        return web.Response()
++
++    app = web.Application()
++    app.router.add_get("/", handler)
++    client = await aiohttp_client(app)
++
++    async with client.get("/", cookies=cookies) as response:
++        assert response.status == 200
++
++
++async def test_explicit_cookie_header_is_not_jar_limited(
++    aiohttp_client: AiohttpClient,
++) -> None:
++    count = _MAX_COOKIES_PER_REQUEST + 1
++    cookie_header = "; ".join(f"cookie{i}=value" for i in range(count))
++
++    async def handler(request: web.Request) -> web.Response:
++        assert request.headers[hdrs.COOKIE] == cookie_header
++        assert len(request.cookies) == count
++        return web.Response()
++
++    app = web.Application()
++    app.router.add_get("/", handler)
++    client = await aiohttp_client(app)
++
++    async with client.get("/", headers={hdrs.COOKIE: cookie_header}) as response:
++        assert response.status == 200
++
++
[email protected](
++    ("set_cookie", "name", "value"),
++    (("path=unquoted", "path", "unquoted"), ('secure="quoted"', "secure", "quoted")),
++)
++async def test_reserved_cookie_name_round_trip(
++    aiohttp_client: AiohttpClient,
++    set_cookie: str,
++    name: str,
++    value: str,
++) -> None:
++    """Reserved attribute words are valid cookie names in first position."""
++    received_cookies: dict[str, str] = {}
++
++    async def set_handler(request: web.Request) -> web.Response:
++        response = web.Response(status=302, headers={hdrs.LOCATION: "/receive"})
++        response.headers.add(hdrs.SET_COOKIE, set_cookie)
++        return response
++
++    async def receive_handler(request: web.Request) -> web.Response:
++        received_cookies.update(request.cookies)
++        return web.Response()
++
++    app = web.Application()
++    app.router.add_get("/set", set_handler)
++    app.router.add_get("/receive", receive_handler)
++    client = await aiohttp_client(app, cookie_jar=aiohttp.CookieJar(unsafe=True))
++
++    async with client.get("/set") as response:
++        assert response.status == 200
++        assert response.history[0].cookies[name].value == value
++
++    assert received_cookies == {name: value}
++
++
+ async def test_cookies_redirect(aiohttp_client) -> None:
+     async def redirect1(request):
+         ret = web.Response(status=301, headers={"Location": "/redirect2"})
+diff --git a/tests/test_client_response.py b/tests/test_client_response.py
+index a5061e0..24e64c9 100644
+--- a/tests/test_client_response.py
++++ b/tests/test_client_response.py
+@@ -13,6 +13,7 @@ from yarl import URL
+ 
+ import aiohttp
+ from aiohttp import ClientSession, hdrs, http
++from aiohttp._cookie_helpers import _MAX_COOKIES_PER_RESPONSE
+ from aiohttp.client_reqrep import ClientResponse, RequestInfo
+ from aiohttp.helpers import TimerNoop
+ from aiohttp.multipart import BadContentDispositionHeader
+@@ -1414,6 +1415,31 @@ def test_response_duplicate_cookie_names(
+     assert response.cookies["user-pref"].value == "light"  # Last one wins
+ 
+ 
++def test_response_cookies_are_bounded_but_raw_headers_remain_available(
++    loop: asyncio.AbstractEventLoop, session: ClientSession
++) -> None:
++    response = ClientResponse(
++        "get",
++        URL("http://example.com"),
++        request_info=mock.Mock(),
++        writer=WriterMock(),
++        continue100=None,
++        timer=TimerNoop(),
++        traces=[],
++        loop=loop,
++        session=session,
++    )
++    cookie_headers = tuple(
++        f"cookie{i}=value" for i in range(_MAX_COOKIES_PER_RESPONSE + 1)
++    )
++    headers = CIMultiDict(("Set-Cookie", value) for value in cookie_headers)
++    response._headers = CIMultiDictProxy(headers)
++    response._raw_cookie_headers = cookie_headers
++
++    assert len(response.cookies) == _MAX_COOKIES_PER_RESPONSE
++    assert response.headers.getall("Set-Cookie") == list(cookie_headers)
++
++
+ def test_response_raw_cookie_headers_preserved(
+     loop: asyncio.AbstractEventLoop, session: ClientSession
+ ) -> None:
+diff --git a/tests/test_cookie_helpers.py b/tests/test_cookie_helpers.py
+index 767e1ea..2f0e754 100644
+--- a/tests/test_cookie_helpers.py
++++ b/tests/test_cookie_helpers.py
+@@ -73,6 +73,24 @@ def test_preserve_morsel_with_coded_value_no_coded_value() -> None:
+     assert result.coded_value == "simple_value"
+ 
+ 
[email protected]("name", sorted(Morsel._reserved))  # type: ignore[attr-defined]
[email protected]("coded_value", ("value", '"value"'))
++def test_preserve_morsel_with_reserved_cookie_name(name: str, coded_value: str) -> None:
++    """A cookie named like an attribute, such as ``path``, is preserved."""
++    cookie: Morsel[str] = Morsel()
++    cookie.__setstate__(  # type: ignore[attr-defined]
++        {"key": name, "value": "value", "coded_value": coded_value}
++    )
++
++    result = preserve_morsel_with_coded_value(cookie)
++
++    assert result is not cookie
++    assert result.key == name
++    assert result.value == "value"
++    assert result.coded_value == coded_value
++    assert result.OutputString() == f"{name}={coded_value}"
++
++
+ def test_parse_set_cookie_headers_simple() -> None:
+     """Test parse_set_cookie_headers with simple cookies."""
+     headers = ["name=value", "session=abc123"]
+@@ -88,6 +106,184 @@ def test_parse_set_cookie_headers_simple() -> None:
+     assert result[1][1].value == "abc123"
+ 
+ 
++def test_parse_set_cookie_headers_limits_accepted_fields() -> None:
++    """Malformed fields do not consume the 50-cookie response budget."""
++    limit = helpers._MAX_COOKIES_PER_RESPONSE
++    headers = ["not-a-cookie"] * 10 + [f"cookie{i}=value" for i in range(limit + 1)]
++
++    result = parse_set_cookie_headers(headers)
++
++    assert len(result) == limit
++    assert result[-1][0] == f"cookie{limit - 1}"
++
++
++def test_parse_set_cookie_headers_duplicate_consumes_response_budget() -> None:
++    limit = helpers._MAX_COOKIES_PER_RESPONSE
++    headers = [f"cookie{i}=value" for i in range(limit - 1)]
++    headers.extend(("cookie0=replaced", "not_stored=over-limit"))
++
++    result = parse_set_cookie_headers(headers)
++
++    assert len(result) == helpers._MAX_COOKIES_PER_RESPONSE
++    assert result[-1][0] == "cookie0"
++    assert all(name != "not_stored" for name, _ in result)
++
++
++def test_parse_set_cookie_headers_attribute_value_limits() -> None:
++    accepted_path = "/" + "x" * (helpers._MAX_COOKIE_ATTRIBUTE_VALUE_LENGTH - 1)
++    ignored_path = accepted_path + "x"
++
++    accepted = parse_set_cookie_headers([f"cookie=value; Path={accepted_path}"])
++    ignored = parse_set_cookie_headers([f"cookie=value; Path={ignored_path}"])
++
++    assert accepted[0][1]["path"] == accepted_path
++    assert ignored[0][1]["path"] == ""
++
++
++def test_parse_set_cookie_headers_many_unknown_attributes() -> None:
++    result = parse_set_cookie_headers(["cookie=value;" + "unknown=x;" * 1000])
++
++    assert len(result) == 1
++    assert result[0][0] == "cookie"
++    assert "unknown" not in result[0][1]
++
++
[email protected](
++    ("attribute", "path", "secure"),
++    (
++        ('Path="/\u00e9"', "/\u00e9", ""),
++        ('Path="/\udcff"', "", ""),
++        ('Secure="\udcff"', "", True),
++        ('Path="/a\tb"', "", ""),
++        ('Path="/' + "\u00e9" * 600 + '"', "", ""),
++    ),
++)
++def test_parse_set_cookie_headers_quoted_attribute_values(
++    attribute: str, path: str, secure: str | bool
++) -> None:
++    result = parse_set_cookie_headers([f"cookie=value; {attribute}"])
++
++    assert result[0][1]["path"] == path
++    assert result[0][1]["secure"] == secure
++
++
[email protected](
++    "header",
++    ("c=v; Path=/x; =junk", "c=v; =junk; Path=/x", "c=v; Path=/x; =junk;; ;"),
++)
++def test_parse_set_cookie_headers_skips_malformed_attribute(header: str) -> None:
++    result = parse_set_cookie_headers([header])
++
++    assert result[0][1]["path"] == "/x"
++
++
[email protected](
++    "header",
++    (
++        'a=b; Path="/x\\012y"; Secure',
++        'a=b; Comment="hi\\011there"; Secure',
++        'a=b; Comment="hi\tthere"; Secure',
++    ),
++)
++def test_parse_set_cookie_headers_ignores_attribute_with_control_character(
++    header: str,
++) -> None:
++    """Control characters, even from unquoting, drop just the attribute."""
++    result = parse_set_cookie_headers([header])
++
++    assert len(result) == 1
++    assert result[0][1]["path"] == ""
++    assert result[0][1]["comment"] == ""
++    assert result[0][1]["secure"] is True
++
++
++def test_parse_set_cookie_headers_limits_attributes_per_field() -> None:
++    limit = helpers._MAX_COOKIE_ATTRIBUTES
++    within = "c=v; " + "x=1; " * (limit - 1) + "Path=/within"
++    beyond = "c=v; " + "x=1; " * limit + "Path=/beyond"
++
++    assert parse_set_cookie_headers([within])[0][1]["path"] == "/within"
++    assert parse_set_cookie_headers([beyond])[0][1]["path"] == ""
++
++
[email protected](
++    ("headers", "message"),
++    (
++        (["ok=1", "", "bad\x01=1", "nameless"], "Ignored 3 invalid"),
++        (
++            [f"c{i}=1" for i in range(helpers._MAX_COOKIES_PER_RESPONSE + 2)],
++            "and 2 over the 50-cookie limit",
++        ),
++    ),
++)
++def test_parse_set_cookie_headers_logs_dropped_fields(
++    caplog: pytest.LogCaptureFixture, headers: list[str], message: str
++) -> None:
++    with caplog.at_level(logging.DEBUG, logger="aiohttp.internal"):
++        parse_set_cookie_headers(headers)
++
++    assert message in caplog.text
++
++
++def test_parse_set_cookie_headers_valid_fields_log_nothing(
++    caplog: pytest.LogCaptureFixture,
++) -> None:
++    with caplog.at_level(logging.DEBUG, logger="aiohttp.internal"):
++        parse_set_cookie_headers(["a=1; Path=/", "b=2"])
++
++    assert not caplog.records
++
++
++def test_parse_set_cookie_headers_quoted_value_with_trailing_text() -> None:
++    # Text after the closing quote means the quoted value isn't the whole
++    # pair, so the pair ends at the first semicolon.
++    result = parse_set_cookie_headers(['name="a;b" junk; Path=/x'])
++
++    assert len(result) == 1
++    assert result[0][1].coded_value == '"a'
++    assert result[0][1]["path"] == "/x"
++
++
++def test_parse_set_cookie_headers_skips_rejected_morsels(
++    monkeypatch: pytest.MonkeyPatch,
++) -> None:
++    original_setstate = Morsel.__setstate__  # type: ignore[attr-defined]
++
++    def setstate(self: Morsel[str], state: dict[str, str]) -> None:
++        if state["key"] == "rejected":
++            raise CookieError()
++        original_setstate(self, state)
++
++    monkeypatch.setattr("aiohttp._cookie_helpers.Morsel.__setstate__", setstate)
++
++    result = parse_set_cookie_headers(["rejected=value", "kept=value"])
++
++    assert [name for name, _ in result] == ["kept"]
++
++
[email protected]("flag", ("Secure", "HttpOnly"))
++def test_parse_set_cookie_headers_flag_values_are_ignored(flag: str) -> None:
++    """An oversized value doesn't strip the flag, as in Firefox."""
++    value = "x" * (helpers._MAX_COOKIE_ATTRIBUTE_VALUE_LENGTH + 1)
++
++    result = parse_set_cookie_headers([f"cookie=value; {flag}={value}"])
++
++    assert result[0][1][flag.lower()] is True
++
++
[email protected](
++    "header",
++    (
++        'cookie="a\x00b"',
++        'cookie="a\x1fb"',
++        'cookie="a\x7fb"',
++        "cookie=value; unknown=a\x07b",
++    ),
++)
++def test_parse_set_cookie_headers_rejects_control_characters(header: str) -> None:
++    assert parse_set_cookie_headers([header]) == []
++
++
+ def test_parse_set_cookie_headers_with_attributes() -> None:
+     """Test parse_set_cookie_headers with cookie attributes."""
+     headers = [
+@@ -168,8 +364,6 @@ def test_parse_set_cookie_headers_empty_and_invalid() -> None:
+         "=value",  # No name
+         "name=",  # Empty value (should be accepted)
+         "justname",  # No value (should be skipped)
+-        "path=/",  # Reserved attribute as name (should be skipped)
+-        "Domain=.com",  # Reserved attribute as name (should be skipped)
+     ]
+ 
+     result = parse_set_cookie_headers(headers)
+@@ -180,6 +374,45 @@ def test_parse_set_cookie_headers_empty_and_invalid() -> None:
+     assert result[0][1].value == ""
+ 
+ 
++def test_parse_set_cookie_headers_trims_wsp_and_preserves_first_equals() -> None:
++    result = parse_set_cookie_headers(["\t name \t=\t value=rest \t; Path=/"])
++
++    assert len(result) == 1
++    assert result[0][0] == "name"
++    assert result[0][1].value == "value=rest"
++
++
[email protected](
++    "header",
++    (
++        "nameless-value",
++        "name with internal space=value",
++        "name=value\twith-tab",
++    ),
++)
++def test_parse_set_cookie_headers_rejects_unserializable_pairs(header: str) -> None:
++    """Pairs that BaseCookie can't serialize unambiguously are rejected."""
++    assert parse_set_cookie_headers([header]) == []
++
++
++def test_parse_set_cookie_headers_rejects_surrogateescaped_value() -> None:
++    assert parse_set_cookie_headers(['name="\udcff"']) == []
++
++
[email protected]("name", ("Path", "Secure", "Domain"))
++def test_parse_set_cookie_headers_accepts_attribute_names_as_cookie_names(
++    name: str,
++) -> None:
++    """Attribute names are ordinary token cookie-names in first position."""
++    result = parse_set_cookie_headers([f"{name}=value; unknown=ignored"])
++
++    assert len(result) == 1
++    assert result[0][0] == name
++    assert result[0][1].key == name
++    assert result[0][1].value == "value"
++    assert "unknown" not in result[0][1]
++
++
+ def test_parse_set_cookie_headers_quoted_values() -> None:
+     """Test parse_set_cookie_headers handles quoted values correctly."""
+     headers = [
+@@ -197,49 +430,36 @@ def test_parse_set_cookie_headers_quoted_values() -> None:
+ 
+ 
+ @pytest.mark.parametrize(
+-    "header",
++    ("header", "expected_name", "expected_value"),
+     [
+-        'session="abc;xyz"; token=123',
+-        'data="value;with;multiple;semicolons"; next=cookie',
+-        'complex="a=b;c=d"; simple=value',
++        ('session="abc;xyz"; token=123', "session", "abc;xyz"),
++        (
++            'data="value;with;multiple;semicolons"; next=cookie',
++            "data",
++            "value;with;multiple;semicolons",
++        ),
++        ('complex="a=b;c=d"; simple=value', "complex", "a=b;c=d"),
+     ],
+ )
+-def test_parse_set_cookie_headers_semicolon_in_quoted_values(header: str) -> None:
+-    """
+-    Test that semicolons inside properly quoted values are handled correctly.
+-
+-    Cookie values can contain semicolons when properly quoted. This test ensures
+-    that our parser handles these cases correctly, matching SimpleCookie behavior.
+-    """
+-    # Test with SimpleCookie
+-    sc = SimpleCookie()
+-    sc.load(header)
+-
+-    # Test with our parser
++def test_parse_set_cookie_headers_semicolon_in_quoted_values(
++    header: str, expected_name: str, expected_value: str
++) -> None:
++    """Semicolons in a quoted value do not create additional cookies."""
+     result = parse_set_cookie_headers([header])
+-
+-    # Should parse the same number of cookies
+-    assert len(result) == len(sc)
+-
+-    # Verify each cookie matches SimpleCookie
+-    for (name, morsel), (sc_name, sc_morsel) in zip(result, sc.items()):
+-        assert name == sc_name
+-        assert morsel.value == sc_morsel.value
++    assert len(result) == 1
++    assert result[0][0] == expected_name
++    assert result[0][1].value == expected_value
+ 
+ 
+ def test_parse_set_cookie_headers_multiple_cookies_same_header() -> None:
+-    """Test parse_set_cookie_headers with multiple cookies in one header."""
+-    # Note: SimpleCookie includes the comma as part of the first cookie's value
++    """A Set-Cookie field creates exactly one cookie."""
+     headers = ["cookie1=value1, cookie2=value2"]
+ 
+     result = parse_set_cookie_headers(headers)
+ 
+-    # Should parse as two separate cookies
+-    assert len(result) == 2
++    assert len(result) == 1
+     assert result[0][0] == "cookie1"
+-    assert result[0][1].value == "value1,"  # Comma is included in the value
+-    assert result[1][0] == "cookie2"
+-    assert result[1][1].value == "value2"
++    assert result[0][1].value == "value1, cookie2=value2"
+ 
+ 
+ @pytest.mark.parametrize(
+@@ -352,25 +572,28 @@ def test_parse_set_cookie_headers_case_insensitive_attrs() -> None:
+ 
+ 
+ def test_parse_set_cookie_headers_unknown_attrs_ignored() -> None:
+-    """Test that unknown attributes are treated as new cookies (same as SimpleCookie)."""
++    """Unknown attributes do not create additional cookies."""
+     headers = [
+         "cookie=value; Path=/; unknownattr=ignored; HttpOnly",
+     ]
+ 
+     result = parse_set_cookie_headers(headers)
+ 
+-    # SimpleCookie treats unknown attributes with values as new cookies
+-    assert len(result) == 2
+-
+-    # First cookie
++    assert len(result) == 1
+     assert result[0][0] == "cookie"
+     assert result[0][1]["path"] == "/"
+-    assert result[0][1]["httponly"] == ""  # Not set on first cookie
++    assert result[0][1]["httponly"] is True
++
+ 
+-    # Second cookie (the unknown attribute)
+-    assert result[1][0] == "unknownattr"
+-    assert result[1][1].value == "ignored"
+-    assert result[1][1]["httponly"] is True  # HttpOnly applies to this cookie
++def test_parse_set_cookie_headers_tolerates_missing_attribute_semicolons() -> None:
++    result = parse_set_cookie_headers(
++        ["cookie=value; Path=/ Max-Age=60; unknown=ignored Secure"]
++    )
++
++    assert len(result) == 1
++    assert result[0][1]["path"] == "/"
++    assert result[0][1]["max-age"] == "60"
++    assert result[0][1]["secure"] is True
+ 
+ 
+ def test_parse_set_cookie_headers_complex_real_world() -> None:
+@@ -655,28 +878,14 @@ def test_cookie_pattern_performance() -> None:
+ 
+ 
+ def test_parse_set_cookie_headers_issue_7993_double_quotes() -> None:
+-    """
+-    Test that cookies with unmatched opening quotes don't break parsing of subsequent cookies.
+-
+-    This reproduces issue #7993 where a cookie containing an unmatched opening double quote
+-    causes subsequent cookies to be silently dropped.
+-    NOTE: This only fixes the specific case where a value starts with a quote but doesn't
+-    end with one (e.g., 'cookie="value'). Other malformed quote cases still behave like
+-    SimpleCookie for compatibility.
+-    """
+-    # Test case from the issue
++    """Unknown segments with unmatched quotes remain attributes of one cookie."""
+     headers = ['foo=bar; baz="qux; foo2=bar2']
+ 
+     result = parse_set_cookie_headers(headers)
+ 
+-    # Should parse all cookies correctly
+-    assert len(result) == 3
++    assert len(result) == 1
+     assert result[0][0] == "foo"
+     assert result[0][1].value == "bar"
+-    assert result[1][0] == "baz"
+-    assert result[1][1].value == '"qux'  # Unmatched quote included
+-    assert result[2][0] == "foo2"
+-    assert result[2][1].value == "bar2"
+ 
+ 
+ def test_parse_set_cookie_headers_empty_headers() -> None:
+@@ -713,50 +922,20 @@ def test_parse_set_cookie_headers_invalid_cookie_syntax() -> None:
+     assert result == []
+ 
+ 
+-def test_parse_set_cookie_headers_illegal_cookie_names(
+-    caplog: pytest.LogCaptureFixture,
+-) -> None:
+-    """
+-    Test that illegal cookie names are rejected.
+-
+-    Note: When a known attribute name is used as a cookie name at the start,
+-    parsing stops early (before any warning can be logged). Warnings are only
+-    logged when illegal names appear after a valid cookie.
+-    """
+-    # Cookie name that is a known attribute (illegal) - parsing stops early
+-    result = parse_set_cookie_headers(["path=value; domain=test"])
+-    assert result == []
+-
++def test_parse_set_cookie_headers_illegal_cookie_names() -> None:
++    """Test that illegal cookie names are rejected."""
+     # Cookie name that doesn't match the pattern
+     result = parse_set_cookie_headers(["=value"])
+     assert result == []
+ 
+-    # Valid cookie after illegal one - parsing stops at illegal
+-    result = parse_set_cookie_headers(["domain=bad; good=value"])
++    # A later valid pair cannot rescue an invalid first cookie-pair.
++    result = parse_set_cookie_headers(["bad name=value; good=value"])
+     assert result == []
+ 
+-    # Illegal cookie name that appears after a valid cookie triggers warning
++    # An illegal segment after a valid cookie is an ignored attribute.
+     result = parse_set_cookie_headers(["good=value; Path=/; invalid,cookie=value;"])
+     assert len(result) == 1
+     assert result[0][0] == "good"
+-    assert "Illegal cookie name 'invalid,cookie'" in caplog.text
+-
+-
+-def test_parse_set_cookie_headers_attributes_before_cookie() -> None:
+-    """Test that attributes before any cookie are invalid."""
+-    # Path attribute before cookie
+-    result = parse_set_cookie_headers(["Path=/; name=value"])
+-    assert result == []
+-
+-    # Domain attribute before cookie
+-    result = parse_set_cookie_headers(["Domain=.example.com; name=value"])
+-    assert result == []
+-
+-    # Multiple attributes before cookie
+-    result = parse_set_cookie_headers(
+-        ["Path=/; Domain=.example.com; Secure; name=value"]
+-    )
+-    assert result == []
+ 
+ 
+ def test_parse_set_cookie_headers_attributes_without_values() -> None:
+@@ -766,86 +945,78 @@ def test_parse_set_cookie_headers_attributes_without_values() -> None:
+     assert len(result) == 1
+     assert result[0][1]["secure"] is True
+ 
+-    # Non-boolean attribute without value (invalid, stops parsing)
++    # A non-boolean attribute without a value is empty.
+     result = parse_set_cookie_headers(["name=value; Path"])
+     assert len(result) == 1
+-    # Path without value stops further attribute parsing
++    assert result[0][1]["path"] == ""
+ 
+-    # Multiple cookies, invalid attribute in middle
++    # It doesn't stop later attributes from applying.
+     result = parse_set_cookie_headers(["name=value; Path; Secure"])
+     assert len(result) == 1
+-    # Secure is not parsed because Path without value stops parsing
++    assert result[0][1]["path"] == ""
++    assert result[0][1]["secure"] is True
+ 
+ 
+ def test_parse_set_cookie_headers_dollar_prefixed_names() -> None:
+-    """Test handling of cookie names starting with $."""
+-    # $Version without preceding cookie (ignored)
++    """A dollar-prefixed first cookie-pair is still the field's one cookie."""
+     result = parse_set_cookie_headers(["$Version=1; name=value"])
+     assert len(result) == 1
+-    assert result[0][0] == "name"
++    assert result[0][0] == "$Version"
+ 
+-    # Multiple $ prefixed without cookie (all ignored)
++    # Later segments remain attributes and do not create another cookie.
+     result = parse_set_cookie_headers(["$Version=1; $Path=/; $Domain=.com; name=value"])
+     assert len(result) == 1
+-    assert result[0][0] == "name"
++    assert result[0][0] == "$Version"
+ 
+-    # $ prefix at start is ignored, cookie follows
+     result = parse_set_cookie_headers(["$Unknown=123; valid=cookie"])
+     assert len(result) == 1
+-    assert result[0][0] == "valid"
++    assert result[0][0] == "$Unknown"
+ 
+ 
+ def test_parse_set_cookie_headers_dollar_attributes() -> None:
+-    """Test handling of $ prefixed attributes after cookies."""
+-    # Test multiple $ attributes with cookie (case-insensitive like SimpleCookie)
++    """Dollar-prefixed attributes are unknown and ignored."""
+     result = parse_set_cookie_headers(["name=value; $Path=/test; $Domain=.example.com"])
+     assert len(result) == 1
+     assert result[0][0] == "name"
+-    assert result[0][1]["path"] == "/test"
+-    assert result[0][1]["domain"] == ".example.com"
++    assert result[0][1]["path"] == ""
++    assert result[0][1]["domain"] == ""
+ 
+     # Test unknown $ attribute (should be ignored)
+     result = parse_set_cookie_headers(["name=value; $Unknown=test"])
+     assert len(result) == 1
+     assert result[0][0] == "name"
+-    # $Unknown should not be set
++    assert "$unknown" not in result[0][1]
+ 
+     # Test $ attribute with empty value
+     result = parse_set_cookie_headers(["name=value; $Path="])
+     assert len(result) == 1
+     assert result[0][1]["path"] == ""
+ 
+-    # Test case sensitivity compatibility with SimpleCookie
++    # Case does not make a dollar-prefixed attribute recognized.
+     result = parse_set_cookie_headers(["test=value; $path=/lower; $PATH=/upper"])
+     assert len(result) == 1
+-    # Last one wins, and it's case-insensitive
+-    assert result[0][1]["path"] == "/upper"
++    assert result[0][1]["path"] == ""
+ 
+ 
+ def test_parse_set_cookie_headers_attributes_after_illegal_cookie() -> None:
+-    """
+-    Test that attributes after an illegal cookie name are handled correctly.
+-
+-    This covers the branches where current_morsel is None because an illegal
+-    cookie name was encountered.
+-    """
++    """Test that attributes after an illegal cookie name are handled correctly."""
+     # Illegal cookie followed by $ attribute
+     result = parse_set_cookie_headers(["good=value; invalid,cookie=bad; $Path=/test"])
+     assert len(result) == 1
+     assert result[0][0] == "good"
+-    # $Path should be ignored since current_morsel is None after illegal cookie
++    assert result[0][1]["path"] == ""
+ 
+     # Illegal cookie followed by boolean attribute
+     result = parse_set_cookie_headers(["good=value; invalid,cookie=bad; HttpOnly"])
+     assert len(result) == 1
+     assert result[0][0] == "good"
+-    # HttpOnly should be ignored since current_morsel is None
++    assert result[0][1]["httponly"] is True
+ 
+     # Illegal cookie followed by regular attribute with value
+     result = parse_set_cookie_headers(["good=value; invalid,cookie=bad; Max-Age=3600"])
+     assert len(result) == 1
+     assert result[0][0] == "good"
+-    # Max-Age should be ignored since current_morsel is None
++    assert result[0][1]["max-age"] == "3600"
+ 
+     # Multiple attributes after illegal cookie
+     result = parse_set_cookie_headers(
+@@ -853,16 +1024,13 @@ def test_parse_set_cookie_headers_attributes_after_illegal_cookie() -> None:
+     )
+     assert len(result) == 1
+     assert result[0][0] == "good"
+-    # All attributes should be ignored after illegal cookie
++    assert result[0][1]["httponly"] is True
++    assert result[0][1]["max-age"] == "60"
++    assert result[0][1]["domain"] == ".com"
+ 
+ 
+ def test_parse_set_cookie_headers_unmatched_quotes_compatibility() -> None:
+-    """
+-    Test that most unmatched quote scenarios behave like SimpleCookie.
+-
+-    For compatibility, we only handle the specific case of unmatched opening quotes
+-    (e.g., 'cookie="value'). Other cases behave the same as SimpleCookie.
+-    """
++    """Malformed later segments never create more cookies from one field."""
+     # Cases that SimpleCookie and our parser both fail to parse completely
+     incompatible_cases = [
+         'cookie1=val"ue; cookie2=value2',  # codespell:ignore
+@@ -872,20 +1040,8 @@ def test_parse_set_cookie_headers_unmatched_quotes_compatibility() -> None:
+     ]
+ 
+     for header in incompatible_cases:
+-        # Test SimpleCookie behavior
+-        sc = SimpleCookie()
+-        sc.load(header)
+-        sc_cookies = list(sc.items())
+-
+-        # Test our parser behavior
+         result = parse_set_cookie_headers([header])
+-
+-        # Both should parse the same cookies (partial parsing)
+-        assert len(result) == len(sc_cookies), (
+-            f"Header: {header}\n"
+-            f"SimpleCookie parsed: {len(sc_cookies)} cookies\n"
+-            f"Our parser parsed: {len(result)} cookies"
+-        )
++        assert len(result) <= 1
+ 
+     # The case we specifically fix (unmatched opening quote)
+     fixed_case = 'cookie1=value1; cookie2="unmatched; cookie3=value3'
+@@ -895,15 +1051,11 @@ def test_parse_set_cookie_headers_unmatched_quotes_compatibility() -> None:
+     sc.load(fixed_case)
+     assert len(sc) == 1  # Only cookie1
+ 
+-    # Our parser handles it better
++    # The first cookie-pair remains available; the rest are attributes.
+     result = parse_set_cookie_headers([fixed_case])
+-    assert len(result) == 3  # All three cookies
++    assert len(result) == 1
+     assert result[0][0] == "cookie1"
+     assert result[0][1].value == "value1"
+-    assert result[1][0] == "cookie2"
+-    assert result[1][1].value == '"unmatched'
+-    assert result[2][0] == "cookie3"
+-    assert result[2][1].value == "value3"
+ 
+ 
+ def test_parse_set_cookie_headers_expires_attribute() -> None:
+@@ -923,12 +1075,26 @@ def test_parse_set_cookie_headers_expires_attribute() -> None:
+ 
+ 
+ def test_parse_set_cookie_headers_edge_cases() -> None:
+-    """Test various edge cases."""
+-    # Very long cookie values
+-    long_value = "x" * 4096
+-    result = parse_set_cookie_headers([f"name={long_value}"])
++    """Cookie name and value are limited to 4096 encoded octets."""
++    boundary_value = "x" * 4092
++    result = parse_set_cookie_headers([f"name={boundary_value}"])
+     assert len(result) == 1
+-    assert result[0][1].value == long_value
++    assert result[0][1].value == boundary_value
++
++    assert parse_set_cookie_headers([f"name={boundary_value}x"]) == []
++
++
++def test_parse_set_cookie_headers_counts_coded_quoted_octets() -> None:
++    coded_value = '"' + r"\a" * 2046 + 'x"'
++    assert len(b"n") + len(coded_value.encode()) == 4096
++
++    result = parse_set_cookie_headers([f"n={coded_value}"])
++    assert len(result) == 1
++    assert len(result[0][1].value) < 4096
++
++    over_limit = coded_value[:-1] + 'x"'
++    assert len(b"n") + len(over_limit.encode()) == 4097
++    assert parse_set_cookie_headers([f"n={over_limit}"]) == []
+ 
+ 
+ def test_parse_set_cookie_headers_various_date_formats_issue_4327() -> None:
+@@ -1095,13 +1261,13 @@ def test_parse_set_cookie_headers_date_formats_with_attributes() -> None:
+ @pytest.mark.parametrize(
+     ("header", "expected_name", "expected_value", "expected_coded"),
+     [
+-        # Test cookie values with octal escape sequences
+-        (r'name="\012newline\012"', "name", "\nnewline\n", r'"\012newline\012"'),
++        # Test cookie values with octal escape sequences (printable chars only)
++        (r'name="\050parens\051"', "name", "(parens)", r'"\050parens\051"'),
+         (
+-            r'tab="\011separated\011values"',
+-            "tab",
+-            "\tseparated\tvalues",
+-            r'"\011separated\011values"',
++            r'punct="\053plus\053values"',
++            "punct",
++            "+plus+values",
++            r'"\053plus\053values"',
+         ),
+         (
+             r'mixed="hello\040world\041"',
+@@ -1110,10 +1276,10 @@ def test_parse_set_cookie_headers_date_formats_with_attributes() -> None:
+             r'"hello\040world\041"',
+         ),
+         (
+-            r'complex="\042quoted\042 text with \012 newline"',
++            r'complex="\042quoted\042 text with \055 hyphen"',
+             "complex",
+-            '"quoted" text with \n newline',
+-            r'"\042quoted\042 text with \012 newline"',
++            '"quoted" text with - hyphen',
++            r'"\042quoted\042 text with \055 hyphen"',
+         ),
+     ],
+ )
+@@ -1789,3 +1955,37 @@ def test_unquote_compatibility_with_simplecookie(test_value: str) -> None:
+         f"our={_unquote(test_value)!r}, "
+         f"SimpleCookie={simplecookie_unquote(test_value)!r}"
+     )
++
++
[email protected](
++    "header",
++    (
++        pytest.param(r'name="\012newline\012"', id="newline-octal-012"),
++        pytest.param(r'tab="\011separated\011values"', id="tab-octal-011"),
++        pytest.param(r'del="\177"', id="delete-octal-177"),
++    ),
++)
++def test_parse_set_cookie_headers_ctl_chars_from_octal(header: str) -> None:
++    """Controls introduced by compatibility unquoting are always rejected."""
++    assert parse_set_cookie_headers([header]) == []
++
++
++def test_parse_set_cookie_headers_literal_ctl_chars() -> None:
++    r"""Ensure literal control characters in a cookie value don't crash the parser.
++
++    If the raw header itself contains a control character (e.g. BEL \\x07),
++    both the decoded value and coded_value are unsalvageable.  The parser
++    should gracefully skip the cookie instead of raising CookieError.
++    """
++    assert parse_set_cookie_headers(['name="a\x07b"']) == []
++
++
++def test_parse_set_cookie_headers_literal_ctl_chars_preserves_others() -> None:
++    """Ensure a cookie with literal control chars doesn't break subsequent cookies."""
++    result = parse_set_cookie_headers(['bad="a\x07b"; good=value', "another=cookie"])
++    # "good" is an attribute of "bad" (same header), so it's not a separate cookie.
++    # "another" is in a separate header and must always be preserved.
++    assert any(name == "another" for name, _ in result)
++
++
++# Tests for parse_cookie_header (RFC 6265 compliant Cookie header parser)
+diff --git a/tests/test_cookiejar.py b/tests/test_cookiejar.py
+index 4c7107c..891a84e 100644
+--- a/tests/test_cookiejar.py
++++ b/tests/test_cookiejar.py
+@@ -6,8 +6,10 @@ import json
+ import logging
+ import pathlib
+ import pickle
++import random
+ import sys
+ import unittest
++from collections import Counter
+ from http.cookies import BaseCookie, Morsel, SimpleCookie
+ from operator import not_
+ from pathlib import Path
+@@ -18,7 +20,12 @@ import pytest
+ from freezegun import freeze_time
+ from yarl import URL
+ 
++import aiohttp.cookiejar as cookiejar_module
+ from aiohttp import CookieJar, DummyCookieJar
++from aiohttp._cookie_helpers import (
++    _MAX_COOKIE_ATTRIBUTE_VALUE_LENGTH,
++    _MAX_COOKIES_PER_RESPONSE,
++)
+ 
+ 
+ def dump_cookiejar() -> bytes:  # pragma: no cover
+@@ -54,6 +61,48 @@ def cookies_to_send():
+     )
+ 
+ 
++def _write_saved(tmp_path: Path, data: object) -> Path:
++    file_path = tmp_path / "cookies.json"
++    file_path.write_text(json.dumps(data), encoding="utf-8")
++    return file_path
++
++
++def _saved_cookie(
++    name: str, value: str = "value", **fields: object
++) -> dict[str, object]:
++    """Build a record in the format CookieJar.save() writes."""
++    return {
++        "key": name,
++        "value": value,
++        "coded_value": value,
++        "domain": "example.com",
++        **fields,
++    }
++
++
++_TRIM = (
++    cookiejar_module._MAX_COOKIES_PER_DOMAIN - cookiejar_module._COOKIE_QUOTA_PER_DOMAIN
++)
++
++
++def _make_morsel(
++    name: str,
++    value: str = "value",
++    *,
++    domain: str = "example.com",
++    path: str = "/",
++    secure: bool = False,
++) -> Morsel[str]:
++    cookies = SimpleCookie()
++    cookies[name] = value
++    morsel = cookies[name]
++    morsel["domain"] = domain
++    morsel["path"] = path
++    if secure:
++        morsel["secure"] = True
++    return morsel
++
++
+ @pytest.fixture
+ def cookies_to_send_with_expired():
+     return SimpleCookie(
+@@ -163,12 +212,13 @@ def test_domain_matching() -> None:
+ async def test_constructor(loop, cookies_to_send, cookies_to_receive) -> None:
+     jar = CookieJar(loop=loop)
+     jar.update_cookies(cookies_to_send)
+-    jar_cookies = SimpleCookie()
+-    for cookie in jar:
+-        dict.__setitem__(jar_cookies, cookie.key, cookie)
+-    expected_cookies = cookies_to_send
+-    assert jar_cookies == expected_cookies
+-    assert jar._loop is loop
++    jar_cookies = {cookie.key: cookie for cookie in jar}
++    assert jar_cookies.keys() == cookies_to_send.keys()
++    for name, expected in cookies_to_send.items():
++        # The jar stores normalized copies, so only the parts that
++        # normalization must not touch are compared here.
++        assert jar_cookies[name].value == expected.value
++        assert jar_cookies[name].coded_value == expected.coded_value
+ 
+ 
+ async def test_constructor_with_expired(
+@@ -184,7 +234,7 @@ async def test_constructor_with_expired(
+     assert jar._loop is loop
+ 
+ 
+-def test_save_load(tmp_path, loop, cookies_to_send, cookies_to_receive) -> None:
++async def test_save_load(tmp_path, loop, cookies_to_send, cookies_to_receive) -> None:
+     file_path = pathlib.Path(str(tmp_path)) / "aiohttp.test.cookie"
+ 
+     # export cookie jar
+@@ -199,10 +249,15 @@ def test_save_load(tmp_path, loop, cookies_to_send, cookies_to_receive) -> None:
+     for cookie in jar_load:
+         jar_test[cookie.key] = cookie
+ 
+-    assert jar_test == cookies_to_receive
++    # The jar stores normalized copies of the received cookies, so the
++    # round-tripped contents are compared against the saved jar itself.
++    jar_expected = SimpleCookie()
++    for cookie in jar_save:
++        dict.__setitem__(jar_expected, cookie.key, cookie)
++    assert jar_test == jar_expected
+ 
+ 
+-def test_save_load_partitioned_cookies(tmp_path, loop) -> None:
++async def test_save_load_partitioned_cookies(tmp_path, loop) -> None:
+     file_path = pathlib.Path(str(tmp_path)) / "aiohttp.test2.cookie"
+     # export cookie jar
+     jar_save = CookieJar(loop=loop)
+@@ -1217,10 +1272,8 @@ async def test_filter_cookies_does_not_leak_memory() -> None:
+         assert len(filtered) == 1
+         assert "test_cookie" in filtered
+ 
+-    # Storage size should not grow significantly
+-    # Only the shared cookie entry ('', '') may be added
+-    final_storage_size = len(jar._cookies)
+-    assert final_storage_size <= initial_storage_size + 1
++    # Storage size should not grow
++    assert len(jar._cookies) == initial_storage_size
+ 
+     # Verify _morsel_cache doesn't leak either
+     # It should only have entries for domains/paths where cookies exist
+@@ -1229,8 +1282,7 @@ async def test_filter_cookies_does_not_leak_memory() -> None:
+ 
+     # Verify no empty entries were created for domain-path combinations
+     for key, cookies in jar._cookies.items():
+-        if key != ("", ""):  # Skip the shared cookie entry
+-            assert len(cookies) > 0, f"Empty cookie entry found for {key}"
++        assert len(cookies) > 0, f"Empty cookie entry found for {key}"
+ 
+     # Verify _morsel_cache entries correspond to actual cookies
+     for key, morsels in jar._morsel_cache.items():
+@@ -1480,6 +1532,35 @@ async def test_update_cookies_from_headers_overwrites_same_cookie() -> None:
+     assert filtered["session"].value == "new-value"
+ 
+ 
++async def test_response_cookie_limit_counts_deletions() -> None:
++    jar = CookieJar()
++    url = URL("https://example.com/")
++    jar.update_cookies({"existing": "value"}, url)
++    headers = ["existing=; Max-Age=0"]
++    headers.extend(f"cookie{i}=value" for i in range(_MAX_COOKIES_PER_RESPONSE - 1))
++    headers.append("over-limit=value")
++
++    jar.update_cookies_from_headers(headers, url)
++
++    names = {cookie.key for cookie in jar}
++    assert "existing" not in names
++    assert f"cookie{_MAX_COOKIES_PER_RESPONSE - 2}" in names
++    assert "over-limit" not in names
++
++
++async def test_response_cookie_limit_precedes_domain_validation() -> None:
++    jar = CookieJar()
++    headers = [
++        f"invalid{i}=value; Domain=other.example"
++        for i in range(_MAX_COOKIES_PER_RESPONSE)
++    ]
++    headers.append("over-limit=value")
++
++    jar.update_cookies_from_headers(headers, URL("https://example.com/"))
++
++    assert not jar
++
++
+ async def test_dummy_cookie_jar_update_cookies_from_headers() -> None:
+     """Test that DummyCookieJar ignores update_cookies_from_headers."""
+     jar: DummyCookieJar = DummyCookieJar()
+@@ -1524,7 +1605,7 @@ async def test_shared_cookie_cache_population() -> None:
+     assert "shared" in jar._morsel_cache[("", "")]
+ 
+     # Verify the cached morsel is the same one returned
+-    cached_morsel = jar._morsel_cache[("", "")]["shared"]
++    cached_morsel = jar._morsel_cache[("", "")]["shared"][0]
+     assert cached_morsel is filtered["shared"]
+ 
+ 
+@@ -1776,7 +1857,12 @@ async def test_load_falls_back_to_pickle(
+     for cookie in jar_load:
+         jar_test[cookie.key] = cookie
+ 
+-    assert jar_test == cookies_to_receive
++    assert jar_test.keys() == cookies_to_receive.keys()
++    for name, expected in cookies_to_receive.items():
++        # The jar stores normalized copies, so only the parts that
++        # normalization must not touch are compared here.
++        assert jar_test[name].value == expected.value
++        assert jar_test[name].coded_value == expected.coded_value
+ 
+ 
+ async def test_save_load_json_roundtrip(
+@@ -2056,3 +2142,925 @@ async def test_update_cookies_negative_max_age_beyond_float_range_expires() -> N
+ 
+     assert "sid" not in jar.filter_cookies(url)
+     assert len(jar) == 0
++
++
++async def test_dummy_cookie_jar_does_not_parse_headers() -> None:
++    with mock.patch.object(cookiejar_module, "parse_set_cookie_headers") as parse:
++        DummyCookieJar().update_cookies_from_headers(
++            ["other=value"], URL("http://example.com/")
++        )
++    parse.assert_not_called()
++
++
++async def test_safe_cookie_jar_rejects_ip_before_parsing() -> None:
++    with mock.patch.object(cookiejar_module, "parse_set_cookie_headers") as parse:
++        CookieJar().update_cookies_from_headers(
++            ["other=value"], URL("http://127.0.0.1/")
++        )
++    parse.assert_not_called()
++
++
++async def test_cookie_jar_limits_cookies_per_domain(
++    caplog: pytest.LogCaptureFixture,
++) -> None:
++    jar = CookieJar()
++    url = URL("https://example.com/")
++    cookies = [
++        ("secure-cookie", _make_morsel("secure-cookie", secure=True)),
++        *(
++            (f"cookie{i}", _make_morsel(f"cookie{i}"))
++            for i in range(cookiejar_module._MAX_COOKIES_PER_DOMAIN)
++        ),
++    ]
++
++    with caplog.at_level(logging.DEBUG, logger="aiohttp.internal"):
++        jar.update_cookies(cookies, url)
++
++    assert caplog.messages == [
++        f"Evicted {_TRIM + 1} cookie(s) for example.com over the 180-cookie"
++        " domain limit"
++    ]
++    # Adding to a full domain trims it back to its quota, oldest
++    # non-secure cookies first.
++    assert len(jar) == cookiejar_module._COOKIE_QUOTA_PER_DOMAIN
++    names = {cookie.key for cookie in jar}
++    assert "secure-cookie" in names
++    assert f"cookie{_TRIM}" not in names
++    assert f"cookie{_TRIM + 1}" in names
++
++
++def _fill_domain(jar: CookieJar, url: URL, *, secure: bool) -> None:
++    jar.update_cookies(
++        [
++            (f"cookie{i}", _make_morsel(f"cookie{i}", secure=secure))
++            for i in range(cookiejar_module._MAX_COOKIES_PER_DOMAIN)
++        ],
++        url,
++    )
++    assert len(jar) == cookiejar_module._MAX_COOKIES_PER_DOMAIN
++
++
++async def test_cookie_jar_replacement_updates_eviction_recency() -> None:
++    jar = CookieJar()
++    url = URL("https://example.com/")
++    _fill_domain(jar, url, secure=False)
++
++    jar.update_cookies({"cookie0": "replaced"}, url)
++    jar.update_cookies({"new": "value"}, url)
++
++    names = {cookie.key for cookie in jar}
++    assert "cookie0" in names
++    assert "cookie1" not in names
++    assert "new" in names
++
++
++async def test_cookie_jar_full_secure_domain_drops_new_non_secure_cookie(
++    caplog: pytest.LogCaptureFixture,
++) -> None:
++    jar = CookieJar()
++    url = URL("https://example.com/")
++    _fill_domain(jar, url, secure=True)
++
++    morsel = _make_morsel("new")
++    morsel["max-age"] = "3600"
++    with caplog.at_level(logging.DEBUG, logger="aiohttp.internal"):
++        jar.update_cookies({"new": morsel}, url)
++
++    assert "Dropped cookie 'new' for example.com" in caplog.text
++
++    assert len(jar) == cookiejar_module._MAX_COOKIES_PER_DOMAIN
++    assert "new" not in {cookie.key for cookie in jar}
++    assert ("example.com", "", "new") not in jar._host_only_cookies
++
++
++async def test_cookie_jar_full_secure_domain_evicts_for_new_secure_cookie() -> None:
++    jar = CookieJar()
++    url = URL("https://example.com/")
++    _fill_domain(jar, url, secure=True)
++
++    jar.update_cookies({"new": _make_morsel("new", secure=True)}, url)
++
++    assert len(jar) == cookiejar_module._COOKIE_QUOTA_PER_DOMAIN
++    names = {cookie.key for cookie in jar}
++    assert "new" in names
++    assert f"cookie{_TRIM}" not in names
++    assert f"cookie{_TRIM + 1}" in names
++
++
++async def test_cookie_jar_evicts_expired_before_live_cookies() -> None:
++    jar = CookieJar()
++    url = URL("https://example.com/")
++    with freeze_time("2030-01-01") as freezer:
++        _fill_domain(jar, url, secure=False)
++        short_lived = _make_morsel("short-lived", secure=True)
++        short_lived["max-age"] = "10"
++        # Replacing an existing cookie in a full domain never evicts.
++        jar.update_cookies(
++            {f"cookie{cookiejar_module._MAX_COOKIES_PER_DOMAIN - 1}": short_lived}, url
++        )
++        assert len(jar) == cookiejar_module._MAX_COOKIES_PER_DOMAIN
++
++        freezer.tick(60)
++        jar.update_cookies({"new": _make_morsel("new")}, url)
++
++    names = {cookie.key for cookie in jar}
++    assert len(jar) == cookiejar_module._COOKIE_QUOTA_PER_DOMAIN
++    assert f"cookie{cookiejar_module._MAX_COOKIES_PER_DOMAIN - 1}" not in names
++    assert "cookie0" not in names
++    assert f"cookie{_TRIM - 1}" not in names
++    assert f"cookie{_TRIM}" in names
++    assert "new" in names
++
++
++async def test_cookie_jar_deleting_cookie_does_not_evict() -> None:
++    jar = CookieJar()
++    url = URL("https://example.com/")
++    _fill_domain(jar, url, secure=False)
++
++    jar.update_cookies_from_headers(["unknown=; Max-Age=0"], url)
++
++    assert len(jar) == cookiejar_module._MAX_COOKIES_PER_DOMAIN
++
++
++async def test_cookie_jar_expired_cookies_make_room_in_full_domain() -> None:
++    jar = CookieJar()
++    url = URL("https://example.com/")
++    with freeze_time("2030-01-01") as freezer:
++        cookies = []
++        for i in range(cookiejar_module._MAX_COOKIES_PER_DOMAIN):
++            morsel = _make_morsel(f"cookie{i}")
++            if i < 40:
++                morsel["max-age"] = "10"
++            cookies.append((f"cookie{i}", morsel))
++        jar.update_cookies(cookies, url)
++        freezer.tick(60)
++
++        jar.update_cookies({"new": _make_morsel("new")}, url)
++
++    names = {cookie.key for cookie in jar}
++    assert len(jar) == cookiejar_module._MAX_COOKIES_PER_DOMAIN - 40 + 1
++    assert "cookie40" in names
++    assert "new" in names
++
++
++async def test_cookie_jar_expired_secure_cookies_admit_non_secure_cookie() -> None:
++    jar = CookieJar()
++    url = URL("https://example.com/")
++    with freeze_time("2030-01-01") as freezer:
++        jar.update_cookies({"other": "value"}, URL("https://other.example/"))
++        cookies = []
++        for i in range(cookiejar_module._MAX_COOKIES_PER_DOMAIN):
++            morsel = _make_morsel(f"cookie{i}", secure=True)
++            if i < 5:
++                morsel["max-age"] = "10"
++            cookies.append((f"cookie{i}", morsel))
++        jar.update_cookies(cookies, url)
++        freezer.tick(60)
++
++        # Like Firefox, freed expired cookies make room without evicting
++        # live secure ones.
++        jar.update_cookies({"new": _make_morsel("new")}, url)
++
++    names = {cookie.key for cookie in jar}
++    assert len(jar) == cookiejar_module._MAX_COOKIES_PER_DOMAIN - 5 + 2
++    assert "new" in names
++    assert "other" in names
++    assert "cookie5" in names
++
++
++async def test_cookie_jar_purge_expired_cookies_keep_live_ones() -> None:
++    jar = CookieJar(unsafe=True)
++    with freeze_time("2030-01-01") as freezer:
++        cookies = []
++        for domain_index in range(66):
++            for cookie_index in range(50):
++                name = f"cookie{domain_index}_{cookie_index}"
++                morsel = _make_morsel(name, domain=f"domain{domain_index}.example")
++                if domain_index < 6:
++                    morsel["max-age"] = "10"
++                cookies.append((name, morsel))
++        jar.update_cookies(cookies)
++        freezer.tick(60)
++
++        jar.update_cookies(
++            {"cookie66_0": _make_morsel("cookie66_0", domain="domain66.example")}
++        )
++
++    names = {cookie.key for cookie in jar}
++    assert len(jar) == cookiejar_module._COOKIE_QUOTA_TOTAL + 1
++    assert "cookie0_0" not in names
++    assert "cookie6_0" in names
++    assert "cookie66_0" in names
++
++
++async def test_filter_cookies_host_cookies_win_over_parent_domain_cookies() -> None:
++    jar = CookieJar()
++    sibling = URL("https://other.example.com/")
++    for batch in range(3):
++        jar.update_cookies_from_headers(
++            [f"p{batch}_{i}=v; Domain=example.com" for i in range(50)], sibling
++        )
++    jar.update_cookies_from_headers(["session=mine"], URL("https://app.example.com/"))
++
++    filtered = jar.filter_cookies(URL("https://app.example.com/"))
++
++    assert len(filtered) == cookiejar_module._MAX_COOKIES_PER_REQUEST
++    assert filtered["session"].value == "mine"
++
++
++async def test_quoted_path_with_semicolon_keeps_its_scope() -> None:
++    jar = CookieJar()
++    jar.update_cookies_from_headers(
++        ['sid=1; Path="/account/secure;v=1"'],
++        URL("https://example.com/account/secure/page"),
++    )
++
++    assert [cookie["path"] for cookie in jar] == ["/account/secure;v=1"]
++    assert not jar.filter_cookies(URL("https://example.com/account/secure/other"))
++
++
++async def test_update_cookies_unquotes_domain_and_path_attributes() -> None:
++    jar = CookieJar()
++    jar.update_cookies_from_headers(
++        ['a=1; Domain="example.com"; Path="/app"'], URL("https://example.com/")
++    )
++
++    assert set(jar.filter_cookies(URL("https://sub.example.com/app"))) == {"a"}
++
++
[email protected](
++    ("response_url", "domain"),
++    ((URL("https://example.com/"), "example.com"), (URL(), "")),
++)
++async def test_filter_cookies_tracks_stored_cookie_name(
++    response_url: URL, domain: str
++) -> None:
++    jar = CookieJar()
++    cookies: SimpleCookie = SimpleCookie()
++    cookies["real"] = "value"
++    jar.update_cookies({"alias": cookies["real"]}, response_url)
++
++    jar.filter_cookies(URL("https://example.com/"))
++
++    assert set(jar._access_generations) == {(domain, "", "alias")}
++
++
++async def test_filter_cookies_cached_length_counts_octets() -> None:
++    jar = CookieJar(quote_cookie=False)
++    url = URL("https://example.com/")
++    # 8 + len("a=") + 2 * 4089 octets is 8,188: "a" fits alone, "a" and "b" don't.
++    jar.update_cookies({"a": "\u00e9" * 4089}, url)
++    assert set(jar.filter_cookies(url)) == {"a"}
++
++    jar.update_cookies({"b": "xx"}, url)
++
++    # "b" is admitted first; the cached "a" must be measured in octets.
++    assert set(jar.filter_cookies(url)) == {"b"}
++
++
++async def test_cookie_jar_send_updates_eviction_recency() -> None:
++    jar = CookieJar()
++    url = URL("https://example.com/hit")
++    cookies = [("sent", _make_morsel("sent", path="/hit"))]
++    cookies.extend(
++        (f"cookie{i}", _make_morsel(f"cookie{i}", path="/miss"))
++        for i in range(cookiejar_module._MAX_COOKIES_PER_DOMAIN - 1)
++    )
++    jar.update_cookies(cookies, url)
++
++    assert set(jar.filter_cookies(url)) == {"sent"}
++    jar.update_cookies({"new": "value"}, url)
++
++    names = {cookie.key for cookie in jar}
++    assert "sent" in names
++    assert "cookie0" not in names
++
++
++async def test_cookie_jar_limits_total_cookies(
++    caplog: pytest.LogCaptureFixture,
++) -> None:
++    jar = CookieJar(unsafe=True)
++    cookies = [
++        (
++            f"cookie{domain_index}_{cookie_index}",
++            _make_morsel(
++                f"cookie{domain_index}_{cookie_index}",
++                domain=f"domain{domain_index}.example",
++            ),
++        )
++        for domain_index in range(66)
++        for cookie_index in range(50)
++    ]
++    assert len(cookies) == cookiejar_module._MAX_COOKIES_TOTAL
++
++    jar.update_cookies(cookies)
++
++    assert len(jar) == cookiejar_module._MAX_COOKIES_TOTAL
++    assert any(cookie.key == "cookie0_0" for cookie in jar)
++
++    with caplog.at_level(logging.DEBUG, logger="aiohttp.internal"):
++        jar.update_cookies(
++            {"cookie66_0": _make_morsel("cookie66_0", domain="domain66.example")}
++        )
++
++    assert caplog.messages == ["Evicted 300 cookie(s) over the 3300-cookie total limit"]
++    # The jar is purged back to the total, oldest first, before adding.
++    assert len(jar) == cookiejar_module._COOKIE_QUOTA_TOTAL + 1
++    names = {cookie.key for cookie in jar}
++    assert "cookie5_49" not in names
++    assert "cookie6_0" in names
++    assert "cookie66_0" in names
++
++
++async def test_cookie_jar_load_resets_recency_and_applies_limits(
++    tmp_path: Path,
++) -> None:
++    data = {
++        "example.com|": {
++            f"cookie{i}": _saved_cookie(f"cookie{i}")
++            for i in range(cookiejar_module._MAX_COOKIES_PER_DOMAIN + 1)
++        }
++    }
++    file_path = _write_saved(tmp_path, data)
++    jar = CookieJar()
++    jar.update_cookies({"old": "value"}, URL("https://old.example/"))
++
++    jar.load(file_path)
++
++    assert len(jar) == cookiejar_module._COOKIE_QUOTA_PER_DOMAIN
++    names = {cookie.key for cookie in jar}
++    assert "old" not in names
++    assert f"cookie{_TRIM}" not in names
++    assert f"cookie{_TRIM + 1}" in names
++    assert f"cookie{cookiejar_module._MAX_COOKIES_PER_DOMAIN}" in names
++
++
[email protected]("deadline", ["nan", "inf", "-inf", "not-a-number", 10**1000])
++async def test_cookie_jar_load_rejects_invalid_expiration(
++    tmp_path: Path, deadline: str | int
++) -> None:
++    data = {
++        "example.com|": {"cookie": _saved_cookie("cookie", expires_timestamp=deadline)}
++    }
++    file_path = _write_saved(tmp_path, data)
++    jar = CookieJar()
++
++    with pytest.raises(
++        ValueError,
++        match=r"Cookie 'cookie' in 'example.com\|': expiration timestamp must be",
++    ) as exc_info:
++        jar.load(file_path)
++
++    assert exc_info.value.__cause__ is not None
++    assert len(jar) == 0
++    assert not jar._expirations
++    assert not jar._expire_heap
++
++
++async def test_cookie_jar_save_load_round_trips_numeric_attribute(
++    tmp_path: Path,
++) -> None:
++    url = URL("https://example.com/")
++    cookies: SimpleCookie = SimpleCookie()
++    cookies["sid"] = "value"
++    cookies["sid"]["version"] = 1
++    jar = CookieJar()
++    jar.update_cookies(cookies, url)
++    file_path = tmp_path / "cookies.json"
++    jar.save(file_path)
++
++    loaded = CookieJar()
++    loaded.load(file_path)
++
++    assert [cookie.key for cookie in loaded] == ["sid"]
++
++
[email protected](("attr", "value"), (("path", 5), ("max-age", ["invalid"])))
++async def test_cookie_jar_load_invalid_attribute_leaves_jar_unchanged(
++    tmp_path: Path, attr: str, value: object
++) -> None:
++    record = _saved_cookie("sid")
++    record[attr] = value
++    file_path = _write_saved(tmp_path, {"example.com|/": {"sid": record}})
++    jar = CookieJar()
++    jar.update_cookies({"existing": "value"}, URL("https://example.com/"))
++
++    with pytest.raises(TypeError):
++        jar.load(file_path)
++
++    assert [cookie.key for cookie in jar] == ["existing"]
++
++
++async def test_cookie_jar_load_failure_leaves_jar_unchanged(tmp_path: Path) -> None:
++    deadline = 4102444800.0
++    cookies = {
++        f"cookie{i}": _saved_cookie(f"cookie{i}", expires_timestamp=deadline)
++        for i in range(1000)
++    }
++    cookies["invalid"] = _saved_cookie("invalid", expires_timestamp="nan")
++    file_path = _write_saved(tmp_path, {"example.com|": cookies})
++    jar = CookieJar()
++    jar.update_cookies({"existing": "value"}, URL("https://example.com/"))
++
++    with pytest.raises(ValueError, match="must be a finite number"):
++        jar.load(file_path)
++
++    assert [cookie.key for cookie in jar] == ["existing"]
++
++
++async def test_oversized_secure_value_keeps_cookie_off_plain_http() -> None:
++    jar = CookieJar()
++    jar.update_cookies_from_headers(
++        [f"sid=1; Secure={'x' * (_MAX_COOKIE_ATTRIBUTE_VALUE_LENGTH + 1)}"],
++        URL("https://example.com/"),
++    )
++
++    assert "sid" in jar.filter_cookies(URL("https://example.com/"))
++    assert "sid" not in jar.filter_cookies(URL("http://example.com/"))
++
++
++def _assert_consistent(jar: CookieJar) -> None:
++    """Check the jar's bookkeeping against the cookies it stores."""
++    stored = {
++        (domain, path, name)
++        for (domain, path), cookies in jar._cookies.items()
++        for name in cookies
++    }
++    assert jar._cookie_count == len(stored) == len(jar)
++    assert jar._domain_counts == Counter(domain for domain, _, _ in stored)
++    assert set(jar._access_generations) == stored
++    assert all(
++        generation <= jar._next_access_generation
++        for generation in jar._access_generations.values()
++    )
++    assert jar._host_only_cookies <= stored
++    assert set(jar._expirations) <= stored
++    for jar_key, morsels in jar._morsel_cache.items():
++        for name, (morsel, _, cookie_key) in morsels.items():
++            assert cookie_key == jar_key + (name,)
++            assert cookie_key in stored
++            assert morsel.value == jar._cookies[jar_key][name].value
++
++
++async def test_cookie_jar_bookkeeping_stays_consistent(
++    monkeypatch: pytest.MonkeyPatch, tmp_path: Path
++) -> None:
++    # Small limits so eviction, purging and output limits happen often.
++    monkeypatch.setattr(cookiejar_module, "_MAX_COOKIES_PER_DOMAIN", 6)
++    monkeypatch.setattr(cookiejar_module, "_COOKIE_QUOTA_PER_DOMAIN", 4)
++    monkeypatch.setattr(cookiejar_module, "_MAX_COOKIES_TOTAL", 14)
++    monkeypatch.setattr(cookiejar_module, "_COOKIE_QUOTA_TOTAL", 10)
++    monkeypatch.setattr(cookiejar_module, "_MAX_COOKIES_PER_REQUEST", 5)
++    rng = random.Random(13930)
++    hosts = ("example.com", "a.example.com", "b.example.com", "c.a.example.com")
++    file_path = tmp_path / "cookies.json"
++    jar = CookieJar()
++
++    def random_url() -> URL:
++        return URL(f"{rng.choice(('http', 'https'))}://{rng.choice(hosts)}/x/y")
++
++    for _ in range(3000):
++        operation = rng.randrange(10)
++        if operation < 5:
++            field = f"c{rng.randrange(10)}={rng.choice(('1', '2', 'x' * 40))}"
++            if rng.random() < 0.5:
++                field += f"; Domain={rng.choice(hosts[:3])}"
++            if rng.random() < 0.5:
++                field += f"; Path={rng.choice(('/', '/x'))}"
++            if rng.random() < 0.4:
++                field += "; Secure"
++            if rng.random() < 0.3:
++                field += f"; Max-Age={rng.choice(('0', '3600'))}"
++            jar.update_cookies_from_headers([field], random_url())
++        elif operation == 5:
++            jar.update_cookies({f"c{rng.randrange(10)}": "v"}, random_url())
++        elif operation == 6:
++            jar.filter_cookies(random_url())
++        elif operation == 7:
++            jar.clear(lambda morsel: bool(morsel["secure"]))
++        elif operation == 8:
++            if rng.random() < 0.5:
++                jar.clear_domain(rng.choice(hosts))
++            else:
++                jar.save(file_path)
++                jar.load(file_path)
++        elif rng.random() < 0.1:
++            jar.clear()
++        _assert_consistent(jar)
++
++
++async def test_cookie_jar_save_load_round_trips_stored_name(tmp_path: Path) -> None:
++    url = URL("https://example.com/")
++    cookies: SimpleCookie = SimpleCookie()
++    cookies["real"] = "value"
++    jar = CookieJar()
++    jar.update_cookies({"alias": cookies["real"]}, url)
++    file_path = tmp_path / "cookies.json"
++    jar.save(file_path)
++
++    loaded = CookieJar()
++    loaded.load(file_path)
++
++    assert loaded.filter_cookies(url).output(header="", sep=";") == (
++        jar.filter_cookies(url).output(header="", sep=";")
++    )
++
++
++async def test_cookie_jar_update_compacts_expirations_after_limit_eviction() -> None:
++    jar = CookieJar()
++    cookies: list[tuple[str, Morsel[str]]] = []
++    for index in range(1000):
++        name = f"cookie{index}"
++        morsel = _make_morsel(name)
++        morsel["max-age"] = "3600"
++        cookies.append((name, morsel))
++
++    jar.update_cookies(cookies, URL("https://example.com/"))
++
++    assert (
++        cookiejar_module._COOKIE_QUOTA_PER_DOMAIN
++        < len(jar)
++        <= cookiejar_module._MAX_COOKIES_PER_DOMAIN
++    )
++    assert len(jar._expirations) == len(jar)
++    assert len(jar._expire_heap) <= max(
++        cookiejar_module._MIN_SCHEDULED_COOKIE_EXPIRATION, 2 * len(jar._expirations)
++    )
++
++
++async def test_session_cookie_replacement_drops_old_expiry() -> None:
++    jar = CookieJar()
++    url = URL("https://example.com/")
++    with freeze_time("2030-01-01") as freezer:
++        jar.update_cookies_from_headers(["sid=old; Max-Age=60"], url)
++        jar.update_cookies_from_headers(["sid=new"], url)
++        freezer.tick(120)
++
++        assert jar.filter_cookies(url)["sid"].value == "new"
++
++
++async def test_cookie_jar_load_session_replacement_drops_old_expiry(
++    tmp_path: Path,
++) -> None:
++    with freeze_time("2030-01-01") as freezer:
++        deadline = datetime.datetime.now(datetime.timezone.utc).timestamp() + 60
++        file_path = _write_saved(
++            tmp_path,
++            {
++                "example.com|": {
++                    "sid": _saved_cookie("sid", "old", expires_timestamp=deadline)
++                },
++                "example.com|/": {"sid": _saved_cookie("sid", "new")},
++            },
++        )
++        jar = CookieJar()
++        jar.load(file_path)
++        freezer.tick(120)
++
++        assert jar.filter_cookies(URL("https://example.com/"))["sid"].value == "new"
++
++
++async def test_cookie_jar_load_replacement_clears_stale_expiration(
++    tmp_path: Path,
++) -> None:
++    file_path = _write_saved(
++        tmp_path,
++        {
++            "example.com|": {
++                "sid": _saved_cookie("sid", "expired", expires_timestamp=0.0)
++            },
++            "example.com|/": {"sid": _saved_cookie("sid", "live")},
++        },
++    )
++    jar = CookieJar()
++
++    jar.load(file_path)
++
++    assert len(jar) == 1
++    assert jar.filter_cookies(URL("https://example.com/"))["sid"].value == "live"
++
++
++async def test_cookie_jar_load_rejected_collision_keeps_expiration(
++    tmp_path: Path,
++) -> None:
++    file_path = _write_saved(
++        tmp_path,
++        {
++            "example.com|": {
++                "sid": _saved_cookie("sid", "expired", expires_timestamp=0.0)
++            },
++            "other.example|": {"sid": _saved_cookie("sid", "rejected")},
++        },
++    )
++    jar = CookieJar()
++
++    jar.load(file_path)
++
++    assert len(jar) == 0
++
++
++async def test_cookie_jar_load_alternating_same_deadline_keeps_heap_bounded(
++    tmp_path: Path,
++) -> None:
++    deadline = 4102444800.0
++    data = {
++        f"example.com|source{index}": {
++            "sid": _saved_cookie(
++                "sid",
++                str(index),
++                path="/",
++                **(
++                    {"expires_timestamp": deadline}
++                    if index % 2 == 0 or index == 999
++                    else {}
++                ),
++            )
++        }
++        for index in range(1000)
++    }
++    file_path = _write_saved(tmp_path, data)
++    jar = CookieJar()
++
++    jar.load(file_path)
++
++    cookie_key = ("example.com", "", "sid")
++    assert len(jar) == 1
++    assert jar.filter_cookies(URL("https://example.com/"))["sid"].value == "999"
++    assert jar._expirations == {cookie_key: deadline}
++    assert len(jar._expire_heap) <= max(
++        cookiejar_module._MIN_SCHEDULED_COOKIE_EXPIRATION, 2 * len(jar._expirations)
++    )
++
++    with mock.patch("aiohttp.cookiejar.time.time", return_value=deadline + 1):
++        jar._do_expiration()
++
++    assert len(jar) == 0
++    assert jar._expire_heap == []
++
++
++async def test_cookie_jar_load_expired_normalized_collisions_clear_heap(
++    tmp_path: Path,
++) -> None:
++    data: dict[str, dict[str, dict[str, object]]] = {}
++    for index in range(1000):
++        name = f"cookie{index}"
++        base = _saved_cookie(name, path="/")
++        data[f"example.com|future{index}"] = {
++            name: {**base, "expires_timestamp": 4102444800.0}
++        }
++        data[f"example.com|expired{index}"] = {name: {**base, "expires_timestamp": 0.0}}
++    file_path = _write_saved(tmp_path, data)
++    jar = CookieJar()
++
++    jar.load(file_path)
++
++    assert len(jar) == 0
++    assert not jar._expirations
++    assert not jar._expire_heap
++
++
++async def test_cookie_jar_load_expires_before_eviction(tmp_path: Path) -> None:
++    cookies = {
++        f"cookie{i}": _saved_cookie(f"cookie{i}", expires_timestamp=4102444800.0)
++        for i in range(cookiejar_module._MAX_COOKIES_PER_DOMAIN)
++    }
++    cookies["expired"] = _saved_cookie("expired", expires_timestamp=0.0)
++    file_path = _write_saved(tmp_path, {"example.com|": cookies})
++
++    jar = CookieJar()
++    jar.load(file_path)
++
++    names = {cookie.key for cookie in jar}
++    assert len(jar) == cookiejar_module._MAX_COOKIES_PER_DOMAIN
++    assert "cookie0" in names
++    assert "expired" not in names
++    assert len(jar._access_generations) == len(jar)
++    assert len(jar._expirations) == len(jar)
++
++
++async def test_cookie_jar_load_cleans_evicted_expiry_metadata(tmp_path: Path) -> None:
++    cookies = {
++        f"cookie{i}": _saved_cookie(f"cookie{i}", secure=True)
++        for i in range(cookiejar_module._MAX_COOKIES_PER_DOMAIN)
++    }
++    cookies["nonsecure"] = _saved_cookie("nonsecure", expires_timestamp=4102444800.0)
++    file_path = _write_saved(tmp_path, {"example.com|": cookies})
++
++    jar = CookieJar()
++    jar.load(file_path)
++
++    rejected_key = ("example.com", "", "nonsecure")
++    assert len(jar) == cookiejar_module._MAX_COOKIES_PER_DOMAIN
++    assert rejected_key not in jar._access_generations
++    assert rejected_key not in jar._expirations
++
++
++async def test_delete_cookies_cleans_access_metadata() -> None:
++    jar = CookieJar()
++    url = URL("https://example.com/")
++    jar.update_cookies({"cookie": "value"}, url)
++    jar.filter_cookies(url)
++    cookie_key = ("example.com", "", "cookie")
++    assert cookie_key in jar._access_generations
++
++    jar._delete_cookies([("example.com", "", "missing")])
++    assert len(jar) == 1
++
++    jar._delete_cookies([cookie_key])
++
++    assert cookie_key not in jar._access_generations
++    assert ("example.com", "") not in jar._cookies
++    assert ("example.com", "") not in jar._morsel_cache
++
++
[email protected](
++    ("cookie_count", "expected_count"),
++    (
++        (cookiejar_module._MAX_COOKIES_PER_REQUEST,) * 2,
++        (
++            cookiejar_module._MAX_COOKIES_PER_REQUEST + 1,
++            cookiejar_module._MAX_COOKIES_PER_REQUEST,
++        ),
++    ),
++)
++async def test_filter_cookies_limits_cookie_count(
++    cookie_count: int, expected_count: int
++) -> None:
++    jar = CookieJar()
++    hostname = "a.b.c.example.com"
++    domains = ("com", "example.com", "c.example.com", "b.c.example.com")
++    cookies = [
++        (
++            f"cookie{domain_index}_{cookie_index}",
++            _make_morsel(f"cookie{domain_index}_{cookie_index}", domain=domain),
++        )
++        for domain_index, domain in enumerate(domains)
++        for cookie_index in range(50)
++    ]
++    jar.update_cookies(cookies[:cookie_count], URL(f"https://{hostname}/"))
++
++    filtered = jar.filter_cookies(URL(f"https://{hostname}/"))
++
++    assert len(filtered) == expected_count
++
++
++async def test_filter_cookies_logs_cookies_over_the_limits(
++    caplog: pytest.LogCaptureFixture,
++) -> None:
++    url = URL("https://example.com/")
++    jar = CookieJar()
++    jar.update_cookies({"small": "v", "big": "x" * 8200}, url)
++
++    with caplog.at_level(logging.DEBUG, logger="aiohttp.internal"):
++        assert set(jar.filter_cookies(url)) == {"small"}
++        jar.update_cookies({"big": "x"}, url)
++        assert set(jar.filter_cookies(url)) == {"small", "big"}
++
++    assert caplog.messages == [
++        "Omitted 1 cookie(s) for example.com over the 150-cookie"
++        " or 8190-octet Cookie header limit"
++    ]
++
++
++async def test_filter_cookies_limits_complete_header_length() -> None:
++    jar = CookieJar()
++    url = URL("https://example.com/")
++    exact_value = "x" * (cookiejar_module._MAX_COOKIE_HEADER_LENGTH - 10)
++    jar.update_cookies({"a": exact_value}, url)
++
++    exact = jar.filter_cookies(url)
++
++    assert cookiejar_module._COOKIE_HEADER_PREFIX_LENGTH + len(
++        exact.output(header="", sep=";").strip().encode()
++    ) == (cookiejar_module._MAX_COOKIE_HEADER_LENGTH)
++
++    jar.update_cookies({"a": exact_value + "x"}, url)
++    assert not jar.filter_cookies(url)
++
++
++async def test_filter_cookies_counts_the_real_separator() -> None:
++    """Two cookies whose real Cookie header is exactly the limit are both sent."""
++    jar = CookieJar()
++    url = URL("https://example.com/")
++    pairs = len("Cookie: ") + len("a=") + len("; ") + len("b=") + 10
++    jar.update_cookies(
++        {
++            "a": "x" * (cookiejar_module._MAX_COOKIE_HEADER_LENGTH - pairs),
++            "b": "y" * 10,
++        },
++        url,
[… more lines in the raw message]

Lines of this file are not shown. View the raw message.

meta-python/recipes-devtools/python/python3-aiohttp_3.13.5.bb +1 -0
index 293d15fdaa..bfd8912a0d 100644

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.35.6

Part of the diff is not shown here. View the raw message.

#4 lore raw

PATCH 4/10 python3-aiohttp: fix CVE-2026-128126

In reply to Ashishkumar Parmar X (asparmar - E INFOCHIPS PRIVATE LIMITED at Cisco)

From: Ashishkumar Parmar <[email protected]>

This patch applies the form field count limit for CVE-2026-128126 from the upstream stable branch [1].

Bound the number of URL-encoded and multipart form fields accepted by a request and return HTTP 413 when the limit is exceeded.

[1] https://github.com/aio-libs/aiohttp/commit/615fec3d4f088f30d2ee72cad760152e92aa1c53
[2] https://github.com/aio-libs/aiohttp/security/advisories/GHSA-xgw8-8ccx-rmqh

---
 .../python3-aiohttp/CVE-2026-128126.patch     | 599 ++++++++++++++++++
 .../python/python3-aiohttp_3.13.5.bb          |   1 +
 2 files changed, 600 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128126.patch
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128126.patch new file +599 -0
new file mode 100644
index 0000000000..ac29cc6e2a
@@ -0,0 +1,599 @@
+From 9560840e8b61ccd1cb7c0ba4930f4921d5a37a1f Mon Sep 17 00:00:00 2001
+From: "J. Nick Koston" <[email protected]>
+Date: Wed, 16 Sep 2026 11:27:29 -0500
+Subject: [PATCH] [PR #13738/8b010057 backport][3.14] Add client_max_fields
+ option to Application (#13741)
+
+Fixes
+#123
+
+CVE: CVE-2026-128126
+Upstream-Status: Backport [https://github.com/aio-libs/aiohttp/commit/615fec3d4f088f30d2ee72cad760152e92aa1c53]
+
+Backport Changes:
+- Retain parse_qsl and use its max_num_fields argument because the
+  current yarl dependency has no query_to_pairs API. Preserve blank
+  values and charset decoding without upgrading that dependency.
+- Adapt the changelog to describe the field limit without claiming a
+  parser switch. Omit upstream versionadded directives because they do
+  not describe this backport.
+- Supply actual_size to HTTPRequestEntityTooLarge, as required by the
+  existing exception constructor, and retain the existing type context.
+- Use the existing StreamReader buffer size in the URL-encoded tests;
+  DEFAULT_CHUNK_SIZE is not available in the current helpers module.
+- Omit the AGENTS.md hunk: that upstream developer-documentation file
+  is absent and is unrelated to the form-field limit.
+
+Signed-off-by: Ashishkumar Parmar <[email protected]>
+---
+ CHANGES/13738.feature.rst    |   7 ++
+ aiohttp/test_utils.py        |  10 ++-
+ aiohttp/web_app.py           |   4 +
+ aiohttp/web_request.py       |  43 ++++++++--
+ docs/web_advanced.rst        |   5 +-
+ docs/web_quickstart.rst      |   6 +-
+ docs/web_reference.rst       |  25 +++++-
+ tests/test_web_functional.py |  59 +++++++++++++-
+ tests/test_web_request.py    | 147 +++++++++++++++++++++++++++++++++++
+ 9 files changed, 293 insertions(+), 13 deletions(-)
+ create mode 100644 CHANGES/13738.feature.rst
+
+diff --git a/CHANGES/13738.feature.rst b/CHANGES/13738.feature.rst
+new file mode 100644
+index 0000000..2aec51e
+--- /dev/null
++++ b/CHANGES/13738.feature.rst
+@@ -0,0 +1,7 @@
++Added the ``client_max_fields`` argument to
++:class:`~aiohttp.web.Application` (default ``1000``) to cap the number
++of URL-encoded and multipart form fields accepted by
++:meth:`~aiohttp.web.BaseRequest.post`. Forms with more than
++1000 fields now receive a ``413`` response unless the cap is raised;
++``0`` disables the limit. Empty URL-encoded segments also count
++toward the limit -- by :user:`bdraco`.
+diff --git a/aiohttp/test_utils.py b/aiohttp/test_utils.py
+index 34b77d4..a0dd261 100644
+--- a/aiohttp/test_utils.py
++++ b/aiohttp/test_utils.py
+@@ -676,6 +676,7 @@ def make_mocked_request(
+     payload: StreamReader = EMPTY_PAYLOAD,
+     sslcontext: Optional[SSLContext] = None,
+     client_max_size: int = 1024**2,
++    client_max_fields: int = 1000,
+     loop: Any = ...,
+ ) -> Request:
+     """Creates mocked web.Request testing purposes.
+@@ -750,7 +751,14 @@ def make_mocked_request(
+     protocol.writer = writer
+ 
+     req = Request(
+-        message, payload, protocol, writer, task, loop, client_max_size=client_max_size
++        message,
++        payload,
++        protocol,
++        writer,
++        task,
++        loop,
++        client_max_size=client_max_size,
++        client_max_fields=client_max_fields,
+     )
+ 
+     match_info = UrlMappingMatchInfo(
+diff --git a/aiohttp/web_app.py b/aiohttp/web_app.py
+index 619c008..3ac8545 100644
+--- a/aiohttp/web_app.py
++++ b/aiohttp/web_app.py
+@@ -114,6 +114,7 @@ class Application(MutableMapping[Union[str, AppKey[Any]], Any]):
+             "_on_shutdown",
+             "_on_cleanup",
+             "_client_max_size",
++            "_client_max_fields",
+             "_cleanup_ctx",
+         ]
+     )
+@@ -126,6 +127,7 @@ class Application(MutableMapping[Union[str, AppKey[Any]], Any]):
+         middlewares: Iterable[Middleware] = (),
+         handler_args: Optional[Mapping[str, Any]] = None,
+         client_max_size: int = 1024**2,
++        client_max_fields: int = 1000,
+         loop: Optional[asyncio.AbstractEventLoop] = None,
+         debug: Any = ...,  # mypy doesn't support ellipsis
+     ) -> None:
+@@ -173,6 +175,7 @@ class Application(MutableMapping[Union[str, AppKey[Any]], Any]):
+         self._on_startup.append(self._cleanup_ctx._on_startup)
+         self._on_cleanup.append(self._cleanup_ctx._on_cleanup)
+         self._client_max_size = client_max_size
++        self._client_max_fields = client_max_fields
+ 
+     def __init_subclass__(cls: Type["Application"]) -> None:
+         warnings.warn(
+@@ -508,6 +511,7 @@ class Application(MutableMapping[Union[str, AppKey[Any]], Any]):
+             task,
+             self._loop,
+             client_max_size=self._client_max_size,
++            client_max_fields=self._client_max_fields,
+         )
+ 
+     def _prepare_middleware(self) -> Iterator[Tuple[Middleware, bool]]:
+diff --git a/aiohttp/web_request.py b/aiohttp/web_request.py
+index 6e9de9a..ca6e7c4 100644
+--- a/aiohttp/web_request.py
++++ b/aiohttp/web_request.py
+@@ -147,6 +147,14 @@ _FORWARDED_PAIR_RE: Final[Pattern[str]] = re.compile(_FORWARDED_PAIR)
+ ############################################################
+ 
+ 
++def _too_many_fields(max_fields: int) -> HTTPRequestEntityTooLarge:
++    return HTTPRequestEntityTooLarge(
++        max_fields,
++        max_fields + 1,
++        text=f"Maximum number of form fields {max_fields} exceeded.",
++    )
++
++
+ class BaseRequest(MutableMapping[str, Any], HeadersMixin):
+ 
+     POST_METHODS = {
+@@ -173,6 +181,7 @@ class BaseRequest(MutableMapping[str, Any], HeadersMixin):
+             "_cache",
+             "_task",
+             "_client_max_size",
++            "_client_max_fields",
+             "_loop",
+             "_transport_sslcontext",
+             "_transport_peername",
+@@ -191,6 +200,7 @@ class BaseRequest(MutableMapping[str, Any], HeadersMixin):
+         loop: asyncio.AbstractEventLoop,
+         *,
+         client_max_size: int = 1024**2,
++        client_max_fields: int = 1000,
+         state: Optional[Dict[str, Any]] = None,
+         scheme: Optional[str] = None,
+         host: Optional[str] = None,
+@@ -233,6 +243,7 @@ class BaseRequest(MutableMapping[str, Any], HeadersMixin):
+         self._state = {} if state is None else state
+         self._task = task
+         self._client_max_size = client_max_size
++        self._client_max_fields = client_max_fields
+         self._loop = loop
+ 
+         self._transport_sslcontext = protocol.ssl_context
+@@ -251,6 +262,7 @@ class BaseRequest(MutableMapping[str, Any], HeadersMixin):
+         host: Union[str, _SENTINEL] = sentinel,
+         remote: Union[str, _SENTINEL] = sentinel,
+         client_max_size: Union[int, _SENTINEL] = sentinel,
++        client_max_fields: Union[int, _SENTINEL] = sentinel,
+     ) -> "BaseRequest":
+         """Clone itself with replacement some attributes.
+ 
+@@ -287,6 +299,8 @@ class BaseRequest(MutableMapping[str, Any], HeadersMixin):
+             kwargs["remote"] = remote
+         if client_max_size is sentinel:
+             client_max_size = self._client_max_size
++        if client_max_fields is sentinel:
++            client_max_fields = self._client_max_fields
+ 
+         return self.__class__(
+             message,
+@@ -296,6 +310,7 @@ class BaseRequest(MutableMapping[str, Any], HeadersMixin):
+             self._task,
+             self._loop,
+             client_max_size=client_max_size,
++            client_max_fields=client_max_fields,
+             state=self._state.copy(),
+             **kwargs,
+         )
+@@ -322,6 +337,10 @@ class BaseRequest(MutableMapping[str, Any], HeadersMixin):
+     def client_max_size(self) -> int:
+         return self._client_max_size
+ 
++    @property
++    def client_max_fields(self) -> int:
++        return self._client_max_fields
++
+     @reify
+     def message(self) -> RawRequestMessage:
+         warnings.warn("Request.message is deprecated", DeprecationWarning, stacklevel=3)
+@@ -757,11 +776,13 @@ class BaseRequest(MutableMapping[str, Any], HeadersMixin):
+             self._post = MultiDictProxy(MultiDict())
+             return self._post
+ 
+-        out: MultiDict[Union[str, bytes, FileField]] = MultiDict()
++        out: MultiDict[Union[str, bytes, FileField]]
+ 
+         if content_type == "multipart/form-data":
++            out = MultiDict()
+             multipart = await self.multipart()
+             max_size = self._client_max_size
++            max_fields = self._client_max_fields
+ 
+             payload = self._payload
+             while (field := await multipart.next()) is not None:
+@@ -771,6 +792,8 @@ class BaseRequest(MutableMapping[str, Any], HeadersMixin):
+                     raise HTTPRequestEntityTooLarge(
+                         max_size=max_size, actual_size=payload.total_bytes
+                     )
++                if 0 < max_fields <= len(out):
++                    raise _too_many_fields(max_fields)
+ 
+                 field_ct = field.headers.get(hdrs.CONTENT_TYPE)
+ 
+@@ -850,17 +873,23 @@ class BaseRequest(MutableMapping[str, Any], HeadersMixin):
+                     raise ValueError(
+                         "To decode nested multipart you need to use custom reader",
+                     )
++        elif not (data := await self.read()):
++            out = MultiDict()
+         else:
+-            data = await self.read()
+-            if data:
+-                charset = self.charset or "utf-8"
+-                out.extend(
++            charset = self.charset or "utf-8"
++            query = data.rstrip().decode(charset)
++            max_fields = self._client_max_fields
++            try:
++                out = MultiDict(
+                     parse_qsl(
+-                        data.rstrip().decode(charset),
++                        query,
+                         keep_blank_values=True,
++                        max_num_fields=max_fields if max_fields > 0 else None,
+                         encoding=charset,
+                     )
+                 )
++            except ValueError:
++                raise _too_many_fields(max_fields) from None
+ 
+         self._post = MultiDictProxy(out)
+         return self._post
+@@ -935,6 +964,7 @@ class Request(BaseRequest):
+         host: Union[str, _SENTINEL] = sentinel,
+         remote: Union[str, _SENTINEL] = sentinel,
+         client_max_size: Union[int, _SENTINEL] = sentinel,
++        client_max_fields: Union[int, _SENTINEL] = sentinel,
+     ) -> "Request":
+         ret = super().clone(
+             method=method,
+@@ -944,6 +974,7 @@ class Request(BaseRequest):
+             host=host,
+             remote=remote,
+             client_max_size=client_max_size,
++            client_max_fields=client_max_fields,
+         )
+         new_ret = cast(Request, ret)
+         new_ret._match_info = self._match_info
+diff --git a/docs/web_advanced.rst b/docs/web_advanced.rst
+index 0912327..766c07f 100644
+--- a/docs/web_advanced.rst
++++ b/docs/web_advanced.rst
+@@ -1255,8 +1255,9 @@ That's why *aiohttp server* should setup *forwarded* headers in custom
+ middleware in tight conjunction with *reverse proxy configuration*.
+ 
+ For changing :attr:`BaseRequest.scheme` :attr:`BaseRequest.host`
+-:attr:`BaseRequest.remote` and :attr:`BaseRequest.client_max_size`
+-the middleware might use :meth:`BaseRequest.clone`.
++:attr:`BaseRequest.remote`, :attr:`BaseRequest.client_max_size` and
++:attr:`BaseRequest.client_max_fields` the middleware might use
++:meth:`BaseRequest.clone`.
+ 
+ .. seealso::
+ 
+diff --git a/docs/web_quickstart.rst b/docs/web_quickstart.rst
+index 2d8c336..6ebe2bc 100644
+--- a/docs/web_quickstart.rst
++++ b/docs/web_quickstart.rst
+@@ -480,8 +480,10 @@ To access form data with ``"POST"`` method use
+ :meth:`aiohttp.web.BaseRequest.post` accepts both
+ ``'application/x-www-form-urlencoded'`` and ``'multipart/form-data'``
+ form's data encoding (e.g. ``<form enctype="multipart/form-data">``).
+-It stores files data in temporary directory. If `client_max_size` is
+-specified `post` raises `ValueError` exception.
++It stores files data in temporary directory. If the body exceeds
++`client_max_size` or the form has more than `client_max_fields` fields
++(1000 by default, `0` disables the cap), `post` raises
++``HTTPRequestEntityTooLarge`` exception.
+ For efficiency use :meth:`aiohttp.web.BaseRequest.multipart`, It is especially effective
+ for uploading large files (:ref:`aiohttp-web-file-upload`).
+ 
+diff --git a/docs/web_reference.rst b/docs/web_reference.rst
+index ddb43e8..f48ecc1 100644
+--- a/docs/web_reference.rst
++++ b/docs/web_reference.rst
+@@ -157,6 +157,15 @@ and :ref:`aiohttp-web-signals` handlers.
+ 
+       Read-only :class:`int` property.
+ 
++   .. attribute:: client_max_fields
++
++      The maximum number of form fields accepted by :meth:`~BaseRequest.post`,
++      ``0`` disables the limit.
++
++      The value could be overridden by :meth:`~BaseRequest.clone`.
++
++      Read-only :class:`int` property.
++
+    .. attribute:: path_qs
+ 
+       The URL including PATH_INFO and the query string. e.g.,
+@@ -492,6 +501,10 @@ and :ref:`aiohttp-web-signals` handlers.
+       *application/x-www-form-urlencoded* or *multipart/form-data*
+       returns empty multidict.
+ 
++      Raises ``HTTPRequestEntityTooLarge`` if the body exceeds
++      :attr:`client_max_size` or the form has more than
++      :attr:`client_max_fields` fields.
++
+       .. note::
+ 
+          The method **does** store read data internally, subsequent
+@@ -1438,7 +1451,7 @@ Application and Router
+ 
+ .. class:: Application(*, logger=<default>, router=None, middlewares=(), \
+                        handler_args=None, client_max_size=1024**2, \
+-                       loop=None, debug=...)
++                       client_max_fields=1000, loop=None, debug=...)
+ 
+    Application is a synonym for web-server.
+ 
+@@ -1491,6 +1504,16 @@ Application and Router
+                            value, it raises an
+                            `HTTPRequestEntityTooLarge` exception.
+ 
++   :param client_max_fields: maximum number of form fields accepted by
++                             :meth:`BaseRequest.post`, counting both
++                             urlencoded pairs and multipart parts.  For
++                             urlencoded bodies every ``&``-separated
++                             segment counts, including empty ones, so the
++                             check runs before any field is decoded.  If a
++                             POST request exceeds this value, it raises an
++                             `HTTPRequestEntityTooLarge` exception.
++                             ``0`` disables the limit.  Default is ``1000``.
++
+    :param loop: event loop
+ 
+       .. deprecated:: 2.0
+diff --git a/tests/test_web_functional.py b/tests/test_web_functional.py
+index ffb2b95..c5c4b5b 100644
+--- a/tests/test_web_functional.py
++++ b/tests/test_web_functional.py
+@@ -6,9 +6,10 @@ import os
+ import pathlib
+ import socket
+ import sys
+-from typing import Any, Dict, Generator, NoReturn, Optional, Tuple
++from typing import Any, Callable, Dict, Generator, NoReturn, Optional, Tuple
+ import zlib
+ from contextlib import suppress
++from functools import partial
+ from unittest import mock
+ 
+ import pytest
+@@ -1993,6 +1994,62 @@ async def test_app_max_client_size(aiohttp_client: AiohttpClient) -> None:
+     await resp.release()
+ 
+ 
++def _multipart_form(count: int) -> aiohttp.FormData:
++    form = aiohttp.FormData(default_to_multipart=True)
++    for i in range(count):
++        form.add_field(f"f{i}", "v")
++    return form
++
++
[email protected](
++    ("make_app", "make_data", "expected_status", "expected_text"),
++    [
++        (
++            partial(web.Application, client_max_fields=2),
++            partial(dict, a="1", b="2", c="3"),
++            413,
++            "2 exceeded",
++        ),
++        (
++            partial(web.Application, client_max_fields=2),
++            partial(_multipart_form, 3),
++            413,
++            "2 exceeded",
++        ),
++        (
++            partial(web.Application, client_max_fields=0),
++            partial(dict, {f"f{i}": "v" for i in range(5)}),
++            200,
++            "5",
++        ),
++        (
++            web.Application,
++            partial(dict, {f"f{i}": "v" for i in range(1001)}),
++            413,
++            "1000 exceeded",
++        ),
++    ],
++)
++async def test_app_max_client_fields(
++    aiohttp_client: AiohttpClient,
++    make_app: Callable[[], web.Application],
++    make_data: Callable[[], object],
++    expected_status: int,
++    expected_text: str,
++) -> None:
++    async def handler(request: web.Request) -> web.Response:
++        form = await request.post()
++        return web.Response(text=str(len(form)))
++
++    app = make_app()
++    app.router.add_post("/", handler)
++    client = await aiohttp_client(app)
++
++    async with client.post("/", data=make_data()) as resp:
++        assert resp.status == expected_status
++        assert expected_text in await resp.text()
++
++
+ async def test_app_max_client_size_adjusted(aiohttp_client: AiohttpClient) -> None:
+     async def handler(request: web.Request) -> web.Response:
+         await request.post()
+diff --git a/tests/test_web_request.py b/tests/test_web_request.py
+index 44bf7a3..0ef96ac 100644
+--- a/tests/test_web_request.py
++++ b/tests/test_web_request.py
+@@ -780,6 +780,23 @@ def test_clone_override_client_max_size() -> None:
+     assert req2.client_max_size == 2048
+ 
+ 
++def test_client_max_fields_default() -> None:
++    req = make_mocked_request("GET", "/path")
++    assert req.client_max_fields == 1000
++
++
++def test_clone_client_max_fields() -> None:
++    req = make_mocked_request("GET", "/path", client_max_fields=5)
++    req2 = req.clone()
++    assert req2.client_max_fields == 5
++
++
++def test_clone_override_client_max_fields() -> None:
++    req = make_mocked_request("GET", "/path", client_max_fields=5)
++    req2 = req.clone(client_max_fields=10)
++    assert req2.client_max_fields == 10
++
++
+ def test_clone_method() -> None:
+     req = make_mocked_request("GET", "/path")
+     req2 = req.clone(method="POST")
+@@ -872,6 +889,136 @@ async def test_multipart_formdata(protocol) -> None:
+     assert dict(result) == {"a": "b", "c": "d"}
+ 
+ 
++def _multipart_form_payload(protocol: BaseProtocol, count: int) -> StreamReader:
++    payload = StreamReader(protocol, 2**16, loop=asyncio.get_running_loop())
++    payload.feed_data(
++        b"".join(
++            b"-----------------------------326931944431359\r\n"
++            b'Content-Disposition: form-data; name="f%d"\r\n'
++            b"\r\n"
++            b"v\r\n" % i
++            for i in range(count)
++        )
++        + b"-----------------------------326931944431359--\r\n"
++    )
++    payload.feed_eof()
++    return payload
++
++
++_MULTIPART_CONTENT_TYPE = (
++    "multipart/form-data; boundary=---------------------------326931944431359"
++)
++
++
++async def test_multipart_formdata_too_many_fields(protocol: BaseProtocol) -> None:
++    payload = _multipart_form_payload(protocol, 3)
++    req = make_mocked_request(
++        "POST",
++        "/",
++        headers={"CONTENT-TYPE": _MULTIPART_CONTENT_TYPE},
++        payload=payload,
++        client_max_fields=2,
++    )
++    with pytest.raises(web.HTTPRequestEntityTooLarge) as err:
++        await req.post()
++    assert err.value.status_code == 413
++    assert err.value.text == "Maximum number of form fields 2 exceeded."
++
++
[email protected](("client_max_fields", "count"), [(2, 2), (0, 5), (-1, 5)])
++async def test_multipart_formdata_within_field_limit(
++    protocol: BaseProtocol, client_max_fields: int, count: int
++) -> None:
++    payload = _multipart_form_payload(protocol, count)
++    req = make_mocked_request(
++        "POST",
++        "/",
++        headers={"CONTENT-TYPE": _MULTIPART_CONTENT_TYPE},
++        payload=payload,
++        client_max_fields=client_max_fields,
++    )
++    result = await req.post()
++    assert len(result) == count
++
++
++def _urlencoded_payload(protocol: BaseProtocol, body: bytes) -> StreamReader:
++    payload = StreamReader(
++        protocol, 2**16, loop=asyncio.get_running_loop()
++    )
++    payload.feed_data(body)
++    payload.feed_eof()
++    return payload
++
++
++_URLENCODED_HEADERS = {"Content-Type": "application/x-www-form-urlencoded"}
++
++
++async def test_urlencoded_form_too_many_fields(protocol: BaseProtocol) -> None:
++    payload = _urlencoded_payload(protocol, b"a=1&b=2&c=3")
++    req = make_mocked_request(
++        "POST", "/", payload=payload, headers=_URLENCODED_HEADERS, client_max_fields=2
++    )
++    with pytest.raises(web.HTTPRequestEntityTooLarge) as err:
++        await req.post()
++    assert err.value.status_code == 413
++    assert err.value.text == "Maximum number of form fields 2 exceeded."
++
++
++async def test_urlencoded_form_empty_segments_count(protocol: BaseProtocol) -> None:
++    payload = _urlencoded_payload(protocol, b"a=1&&b=2")
++    req = make_mocked_request(
++        "POST", "/", payload=payload, headers=_URLENCODED_HEADERS, client_max_fields=2
++    )
++    with pytest.raises(web.HTTPRequestEntityTooLarge):
++        await req.post()
++
++
[email protected](("client_max_fields", "count"), [(2, 2), (0, 5), (-1, 5)])
++async def test_urlencoded_form_within_field_limit(
++    protocol: BaseProtocol, client_max_fields: int, count: int
++) -> None:
++    body = "&".join(f"f{i}=v" for i in range(count)).encode()
++    payload = _urlencoded_payload(protocol, body)
++    req = make_mocked_request(
++        "POST",
++        "/",
++        payload=payload,
++        headers=_URLENCODED_HEADERS,
++        client_max_fields=client_max_fields,
++    )
++    result = await req.post()
++    assert len(result) == count
++
++
++async def test_urlencoded_form_empty_body(protocol: BaseProtocol) -> None:
++    payload = _urlencoded_payload(protocol, b"")
++    req = make_mocked_request("POST", "/", payload=payload, headers=_URLENCODED_HEADERS)
++    result = await req.post()
++    assert len(result) == 0
++
++
++async def test_urlencoded_form_parse_qsl_parity(protocol: BaseProtocol) -> None:
++    payload = _urlencoded_payload(protocol, b"a=1+2&b=&&c&d=%zz&e=%C3%A9&f=%FF")
++    req = make_mocked_request("POST", "/", payload=payload, headers=_URLENCODED_HEADERS)
++    result = await req.post()
++    assert list(result.items()) == [
++        ("a", "1 2"),
++        ("b", ""),
++        ("c", ""),
++        ("d", "%zz"),
++        ("e", "\u00e9"),
++        ("f", "\ufffd"),
++    ]
++
++
++async def test_urlencoded_form_with_non_utf8_charset(protocol: BaseProtocol) -> None:
++    payload = _urlencoded_payload(protocol, b"a=%E9&b=\xe9")
++    headers = {"Content-Type": "application/x-www-form-urlencoded; charset=latin-1"}
++    req = make_mocked_request("POST", "/", payload=payload, headers=headers)
++    result = await req.post()
++    assert list(result.items()) == [("a", "\u00e9"), ("b", "\u00e9")]
++
++
+ async def test_multipart_formdata_field_missing_name(protocol: BaseProtocol) -> None:
+     # Ensure ValueError is raised when Content-Disposition has no name
+     payload = StreamReader(protocol, 2**16, loop=asyncio.get_event_loop())
meta-python/recipes-devtools/python/python3-aiohttp_3.13.5.bb +1 -0
index bfd8912a0d..9424943281 100644
@@ -36,6 +36,7 @@ SRC_URI += " \
     file://CVE-2026-123817_p2.patch \
     file://CVE-2026-128124.patch \
     file://CVE-2026-128125.patch \
+    file://CVE-2026-128126.patch \
 "
 
 CVE_PRODUCT = "aiohttp:aiohttp"
Signature · 1 line
2.35.6
#5 lore raw

PATCH 5/10 python3-aiohttp: fix CVE-2026-128127

In reply to Ashishkumar Parmar X (asparmar - E INFOCHIPS PRIVATE LIMITED at Cisco)

From: Ashishkumar Parmar <[email protected]>

This patch applies the multipart base64 reader fix for CVE-2026-128127 from the upstream stable branch [1].

Bound retained base64 input and handle incomplete encoded chunks without retaining unbounded discarded input.

[1] https://github.com/aio-libs/aiohttp/commit/a555ab698e08e9baea7386d5b4c0761cb8956fdd
[2] https://github.com/aio-libs/aiohttp/security/advisories/GHSA-24c4-3p7v-29cm

---
 .../python3-aiohttp/CVE-2026-128127.patch     | 291 ++++++++++++++++++
 .../python/python3-aiohttp_3.13.5.bb          |   1 +
 2 files changed, 292 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128127.patch
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128127.patch new file +291 -0
new file mode 100644
index 0000000000..af91c2f53d
@@ -0,0 +1,291 @@
+From 997df9aca0b9e9d6c5cdc70856e5f4482bbce8b7 Mon Sep 17 00:00:00 2001
+From: "patchback[bot]" <45432694+patchback[bot]@users.noreply.github.com>
+Date: Sat, 22 Aug 2026 18:45:23 +0100
+Subject: [PATCH] [PR #13509/2d9c5c10 backport][3.14] Fix multipart base64 edge
+ cases (#13513)
+
+**This is a backport of PR #13509 as merged into master
+(2d9c5c1062eff0034fb3ab120897a6c1b3ff7041).**
+
+---------
+
+CVE: CVE-2026-128127
+Upstream-Status: Backport [https://github.com/aio-libs/aiohttp/commit/a555ab698e08e9baea7386d5b4c0761cb8956fdd]
+
+Backport Changes:
+- Omit tests/test_benchmarks_multipart.py: the upstream-only codspeed
+  benchmark imports an unavailable DEFAULT_CHUNK_SIZE helper and uses
+  a BodyPartReader client_max_size argument absent from the current
+  API. Retain all multipart regression tests and the changelog.
+
+Co-authored-by: Sam Bull <[email protected]>
+Signed-off-by: Ashishkumar Parmar <[email protected]>
+---
+ CHANGES/13509.bugfix.rst |   1 +
+ aiohttp/multipart.py     |  74 ++++++++++++++++---------
+ tests/test_multipart.py  | 117 ++++++++++++++++++++++++++++++++++++++-
+ 3 files changed, 165 insertions(+), 27 deletions(-)
+ create mode 100644 CHANGES/13509.bugfix.rst
+
+diff --git a/CHANGES/13509.bugfix.rst b/CHANGES/13509.bugfix.rst
+new file mode 100644
+index 0000000..8e74540
+--- /dev/null
++++ b/CHANGES/13509.bugfix.rst
+@@ -0,0 +1 @@
++Fixed some edge case handling in multipart parts using base 64 encoding -- by :user:`Dreamsorcerer`.
+diff --git a/aiohttp/multipart.py b/aiohttp/multipart.py
+index ec8b82b..36c4971 100644
+--- a/aiohttp/multipart.py
++++ b/aiohttp/multipart.py
+@@ -72,6 +72,13 @@ __all__ = (
+ )
+ 
+ 
++# The base64 alphabet plus the padding character.
++_BASE64_CHARS = frozenset(
++    b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
++)
++_NON_BASE64_BYTES = bytes(b for b in range(256) if b not in _BASE64_CHARS)
++
++
+ if TYPE_CHECKING:
+     from .client_reqrep import ClientResponse
+ 
+@@ -293,6 +300,7 @@ class BodyPartReader:
+         length = None if self._is_form_data else self.headers.get(CONTENT_LENGTH, None)
+         self._length = int(length) if length is not None else None
+         self._read_bytes = 0
++        self._b64_carry = b""
+         self._unread: Deque[bytes] = deque()
+         self._prev_chunk: Optional[bytes] = None
+         self._content_eof = 0
+@@ -340,43 +348,59 @@ class BodyPartReader:
+         """
+         if self._at_eof:
+             return b""
++        carry = self._b64_carry
++        want = size - len(carry)
++        if carry:
++            self._b64_carry = b""
++            want = max(want, self._boundary_len)
+         if self._length:
+-            chunk = await self._read_chunk_from_length(size)
++            fresh = await self._read_chunk_from_length(want)
+         else:
+-            chunk = await self._read_chunk_from_stream(size)
++            fresh = await self._read_chunk_from_stream(want)
++        chunk = carry + fresh
++        self._read_bytes += len(fresh)
+ 
+-        # For the case of base64 data, we must read a fragment of size with a
+-        # remainder of 0 by dividing by 4 for string without symbols \n or \r
++        # base64 decodes in quartets and every chunk is decoded on its own, so
++        # a chunk should not end mid-quartet.
+         encoding = self.headers.get(CONTENT_TRANSFER_ENCODING)
+         if encoding and encoding.lower() == "base64":
+-            stripped_chunk = b"".join(chunk.split())
+-            remainder = len(stripped_chunk) % 4
+-
+-            while remainder != 0 and not self.at_eof():
+-                over_chunk_size = 4 - remainder
+-                over_chunk = b""
+-
+-                if self._prev_chunk:
+-                    over_chunk = self._prev_chunk[:over_chunk_size]
+-                    self._prev_chunk = self._prev_chunk[len(over_chunk) :]
+-
+-                if len(over_chunk) != over_chunk_size:
+-                    over_chunk += await self._content.read(4 - len(over_chunk))
++            chunk = self._align_base64_chunk(chunk, len(carry) + want)
+ 
+-                if not over_chunk:
+-                    self._at_eof = True
+-
+-                stripped_chunk += b"".join(over_chunk.split())
+-                chunk += over_chunk
+-                remainder = len(stripped_chunk) % 4
+-
+-        self._read_bytes += len(chunk)
+         if self._read_bytes == self._length:
+             self._at_eof = True
+         if self._at_eof and await self._content.readline() != b"\r\n":
+             raise ValueError("Reader did not read all the data or it is malformed")
+         return chunk
+ 
++    def _align_base64_chunk(self, chunk: bytes, size: int) -> bytes:
++        at_end = self._at_eof or (
++            self._length is not None and self._read_bytes >= self._length
++        )
++        if not at_end and len(chunk) > size:
++            self._b64_carry = chunk[size:]
++            chunk = chunk[:size]
++
++        remainder = len(chunk.translate(None, _NON_BASE64_BYTES)) % 4
++        if not remainder or at_end:
++            return chunk
++
++        # Walk back over the trailing partial quartet and carry it into the
++        # next chunk.
++        cut = len(chunk)
++        left = remainder
++        while left:
++            cut -= 1
++            if chunk[cut] in _BASE64_CHARS:
++                left -= 1
++        if not cut:
++            # No whole quartet to hand back, and carrying the lot would make
++            # no progress: the caller asked for this many bytes, and a part
++            # that holds no quartet within them holds none to give.
++            return chunk
++
++        self._b64_carry = chunk[cut:] + self._b64_carry
++        return chunk[:cut]
++
+     async def _read_chunk_from_length(self, size: int) -> bytes:
+         # Reads body part content chunk of the specified size.
+         # The body part must has Content-Length header with proper value.
+diff --git a/tests/test_multipart.py b/tests/test_multipart.py
+index 587d383..92d2241 100644
+--- a/tests/test_multipart.py
++++ b/tests/test_multipart.py
+@@ -1,4 +1,5 @@
+ import asyncio
++import base64
+ import io
+ import json
+ import pathlib
+@@ -399,7 +400,7 @@ class TestPartReader:
+             obj = aiohttp.BodyPartReader(BOUNDARY, h, stream)
+             result = b""
+             while not obj.at_eof():
+-                chunk = await obj.read_chunk(size=6)
++                chunk = await obj.read_chunk(size=8)
+                 result += obj.decode(chunk)
+         assert b"Time to Relax!" == result
+ 
+@@ -409,11 +410,123 @@ class TestPartReader:
+             obj = aiohttp.BodyPartReader(BOUNDARY, h, stream)
+             result = b""
+             while not obj.at_eof():
+-                chunk = await obj.read_chunk(size=6)
++                chunk = await obj.read_chunk(size=8)
+                 async for decoded_chunk in obj.decode_iter(chunk):
+                     result += decoded_chunk
+         assert b"Time to Relax!" == result
+ 
++    async def test_read_chunk_base64_content_length_no_overread(self) -> None:
++        # A base64 part whose Content-Length is not a multiple of 4 must not
++        # let the base64 realignment loop read past the declared length into
++        # the boundary and the parts that follow (regression for a negative
++        # `_read_chunk_from_length` chunk_size / StreamReader.read(-1) bypass
++        # of client_max_size).
++        b64 = b"VGltZSB0byBSZWxheCE"  # 19 chars, 19 % 4 == 3 (unpadded)
++        secret = b"secret-from-next-part"
++        rest = b"\r\n--:\r\nContent-Length: %d\r\n\r\n%s\r\n--:--\r\n" % (
++            len(secret),
++            secret,
++        )
++        h = CIMultiDict(
++            {"CONTENT-LENGTH": str(len(b64)), CONTENT_TRANSFER_ENCODING: "base64"}
++        )
++        with Stream(b64 + rest) as stream:
++            obj = aiohttp.BodyPartReader(BOUNDARY, h, stream)
++            chunk = await obj.read_chunk(8192)
++            assert chunk == b64
++            assert obj.at_eof()
++            assert secret not in chunk
++            # The following part is left intact on the stream.
++            assert secret in await stream.read()
++
++    async def test_read_chunk_base64_bounded_by_requested_size(self) -> None:
++        # Whole quartets are handed back and the trailing partial quartet is
++        # carried into the next read, so size acts as a cap rather than a
++        # starting point. The carry is subtracted from the next read instead
++        # of being pushed back, so nothing accumulates over a long part: the
++        # lookahead would otherwise gain a couple of bytes on every call.
++        payload = b"x" * 8192
++        h = CIMultiDict({CONTENT_TRANSFER_ENCODING: "base64"})
++        body = base64.encodebytes(payload).replace(b"\n", b"\r\n")
++        with Stream(body + b"\r\n--:--") as stream:
++            obj = aiohttp.BodyPartReader(BOUNDARY, h, stream)
++            decoded = b""
++            chunks = []
++            carried = 0
++            while not obj.at_eof():
++                chunks.append(await obj.read_chunk(64))
++                decoded += obj.decode(chunks[-1])
++                carried += bool(obj._b64_carry)
++                assert len(obj._prev_chunk or b"") <= 64
++                assert len(obj._b64_carry) < 64
++        assert decoded == payload
++        assert all(len(c) <= 64 for c in chunks[:-1])
++        # The bound above is only meaningful if the carry is exercised, and
++        # over enough calls for a per-call drift to become visible.
++        assert len(chunks) > 100
++        assert carried > len(chunks) // 2
++
++    async def test_read_chunk_base64_padding_run_does_not_amplify(self) -> None:
++        # A part padded with a long run of insignificant bytes used to make a
++        # single call swallow the whole run. Such a run holds no whole quartet,
++        # so this covers the branch that hands the chunk straight back: it must
++        # still cap the chunk at the size asked for, and must hand back
++        # something every time so callers looping on a truthy chunk make
++        # progress. Nothing is carried here, so this says nothing about the
++        # deferral path -- that is bounded by
++        # test_read_chunk_base64_bounded_by_requested_size.
++        h = CIMultiDict({CONTENT_TRANSFER_ENCODING: "base64"})
++        body = b"A" + b" " * (64 * 1024) + b"BBB\r\n--:--"
++        with Stream(body) as stream:
++            obj = aiohttp.BodyPartReader(BOUNDARY, h, stream)
++            while not obj.at_eof():
++                chunk = await obj.read_chunk(8192)
++                assert chunk
++                assert len(chunk) <= 8192
++
++    async def test_read_chunk_base64_length_delimited_carries_quartet(self) -> None:
++        # A length-delimited part has no lookahead (_prev_chunk stays None), so
++        # this covers carrying a partial quartet on that path. The carry is
++        # subtracted from the next read, which the Content-Length accounting
++        # has to agree with, or the part overruns its declared length and the
++        # trailing CRLF check rejects it. Sizes are chosen to land mid-quartet.
++        payload = b"z" * 300
++        b64 = base64.b64encode(payload)
++        h = CIMultiDict(
++            {"CONTENT-LENGTH": str(len(b64)), CONTENT_TRANSFER_ENCODING: "base64"}
++        )
++        for size in (6, 7, 9, 13):
++            with Stream(b64 + b"\r\n--:--") as stream:
++                obj = aiohttp.BodyPartReader(BOUNDARY, h, stream)
++                assert obj._prev_chunk is None
++                decoded = b""
++                carried = 0
++                while not obj.at_eof():
++                    decoded += obj.decode(await obj.read_chunk(size))
++                    carried += bool(obj._b64_carry)
++                assert decoded == payload, size
++                # Guard against this quietly becoming a no-op: the point is
++                # that the carry is exercised, not merely that reading works.
++                assert carried > 10, (size, carried)
++
++    @pytest.mark.parametrize("size", (5, 6, 7, 8))
++    async def test_read_chunk_base64_small_size_carry_drains(self, size: int) -> None:
++        # _read_chunk_from_stream refuses to read fewer than boundary_len
++        # bytes, so for a size this small the carry cannot always be
++        # subtracted from the next read. The chunk then has to be allowed over
++        # size: capping it back would read more than it hands back on every
++        # call, and the carry would climb without ever draining.
++        payload = b"q" * 600
++        h = CIMultiDict({CONTENT_TRANSFER_ENCODING: "base64"})
++        body = base64.encodebytes(payload).replace(b"\n", b"\r\n")
++        with Stream(body + b"\r\n--:--") as stream:
++            obj = aiohttp.BodyPartReader(BOUNDARY, h, stream)
++            decoded = b""
++            while not obj.at_eof():
++                decoded += obj.decode(await obj.read_chunk(size))
++                assert len(obj._b64_carry) <= size + obj._boundary_len
++        assert decoded == payload
++
+     async def test_decode_with_content_encoding_deflate(self) -> None:
+         h = CIMultiDictProxy(CIMultiDict({CONTENT_ENCODING: "deflate"}))
+         data = b"\x0b\xc9\xccMU(\xc9W\x08J\xcdI\xacP\x04\x00"
meta-python/recipes-devtools/python/python3-aiohttp_3.13.5.bb +1 -0
index 9424943281..3ac8f15bbf 100644
@@ -37,6 +37,7 @@ SRC_URI += " \
     file://CVE-2026-128124.patch \
     file://CVE-2026-128125.patch \
     file://CVE-2026-128126.patch \
+    file://CVE-2026-128127.patch \
 "
 
 CVE_PRODUCT = "aiohttp:aiohttp"
Signature · 1 line
2.35.6
#6 lore raw

PATCH 6/10 python3-aiohttp: fix CVE-2026-128128

In reply to Ashishkumar Parmar X (asparmar - E INFOCHIPS PRIVATE LIMITED at Cisco)

From: Ashishkumar Parmar <[email protected]>

This patch applies the WebSocket declared-length checks for CVE-2026-128128 from the upstream stable branch [1].

Avoid signed size arithmetic overflow in the accelerated reader and reject lengths that cannot fit the parser size type.

The embedded backport notes describe the required prerequisite or follow-up changes and the adaptations to the current APIs.

[1] https://github.com/aio-libs/aiohttp/commit/8cfbe9abe5e11b84006a10f9bdf82bf607671dab
[2] https://github.com/aio-libs/aiohttp/commit/bd89ad6704783015bc4d97dd847509023199904e
[3] https://github.com/aio-libs/aiohttp/security/advisories/GHSA-3rp8-rxj8-mvjw

---
 .../python3-aiohttp/CVE-2026-128128.patch     | 206 ++++++++++++++++++
 .../python/python3-aiohttp_3.13.5.bb          |   1 +
 2 files changed, 207 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128128.patch
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128128.patch new file +206 -0
new file mode 100644
index 0000000000..6dd219a678
@@ -0,0 +1,206 @@
+From 1ac5baa4a25023efa0856c2c4585401bf33f304b Mon Sep 17 00:00:00 2001
+From: "patchback[bot]" <45432694+patchback[bot]@users.noreply.github.com>
+Date: Sat, 22 Aug 2026 17:49:48 +0100
+Subject: [PATCH] [PR #13415/8c8906a1 backport][3.14] Fix oversized frames on
+ websocket messages (#13494)
+
+**This is a backport of PR #13415 as merged into master
+(8c8906a19f64e52ef6a7d44d65217eb3c5af413f).**
+
+Co-authored-by: Sam Bull <[email protected]>
+
+CVE: CVE-2026-128128
+Upstream-Status: Backport [https://github.com/aio-libs/aiohttp/commit/8cfbe9abe5e11b84006a10f9bdf82bf607671dab]
+
+Backport Changes:
+- Fold the frame-length range check and regression tests from upstream
+  bd89ad6704783015bc4d97dd847509023199904e so declared lengths that
+  exceed Py_ssize_t are rejected before conversion on 32-bit builds.
+- Remove decode_text arguments from the added tests because the current
+  WebSocketReader does not expose that option and always decodes text.
+- Omit CHANGES/13415.bugfix.rst, which records an upstream release note.
+
+Signed-off-by: Ashishkumar Parmar <[email protected]>
+---
+ aiohttp/_websocket/reader_c.pxd |  4 ++
+ aiohttp/_websocket/reader_py.py | 27 ++++++++++--
+ tests/test_websocket_parser.py  | 76 +++++++++++++++++++++++++++++++++
+ 3 files changed, 103 insertions(+), 4 deletions(-)
+
+diff --git a/aiohttp/_websocket/reader_c.pxd b/aiohttp/_websocket/reader_c.pxd
+index 4f8a1b2..fcb7b4d 100644
+--- a/aiohttp/_websocket/reader_c.pxd
++++ b/aiohttp/_websocket/reader_c.pxd
+@@ -8,6 +8,8 @@ cdef unsigned int READ_PAYLOAD_LENGTH
+ cdef unsigned int READ_PAYLOAD_MASK
+ cdef unsigned int READ_PAYLOAD
+ 
++cdef unsigned long long MAX_PAYLOAD_LEN
++
+ cdef int OP_CODE_NOT_SET
+ cdef int OP_CODE_CONTINUATION
+ cdef int OP_CODE_TEXT
+@@ -107,6 +109,8 @@ cdef class WebSocketReader:
+         has_mask=bint,
+         fin=bint,
+         had_fragments=Py_ssize_t,
++        partial_len=Py_ssize_t,
++        frame_len="unsigned long long",
+         payload_bytearray=bytearray,
+     )
+     cpdef void _feed_data(self, bytes data) except *
+diff --git a/aiohttp/_websocket/reader_py.py b/aiohttp/_websocket/reader_py.py
+index 6499fa7..e9472bd 100644
+--- a/aiohttp/_websocket/reader_py.py
++++ b/aiohttp/_websocket/reader_py.py
+@@ -2,6 +2,7 @@
+ 
+ import asyncio
+ import builtins
++import sys
+ from collections import deque
+ from typing import Deque, Final, Optional, Set, Tuple, Union
+ 
+@@ -27,6 +28,12 @@ READ_PAYLOAD_LENGTH = 2
+ READ_PAYLOAD_MASK = 3
+ READ_PAYLOAD = 4
+ 
++# Largest declared payload length the reader can represent: the compiled
++# reader stores it in a Py_ssize_t, which holds 2**31-1 on the 32-bit builds
++# (the win32 and armv7l wheels) and 2**63-1 everywhere else.
++# TODO: Remove when we drop 32 bit support (and from reader_c.pxd).
++MAX_PAYLOAD_LEN = sys.maxsize
++
+ WS_MSG_TYPE_BINARY = WSMsgType.BINARY
+ WS_MSG_TYPE_TEXT = WSMsgType.TEXT
+ 
+@@ -413,7 +420,16 @@ class WebSocketReader:
+                 elif len_flag > 126:
+                     if data_len - start_pos < 8:
+                         break
+-                    self._payload_bytes_to_read = UNPACK_LEN3(data, start_pos)[0]
++                    # The declared length is an unsigned 64-bit integer that
++                    # does not necessarily fit _payload_bytes_to_read.
++                    frame_len = UNPACK_LEN3(data, start_pos)[0]
++                    if frame_len > MAX_PAYLOAD_LEN:
++                        raise WebSocketError(
++                            WSCloseCode.MESSAGE_TOO_BIG,
++                            f"Message size {int(frame_len) + len(self._partial)} "
++                            f"exceeds limit {self._max_msg_size or MAX_PAYLOAD_LEN}",
++                        )
++                    self._payload_bytes_to_read = frame_len
+                     start_pos += 8
+                 else:
+                     self._payload_bytes_to_read = len_flag
+@@ -426,11 +442,14 @@ class WebSocketReader:
+                     OP_CODE_BINARY,
+                     OP_CODE_CONTINUATION,
+                 }:
+-                    projected_size = self._payload_bytes_to_read + len(self._partial)
+-                    if projected_size >= self._max_msg_size:
++                    # partial_len declared in reader_c.pxd to keep it in C.
++                    partial_len = len(self._partial)
++                    # payload_bytes_to_read is a signed Py_ssize_t C value,
++                    # use subtraction here to avoid an integer overflow.
++                    if self._payload_bytes_to_read >= self._max_msg_size - partial_len:
+                         raise WebSocketError(
+                             WSCloseCode.MESSAGE_TOO_BIG,
+-                            f"Message size {projected_size} "
++                            f"Message size {int(self._payload_bytes_to_read) + partial_len} "
+                             f"exceeds limit {self._max_msg_size}",
+                         )
+ 
+diff --git a/tests/test_websocket_parser.py b/tests/test_websocket_parser.py
+index abb412b..c3ec201 100644
+--- a/tests/test_websocket_parser.py
++++ b/tests/test_websocket_parser.py
+@@ -2,6 +2,7 @@ import asyncio
+ import pickle
+ import random
+ import struct
++import sys
+ from typing import Union
+ from unittest import mock
+ 
+@@ -698,6 +699,81 @@ def test_msg_too_large_text_after_non_fin_text(out: WebSocketDataQueue) -> None:
+     assert ctx.value.code == WSCloseCode.MESSAGE_TOO_BIG
+ 
+ 
++def test_msg_too_large_declared_length_near_ssize_t_max(
++    out: WebSocketDataQueue,
++) -> None:
++    # Regression test: the header-time size check compares
++    # `payload_bytes_to_read + len(partial)` against max_msg_size. In the
++    # compiled Cython reader payload_bytes_to_read is a signed Py_ssize_t C
++    # value, and RFC 6455 allows a declared length up to 2**63-1, so a naive
++    # addition can wrap around to a negative number and bypass the limit
++    # entirely once anything is already buffered in `partial`.
++    max_msg_size = 4 * 1024 * 1024
++    parser = WebSocketReader(out, max_msg_size, compress=False)
++
++    # Buffer one byte in `partial` via a non-fin fragment.
++    first = build_frame(b"a", WSMsgType.TEXT, is_fin=False)
++    parser._feed_data(first)
++
++    # Continuation header alone declares the largest length RFC 6455
++    # allows: 2**63-1.
++    header = PACK_LEN3(WSMsgType.CONTINUATION, 127, 2**63 - 1)
++    with pytest.raises(
++        WebSocketError,
++        match=rf"^Message size {2**63} exceeds limit {max_msg_size}$",
++    ) as ctx:
++        parser._feed_data(header)
++    assert ctx.value.code == WSCloseCode.MESSAGE_TOO_BIG
++
++
[email protected](
++    "declared",
++    (sys.maxsize + 1, 2**64 - 1),
++    ids=("ssize_t_max_plus_one", "uint64_max"),
++)
[email protected](
++    "max_msg_size", (4 * 1024 * 1024, 0), ids=("bounded", "unbounded")
++)
++def test_msg_too_large_declared_length_above_ssize_t_max(
++    out: WebSocketDataQueue, max_msg_size: int, declared: int
++) -> None:
++    # RFC 6455 allows an unsigned 64-bit declared length, which does not fit
++    # the signed Py_ssize_t payload_bytes_to_read of the compiled reader:
++    # anything above sys.maxsize (2**31-1 on the 32-bit builds) has to be
++    # rejected before it is stored there, or storing it raises OverflowError
++    # and escapes as an abnormal closure instead of MESSAGE_TOO_BIG. Such a
++    # frame can never be buffered, so an unlimited max_msg_size is checked
++    # too.
++    parser = WebSocketReader(out, max_msg_size, compress=False)
++
++    header = PACK_LEN3(0x80 | WSMsgType.TEXT, 127, declared)
++    with pytest.raises(
++        WebSocketError,
++        match=rf"^Message size {declared} exceeds limit {max_msg_size or sys.maxsize}$",
++    ) as ctx:
++        parser._feed_data(header)
++    assert ctx.value.code == WSCloseCode.MESSAGE_TOO_BIG
++
++
++def test_msg_too_large_above_ssize_t_max_reports_buffered_fragments(
++    out: WebSocketDataQueue,
++) -> None:
++    # The reported size adds what is already buffered, so the message reads the
++    # same whether the declared length is caught by the Py_ssize_t range check
++    # or by the max_msg_size comparison below it.
++    max_msg_size = 4 * 1024 * 1024
++    parser = WebSocketReader(out, max_msg_size, compress=False)
++
++    parser._feed_data(build_frame(b"a", WSMsgType.TEXT, is_fin=False))
++
++    header = PACK_LEN3(WSMsgType.CONTINUATION, 127, 2**64 - 1)
++    with pytest.raises(
++        WebSocketError, match=rf"^Message size {2**64} exceeds limit {max_msg_size}$"
++    ) as ctx:
++        parser._feed_data(header)
++    assert ctx.value.code == WSCloseCode.MESSAGE_TOO_BIG
++
++
+ @pytest.mark.parametrize(
+     "opcode",
+     (0x3, 0x4, 0x5, 0x6, 0x7, 0xB, 0xC, 0xD, 0xE, 0xF),
meta-python/recipes-devtools/python/python3-aiohttp_3.13.5.bb +1 -0
index 3ac8f15bbf..06e0156e14 100644
@@ -38,6 +38,7 @@ SRC_URI += " \
     file://CVE-2026-128125.patch \
     file://CVE-2026-128126.patch \
     file://CVE-2026-128127.patch \
+    file://CVE-2026-128128.patch \
 "
 
 CVE_PRODUCT = "aiohttp:aiohttp"
Signature · 1 line
2.35.6
#7 lore raw

PATCH 7/10 python3-aiohttp: fix CVE-2026-128129

In reply to Ashishkumar Parmar X (asparmar - E INFOCHIPS PRIVATE LIMITED at Cisco)

From: Ashishkumar Parmar <[email protected]>

This patch applies the upgrade-tail flow control fix for CVE-2026-128129 from the upstream stable branch [1].

Pause reads while upgraded request data fills the bounded tail and resume safely when an upgrade is accepted or declined.

The embedded backport notes describe the required prerequisite or follow-up changes and the adaptations to the current APIs.

[1] https://github.com/aio-libs/aiohttp/commit/3d850ee9b92573c7e913821cbcb96005beb3f4df
[2] https://github.com/aio-libs/aiohttp/commit/716c83d2b697e56fd74f95a1aa3a451fd2fb02e8
[3] https://github.com/aio-libs/aiohttp/security/advisories/GHSA-pw86-h8fm-j323

---
 .../python3-aiohttp/CVE-2026-128129.patch     | 677 ++++++++++++++++++
 .../python/python3-aiohttp_3.13.5.bb          |   1 +
 2 files changed, 678 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128129.patch
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128129.patch new file +677 -0
new file mode 100644
index 0000000000..70235cda0e
@@ -0,0 +1,677 @@
+From 4a4fb46343ee9407de28754700a5620aa1cdc1d2 Mon Sep 17 00:00:00 2001
+From: Sam Bull <[email protected]>
+Date: Sat, 22 Aug 2026 15:03:24 +0100
+Subject: [PATCH] Fix limit on message tail (#13501) (#13511)
+
+(cherry picked from commit c207cadb257e0959b192ffca0548eca8c71eb96a)
+
+CVE: CVE-2026-128129
+Upstream-Status: Backport [https://github.com/aio-libs/aiohttp/commit/3d850ee9b92573c7e913821cbcb96005beb3f4df]
+
+Backport Changes:
+- Retain the current _request_parser and _upgrade attribute names.
+- Fold the declined-upgrade replay guard and regression tests from
+  716c83d2b697e56fd74f95a1aa3a451fd2fb02e8. Without its guard the
+  pipelined WebSocket handshake test times out after ordinary queued
+  responses consume the buffered frame data as HTTP.
+- Retain the upstream dummy_reader fixture and WebSocketReader import
+  required by the added parser-handoff regression test.
+- Keep the socket-read bound local to the regression tests because the
+  current helpers module does not expose DEFAULT_CHUNK_SIZE.
+- Omit CHANGES/13501.bugfix.rst, which records an upstream release note.
+
+Signed-off-by: Ashishkumar Parmar <[email protected]>
+---
+ aiohttp/web_protocol.py                |  67 ++++++--
+ tests/test_web_functional.py           | 221 +++++++++++++++++++++++++
+ tests/test_web_protocol.py             |  90 ++++++++++
+ tests/test_web_websocket_functional.py | 155 +++++++++++++++++
+ 4 files changed, 522 insertions(+), 11 deletions(-)
+
+diff --git a/aiohttp/web_protocol.py b/aiohttp/web_protocol.py
+index c04aa10..5968d10 100644
+--- a/aiohttp/web_protocol.py
++++ b/aiohttp/web_protocol.py
+@@ -164,6 +164,7 @@ class RequestHandler(BaseProtocol):
+         "_msg_queue_resume_size",
+         "_msg_queue_paused",
+         "_message_tail",
++        "_read_bufsize",
+         "_handler_waiter",
+         "_waiter",
+         "_task_handler",
+@@ -209,6 +210,7 @@ class RequestHandler(BaseProtocol):
+         # Low-water mark: resume reading once the queue drains to half the limit
+         # so we refill in batches instead of churning pause/resume per request.
+         self._msg_queue_resume_size = MAX_MSG_QUEUE_SIZE // 2
++        self._read_bufsize = read_bufsize
+         self._msg_queue_paused = False
+         super().__init__(loop)
+ 
+@@ -421,6 +423,9 @@ class RequestHandler(BaseProtocol):
+             self._payload_parser.feed_data(self._message_tail)
+             self._message_tail = b""
+ 
++        if self._msg_queue_paused:
++            self._resume_msg_queue_reading()
++
+     def eof_received(self) -> None:
+         pass
+ 
+@@ -464,6 +469,11 @@ class RequestHandler(BaseProtocol):
+         # no parser, just store
+         elif self._payload_parser is None and self._upgrade and data:
+             self._message_tail += data
++            if (
++                not self._msg_queue_paused
++                and len(self._message_tail) >= self._read_bufsize
++            ):
++                self._pause_msg_queue_reading()
+ 
+         # feed payload
+         elif data:
+@@ -485,6 +495,10 @@ class RequestHandler(BaseProtocol):
+                 pass
+ 
+     def _resume_msg_queue_reading(self) -> None:
++        # Tested empty-first so a read_bufsize of 0 cannot wedge the connection.
++        if self._message_tail and len(self._message_tail) >= self._read_bufsize:
++            return
++
+         if not self._upgrade:
+             # Reparse buffered pipelined requests while still marked paused so
+             # a refill past the limit does not re-pause an already-paused
+@@ -765,25 +779,56 @@ class RequestHandler(BaseProtocol):
+         prematurely.
+         """
+         request._finish()
+-        if self._request_parser is not None:
++
++        # Handle feeding the message tail following an upgrade request that
++        # was declined.
++        # The upgrade request is the last request before the parser paused,
++        # so wait for self._messages to be empty.
++        # payload_parser is not None if the upgrade was accepted.
++        if (
++            self._upgrade
++            and not self._messages
++            and self._payload_parser is None
++            and self._request_parser is not None
++        ):
+             self._request_parser.set_upgraded(False)
+             self._upgrade = False
+             if self._message_tail:
+-                messages, _upgraded, tail = self._request_parser.feed_data(
+-                    self._message_tail
+-                )
++                messages: Sequence[_MsgType]
++                try:
++                    messages, upgraded, tail = self._request_parser.feed_data(
++                        self._message_tail
++                    )
++                except HttpProcessingError as parse_exc:
++                    # Garbage (or an oversized request line) buffered behind the
++                    # upgrade: answer 400 instead of letting the error escape
++                    # and lose this response, like data_received() does.
++                    messages = [
++                        (
++                            _ErrInfo(
++                                status=400,
++                                exc=parse_exc,
++                                message=parse_exc.message,
++                            ),
++                            EMPTY_PAYLOAD,
++                        )
++                    ]
++                    upgraded = False
++                    tail = b""
++                # A further upgrade request in the tail buffers its own remainder.
++                self._upgrade = upgraded
+                 self._message_tail = tail
+                 for msg, payload in messages:
+                     self._request_count += 1
+                     self._messages.append((msg, payload))
+-                # Pause the transport, like in data_received().
+-                if (
+-                    not self._msg_queue_paused
+-                    and len(self._messages) >= self._max_msg_queue_size
+-                ):
++                if len(self._messages) >= self._max_msg_queue_size:
++                    # Pause the transport, like in data_received().
+                     self._pause_msg_queue_reading()
+-                # This should not be possible. If a future refactor results in
+-                # this failing, update the code to set the waiter.
++                elif self._msg_queue_paused:
++                    # Resume reading now the tail has been parsed.
++                    self._resume_msg_queue_reading()
++                # This shouldn't be possible. If a future refactor results in this
++                # failing, then the code may need to be updated to set the waiter.
+                 assert self._waiter is None
+         try:
+             prepare_meth = resp.prepare
+diff --git a/tests/test_web_functional.py b/tests/test_web_functional.py
+index c5c4b5b..c9146ca 100644
+--- a/tests/test_web_functional.py
++++ b/tests/test_web_functional.py
+@@ -26,8 +26,11 @@ from aiohttp import (
+     multipart,
+     web,
+ )
++from aiohttp._websocket.writer import WebSocketWriter
++from aiohttp.base_protocol import BaseProtocol
+ from aiohttp.compression_utils import ZLibBackend, ZLibCompressObjProtocol
+ from aiohttp.hdrs import CONTENT_LENGTH, CONTENT_TYPE, TRANSFER_ENCODING
++from aiohttp.http import WSMsgType
+ from aiohttp.pytest_plugin import AiohttpClient, AiohttpServer
+ from aiohttp.streams import StreamReader
+ from aiohttp.typedefs import Handler
+@@ -1871,6 +1874,224 @@ async def test_http1_pipelined_behind_declined_upgrade_served_once(
+     assert len(set(handled)) == len(handled)
+ 
+ 
++DEFAULT_CHUNK_SIZE = 256 * 1024
++
++
++async def test_upgrade_tail_is_byte_limited(
++    aiohttp_server: AiohttpServer,
++    monkeypatch: pytest.MonkeyPatch,
++) -> None:
++    """Bytes buffered behind an in-flight upgrade must not grow unbounded.
++
++    A request the parser flagged as an upgrade has no payload, so everything
++    arriving while its handler runs is buffered whole until the handler either
++    prepares a websocket or answers normally. Only ``read_bufsize`` of it may be
++    held before reading is paused, regardless of how much is sent.
++    """
++    # Above the default so a ceiling that ignores read_bufsize fails the lower
++    # bound, and well below what is sent so no cap at all fails the upper one.
++    read_bufsize = 1024 * 1024
++    handler_started = asyncio.Event()
++    release_handler = asyncio.Event()
++    reading_paused = asyncio.Event()
++    max_tail = 0
++    data_received = RequestHandler.data_received
++
++    def observe_data_received(self: RequestHandler, data: bytes) -> None:
++        nonlocal max_tail
++        data_received(self, data)
++        if self._message_tail:
++            max_tail = max(max_tail, len(self._message_tail))
++            if self._msg_queue_paused:
++                reading_paused.set()
++
++    monkeypatch.setattr(RequestHandler, "data_received", observe_data_received)
++
++    async def upgrade_handler(request: web.Request) -> web.Response:
++        handler_started.set()
++        await release_handler.wait()
++        return web.Response(text="declined")
++
++    app = web.Application()
++    app.router.add_get("/upgrade", upgrade_handler)
++    server = await aiohttp_server(app, read_bufsize=read_bufsize)
++
++    chunk = b"A" * (64 * 1024)
++    chunks = (4 * 1024 * 1024) // len(chunk)
++
++    reader, writer = await asyncio.open_connection(server.host, server.port)
++    try:
++        writer.write(
++            b"GET /upgrade HTTP/1.1\r\nHost: localhost\r\n"
++            b"Connection: Upgrade\r\nUpgrade: websocket\r\n\r\n"
++        )
++        await writer.drain()
++        await asyncio.wait_for(handler_started.wait(), 1)
++
++        async def send_until_paused() -> None:
++            for _ in range(chunks):  # pragma: no branch
++                if reading_paused.is_set():
++                    break
++                writer.write(chunk)
++                await writer.drain()
++
++        sender = asyncio.create_task(send_until_paused())
++        try:
++            # Only elapses if nothing caps the buffer, in which case the
++            # assertions below report what was actually buffered.
++            with suppress(asyncio.TimeoutError):
++                await asyncio.wait_for(reading_paused.wait(), 5)
++        finally:
++            sender.cancel()
++            with suppress(asyncio.CancelledError):
++                await sender
++    finally:
++        release_handler.set()
++        writer.close()
++        with suppress(ConnectionResetError, BrokenPipeError):
++            await writer.wait_closed()
++
++    assert reading_paused.is_set(), f"reading never paused, buffered {max_tail} bytes"
++    # pause_reading() only takes effect after the read in flight, and asyncio
++    # reads at most DEFAULT_CHUNK_SIZE per call, so one extra chunk may land.
++    assert read_bufsize <= max_tail < read_bufsize + DEFAULT_CHUNK_SIZE
++
++
++async def test_upgrade_tail_resumes_reading_after_websocket_prepare(
++    aiohttp_server: AiohttpServer,
++    monkeypatch: pytest.MonkeyPatch,
++) -> None:
++    """A websocket paused while its tail filled up must keep reading.
++
++    A client may pipeline frames straight after the handshake request, filling
++    the tail buffer and pausing reading before the handler prepares. Once the
++    websocket owns the connection the tail is handed over, so reading has to
++    resume or whatever the client sent meanwhile is never read.
++    """
++    handshake_seen = asyncio.Event()
++    reading_paused = asyncio.Event()
++    release_handler = asyncio.Event()
++    last_received = asyncio.Event()
++    received: list[str] = []
++    data_received = RequestHandler.data_received
++
++    def observe_data_received(self: RequestHandler, data: bytes) -> None:
++        data_received(self, data)
++        if self._msg_queue_paused:
++            reading_paused.set()
++
++    monkeypatch.setattr(RequestHandler, "data_received", observe_data_received)
++
++    async def ws_handler(request: web.Request) -> web.WebSocketResponse:
++        handshake_seen.set()
++        await release_handler.wait()
++        ws = web.WebSocketResponse()
++        await ws.prepare(request)
++        async for msg in ws:  # pragma: no branch
++            assert isinstance(msg.data, str)
++            received.append(msg.data)
++            if msg.data == "last":
++                last_received.set()
++                break
++        return ws
++
++    app = web.Application()
++    app.router.add_get("/ws", ws_handler)
++    read_bufsize = 64 * 1024
++    server = await aiohttp_server(app, read_bufsize=read_bufsize)
++
++    # Enough pipelined frames to fill the tail, so reading must pause.
++    frame_payload = "B" * (32 * 1024)
++    frames = (read_bufsize // len(frame_payload)) + 2
++
++    reader, writer = await asyncio.open_connection(server.host, server.port)
++    try:
++        writer.write(
++            b"GET /ws HTTP/1.1\r\nHost: localhost\r\n"
++            b"Connection: Upgrade\r\nUpgrade: websocket\r\n"
++            b"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
++            b"Sec-WebSocket-Version: 13\r\n\r\n"
++        )
++        await writer.drain()
++        await asyncio.wait_for(handshake_seen.wait(), 1)
++
++        # Encode client frames off to the side, as tests/test_websocket_writer.py
++        # does, and put the bytes on the wire ourselves.
++        encoded = bytearray()
++        frame_transport = mock.create_autospec(
++            asyncio.Transport, spec_set=True, instance=True
++        )
++        # Defaults to a truthy Mock, which WebSocketWriter reads as closing.
++        frame_transport.is_closing.return_value = False
++        frame_transport.write.side_effect = encoded.extend
++        ws_writer = WebSocketWriter(
++            mock.create_autospec(BaseProtocol, spec_set=True, instance=True),
++            frame_transport,
++            use_mask=True,
++        )
++
++        for _ in range(frames):
++            await ws_writer.send_frame(frame_payload.encode(), WSMsgType.TEXT)
++        writer.write(encoded)
++        await writer.drain()
++        await asyncio.wait_for(reading_paused.wait(), 5)
++
++        # Sent while reading is paused, so this frame is only ever read if the
++        # handover to the websocket resumes the transport.
++        encoded.clear()
++        await ws_writer.send_frame(b"last", WSMsgType.TEXT)
++        writer.write(encoded)
++        await writer.drain()
++        release_handler.set()
++
++        await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), 5)
++        await asyncio.wait_for(last_received.wait(), 5)
++    finally:
++        release_handler.set()
++        writer.close()
++        with suppress(ConnectionResetError, BrokenPipeError):
++            await writer.wait_closed()
++
++    assert received == [frame_payload] * frames + ["last"]
++
++
++async def test_bad_pipelined_data_behind_declined_upgrade_answers_400(
++    aiohttp_server: AiohttpServer,
++) -> None:
++    """Junk buffered behind an upgrade must not swallow the upgrade response.
++
++    The tail is only parsed once the handler answers, so a parse error there
++    has to be reported as a 400 like it would be from data_received(); letting
++    it escape loses the response that was about to be written.
++    """
++
++    async def upgrade_handler(request: web.Request) -> web.Response:
++        return web.Response(text="declined")
++
++    app = web.Application()
++    app.router.add_get("/upgrade", upgrade_handler)
++    server = await aiohttp_server(app)
++
++    reader, writer = await asyncio.open_connection(server.host, server.port)
++    try:
++        writer.write(
++            b"GET /upgrade HTTP/1.1\r\nHost: localhost\r\n"
++            b"Connection: Upgrade\r\nUpgrade: websocket\r\n\r\n"
++            b"\x00" * 64
++        )
++        await writer.drain()
++        response = await asyncio.wait_for(reader.read(), 5)
++    finally:
++        writer.close()
++        with suppress(ConnectionResetError, BrokenPipeError):
++            await writer.wait_closed()
++
++    assert b"declined" in response, response
++    # A 400 only follows if the parse error was reported instead of escaping,
++    # and "declined" only arrives if it did not abort this response first.
++    assert b" 400 " in response, response
++
++
+ @pytest.mark.parametrize("decompressed_size", [4 * 1024 * 1024, 32 * 1024 * 1024])
+ async def test_unread_compressed_body_drain_is_bounded(
+     aiohttp_server: AiohttpServer,
+diff --git a/tests/test_web_protocol.py b/tests/test_web_protocol.py
+index 879be20..a3bce7b 100644
+--- a/tests/test_web_protocol.py
++++ b/tests/test_web_protocol.py
+@@ -3,6 +3,7 @@ from unittest import mock
+ 
+ import pytest
+ 
++from aiohttp.http import WebSocketReader
+ from aiohttp.web_protocol import RequestHandler
+ from aiohttp.web_server import Server
+ 
+@@ -17,6 +18,13 @@ def dummy_manager() -> Server:
+     )
+ 
+ 
[email protected]
++def dummy_reader() -> tuple[WebSocketReader, mock.Mock]:
++    m = mock.create_autospec(WebSocketReader, spec_set=True, instance=True)
++    m.feed_data.return_value = False, b""
++    return m, m
++
++
+ def test_pause_msg_queue_reading_without_transport(
+     loop: asyncio.AbstractEventLoop,
+     dummy_manager: Server,
+@@ -65,6 +73,88 @@ def test_resume_msg_queue_reading_without_transport(
+     assert handler._msg_queue_paused is False
+ 
+ 
++def test_resume_msg_queue_reading_stays_paused_for_full_tail(
++    loop: asyncio.AbstractEventLoop,
++    dummy_manager: Server,
++) -> None:
++    """Resume is refused while an in-flight upgrade holds read_bufsize of tail.
++
++    The tail is drained by set_parser()/finish_response(), so resuming before
++    then would let the buffer grow past its ceiling one read at a time.
++    """
++    handler = RequestHandler(dummy_manager, loop=loop, read_bufsize=1024)
++    transport = mock.create_autospec(asyncio.Transport, spec_set=True, instance=True)
++    handler.transport = transport
++    handler._upgrade = True
++    handler._msg_queue_paused = True
++    handler._message_tail = b"x" * 1024
++
++    handler._resume_msg_queue_reading()
++
++    assert handler._msg_queue_paused is True
++    transport.resume_reading.assert_not_called()
++
++
++def test_resume_msg_queue_reading_with_room_left_in_tail(
++    loop: asyncio.AbstractEventLoop,
++    dummy_manager: Server,
++) -> None:
++    """A tail under read_bufsize does not hold the transport paused."""
++    handler = RequestHandler(dummy_manager, loop=loop, read_bufsize=1024)
++    transport = mock.create_autospec(asyncio.Transport, spec_set=True, instance=True)
++    handler.transport = transport
++    handler._upgrade = True
++    handler._msg_queue_paused = True
++    handler._message_tail = b"x" * 1023
++
++    handler._resume_msg_queue_reading()
++
++    assert handler._msg_queue_paused is False
++    transport.resume_reading.assert_called_once_with()
++
++
++def test_resume_msg_queue_reading_with_zero_read_bufsize(
++    loop: asyncio.AbstractEventLoop,
++    dummy_manager: Server,
++) -> None:
++    """An empty tail resumes even when read_bufsize leaves it no room.
++
++    Guards the degenerate ``read_bufsize=0`` case: comparing sizes alone would
++    match an empty tail and wedge the connection paused for good.
++    """
++    handler = RequestHandler(dummy_manager, loop=loop, read_bufsize=0)
++    transport = mock.create_autospec(asyncio.Transport, spec_set=True, instance=True)
++    handler.transport = transport
++    handler._upgrade = True
++    handler._msg_queue_paused = True
++
++    handler._resume_msg_queue_reading()
++
++    assert handler._msg_queue_paused is False
++    transport.resume_reading.assert_called_once_with()
++
++
++def test_set_parser_resumes_reading_paused_for_tail(
++    loop: asyncio.AbstractEventLoop,
++    dummy_manager: Server,
++    dummy_reader: tuple[WebSocketReader, mock.Mock],
++) -> None:
++    """Handing a full tail to the upgraded protocol resumes reading."""
++    handler = RequestHandler(dummy_manager, loop=loop, read_bufsize=1024)
++    transport = mock.create_autospec(asyncio.Transport, spec_set=True, instance=True)
++    handler.transport = transport
++    handler._upgrade = True
++    handler._msg_queue_paused = True
++    handler._message_tail = b"x" * 1024
++
++    handler.set_parser(dummy_reader[0])
++
++    dummy_reader[1].feed_data.assert_called_once_with(b"x" * 1024)
++    assert handler._message_tail == b""
++    assert handler._msg_queue_paused is False
++    transport.resume_reading.assert_called_once_with()
++
++
+ def test_resume_reading_stays_paused_for_msg_queue(
+     loop: asyncio.AbstractEventLoop,
+     dummy_manager: Server,
+diff --git a/tests/test_web_websocket_functional.py b/tests/test_web_websocket_functional.py
+index 871987e..6035b77 100644
+--- a/tests/test_web_websocket_functional.py
++++ b/tests/test_web_websocket_functional.py
+@@ -13,6 +13,7 @@ import aiohttp
+ from aiohttp import web
+ from aiohttp.http import WSCloseCode, WSMsgType
+ from aiohttp.pytest_plugin import AiohttpClient, AiohttpServer
++from aiohttp.web_protocol import MAX_MSG_QUEUE_SIZE
+ 
+ 
+ async def test_websocket_can_prepare(loop, aiohttp_client) -> None:
+@@ -1422,3 +1423,157 @@ async def test_websocket_prepared_property(
+     assert msg.type is WSMsgType.TEXT
+     assert msg.data == "test"
+     await ws.close()
++
++
++def _raw_get(path: str) -> bytes:
++    return f"GET {path} HTTP/1.1\r\nHost: localhost\r\n\r\n".encode("ascii")
++
++
++_RAW_UPGRADE = (
++    b"GET /ws HTTP/1.1\r\n"
++    b"Host: localhost\r\n"
++    b"Upgrade: websocket\r\n"
++    b"Connection: Upgrade\r\n"
++    b"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
++    b"Sec-WebSocket-Version: 13\r\n"
++    b"\r\n"
++)
++
++
++def _masked_text_frame(payload: bytes) -> bytes:
++    """Build a client text frame; frames sent to a server must be masked."""
++    assert len(payload) < 126
++    mask = b"\x37\xfa\x21\x3d"
++    return (
++        b"\x81"
++        + bytes((0x80 | len(payload),))
++        + mask
++        + bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
++    )
++
++
++async def test_websocket_frames_pipelined_behind_request_burst(
++    aiohttp_server: AiohttpServer,
++) -> None:
++    """A websocket upgraded from within a request burst still reads frames.
++
++    The parser stops at the upgrade request and buffers everything after it,
++    which is websocket data once the handshake succeeds. Answering the requests
++    queued ahead of the upgrade must neither consume that buffer as HTTP nor
++    leave the transport paused by the pipeline queue after switching protocols.
++    """
++    # More than the queue holds, so reading pauses and the parser buffers.
++    pipelined_requests = MAX_MSG_QUEUE_SIZE + 8
++    handled: list[str] = []
++
++    async def handler(request: web.Request) -> web.Response:
++        handled.append(request.path)
++        return web.Response()
++
++    async def ws_handler(request: web.Request) -> web.WebSocketResponse:
++        ws = web.WebSocketResponse()
++        await ws.prepare(request)
++        await ws.send_str(await ws.receive_str())
++        return ws
++
++    app = web.Application()
++    app.router.add_get("/ws", ws_handler)
++    app.router.add_get("/{tail:.*}", handler)
++    server = await aiohttp_server(app)
++
++    reader, writer = await asyncio.open_connection(server.host, server.port)
++    try:
++        writer.write(
++            b"".join(_raw_get(f"/r{i}") for i in range(pipelined_requests))
++            + _RAW_UPGRADE
++            + _masked_text_frame(b"frame-ok")
++        )
++        await writer.drain()
++
++        # Without the fix the frame is eaten by the http parser and the paused
++        # transport is never resumed, so nothing is echoed back.
++        await asyncio.wait_for(reader.readuntil(b"\x81\x08frame-ok"), timeout=10)
++    finally:
++        writer.close()
++        with contextlib.suppress(ConnectionResetError, BrokenPipeError):
++            await writer.wait_closed()
++
++    assert handled == [f"/r{i}" for i in range(pipelined_requests)]
++
++
++async def test_pipelined_request_after_declined_upgrade_behind_burst(
++    aiohttp_server: AiohttpServer,
++) -> None:
++    """A declined upgrade replays its tail even when queued behind a request.
++
++    Only the upgrade request's own response settles whether the buffered bytes
++    are websocket data or pipelined HTTP, so an earlier request completing must
++    leave them alone and the declining response still has to replay them.
++    """
++    handled: list[str] = []
++
++    async def handler(request: web.Request) -> web.Response:
++        handled.append(request.path)
++        return web.Response(text=f"{request.path[1:]}-ok")
++
++    async def ws_handler(request: web.Request) -> NoReturn:
++        raise web.HTTPUpgradeRequired()
++
++    app = web.Application()
++    app.router.add_get("/ws", ws_handler)
++    app.router.add_get("/{tail:.*}", handler)
++    server = await aiohttp_server(app)
++
++    reader, writer = await asyncio.open_connection(server.host, server.port)
++    try:
++        writer.write(_raw_get("/first") + _RAW_UPGRADE + _raw_get("/second"))
++        await writer.drain()
++
++        # Without the replay the trailing request stalls until keep-alive expires.
++        data = await asyncio.wait_for(reader.readuntil(b"second-ok"), timeout=10)
++    finally:
++        writer.close()
++        with contextlib.suppress(ConnectionResetError, BrokenPipeError):
++            await writer.wait_closed()
++
++    assert handled == ["/first", "/second"]
++    assert data.count(b"HTTP/1.1 200 OK") == 2, data
++    assert b"426" in data, data
++
++
++async def test_pipelined_request_after_two_declined_upgrades(
++    aiohttp_server: AiohttpServer,
++) -> None:
++    """A second upgrade inside a replayed tail buffers its own remainder again.
++
++    Replaying a declined upgrade's tail can turn up another upgrade request,
++    which puts the parser back into upgraded mode. Losing that leaves the bytes
++    behind the second upgrade buffered with nothing left to replay them.
++    """
++    handled: list[str] = []
++
++    async def handler(request: web.Request) -> web.Response:
++        handled.append(request.path)
++        return web.Response(text="second-ok")
++
++    async def ws_handler(request: web.Request) -> NoReturn:
++        raise web.HTTPUpgradeRequired()
++
++    app = web.Application()
++    app.router.add_get("/ws", ws_handler)
++    app.router.add_get("/{tail:.*}", handler)
++    server = await aiohttp_server(app)
++
++    reader, writer = await asyncio.open_connection(server.host, server.port)
++    try:
++        writer.write(_RAW_UPGRADE + _RAW_UPGRADE + _raw_get("/second"))
++        await writer.drain()
++
++        data = await asyncio.wait_for(reader.readuntil(b"second-ok"), timeout=10)
++    finally:
++        writer.close()
++        with contextlib.suppress(ConnectionResetError, BrokenPipeError):
++            await writer.wait_closed()
++
++    assert handled == ["/second"]
++    assert data.count(b"HTTP/1.1 426 ") == 2, data
meta-python/recipes-devtools/python/python3-aiohttp_3.13.5.bb +1 -0
index 06e0156e14..1ddfec27aa 100644
@@ -39,6 +39,7 @@ SRC_URI += " \
     file://CVE-2026-128126.patch \
     file://CVE-2026-128127.patch \
     file://CVE-2026-128128.patch \
+    file://CVE-2026-128129.patch \
 "
 
 CVE_PRODUCT = "aiohttp:aiohttp"
Signature · 1 line
2.35.6
#8 lore raw

PATCH 8/10 python3-aiohttp: ignore CVE-2026-128131

In reply to Ashishkumar Parmar X (asparmar - E INFOCHIPS PRIVATE LIMITED at Cisco)

From: Ashishkumar Parmar <[email protected]>

The current sources do not include the concatenated gzip/deflate or Zstandard member iteration that introduces this issue [1]. Both decompressors pass the input to a single decompressor without the loops introduced by [2] and [3]. The existing recipe patches do not add those loops.

Use not-applicable-config for the absent implementation; OE-Core maps this status to the vulnerableCodeNotPresent VEX justification [4]. The aiohttp:aiohttp product identifies the correct component, so cpe-incorrect does not describe this case.

[1] https://github.com/aio-libs/aiohttp/security/advisories/GHSA-h4cc-hm5h-fmm9
[2] https://github.com/aio-libs/aiohttp/commit/2049ba85701586fb065378787a74f99eb2b91108
[3] https://github.com/aio-libs/aiohttp/commit/374fb1dc29baa5e5b11a113ce1a5d0d04116f8e3
[4] https://github.com/openembedded/openembedded-core/blob/16a03ed6c2db2fa1d7edac4f288a74958a00eb9f/meta/conf/cve-check-map.conf#L29-L31

---
 meta-python/recipes-devtools/python/python3-aiohttp_3.13.5.bb | 1 +
 1 file changed, 1 insertion(+)
meta-python/recipes-devtools/python/python3-aiohttp_3.13.5.bb +1 -0
index 1ddfec27aa..91d11cf124 100644
@@ -43,6 +43,7 @@ SRC_URI += " \
 "
 
 CVE_PRODUCT = "aiohttp:aiohttp"
+CVE_STATUS[CVE-2026-128131] = "not-applicable-config: The current sources and recipe patches lack concatenated-member iteration in ZLibDecompressor and ZSTDDecompressor."
 CVE_STATUS_GROUPS = "CVE_AIOHTTP_FIX_3_13_4"
 CVE_AIOHTTP_FIX_3_13_4[status] = "fixed-version: fixed in 3.13.4"
 CVE_AIOHTTP_FIX_3_13_4 = "CVE-2026-22815 CVE-2026-34513 CVE-2026-34514 \
Signature · 1 line
2.35.6
#9 lore raw

PATCH 9/10 python3-aiohttp: fix CVE-2026-128132

In reply to Ashishkumar Parmar X (asparmar - E INFOCHIPS PRIVATE LIMITED at Cisco)

From: Ashishkumar Parmar <[email protected]>

This patch applies the WebSocket queue backpressure fix for CVE-2026-128132 from the upstream stable branch [1].

Account for per-message object overhead and stop parsing buffered frames when the queue crosses its high-water limit.

[1] https://github.com/aio-libs/aiohttp/commit/0ae507423f681161efa77d20052b4054397c7fb6
[2] https://github.com/aio-libs/aiohttp/security/advisories/GHSA-5rmc-48h2-hvcm

---
 .../python3-aiohttp/CVE-2026-128132.patch     | 1242 +++++++++++++++++
 .../python/python3-aiohttp_3.13.5.bb          |    1 +
 2 files changed, 1243 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128132.patch
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-128132.patch new file +1242 -0
new file mode 100644
index 0000000000..97a7cb7ead
@@ -0,0 +1,1242 @@
+From 62c5f7aa938f592676662c306f9d05baca3e521d Mon Sep 17 00:00:00 2001
+From: Sam Bull <[email protected]>
+Date: Fri, 28 Aug 2026 16:59:56 +0100
+Subject: [PATCH] Fix memory consumption on empty/small messages (#13393)
+ (#13545) (#13546)
+
+(cherry picked from commit 5e54037933fa8422be5fa8a2002d118ed2d4e5e0)
+
+Co-authored-by: J. Nick Koston <[email protected]>
+
+CVE: CVE-2026-128132
+Upstream-Status: Backport [https://github.com/aio-libs/aiohttp/commit/0ae507423f681161efa77d20052b4054397c7fb6]
+
+Backport Changes:
+- Retain the current constructors and callback interfaces, which have
+  no decode_text or data_received_cb options. Preserve response ownership
+  of stalled parsers and all upstream close/error cleanup paths.
+- Keep existing typing imports and annotations for the current API.
+- Remove decode_text arguments from the added parser tests, and keep
+  their socket-read bound local because helpers has no DEFAULT_CHUNK_SIZE.
+- Keep only the added regression tests when resolving newer test-file
+  context, retaining the queued-fragment checks already in the source.
+- Omit CHANGES/13393.breaking.rst and CHANGES/13393.bugfix.rst, which
+  record upstream release notes.
+
+Signed-off-by: Ashishkumar Parmar <[email protected]>
+---
+ aiohttp/_websocket/reader_c.pxd        |  12 +-
+ aiohttp/_websocket/reader_py.py        |  55 +++-
+ aiohttp/client.py                      |  10 +-
+ aiohttp/client_ws.py                   |  58 ++--
+ aiohttp/web_ws.py                      |  99 ++++---
+ tests/test_client_ws_functional.py     | 163 ++++++++++-
+ tests/test_web_websocket_functional.py | 178 ++++++++++++
+ tests/test_websocket_parser.py         | 361 +++++++++++++++++++++++++
+ 8 files changed, 859 insertions(+), 77 deletions(-)
+
+diff --git a/aiohttp/_websocket/reader_c.pxd b/aiohttp/_websocket/reader_c.pxd
+index fcb7b4d..ab2d4c8 100644
+--- a/aiohttp/_websocket/reader_c.pxd
++++ b/aiohttp/_websocket/reader_c.pxd
+@@ -38,11 +38,13 @@ cdef set MESSAGE_TYPES_WITH_CONTENT
+ cdef tuple EMPTY_FRAME
+ cdef tuple EMPTY_FRAME_ERROR
+ 
++cdef unsigned int MSG_SIZE_OVERHEAD
++
+ cdef class WebSocketDataQueue:
+ 
+-    cdef unsigned int _size
++    cdef readonly unsigned int _size
+     cdef public object _protocol
+-    cdef unsigned int _limit
++    cdef readonly unsigned int _limit
+     cdef object _loop
+     cdef bint _eof
+     cdef object _waiter
+@@ -50,6 +52,7 @@ cdef class WebSocketDataQueue:
+     cdef public object _buffer
+     cdef object _get_buffer
+     cdef object _put_buffer
++    cdef readonly object _stalled_reader
+ 
+     cdef void _release_waiter(self)
+ 
+@@ -60,6 +63,11 @@ cdef class WebSocketDataQueue:
+ 
+ cdef class WebSocketReader:
+ 
++    # cdef classes are not weak-referenceable without this; the queue parks a
++    # weakref here while parsing is stalled.
++    cdef object __weakref__
++    cdef object _weak_self
++
+     cdef WebSocketDataQueue queue
+     cdef unsigned int _max_msg_size
+ 
+diff --git a/aiohttp/_websocket/reader_py.py b/aiohttp/_websocket/reader_py.py
+index e9472bd..06bd9d1 100644
+--- a/aiohttp/_websocket/reader_py.py
++++ b/aiohttp/_websocket/reader_py.py
+@@ -3,12 +3,14 @@
+ import asyncio
+ import builtins
+ import sys
++import weakref
+ from collections import deque
+ from typing import Deque, Final, Optional, Set, Tuple, Union
+ 
+ from ..base_protocol import BaseProtocol
+ from ..compression_utils import ZLibDecompressor
+ from ..helpers import _EXC_SENTINEL, set_exception
++from ..log import ws_logger
+ from ..streams import EofStream
+ from .helpers import UNPACK_CLOSE_CODE, UNPACK_LEN3, websocket_mask
+ from .models import (
+@@ -55,6 +57,15 @@ COMPRESSED_TRUE = 1
+ 
+ TUPLE_NEW = tuple.__new__
+ 
++# Overhead added to each message to ensure that tiny messages can't use
++# unreasonable amounts of memory.
++MSG_SIZE_OVERHEAD: Final[int] = 128
++
++STALLED_READER_COLLECTED: Final[str] = (
++    "WebSocketReader was garbage collected while stalled; "
++    "callers of set_parser() must hold a strong reference"
++)
++
+ cython_int = int  # Typed to int in Python, but cython with use a signed int in the pxd
+ 
+ 
+@@ -77,6 +88,7 @@ class WebSocketDataQueue:
+         self._buffer: Deque[Tuple[WSMessage, int]] = deque()
+         self._get_buffer = self._buffer.popleft
+         self._put_buffer = self._buffer.append
++        self._stalled_reader: "weakref.ref[WebSocketReader] | None" = None
+ 
+     def is_eof(self) -> bool:
+         return self._eof
+@@ -108,7 +120,7 @@ class WebSocketDataQueue:
+         self._exception = None  # Break cyclic references
+ 
+     def feed_data(self, data: "WSMessage", size: "cython_int") -> None:
+-        self._size += size
++        self._size += size + MSG_SIZE_OVERHEAD
+         self._put_buffer((data, size))
+         self._release_waiter()
+         if self._size > self._limit and not self._protocol._reading_paused:
+@@ -128,8 +140,33 @@ class WebSocketDataQueue:
+     def _read_from_buffer(self) -> WSMessage:
+         if self._buffer:
+             data, size = self._get_buffer()
+-            self._size -= size
+-            if self._size < self._limit and self._protocol._reading_paused:
++            self._size -= size + MSG_SIZE_OVERHEAD
++            if self._stalled_reader is not None and self._size <= self._limit // 2:
++                # Resume parsing once the queue drains to the low-water mark.
++                # Each resume re-slices the parser's unparsed tail, so waiting
++                # for headroom makes a drain cost one copy per batch of
++                # messages instead of one per message.
++                if (reader := self._stalled_reader()) is not None:
++                    reader.feed_data(b"")
++                else:
++                    # The stash died with the reader. Deliver what was already
++                    # queued, then surface the contract violation on the next
++                    # read instead of hanging. Log as well, since a caller that
++                    # stops reading early never sees the deferred exception. A
++                    # real failure that was already recorded stays the reported
++                    # cause.
++                    self._stalled_reader = None
++                    ws_logger.warning(STALLED_READER_COLLECTED)
++                    if self._exception is None:
++                        self.set_exception(RuntimeError(STALLED_READER_COLLECTED))
++            # Resuming the transport while a stash remains would admit
++            # another socket read into the tail for every couple of messages
++            # drained, moving the memory bound from the queue into the tail.
++            if (
++                self._stalled_reader is None
++                and self._size < self._limit
++                and self._protocol._reading_paused
++            ):
+                 self._protocol.resume_reading()
+             return data
+         if self._exception is not None:
+@@ -143,6 +180,9 @@ class WebSocketReader:
+     ) -> None:
+         self.queue = queue
+         self._max_msg_size = max_msg_size
++        # Parked on the queue while parsing is stalled; created once so
++        # stalling does not allocate.
++        self._weak_self = weakref.ref(self)
+ 
+         self._exc: Optional[Exception] = None
+         self._partial = bytearray()
+@@ -322,6 +362,7 @@ class WebSocketReader:
+ 
+     def _feed_data(self, data: bytes) -> None:
+         """Return the next frame from the socket."""
++        self.queue._stalled_reader = None
+         if self._tail:
+             data, self._tail = self._tail + data, b""
+ 
+@@ -330,6 +371,14 @@ class WebSocketReader:
+         data_cstr = data
+ 
+         while True:
++            if start_pos < data_len and self.queue._size > self.queue._limit:
++                # Over the high-water mark with unparsed bytes left: stash the
++                # remainder and stall. Gating on unparsed bytes keeps a read
++                # that ended on a frame boundary from arming an empty stall,
++                # which would hold the transport paused with nothing to drain.
++                self.queue._stalled_reader = self._weak_self
++                break
++
+             # read header
+             if self._state == READ_HEADER:
+                 if data_len - start_pos < 2:
+diff --git a/aiohttp/client.py b/aiohttp/client.py
+index fafc5d3..8c642ef 100644
+--- a/aiohttp/client.py
++++ b/aiohttp/client.py
+@@ -1198,9 +1198,6 @@ class ClientSession:
+             transport = conn.transport
+             assert transport is not None
+             reader = WebSocketDataQueue(conn_proto, 2**16, loop=self._loop)
+-            conn_proto.set_parser(
+-                WebSocketReader(reader, max_msg_size, compress=bool(compress)), reader
+-            )
+             writer = WebSocketWriter(
+                 conn_proto,
+                 transport,
+@@ -1212,7 +1209,7 @@ class ClientSession:
+             resp.close()
+             raise
+         else:
+-            return self._ws_response_class(
++            ws_resp = self._ws_response_class(
+                 reader,
+                 writer,
+                 protocol,
+@@ -1225,6 +1222,11 @@ class ClientSession:
+                 compress=compress,
+                 client_notakeover=notakeover,
+             )
++            ws_resp._parser = WebSocketReader(
++                reader, max_msg_size, compress=bool(compress)
++            )
++            conn_proto.set_parser(ws_resp._parser, reader)
++            return ws_resp
+ 
+     def _prepare_headers(self, headers: Optional[LooseHeaders]) -> "CIMultiDict[str]":
+         """Add default headers and transform it to CIMultiDict"""
+diff --git a/aiohttp/client_ws.py b/aiohttp/client_ws.py
+index daa57d1..1a85bdd 100644
+--- a/aiohttp/client_ws.py
++++ b/aiohttp/client_ws.py
+@@ -7,7 +7,7 @@ from typing import Any, Optional, Type, cast
+ 
+ import attr
+ 
+-from ._websocket.reader import WebSocketDataQueue
++from ._websocket.reader import WebSocketDataQueue, WebSocketReader
+ from .client_exceptions import ClientError, ServerTimeoutError, WSMessageTypeError
+ from .client_reqrep import ClientResponse
+ from .helpers import calculate_timeout_when, set_result
+@@ -64,6 +64,10 @@ class ClientWebSocketResponse:
+ 
+         self._writer = writer
+         self._reader = reader
++        # Set by ClientSession._ws_connect; owns the parser so a stalled
++        # reader parked on the queue by weakref stays alive while this
++        # response can still be drained.
++        self._parser: Optional[WebSocketReader] = None
+         self._protocol = protocol
+         self._closed = False
+         self._closing = False
+@@ -172,6 +176,8 @@ class ClientWebSocketResponse:
+         if self._closed:
+             return
+         self._set_closed()
++        # close() is never reached after this; release the parser here.
++        self._parser = None
+         self._close_code = WSCloseCode.ABNORMAL_CLOSURE
+         self._exception = exc
+         self._response.close()
+@@ -275,25 +281,8 @@ class ClientWebSocketResponse:
+ 
+         self._set_closed()
+         try:
+-            await self._writer.close(code, message)
+-        except asyncio.CancelledError:
+-            self._close_code = WSCloseCode.ABNORMAL_CLOSURE
+-            self._response.close()
+-            raise
+-        except Exception as exc:
+-            self._close_code = WSCloseCode.ABNORMAL_CLOSURE
+-            self._exception = exc
+-            self._response.close()
+-            return True
+-
+-        if self._close_code:
+-            self._response.close()
+-            return True
+-
+-        while True:
+             try:
+-                async with async_timeout.timeout(self._timeout.ws_close):
+-                    msg = await self._reader.read()
++                await self._writer.close(code, message)
+             except asyncio.CancelledError:
+                 self._close_code = WSCloseCode.ABNORMAL_CLOSURE
+                 self._response.close()
+@@ -304,11 +293,33 @@ class ClientWebSocketResponse:
+                 self._response.close()
+                 return True
+ 
+-            if msg.type is WSMsgType.CLOSE:
+-                self._close_code = msg.data
++            if self._close_code:
+                 self._response.close()
+                 return True
+ 
++            while True:
++                try:
++                    async with async_timeout.timeout(self._timeout.ws_close):
++                        msg = await self._reader.read()
++                except asyncio.CancelledError:
++                    self._close_code = WSCloseCode.ABNORMAL_CLOSURE
++                    self._response.close()
++                    raise
++                except Exception as exc:
++                    self._close_code = WSCloseCode.ABNORMAL_CLOSURE
++                    self._exception = exc
++                    self._response.close()
++                    return True
++
++                if msg.type is WSMsgType.CLOSE:
++                    self._close_code = msg.data
++                    self._response.close()
++                    return True
++        finally:
++            # Once closed the response can no longer be drained; release the
++            # parser and the stash it retains.
++            self._parser = None
++
+     async def receive(self, timeout: Optional[float] = None) -> WSMessage:
+         receive_timeout = timeout or self._timeout.ws_receive
+ 
+@@ -347,7 +358,10 @@ class ClientWebSocketResponse:
+                 await self.close()
+                 return WSMessage(WSMsgType.CLOSED, None, None)
+             except ClientError:
+-                # Likely ServerDisconnectedError when connection is lost
++                # Likely ServerDisconnectedError when connection is lost.
++                # close() is not called on this path, so release the parser
++                # and the stash it retains here.
++                self._parser = None
+                 self._set_closed()
+                 self._close_code = WSCloseCode.ABNORMAL_CLOSURE
+                 return WS_CLOSED_MESSAGE
+diff --git a/aiohttp/web_ws.py b/aiohttp/web_ws.py
+index 575f9a3..134274c 100644
+--- a/aiohttp/web_ws.py
++++ b/aiohttp/web_ws.py
+@@ -65,6 +65,7 @@ class WebSocketResponse(StreamResponse):
+     _ws_protocol: Optional[str] = None
+     _writer: Optional[WebSocketWriter] = None
+     _reader: Optional[WebSocketDataQueue] = None
++    _parser: Optional[WebSocketReader] = None
+     _closed: bool = False
+     _closing: bool = False
+     _conn_lost: int = 0
+@@ -193,6 +194,8 @@ class WebSocketResponse(StreamResponse):
+         if self._closed:
+             return
+         self._set_closed()
++        # close() is never reached after this; release the parser here.
++        self._parser = None
+         self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
+         self._exception = exc
+         if self._waiting and not self._closing and self._reader is not None:
+@@ -336,11 +339,12 @@ class WebSocketResponse(StreamResponse):
+         loop = self._loop
+         assert loop is not None
+         self._reader = WebSocketDataQueue(request._protocol, 2**16, loop=loop)
+-        request.protocol.set_parser(
+-            WebSocketReader(
+-                self._reader, self._max_msg_size, compress=bool(self._compress)
+-            )
++        # Owns the parser so a stalled reader parked on the queue by weakref
++        # stays alive while this response can still be drained.
++        self._parser = WebSocketReader(
++            self._reader, self._max_msg_size, compress=bool(self._compress)
+         )
++        request.protocol.set_parser(self._parser)
+         # disable HTTP keepalive for WebSocket
+         request.protocol.keep_alive(False)
+ 
+@@ -455,48 +459,53 @@ class WebSocketResponse(StreamResponse):
+         self._set_closed()
+ 
+         try:
+-            await self._writer.close(code, message)
+-            writer = self._payload_writer
+-            assert writer is not None
+-            if drain:
+-                await writer.drain()
+-        except (asyncio.CancelledError, asyncio.TimeoutError):
+-            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
+-            raise
+-        except Exception as exc:
+-            self._exception = exc
+-            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
+-            return True
+-
+-        reader = self._reader
+-        assert reader is not None
+-        # we need to break `receive()` cycle before we can call
+-        # `reader.read()` as `close()` may be called from different task
+-        if self._waiting:
+-            assert self._loop is not None
+-            assert self._close_wait is None
+-            self._close_wait = self._loop.create_future()
+-            reader.feed_data(WS_CLOSING_MESSAGE, 0)
+-            await self._close_wait
+-
+-        if self._closing:
+-            self._close_transport()
+-            return True
++            try:
++                await self._writer.close(code, message)
++                writer = self._payload_writer
++                assert writer is not None
++                if drain:
++                    await writer.drain()
++            except (asyncio.CancelledError, asyncio.TimeoutError):
++                self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
++                raise
++            except Exception as exc:
++                self._exception = exc
++                self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
++                return True
+ 
+-        try:
+-            async with async_timeout.timeout(self._timeout):
+-                while True:
+-                    msg = await reader.read()
+-                    if msg.type is WSMsgType.CLOSE:
+-                        self._set_code_close_transport(msg.data)
+-                        return True
+-        except asyncio.CancelledError:
+-            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
+-            raise
+-        except Exception as exc:
+-            self._exception = exc
+-            self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
+-            return True
++            reader = self._reader
++            assert reader is not None
++            # we need to break `receive()` cycle before we can call
++            # `reader.read()` as `close()` may be called from different task
++            if self._waiting:
++                assert self._loop is not None
++                assert self._close_wait is None
++                self._close_wait = self._loop.create_future()
++                reader.feed_data(WS_CLOSING_MESSAGE, 0)
++                await self._close_wait
++
++            if self._closing:
++                self._close_transport()
++                return True
++
++            try:
++                async with async_timeout.timeout(self._timeout):
++                    while True:
++                        msg = await reader.read()
++                        if msg.type is WSMsgType.CLOSE:
++                            self._set_code_close_transport(msg.data)
++                            return True
++            except asyncio.CancelledError:
++                self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
++                raise
++            except Exception as exc:
++                self._exception = exc
++                self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE)
++                return True
++        finally:
++            # Once closed the response can no longer be drained; release the
++            # parser and the stash it retains.
++            self._parser = None
+ 
+     def _set_closing(self, code: WSCloseCode) -> None:
+         """Set the close code and mark the connection as closing."""
+diff --git a/tests/test_client_ws_functional.py b/tests/test_client_ws_functional.py
+index a67769c..0bb1288 100644
+--- a/tests/test_client_ws_functional.py
++++ b/tests/test_client_ws_functional.py
+@@ -1,4 +1,9 @@
+ import asyncio
++import base64
++import contextlib
++import gc
++import hashlib
++import socket
+ import struct
+ import sys
+ import zlib
+@@ -19,7 +24,7 @@ from aiohttp import (
+ from aiohttp._websocket.reader import WebSocketDataQueue
+ from aiohttp._websocket.models import WS_DEFLATE_TRAILING
+ from aiohttp.client_ws import ClientWSTimeout
+-from aiohttp.http import WebSocketError, WSCloseCode
++from aiohttp.http import WS_KEY, WebSocketError, WSCloseCode
+ from aiohttp.pytest_plugin import AiohttpClient
+ 
+ if sys.version_info >= (3, 11):
+@@ -1314,3 +1319,159 @@ async def test_client_rejects_compressed_frame_without_negotiation(
+     assert msg.type is WSMsgType.ERROR, msg
+     assert isinstance(msg.data, WebSocketError)
+     assert msg.data.code == WSCloseCode.PROTOCOL_ERROR
++
++
++async def test_stashed_frames_survive_connection_loss(
++    unused_port_socket: socket.socket,
++) -> None:
++    """Frames stashed by receive-queue backpressure outlive the connection.
++
++    Mirror of the server-side test: a peer can pack more complete frames into
++    one read than the queue's high-water mark allows, so the parser stalls
++    with the rest in its tail. ``connection_lost()`` drops the protocol's
++    reference to the parser, so only ``ClientWebSocketResponse._parser`` keeps
++    it alive; without that the queue's weak link dies and the stash is lost.
++    """
++    sent = 8000
++
++    writers: list[asyncio.StreamWriter] = []
++
++    async def raw_server(
++        reader: asyncio.StreamReader, writer: asyncio.StreamWriter
++    ) -> None:
++        writers.append(writer)
++        request = await reader.readuntil(b"\r\n\r\n")
++        key = next(
++            line.split(b":", 1)[1].strip()
++            for line in request.split(b"\r\n")
++            if line.lower().startswith(b"sec-websocket-key")
++        )
++        accept = base64.b64encode(hashlib.sha1(key + WS_KEY).digest())
++        writer.write(
++            b"HTTP/1.1 101 Switching Protocols\r\n"
++            b"Upgrade: websocket\r\n"
++            b"Connection: Upgrade\r\n"
++            b"Sec-WebSocket-Accept: " + accept + b"\r\n\r\n"
++            # One oversized read: empty unmasked TEXT frames, 2 bytes each.
++            + b"\x81\x00" * sent
++        )
++        await writer.drain()
++
++    server = await asyncio.start_server(raw_server, sock=unused_port_socket)
++    port = unused_port_socket.getsockname()[1]
++    try:
++        async with aiohttp.ClientSession() as session:
++            ws = await session.ws_connect(f"http://127.0.0.1:{port}/")
++            queue = ws._reader
++            # Usually the whole burst rides along with the 101 response and
++            # is parsed before ws_connect() returns, so the wait is a
++            # fallback for split reads only.
++            for _ in range(1000):  # pragma: no cover
++                if queue._stalled_reader is not None:
++                    break
++                await asyncio.sleep(0.01)
++            assert queue._stalled_reader is not None, "parser never stalled"
++            stalled = len(queue._buffer)
++
++            # Tear the connection down for real: closing the transport is what
++            # drives connection_lost(), which drops the protocol's reference to
++            # the parser. A paused transport never sees the peer's FIN, so this
++            # cannot be triggered by the peer going away.
++            connection = ws._conn
++            assert connection is not None
++            protocol = connection.protocol
++            assert protocol is not None
++            assert protocol.transport is not None
++            protocol.transport.close()
++            for _ in range(1000):  # pragma: no branch
++                if protocol._payload_parser is None:
++                    break
++                await asyncio.sleep(0)
++            assert protocol._payload_parser is None, "connection_lost never ran"
++
++            count = 0
++            while (msg := await ws.receive()).type is WSMsgType.TEXT:
++                count += 1
++            # A clean drain ends with the queue's close, not an error.
++            assert msg.type is WSMsgType.CLOSED
++    finally:
++        for writer in writers:
++            writer.close()
++            with contextlib.suppress(Exception):
++                await writer.wait_closed()
++        server.close()
++        await server.wait_closed()
++
++    assert stalled < count <= sent
++
++
++async def test_stalled_parser_outlives_connection_lost(
++    aiohttp_client: AiohttpClient,
++) -> None:
++    """Frames the parser stopped short of are delivered after the peer vanishes.
++
++    Once the queue is over its high-water mark the parser stops mid-read and
++    parks the rest of the read on itself, reachable from the queue only through
++    a weak reference. Connection loss releases the protocol's reference to the
++    parser, so the response has to be the owner or those frames are collected
++    and the application silently sees a short stream.
++    """
++
++    async def handler(request: web.Request) -> web.WebSocketResponse:
++        ws = web.WebSocketResponse()
++        await ws.prepare(request)
++        # Hold the connection open. TestServer cancels the handler on
++        # connection loss; swallow it so the handler exits normally.
++        with contextlib.suppress(asyncio.CancelledError):
++            await ws.receive()
++        return ws
++
++    app = web.Application()
++    app.router.add_get("/", handler)
++    client = await aiohttp_client(app)
++    ws = await client.ws_connect("/")
++
++    # Empty server->client TEXT frames: two bytes on the wire, but each one is
++    # charged MSG_SIZE_OVERHEAD in the queue, so a single read crosses the
++    # high-water mark and the parser stalls part way through it.
++    sent = 8000
++    assert ws._conn is not None
++    protocol = ws._conn.protocol
++    assert protocol is not None
++    transport = protocol.transport
++    assert transport is not None
++    protocol.data_received(b"\x81\x00" * sent)
++    assert ws._reader._stalled_reader is not None, "parser never stalled"
++
++    # Simulate the peer vanishing: the socket is gone and the protocol drops
++    # its reference to the parser, exactly as the event loop would do it.
++    transport.abort()
++    protocol.connection_lost(None)
++    for _ in range(3):  # PyPy can need more than one pass
++        gc.collect()
++
++    count = 0
++    while (await ws.receive()).type is not WSMsgType.CLOSED:
++        count += 1
++    assert count == sent
++    # Exhausting the queue releases the parser and the stash it retains.
++    assert ws._parser is None
++
++
++async def test_close_releases_parser(aiohttp_client: AiohttpClient) -> None:
++    """A normal close handshake releases the parser and the state it holds."""
++
++    async def handler(request: web.Request) -> web.WebSocketResponse:
++        ws = web.WebSocketResponse()
++        await ws.prepare(request)
++        await ws.receive()  # the peer's CLOSE
++        return ws
++
++    app = web.Application()
++    app.router.add_get("/", handler)
++    client = await aiohttp_client(app)
++    resp = await client.ws_connect("/")
++
++    assert resp._parser is not None
++    await resp.close()
++    assert resp._parser is None
+diff --git a/tests/test_web_websocket_functional.py b/tests/test_web_websocket_functional.py
+index 6035b77..c607d17 100644
+--- a/tests/test_web_websocket_functional.py
++++ b/tests/test_web_websocket_functional.py
+@@ -2,6 +2,8 @@
+ 
+ import asyncio
+ import contextlib
++import gc
++import socket
+ import sys
+ import weakref
+ from typing import Any, NoReturn, Optional
+@@ -1577,3 +1579,179 @@ async def test_pipelined_request_after_two_declined_upgrades(
+ 
+     assert handled == ["/second"]
+     assert data.count(b"HTTP/1.1 426 ") == 2, data
++
++
++async def test_stashed_frames_survive_connection_loss(
++    unused_port_socket: socket.socket,
++) -> None:
++    """Frames stashed by receive-queue backpressure outlive the connection.
++
++    A peer can pack far more complete frames into one read than the queue's
++    high-water mark allows, so the parser stops part-way and leaves the rest
++    in its tail. ``connection_lost()`` then drops the protocol's reference to
++    the parser, so only ``WebSocketResponse._parser`` keeps it alive; without
++    that the queue's weak link dies with the connection and every stashed
++    frame is silently lost.
++    """
++    sent = 8000
++    # (frames queued when the parser stalled, frames delivered in total)
++    received: asyncio.Future[tuple[int, int]] = (
++        asyncio.get_running_loop().create_future()
++    )
++
++    async def handler(request: web.Request) -> web.WebSocketResponse:
++        ws = web.WebSocketResponse()
++        await ws.prepare(request)
++        try:
++            queue = ws._reader
++            assert queue is not None
++
++            # Wait for the parser to stall with frames still stashed in its
++            # tail. The transport is paused from here, so the peer's FIN
++            # cannot be observed until reading resumes.
++            for _ in range(1000):  # pragma: no branch
++                if queue._stalled_reader is not None:
++                    break
++                await asyncio.sleep(0.01)
++            assert queue._stalled_reader is not None, "parser never stalled"
++            stalled = len(queue._buffer)
++
++            # Tear the connection down for real: closing the transport is
++            # what drives connection_lost(), which drops the protocol's only
++            # reference to the parser, leaving ws._parser holding it.
++            protocol = request.protocol
++            transport = protocol.transport
++            assert transport is not None
++            transport.close()
++            for _ in range(1000):  # pragma: no branch
++                if protocol._payload_parser is None:
++                    break
++                await asyncio.sleep(0)
++            assert protocol._payload_parser is None, "connection_lost never ran"
++
++            count = 0
++            while (msg := await ws.receive()).type is WSMsgType.TEXT:
++                count += 1
++            # A clean drain ends with the queue's close, not an error.
++            assert msg.type is WSMsgType.CLOSED
++
++            received.set_result((stalled, count))
++        except Exception as exc:  # pragma: no cover
++            # Surface handler failures instead of an opaque timeout.
++            received.set_exception(exc)
++            raise
++        return ws
++
++    # A plain AppRunner, not the aiohttp_server fixture: TestServer forces
++    # handler_cancellation=True, which kills the handler on connection loss.
++    # Production defaults to False, and that is the case where the stash
++    # still has to be drainable.
++    app = web.Application()
++    app.router.add_route("GET", "/ws", handler)
++    runner = web.AppRunner(app)
++    await runner.setup()
++    try:
++        await web.SockSite(runner, unused_port_socket).start()
++        port = unused_port_socket.getsockname()[1]
++
++        reader, writer = await asyncio.open_connection("127.0.0.1", port)
++        try:
++            writer.write(_RAW_UPGRADE)
++            await writer.drain()
++            await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), timeout=5)
++
++            # Written as one call, but whether it arrives as one read is the
++            # kernel's choice.
++            writer.write(b"\x81\x80\x00\x00\x00\x00" * sent)
++            await writer.drain()
++
++            stalled, count = await asyncio.wait_for(received, timeout=10)
++            assert stalled < count <= sent
++        finally:
++            writer.close()
++            with contextlib.suppress(ConnectionResetError):
++                await writer.wait_closed()
++    finally:
++        await runner.cleanup()
++
++
++async def test_stalled_parser_outlives_connection_lost(
++    aiohttp_client: AiohttpClient,
++) -> None:
++    """Frames the parser stopped short of are delivered after the peer vanishes.
++
++    Once the queue is over its high-water mark the parser stops mid-read and
++    parks the rest of the read on itself, reachable from the queue only through
++    a weak reference. Connection loss releases the protocol's reference to the
++    parser, so the response has to be the owner or those frames are collected
++    and the handler silently sees a short stream.
++    """
++    sent = 8000
++    received: asyncio.Future[int] = asyncio.get_running_loop().create_future()
++
++    async def handler(request: web.Request) -> web.WebSocketResponse:
++        ws = web.WebSocketResponse()
++        await ws.prepare(request)
++        try:
++            protocol = request.protocol
++            transport = request.transport
++            assert transport is not None
++            # Empty masked client->server TEXT frames: six bytes on the wire,
++            # but each one is charged MSG_SIZE_OVERHEAD in the queue, so a
++            # single read crosses the high-water mark and the parser stalls
++            # part way through.
++            protocol.data_received(b"\x81\x80\x00\x00\x00\x00" * sent)
++            queue = ws._reader
++            assert queue is not None
++            assert queue._stalled_reader is not None, "parser never stalled"
++
++            # Simulate the peer vanishing: the socket is gone and the
++            # protocol drops its reference to the parser, as the event loop
++            # would do it. Detach the handler task first: TestServer forces
++            # handler_cancellation=True (production defaults to False), and
++            # the cancellation would land on this very task at its next yield.
++            protocol._task_handler = None
++            transport.abort()
++            protocol.connection_lost(None)
++            for _ in range(3):  # PyPy can need more than one pass
++                gc.collect()
++
++            count = 0
++            while (await ws.receive()).type is not WSMsgType.CLOSED:
++                count += 1
++            # Exhausting the queue releases the parser and its stash.
++            assert ws._parser is None
++            received.set_result(count)
++        except Exception as exc:  # pragma: no cover
++            # Surface handler failures instead of an opaque timeout.
++            received.set_exception(exc)
++            raise
++        return ws
++
++    app = web.Application()
++    app.router.add_get("/", handler)
++    client = await aiohttp_client(app)
++    await client.ws_connect("/")
++
++    assert await asyncio.wait_for(received, 10) == sent
++
++
++async def test_close_releases_parser(aiohttp_client: AiohttpClient) -> None:
++    """A normal close handshake releases the parser and the state it holds."""
++    released: asyncio.Future[bool] = asyncio.get_running_loop().create_future()
++
++    async def handler(request: web.Request) -> web.WebSocketResponse:
++        ws = web.WebSocketResponse()
++        await ws.prepare(request)
++        assert ws._parser is not None
++        await ws.close()
++        released.set_result(ws._parser is None)
++        return ws
++
++    app = web.Application()
++    app.router.add_get("/", handler)
++    client = await aiohttp_client(app)
++    ws = await client.ws_connect("/")
++
++    await ws.receive()  # the server's CLOSE
++    assert await asyncio.wait_for(released, 5) is True
+diff --git a/tests/test_websocket_parser.py b/tests/test_websocket_parser.py
+index c3ec201..22a469d 100644
+--- a/tests/test_websocket_parser.py
++++ b/tests/test_websocket_parser.py
+@@ -1,8 +1,10 @@
+ import asyncio
++import gc
+ import pickle
+ import random
+ import struct
+ import sys
++import weakref
+ from typing import Union
+ from unittest import mock
+ 
+@@ -19,6 +21,7 @@ from aiohttp._websocket.helpers import (
+ )
+ from aiohttp._websocket.models import WS_DEFLATE_TRAILING
+ from aiohttp._websocket.reader import WebSocketDataQueue
++from aiohttp._websocket.reader_py import MSG_SIZE_OVERHEAD
+ from aiohttp._websocket.reader_py import (
+     WebSocketDataQueue as PyWebSocketDataQueue,
+     WebSocketReader as PyWebSocketReader,
+@@ -27,6 +30,7 @@ from aiohttp.base_protocol import BaseProtocol
+ from aiohttp.compression_utils import ZLibBackend
+ from aiohttp.http import WebSocketError, WSCloseCode, WSMessage, WSMsgType
+ from aiohttp.http_websocket import WebSocketReader
++from aiohttp.streams import EofStream
+ 
+ 
+ class PatchableWebSocketReader(WebSocketReader):
+@@ -1008,3 +1012,360 @@ async def test_max_msg_size_zero_opts_out_of_the_fold(
+     parser.feed_data(b"x")
+     msg = await out.read()
+     assert msg.data == b"x" * payload_len
++
++
++DEFAULT_CHUNK_SIZE = 256 * 1024
++
++
++def _compressed_burst(payload: bytes, count: int) -> bytes:
++    """`count` complete, independently deflated BINARY messages in one read."""
++    return (
++        build_frame(payload, WSMsgType.BINARY, ZLibBackend=ZLibBackend, use_mask=True)
++        * count
++    )
++
++
++async def test_empty_messages_apply_backpressure(protocol: BaseProtocol) -> None:
++    # Zero-length messages are not free: each one is a queued object. They used
++    # to add nothing to the queue's byte counter, so a peer could stream empty
++    # frames forever without the transport ever being paused.
++    loop = asyncio.get_running_loop()
++    out = WebSocketDataQueue(protocol, 2**16, loop=loop)
++    parser = WebSocketReader(out, 4 * 1024 * 1024, compress=False)
++
++    sent = 10000
++    parser.feed_data(build_frame(b"", WSMsgType.TEXT, use_mask=True) * sent)
++
++    assert protocol._reading_paused is True
++    assert len(out._buffer) < sent
++    # Overshoot is capped at the one message that crossed the mark.
++    assert out._size <= out._limit + MSG_SIZE_OVERHEAD
++
++
++async def test_compressed_burst_stops_at_high_water(protocol: BaseProtocol) -> None:
++    # permessage-deflate reaches ~1000:1, so a single read can carry dozens of
++    # complete frames that each inflate to max_msg_size. pause_reading() only
++    # stops the transport from delivering more data; the parser has to stop
++    # too, or the whole read is inflated into the queue in one go.
++    loop = asyncio.get_running_loop()
++    out = WebSocketDataQueue(protocol, 2**16, loop=loop)
++    parser = WebSocketReader(out, 1024 * 1024, compress=True)
++
++    payload = b"\0" * (512 * 1024)
++    burst = _compressed_burst(payload, 32)
++    assert len(burst) < 2**16  # the whole burst is one plausible socket read
++
++    parser.feed_data(burst)
++
++    assert protocol._reading_paused is True
++    # Overshoot is capped at the one message that crossed the mark, not the
++    # 16 MiB the peer asked us to inflate.
++    assert len(out._buffer) == 1
++
++
++async def test_read_arriving_over_high_water_inflates_nothing(
++    protocol: BaseProtocol,
++) -> None:
++    # pause_reading() does not retract a read already in flight (the proactor
++    # transport completes its outstanding overlapped read, and a transport
++    # without flow control ignores the pause entirely). Such a read must not
++    # buy the peer one more inflated message before the parser stops again.
++    loop = asyncio.get_running_loop()
++    out = WebSocketDataQueue(protocol, 2**16, loop=loop)
++    parser = WebSocketReader(out, 1024 * 1024, compress=True)
++
++    payload = b"\0" * (512 * 1024)
++    parser.feed_data(_compressed_burst(payload, 2))
++    assert len(out._buffer) == 1
++
++    # Lands while the queue is still over the mark and nothing has drained.
++    parser.feed_data(_compressed_burst(payload, 2))
++    assert len(out._buffer) == 1
++
++    # All four are still delivered once the application catches up.
++    for _ in range(4):
++        msg = await asyncio.wait_for(out.read(), 5)
++        assert msg.data == payload
++
++
++async def test_backpressure_does_not_drop_stashed_frames(
++    protocol: BaseProtocol,
++) -> None:
++    # The frames the parser stopped short of must still be delivered as the
++    # application drains the queue, with no further socket data to drive it.
++    loop = asyncio.get_running_loop()
++    out = WebSocketDataQueue(protocol, 2**16, loop=loop)
++    parser = WebSocketReader(out, 1024 * 1024, compress=True)
++
++    payload = b"\0" * (512 * 1024)
++    parser.feed_data(_compressed_burst(payload, 32))
++
++    for _ in range(32):
++        msg = await asyncio.wait_for(out.read(), 5)
++        assert msg.data == payload
++
++    assert not out._buffer
++    # feed_data() adds MSG_SIZE_OVERHEAD and _read_from_buffer() subtracts it;
++    # _size is an unsigned int under Cython, so if those ever drift the
++    # subtraction wraps to ~4G rather than going negative. _size < _limit is
++    # then permanently false and the connection wedges silently: the transport
++    # is never resumed and the stalled parser is never driven again.
++    assert out._size == 0
++    assert protocol._reading_paused is False
++
++
++async def test_drain_resumes_parsing_in_batches(protocol: BaseProtocol) -> None:
++    # The parser is re-driven only at the low-water mark. Each resume
++    # re-slices the whole unparsed tail, so re-driving on every pop would
++    # make draining a burst of tiny messages quadratic in its size.
++    loop = asyncio.get_running_loop()
++    out = WebSocketDataQueue(protocol, 2**16, loop=loop)
++    parser = WebSocketReader(out, 1024 * 1024, compress=False)
++
++    sent = 8000
++    parser.feed_data(build_frame(b"", WSMsgType.TEXT, use_mask=True) * sent)
++    stalled = len(out._buffer)
++    assert stalled < sent
++
++    # Above the low-water mark a pop must not re-drive the parser.
++    await asyncio.wait_for(out.read(), 5)
++    assert len(out._buffer) == stalled - 1
++
++    # The pop that reaches the low-water mark refills the queue in one batch.
++    low_water_msgs = (out._limit // 2) // MSG_SIZE_OVERHEAD
++    for _ in range(stalled - 1 - low_water_msgs):
++        await asyncio.wait_for(out.read(), 5)
++    assert len(out._buffer) > low_water_msgs
++    assert out._size > out._limit
++
++
++async def test_transport_stays_paused_while_stash_remains(
++    protocol: BaseProtocol,
++) -> None:
++    # Resuming the transport before the stash is exhausted would admit a
++    # fresh socket read into the tail for every couple of messages drained,
++    # moving the memory bound from the queue into the tail.
++    loop = asyncio.get_running_loop()
++    out = WebSocketDataQueue(protocol, 2**16, loop=loop)
++    parser = WebSocketReader(out, 1024 * 1024, compress=False)
++
++    sent = 8000
++    parser.feed_data(build_frame(b"", WSMsgType.TEXT, use_mask=True) * sent)
++    assert protocol._reading_paused is True
++
++    count = 0
++    while out._stalled_reader is not None:
++        await asyncio.wait_for(out.read(), 5)
++        count += 1
++        if out._stalled_reader is not None:
++            assert protocol._reading_paused is True, f"resumed after {count} pops"
++    assert count < sent
++
++    # The pop that exhausted the stash resumed the transport.
++    assert protocol._reading_paused is False
++
++
++async def test_read_ending_on_frame_boundary_does_not_stall(
++    protocol: BaseProtocol,
++) -> None:
++    # A read that crosses the high-water mark but ends exactly on a frame
++    # boundary leaves nothing stashed, so the parser must not arm the stall;
++    # ordinary backpressure then resumes at the queue limit, not the low-water
++    # mark reserved for draining a stash.
++    loop = asyncio.get_running_loop()
++    out = WebSocketDataQueue(protocol, 1024, loop=loop)
++    parser = WebSocketReader(out, 1024 * 1024, compress=False)
++
++    # 17 empty frames * MSG_SIZE_OVERHEAD crosses out._limit (2048); the whole
++    # burst is complete frames, so parsing ends with an empty tail.
++    parser.feed_data(build_frame(b"", WSMsgType.TEXT, use_mask=True) * 17)
++    assert out._size > out._limit
++    assert protocol._reading_paused is True
++    assert out._stalled_reader is None, "empty-tail read must not arm the stall"
++
++    # Draining back under the limit resumes well above _limit // 2, so the
++    # low-water mark reserved for stashes is not in play.
++    await asyncio.wait_for(out.read(), 5)
++    await asyncio.wait_for(out.read(), 5)
++    assert out._limit // 2 < out._size < out._limit
++    assert protocol._reading_paused is False
++
++
++async def test_backpressure_stash_survives_eof(protocol: BaseProtocol) -> None:
++    # A peer that bursts and then disconnects must not lose the tail: at EOF
++    # there is no resume to ride on, so draining has to keep driving the parser.
++    loop = asyncio.get_running_loop()
++    out = WebSocketDataQueue(protocol, 2**16, loop=loop)
++    parser = WebSocketReader(out, 1024 * 1024, compress=True)
++
++    payload = b"\0" * (512 * 1024)
++    parser.feed_data(_compressed_burst(payload, 8))
++    parser.feed_eof()
++
++    for _ in range(8):
++        msg = await asyncio.wait_for(out.read(), 5)
++        assert msg.data == payload
++
++    with pytest.raises(EofStream):
++        await asyncio.wait_for(out.read(), 5)
++
++
++async def test_stalled_reader_reference_released_after_drain(
++    protocol: BaseProtocol,
++) -> None:
++    # The queue holds the reader back only while parsing is stalled. Keeping it
++    # any longer would leave reader <-> queue as a cycle outliving the
++    # connection, reclaimable only by the collector rather than by refcounting.
++    loop = asyncio.get_running_loop()
++    out = WebSocketDataQueue(protocol, 2**16, loop=loop)
++    parser = WebSocketReader(out, 1024 * 1024, compress=True)
++
++    payload = b"\0" * (512 * 1024)
++    parser.feed_data(_compressed_burst(payload, 4))
++    stalled = out._stalled_reader
++    assert stalled is not None and stalled() is parser
++
++    for _ in range(4):
++        await asyncio.wait_for(out.read(), 5)
++
++    assert out._stalled_reader is None
++
++
++async def test_set_exception_still_delivers_stashed_frames(
++    protocol: BaseProtocol,
++) -> None:
++    # set_exception() is also the transport-died hook (WebSocketResponse._cancel).
++    # _read_from_buffer() only raises once the buffer is empty, so complete
++    # frames the parser stopped short of must still be delivered first, exactly
++    # as they were before the parser learned to stall.
++    loop = asyncio.get_running_loop()
++    out = WebSocketDataQueue(protocol, DEFAULT_CHUNK_SIZE, loop=loop)
++    parser = WebSocketReader(out, 1024 * 1024, compress=False)
++
++    sent = 8000
++    parser.feed_data(build_frame(b"", WSMsgType.TEXT, use_mask=True) * sent)
++    stalled = len(out._buffer)
++    assert stalled < sent
++
++    out.set_exception(ConnectionResetError())
++
++    for _ in range(sent):
++        await asyncio.wait_for(out.read(), 5)
++    with pytest.raises(ConnectionResetError):
++        await out.read()
++
++
++async def test_parse_error_abandons_the_stash(protocol: BaseProtocol) -> None:
++    # A parse error poisons the reader, so re-driving it from a drain is a
++    # no-op and the error surfaces once the buffer is empty.
++    loop = asyncio.get_running_loop()
++    out = WebSocketDataQueue(protocol, 2**16, loop=loop)
++    parser = WebSocketReader(out, 1024 * 1024, compress=True)
++
++    payload = b"\0" * (512 * 1024)
++    # The reserved opcode sits behind the stash, so it is only reached on a
++    # drain-driven resume.
++    parser.feed_data(
++        _compressed_burst(payload, 3) + build_frame(b"", 0x3, use_mask=True)
++    )
++    stalled = out._stalled_reader
++    assert stalled is not None and stalled() is parser
++
++    for _ in range(3):
++        await asyncio.wait_for(out.read(), 5)
++    with pytest.raises(WebSocketError):
++        await asyncio.wait_for(out.read(), 5)
++
++
++async def test_queue_does_not_keep_stalled_reader_alive(
++    protocol: BaseProtocol,
++) -> None:
++    # The one case feed_eof() cannot clean up: the connection dies while
++    # parsing is stalled, then the application drops the response without
++    # draining. The queue's link back must be weak or reader <-> queue
++    # survives as a cycle that only the collector can reclaim.
++    loop = asyncio.get_running_loop()
++    out = WebSocketDataQueue(protocol, 2**16, loop=loop)
++    parser = WebSocketReader(out, 1024 * 1024, compress=True)
++
++    parser.feed_data(_compressed_burst(b"\0" * (512 * 1024), 4))
++    parser.feed_eof()
++    # `parser` deliberately never appears in an assert: pytest's assertion
++    # rewriting keeps temporaries for the failure message, and a lingering
++    # reference to it would mask the very thing under test.
++    stalled = out._stalled_reader
++    assert stalled is not None
++
++    ref = weakref.ref(parser)
++    del parser, stalled
++    # `out` deliberately stays alive across the collection: a strong link back
++    # would keep the reader reachable from a live root, so this proves the link
++    # is weak rather than merely testing reclamation timing. Collect instead of
++    # disabling the gc -- PyPy has no refcounting to reclaim eagerly, and can
++    # need more than one pass to clear the weakref.
++    for _ in range(3):
++        gc.collect()
++
++    assert ref() is None, "queue kept the stalled reader alive"
++
++
++def _queue_with_collected_reader(
++    protocol: BaseProtocol, loop: asyncio.AbstractEventLoop, *, eof: bool
++) -> WebSocketDataQueue:
++    """A queue whose reader stalled on a burst and was then collected."""
++    out = WebSocketDataQueue(protocol, 2**16, loop=loop)
++    parser = WebSocketReader(out, 1024 * 1024, compress=True)
++    parser.feed_data(_compressed_burst(b"\0" * (512 * 1024), 4))
++    if eof:
++        parser.feed_eof()
++    del parser
++    for _ in range(3):
++        gc.collect()
++    return out
++
++
++async def test_collected_stalled_reader_surfaces_contract_error(
++    protocol: BaseProtocol, caplog: pytest.LogCaptureFixture
++) -> None:
++    # Every strong reference to the reader was dropped while it was stalled,
++    # so the stash is gone. Whatever was already queued is still delivered,
++    # then the contract violation surfaces instead of a silent short stream.
++    # It is also logged, for callers that stop reading before the exception.
++    loop = asyncio.get_running_loop()
++    out = _queue_with_collected_reader(protocol, loop, eof=True)
++
++    for _ in range(len(out._buffer)):
++        await asyncio.wait_for(out.read(), 5)
++    assert "must hold a strong reference" in caplog.text
++    with pytest.raises(RuntimeError, match="must hold a strong reference"):
++        await out.read()
++
++
++async def test_collected_stalled_reader_preserves_existing_exception(
++    protocol: BaseProtocol,
++) -> None:
++    # set_exception() is also the transport-died hook; losing the reader on
++    # top of that must not replace the real cause with the contract error.
++    loop = asyncio.get_running_loop()
++    out = _queue_with_collected_reader(protocol, loop, eof=False)
++    out.set_exception(ConnectionResetError())
++
++    for _ in range(len(out._buffer)):
++        await asyncio.wait_for(out.read(), 5)
++    with pytest.raises(ConnectionResetError):
++        await out.read()
++
++
++async def test_burst_under_high_water_is_parsed_in_one_read(
++    protocol: BaseProtocol,
++) -> None:
++    # Ordinary pipelined traffic that fits under the mark must not be stalled
++    # or split across reads by the backpressure check.
++    loop = asyncio.get_running_loop()
++    out = WebSocketDataQueue(protocol, 2**16, loop=loop)
++    parser = WebSocketReader(out, 1024 * 1024, compress=False)
++
++    parser.feed_data(build_frame(b"hello", WSMsgType.TEXT, use_mask=True) * 50)
++
++    assert len(out._buffer) == 50
++    assert protocol._reading_paused is False
meta-python/recipes-devtools/python/python3-aiohttp_3.13.5.bb +1 -0
index 91d11cf124..473ab87614 100644
@@ -40,6 +40,7 @@ SRC_URI += " \
     file://CVE-2026-128127.patch \
     file://CVE-2026-128128.patch \
     file://CVE-2026-128129.patch \
+    file://CVE-2026-128132.patch \
 "
 
 CVE_PRODUCT = "aiohttp:aiohttp"
Signature · 1 line
2.35.6
#10 lore raw

PATCH 10/10 python3-aiohttp: mark CVE-2026-128130 patched

In reply to Ashishkumar Parmar X (asparmar - E INFOCHIPS PRIVATE LIMITED at Cisco)

From: Ashishkumar Parmar <[email protected]>

The existing CVE-2026-54273_p2.patch backports aiohttp commit 47babd8c23ca79e2bae6cc8dcb5752b61e369fc7. The upstream advisory also identifies that commit as the fix for CVE-2026-128130. Its CVE: field names only CVE-2026-54273, so cve-check does not credit the second CVE.

Add CVE-2026-128130 to the existing field. The source fix is already present; this commit changes only patch metadata.

Reference: https://github.com/aio-libs/aiohttp/security/advisories/GHSA-28qf-cpwq-vmc2

---
 .../python/python3-aiohttp/CVE-2026-54273_p2.patch              | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-54273_p2.patch +1 -1
index c6a318798d..2267f0a44e 100644
@@ -9,7 +9,7 @@ Subject: [PATCH] [PR #13356/72eaa429 backport][3.14] Stop handing back
 
 ---------
 
-CVE: CVE-2026-54273
+CVE: CVE-2026-54273 CVE-2026-128130
 Upstream-Status: Backport [https://github.com/aio-libs/aiohttp/commit/47babd8c23ca79e2bae6cc8dcb5752b61e369fc7]
 
 Backport Changes:
Signature · 1 line
2.35.6