Skip to contentSkip to conversation

python3-aiohttp: backport fixes for ten CVEs

PATCH New Darsh Kelaiya -X (dkelaiya - E INFOCHIPS PRIVATE LIMITED at Cisco) 1 participant 10 messages Nov 25

lore
Share & tools
lore
#0 lore raw

cover python3-aiohttp: backport fixes for ten CVEs

From: Darsh Kelaiya <[email protected]>

Backport fixes for ten CVEs to aiohttp 3.9.5 on Scarthgap. The series covers HTTP parsing, cookie handling, multipart resource limits, and the initial request-header timeout.

Patch 8 carries CVE-2026-69243_p1.patch and CVE-2026-69243_p2.patch, followed by CVE-2026-69243_CVE-2026-128129.patch. The shared patch backports upstream commit 3d850ee9 to limit buffering while an upgrade is pending and records both CVEs for cve-check.

All 44 recipe patches applied without fuzz or rejects. The C parser built against native Python 3.12 and 69 focused tests passed. Loopback tests cover idle and partial-header expiry, plus upgrade requests with nonempty bodies and trailing HTTP bytes. Both parsers handle Content-Length and chunked framing with combined and split writes. The C parser rejects malformed status-line input and includes the rejected line in its diagnostic.

Darsh Kelaiya (9):
python3-aiohttp: fix CVE-2026-111750
python3-aiohttp: fix CVE-2026-111749
python3-aiohttp: fix CVE-2026-111748
python3-aiohttp: fix CVE-2026-111066
python3-aiohttp: fix CVE-2026-111065
python3-aiohttp: fix CVE-2026-111064
python3-aiohttp: fix CVE-2026-111063
python3-aiohttp: fix CVE-2026-69243 and CVE-2026-128129
python3-aiohttp: fix CVE-2026-69244

 .../python3-aiohttp/CVE-2026-111063_p1.patch  | 122 ++++
 .../python3-aiohttp/CVE-2026-111063_p2.patch  | 257 +++++++
 .../python3-aiohttp/CVE-2026-111064.patch     | 398 +++++++++++
 .../python3-aiohttp/CVE-2026-111065.patch     | 171 +++++
 .../python3-aiohttp/CVE-2026-111066_p1.patch  | 397 +++++++++++
 .../python3-aiohttp/CVE-2026-111066_p2.patch  |  59 ++
 .../python3-aiohttp/CVE-2026-111748_p1.patch  | 410 +++++++++++
 .../python3-aiohttp/CVE-2026-111748_p2.patch  | 259 +++++++
 .../python3-aiohttp/CVE-2026-111749.patch     | 197 +++++
 .../python3-aiohttp/CVE-2026-111750.patch     |  84 +++
 .../CVE-2026-69243_CVE-2026-128129.patch      | 673 ++++++++++++++++++
 .../python3-aiohttp/CVE-2026-69243_p1.patch   | 300 ++++++++
 .../python3-aiohttp/CVE-2026-69243_p2.patch   |  93 +++
 .../python3-aiohttp/CVE-2026-69244.patch      | 248 +++++++
 .../python/python3-aiohttp_3.9.5.bb           |  14 +
 15 files changed, 3682 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111063_p1.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111063_p2.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111064.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111065.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111066_p1.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111066_p2.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111748_p1.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111748_p2.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111749.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111750.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-69243_CVE-2026-128129.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-69243_p1.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-69243_p2.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-69244.patch
Signature · 1 line
2.35.6
#1 lore raw

PATCH 1/9 python3-aiohttp: fix CVE-2026-111750

From: Darsh Kelaiya <[email protected]>

Backport the upstream HEAD request parsing fix [1] to aiohttp 3.9.5, as identified by [2]. Only responses to HEAD may skip their body; incoming HEAD requests must consume the declared request body.

Retain the upstream regression that embeds a request in a HEAD body and verifies that the following request remains correctly framed. The pure-Python parser remains available with extensions installed.

[1] https://github.com/aio-libs/aiohttp/commit/9b27347e61454d9f8ca2055f4c67a37dee336e83
[2] https://github.com/aio-libs/aiohttp/security/advisories/GHSA-pqxq-w44r-73xw

---
 .../python3-aiohttp/CVE-2026-111750.patch     | 84 +++++++++++++++++++
 .../python/python3-aiohttp_3.9.5.bb           |  1 +
 2 files changed, 85 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111750.patch
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111750.patch new file +84 -0
new file mode 100644
index 0000000000..860b7aec03
@@ -0,0 +1,84 @@
+From 9b27347e61454d9f8ca2055f4c67a37dee336e83 Mon Sep 17 00:00:00 2001
+From: Sam Bull <[email protected]>
+Date: Wed, 9 Sep 2026 01:25:13 +0100
+Subject: [PATCH] Fix head request parsing (#13671) (#13673)
+
+CVE: CVE-2026-111750
+Upstream-Status: Backport [https://github.com/aio-libs/aiohttp/commit/9b27347e61454d9f8ca2055f4c67a37dee336e83]
+
+Backport Changes:
+- Use the existing empty-body helper functions instead of the newer
+  EMPTY_BODY_* constants, and adapt the explanatory comment.
+
+(cherry picked from commit 5789546e37fe35af27d0a2f840870b22bc15bfc4)
+Signed-off-by: Darsh Kelaiya <[email protected]>
+---
+ CHANGES/13671.bugfix.rst  |  1 +
+ aiohttp/http_parser.py    |  6 +++++-
+ tests/test_http_parser.py | 27 ++++++++++++++++++++++++++-
+ 3 files changed, 32 insertions(+), 2 deletions(-)
+ create mode 100644 CHANGES/13671.bugfix.rst
+
+diff --git a/CHANGES/13671.bugfix.rst b/CHANGES/13671.bugfix.rst
+new file mode 100644
+index 0000000..e6fbc70
+--- /dev/null
++++ b/CHANGES/13671.bugfix.rst
+@@ -0,0 +1 @@
++Fixed pure-Python request parser not reading a body in a ``HEAD`` request -- by :user:`Dreamsorcerer`.
+diff --git a/aiohttp/http_parser.py b/aiohttp/http_parser.py
+index 37a0dff..58f0a50 100644
+--- a/aiohttp/http_parser.py
++++ b/aiohttp/http_parser.py
+@@ -420,8 +420,12 @@ class HttpParser(abc.ABC, Generic[_MsgT]):
+ 
+                         assert self.protocol is not None
+                         # calculate payload
++                        # https://www.rfc-editor.org/info/rfc9112/#name-message-body-length
++                        # https://www.rfc-editor.org/info/rfc9110/#section-9.3.1-6
++                        # Empty-body methods should only apply to responses.
++                        # self.method is None on request parser.
+                         empty_body = status_code_must_be_empty_body(code) or bool(
+-                            method and method_must_be_empty_body(method)
++                            self.method and method_must_be_empty_body(self.method)
+                         )
+                         if not empty_body and (
+                             ((length is not None and length > 0) or msg.chunked)
+diff --git a/tests/test_http_parser.py b/tests/test_http_parser.py
+index b29518a..d08698a 100644
+--- a/tests/test_http_parser.py
++++ b/tests/test_http_parser.py
+@@ -1537,7 +1537,32 @@ def test_http_request_chunked_payload_and_next_message(parser) -> None:
+     assert not payload2.is_eof()
+ 
+ 
+-def test_http_request_chunked_payload_chunks(parser) -> None:
++def test_http_request_parser_head_with_content_length_payload(
++    parser: HttpRequestParser,
++) -> None:
++    smuggled = b"GET /smuggled HTTP/1.1\r\nHost: a\r\n\r\n"
++    text = (
++        b"HEAD /test HTTP/1.1\r\nHost: a\r\nContent-Length: %d\r\n\r\n" % len(smuggled)
++        + smuggled
++        + b"POST /next HTTP/1.1\r\nHost: a\r\nContent-Length: 0\r\n\r\n"
++    )
++    messages, upgraded, tail = parser.feed_data(text)
++
++    assert len(messages) == 2
++    msg, payload = messages[0]
++    assert msg.method == "HEAD"
++    assert b"".join(payload._buffer) == smuggled
++    assert payload.is_eof()
++
++    msg2, payload2 = messages[1]
++    assert msg2.method == "POST"
++    assert msg2.path == "/next"
++    assert payload2.is_eof()
++    assert not upgraded
++    assert not tail
++
++
++def test_http_request_chunked_payload_chunks(parser: HttpRequestParser) -> None:
+     text = b"GET /test HTTP/1.1\r\n" b"transfer-encoding: chunked\r\n\r\n"
+     msg, payload = parser.feed_data(text)[0][0]
+ 
meta-python/recipes-devtools/python/python3-aiohttp_3.9.5.bb +1 -0
index 893d5124f7..3c9a82b012 100644
@@ -36,6 +36,7 @@ SRC_URI += "file://CVE-2024-52304.patch \
            file://CVE-2026-54279.patch \
            file://CVE-2026-54273_p1.patch \
            file://CVE-2026-54273_p2.patch \
+           file://CVE-2026-111750.patch \
            "
 
 CVE_STATUS[CVE-2026-34515] = "not-applicable-platform: Vulnerability only affects applications running on Windows"
Signature · 1 line
2.35.6
#2 lore raw

PATCH 2/9 python3-aiohttp: fix CVE-2026-111749

In reply to Darsh Kelaiya -X (dkelaiya - E INFOCHIPS PRIVATE LIMITED at Cisco)

From: Darsh Kelaiya <[email protected]>

Backport the upstream host-only cookie state fix [1] to aiohttp 3.9.5, as identified by [2]. Track host-only state by domain, path and name so expiring another cookie cannot widen its domain scope.

Preserve this identity during filtering, replacement and JSON persistence. Adapt regression assertions to the existing private state because 3.9.5 lacks the newer public inspection property.

[1] https://github.com/aio-libs/aiohttp/commit/6a07c171ef9f3be583e2907dcd1931372efca8d6
[2] https://github.com/aio-libs/aiohttp/security/advisories/GHSA-gx76-c99x-2c96

---
 .../python3-aiohttp/CVE-2026-111749.patch     | 197 ++++++++++++++++++
 .../python/python3-aiohttp_3.9.5.bb           |   1 +
 2 files changed, 198 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111749.patch
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111749.patch new file +197 -0
new file mode 100644
index 0000000000..2a67cf3542
@@ -0,0 +1,197 @@
+From 6a07c171ef9f3be583e2907dcd1931372efca8d6 Mon Sep 17 00:00:00 2001
+From: Sam Bull <[email protected]>
+Date: Wed, 9 Sep 2026 02:21:06 +0100
+Subject: [PATCH] Fix host-only state on cookie expiration (#13674) (#13676)
+
+CVE: CVE-2026-111749
+Upstream-Status: Backport [https://github.com/aio-libs/aiohttp/commit/6a07c171ef9f3be583e2907dcd1931372efca8d6]
+
+Backport Changes:
+- Apply marker deletion in clear() because 3.9.5 predates the
+  _delete_cookies() helper, and preserve its untrimmed path keys.
+  Root cookie markers therefore use "/" instead of an empty path.
+- Use 3.9.5 Set/Tuple annotations and update_cookies(SimpleCookie)
+  calls; adapt regressions to private _host_only_cookies assertions.
+- Omit public host_only_cookies annotations and documentation in
+  CookieJar, DummyCookieJar and AbstractCookieJar, and the associated
+  test-jar/property changes; those interfaces are absent in 3.9.5.
+
+(cherry picked from commit 9332972cfcb0f5a2b6677e7307819ab8f13b5d09)
+Signed-off-by: Darsh Kelaiya <[email protected]>
+---
+ CHANGES/13674.bugfix.rst |  1 +
+ aiohttp/cookiejar.py     | 25 +++++++++-------
+ tests/test_cookiejar.py  | 62 +++++++++++++++++++++++++++++++++++++++-
+ 3 files changed, 76 insertions(+), 12 deletions(-)
+ create mode 100644 CHANGES/13674.bugfix.rst
+
+diff --git a/CHANGES/13674.bugfix.rst b/CHANGES/13674.bugfix.rst
+new file mode 100644
+index 0000000..5152bce
+--- /dev/null
++++ b/CHANGES/13674.bugfix.rst
+@@ -0,0 +1 @@
++Fixed host-only cookie state being lost on expiration -- by :user:`Dreamsorcerer`.
+diff --git a/aiohttp/cookiejar.py b/aiohttp/cookiejar.py
+index 4f694b6..0800a53 100644
+--- a/aiohttp/cookiejar.py
++++ b/aiohttp/cookiejar.py
+@@ -124,7 +124,8 @@ class CookieJar(AbstractCookieJar):
+         self._cookies: DefaultDict[Tuple[str, str], SimpleCookie] = defaultdict(
+             SimpleCookie
+         )
+-        self._host_only_cookies: Set[Tuple[str, str]] = set()
++        # Cookie identity is (domain, path, name).
++        self._host_only_cookies: Set[Tuple[str, str, str]] = set()
+         self._unsafe = unsafe
+         self._quote_cookie = quote_cookie
+         if treat_as_secure_origin is None:
+@@ -167,7 +168,7 @@ class CookieJar(AbstractCookieJar):
+                     if attr_val:
+                         morsel_data[attr] = attr_val
+                 # Persist or it reloads as a domain cookie and leaks to subdomains.
+-                if (domain, name) in self._host_only_cookies:
++                if (domain, path, name) in self._host_only_cookies:
+                     morsel_data["host_only"] = True
+                 if (exp := self._expirations.get((domain, path, name))) is not None:
+                     morsel_data["expires_timestamp"] = exp
+@@ -256,7 +257,7 @@ class CookieJar(AbstractCookieJar):
+                     to_del.append(key)
+ 
+         for domain, path, name in to_del:
+-            self._host_only_cookies.discard((domain, name))
++            self._host_only_cookies.discard((domain, path, name))
+             key = (domain, path, name)
+             if key in self._expirations:
+                 del self._expirations[(domain, path, name)]
+@@ -310,18 +311,12 @@ class CookieJar(AbstractCookieJar):
+                 domain = ""
+                 del cookie["domain"]
+ 
+-            if not domain and hostname is not None:
+-                # Set the cookie's domain to the response hostname
+-                # and set its host-only-flag
+-                self._host_only_cookies.add((hostname, name))
+-                domain = cookie["domain"] = hostname
+-
+             if domain.startswith("."):
+                 # Remove leading dot
+                 domain = domain[1:]
+                 cookie["domain"] = domain
+ 
+-            if hostname and not self._is_domain_match(domain, hostname):
++            if domain and hostname and not self._is_domain_match(domain, hostname):
+                 # Setting cookies for different domains is not allowed
+                 continue
+ 
+@@ -336,6 +331,14 @@ class CookieJar(AbstractCookieJar):
+                     path = "/" + path[1 : path.rfind("/")]
+                 cookie["path"] = path
+ 
++            if not domain and hostname is not None:
++                self._host_only_cookies.add((hostname, path, name))
++                domain = cookie["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))
++
+             max_age = cookie["max-age"]
+             if max_age:
+                 try:
+@@ -393,7 +396,7 @@ class CookieJar(AbstractCookieJar):
+             if not self._unsafe and is_ip_address(hostname):
+                 continue
+ 
+-            if (domain, name) in self._host_only_cookies:
++            if (domain, cookie["path"], name) in self._host_only_cookies:
+                 if domain != hostname:
+                     continue
+             elif not self._is_domain_match(domain, hostname):
+diff --git a/tests/test_cookiejar.py b/tests/test_cookiejar.py
+index df59759..3e344c2 100644
+--- a/tests/test_cookiejar.py
++++ b/tests/test_cookiejar.py
+@@ -868,6 +868,44 @@ async def test_treat_as_secure_origin() -> None:
+     assert len(filtered_cookies) == 1
+ 
+ 
++async def test_host_only_marker_survives_same_name_expiry_on_other_path() -> None:
++    """Expiring a same-name cookie on another path must not clear host-only state."""
++    jar = CookieJar()
++    origin = URL("http://auth.example.com/")
++    subdomain = URL("http://evil.auth.example.com/")
++
++    jar.update_cookies(SimpleCookie("sid=secret; Path=/"), origin)
++    assert "sid" not in jar.filter_cookies(subdomain)
++
++    # Attacker-controlled descendant expires a same-name cookie on its own path.
++    jar.update_cookies(
++        SimpleCookie("sid=gone; Domain=auth.example.com; Path=/attacker; Max-Age=0"),
++        subdomain,
++    )
++
++    assert ("auth.example.com", "/", "sid") in jar._host_only_cookies
++    assert "sid" not in jar.filter_cookies(subdomain)
++    assert jar.filter_cookies(origin)["sid"].value == "secret"
++
++
++async def test_explicit_domain_replacement_clears_host_only_marker() -> None:
++    """A replacing cookie with an explicit Domain is a domain cookie."""
++    jar = CookieJar()
++    origin = URL("http://example.com/")
++    subdomain = URL("http://sub.example.com/")
++
++    jar.update_cookies(SimpleCookie("sid=hostonly; Path=/"), origin)
++    assert ("example.com", "/", "sid") in jar._host_only_cookies
++    assert "sid" not in jar.filter_cookies(subdomain)
++
++    jar.update_cookies(
++        SimpleCookie("sid=domainwide; Domain=example.com; Path=/"), origin
++    )
++
++    assert jar._host_only_cookies == set()
++    assert jar.filter_cookies(subdomain)["sid"].value == "domainwide"
++
++
+ # === Security tests for restricted unpickler and JSON save/load ===
+ 
+ 
+@@ -994,7 +1032,7 @@ async def test_save_load_json_preserves_host_only_scope(tmp_path: Path) -> None:
+     jar_load = CookieJar()
+     jar_load.load(file_path=file_path)
+ 
+-    assert jar_load._host_only_cookies == {("auth.example.com", "sid")}
++    assert jar_load._host_only_cookies == {("auth.example.com", "/", "sid")}
+     assert "sid" not in jar_load.filter_cookies(subdomain)
+     assert "sid" in jar_load.filter_cookies(issuer)
+ 
+@@ -1020,6 +1058,28 @@ async def test_save_load_json_domain_cookie_still_matches_subdomain(
+     assert "sid" in jar_load.filter_cookies(subdomain)
+ 
+ 
++async def test_save_load_json_host_only_per_path(tmp_path: Path) -> None:
++    """Verify save/load keeps host-only state per (domain, path, name)."""
++    file_path = tmp_path / "per_path.json"
++    origin = URL("https://example.com/")
++    subdomain = URL("https://sub.example.com/")
++
++    jar_save = CookieJar()
++    jar_save.update_cookies(SimpleCookie("sid=hostonly; Path=/"), origin)
++    jar_save.update_cookies(
++        SimpleCookie("sid=domainwide; Domain=example.com; Path=/api"), origin
++    )
++    jar_save.save(file_path=file_path)
++
++    jar_load = CookieJar()
++    jar_load.load(file_path=file_path)
++
++    assert jar_load._host_only_cookies == {("example.com", "/", "sid")}
++    assert "sid" not in jar_load.filter_cookies(subdomain)
++    filtered = jar_load.filter_cookies(URL("https://sub.example.com/api/x"))
++    assert filtered["sid"].value == "domainwide"
++
++
+ async def test_save_load_json_preserves_max_age_deadline(tmp_path: Path) -> None:
+     """Verify save/load restores the absolute deadline without resetting it."""
+     file_path = tmp_path / "max_age.json"
meta-python/recipes-devtools/python/python3-aiohttp_3.9.5.bb +1 -0
index 3c9a82b012..90475a5aff 100644
@@ -37,6 +37,7 @@ SRC_URI += "file://CVE-2024-52304.patch \
            file://CVE-2026-54273_p1.patch \
            file://CVE-2026-54273_p2.patch \
            file://CVE-2026-111750.patch \
+           file://CVE-2026-111749.patch \
            "
 
 CVE_STATUS[CVE-2026-34515] = "not-applicable-platform: Vulnerability only affects applications running on Windows"
Signature · 1 line
2.35.6
#3 lore raw

PATCH 3/9 python3-aiohttp: fix CVE-2026-111748

In reply to Darsh Kelaiya -X (dkelaiya - E INFOCHIPS PRIVATE LIMITED at Cisco)

From: Darsh Kelaiya <[email protected]>

Backport the protocol-scheme fix [1] to aiohttp 3.9.5, as identified by [3]. Derive Request.scheme from the transport rather than the untrusted scheme in an absolute-form request target.

Include the authority-validation correction [2] to reject malformed targets before URL parsing, independently of yarl normalization. Retain the upstream parser and request regressions. Use cached transport details and explicitly evaluate URL.port before reading raw_host because yarl 1.9.4 defers encoded-URL port validation. The recipe regenerates the C parser from the patched Cython source.

[1] https://github.com/aio-libs/aiohttp/commit/6d4e7b01f9b951aa084a75d7356e907d4ee80411
[2] https://github.com/aio-libs/aiohttp/commit/186065caf37d5999e91fd3d4ddfd03b43eb08801
[3] https://github.com/aio-libs/aiohttp/security/advisories/GHSA-f9xw-jh8m-3mwq

---
 .../python3-aiohttp/CVE-2026-111748_p1.patch  | 410 ++++++++++++++++++
 .../python3-aiohttp/CVE-2026-111748_p2.patch  | 259 +++++++++++
 .../python/python3-aiohttp_3.9.5.bb           |   2 +
 3 files changed, 671 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111748_p1.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111748_p2.patch
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111748_p1.patch new file +410 -0
new file mode 100644
index 0000000000..9f1ec42706
@@ -0,0 +1,410 @@
+From 6d4e7b01f9b951aa084a75d7356e907d4ee80411 Mon Sep 17 00:00:00 2001
+From: Sam Bull <[email protected]>
+Date: Sun, 27 Sep 2026 18:11:00 +0100
+Subject: [PATCH] Use protocol scheme for absolute-form requests (#13821)
+ (#13827) (#13828)
+
+CVE: CVE-2026-111748
+Upstream-Status: Backport [https://github.com/aio-libs/aiohttp/commit/6d4e7b01f9b951aa084a75d7356e907d4ee80411]
+
+Backport Changes:
+- Omit the enum hunk because HTTP_OPTIONS is already declared.
+- Cache transport details before URL normalization because
+  RequestHandler has no ssl_context attribute in aiohttp 3.9.5.
+- Apply explicit clone(scheme=...) and clone(host=...) overrides to
+  the cached absolute URL so Request.url stays consistent. Keep
+  authority-form URLs scheme-less unless clone supplies a scheme.
+- Evaluate URL.port before accepting raw_host in both parsers:
+  yarl 1.9.4 defers port validation for encoded URLs.
+- Adapt the constructor mock to transport.get_extra_info() and add
+  the upstream absolute-URL clone tests missing from aiohttp 3.9.5.
+- Keep 3.9.5's existing websocket-key test annotation; the omitted
+  typing-only update does not change its regression assertions.
+
+(cherry picked from commit a921cfd0fec28d5a9e5bf8d6f4372b8fa63c49df)
+(cherry picked from commit 93d91e37e7c6035d09e89646b3de737735ed91b5)
+Signed-off-by: Darsh Kelaiya <[email protected]>
+---
+ CHANGES/13821.bugfix.rst     |  1 +
+ aiohttp/_http_parser.pyx     | 31 ++++++++++++++++---
+ aiohttp/http_parser.py       | 28 ++++++++++++++---
+ aiohttp/web_request.py       | 20 ++++++++----
+ tests/test_http_parser.py    | 59 ++++++++++++++++++++++++++++++++++++
+ tests/test_web_functional.py | 46 ++++++++++++++++++++++++++--
+ tests/test_web_request.py    | 52 ++++++++++++++++++++++++++-----
+ 7 files changed, 214 insertions(+), 23 deletions(-)
+ create mode 100644 CHANGES/13821.bugfix.rst
+
+diff --git a/CHANGES/13821.bugfix.rst b/CHANGES/13821.bugfix.rst
+new file mode 100644
+index 00000000..f35418d2
+--- /dev/null
++++ b/CHANGES/13821.bugfix.rst
+@@ -0,0 +1 @@
++Fixed the web server trusting the scheme of an absolute-form request-target -- by :user:`Dreamsorcerer`.
+diff --git a/aiohttp/_http_parser.pyx b/aiohttp/_http_parser.pyx
+index 4eb57893..7d97bfe8 100644
+--- a/aiohttp/_http_parser.pyx
++++ b/aiohttp/_http_parser.pyx
+@@ -668,12 +668,21 @@ cdef class HttpRequestParser(HttpParser):
+             return
+         self._path = self._buf.decode('utf-8', 'surrogateescape')
+         try:
+-            idx3 = len(self._path)
+             if self._cparser.method == cparser.HTTP_CONNECT:
+                 # authority-form,
+                 # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.3
+-                self._url = URL.build(authority=self._path, encoded=True)
+-            elif idx3 > 1 and self._path[0] == '/':
++                try:
++                    self._url = URL.build(authority=self._path, encoded=True)
++                    _ = self._url.port
++                    host = self._url.raw_host
++                except ValueError:
++                    host = None
++                if host is None:
++                    raise InvalidURLError(
++                        self._path.encode(errors="surrogateescape")
++                        .decode("latin1")
++                    )
++            elif self._path[0] == '/':
+                 # origin-form,
+                 # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.1
+                 idx1 = self._path.find("?")
+@@ -704,10 +713,24 @@ cdef class HttpRequestParser(HttpParser):
+                     fragment=fragment,
+                     encoded=True,
+                 )
++            elif self._path == '*' and self._cparser.method == cparser.HTTP_OPTIONS:
++                # asterisk-form,
++                self._url = URL(self._path, encoded=True)
+             else:
+                 # absolute-form for proxy maybe,
+                 # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.2
+-                self._url = URL(self._path, encoded=True)
++                try:
++                    self._url = URL(self._path, encoded=True)
++                    _ = self._url.port
++                    host = self._url.raw_host
++                except ValueError:
++                    host = None
++                # https://www.rfc-editor.org/rfc/rfc9110#section-4.2.1-4
++                if host is None:
++                    raise InvalidURLError(
++                        self._path.encode(errors="surrogateescape")
++                        .decode("latin1")
++                    )
+         finally:
+             PyByteArray_Resize(self._buf, 0)
+ 
+diff --git a/aiohttp/http_parser.py b/aiohttp/http_parser.py
+index 37a0dff4..789c2bdc 100644
+--- a/aiohttp/http_parser.py
++++ b/aiohttp/http_parser.py
+@@ -641,7 +641,19 @@ class HttpRequestParser(HttpParser[RawRequestMessage]):
+         if method == "CONNECT":
+             # authority-form,
+             # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.3
+-            url = URL.build(authority=path, encoded=True)
++            try:
++                url = URL.build(authority=path, encoded=True)
++                _ = url.port
++                host = url.raw_host
++            except ValueError:
++                # Duplicated so mypy understands that url must be defined below.
++                raise InvalidURLError(
++                    path.encode(errors="surrogateescape").decode("latin1")
++                )
++            if host is None:
++                raise InvalidURLError(
++                    path.encode(errors="surrogateescape").decode("latin1")
++                )
+         elif path.startswith("/"):
+             # origin-form,
+             # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.1
+@@ -664,9 +676,17 @@ class HttpRequestParser(HttpParser[RawRequestMessage]):
+         else:
+             # absolute-form for proxy maybe,
+             # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.2
+-            url = URL(path, encoded=True)
+-            if url.scheme == "":
+-                # not absolute-form
++            try:
++                url = URL(path, encoded=True)
++                _ = url.port
++                host = url.raw_host
++            except ValueError:
++                # Duplicated so mypy understands that url must be defined below.
++                raise InvalidURLError(
++                    path.encode(errors="surrogateescape").decode("latin1")
++                )
++            # https://www.rfc-editor.org/rfc/rfc9110#section-4.2.1-4
++            if host is None:
+                 raise InvalidURLError(
+                     path.encode(errors="surrogateescape").decode("latin1")
+                 )
+diff --git a/aiohttp/web_request.py b/aiohttp/web_request.py
+index f9de5957..06c0bffc 100644
+--- a/aiohttp/web_request.py
++++ b/aiohttp/web_request.py
+@@ -173,14 +173,27 @@ class BaseRequest(MutableMapping[str, Any], HeadersMixin):
+         self._method = message.method
+         self._version = message.version
+         self._cache: Dict[str, Any] = {}
++        transport = self._protocol.transport
++        assert transport is not None
++        self._transport_sslcontext = transport.get_extra_info("sslcontext")
++        self._transport_peername = transport.get_extra_info("peername")
+         url = message.url
+         if url.is_absolute():
++            if scheme is None and url.scheme:
++                # Absolute URL is peer-controlled, use the protocol.
++                scheme = "https" if self._transport_sslcontext else "http"
++            if scheme is not None:
++                # Authority-form (CONNECT) has no scheme: leave the target
++                # unchanged unless clone(scheme=...) overrides it.
++                url = url.with_scheme(scheme)
++                self._cache["scheme"] = scheme
++            if host is not None:
++                url = url.with_host(host)
+             # absolute URL is given,
+             # override auto-calculating url, host, and scheme
+             # all other properties should be good
+             self._cache["url"] = url
+             self._cache["host"] = url.host
+-            self._cache["scheme"] = url.scheme
+             self._rel_url = url.relative()
+         else:
+             self._rel_url = message.url
+@@ -192,11 +205,6 @@ class BaseRequest(MutableMapping[str, Any], HeadersMixin):
+         self._client_max_size = client_max_size
+         self._loop = loop
+ 
+-        transport = self._protocol.transport
+-        assert transport is not None
+-        self._transport_sslcontext = transport.get_extra_info("sslcontext")
+-        self._transport_peername = transport.get_extra_info("peername")
+-
+         if scheme is not None:
+             self._cache["scheme"] = scheme
+         if host is not None:
+diff --git a/tests/test_http_parser.py b/tests/test_http_parser.py
+index b29518ab..ebbb58d8 100644
+--- a/tests/test_http_parser.py
++++ b/tests/test_http_parser.py
+@@ -866,6 +866,65 @@ def test_url_absolute(parser: Any) -> None:
+     assert msg.url == URL("https://www.google.com/path/to.html")
+ 
+ 
++def test_url_authority_form_only_connect(parser: HttpRequestParser) -> None:
++    # https://www.rfc-editor.org/info/rfc9112/#section-3.2.3-1
++    with pytest.raises(http_exceptions.InvalidURLError):
++        parser.feed_data(b"GET www.google.com:443 HTTP/1.1\r\nHost: a\r\n\r\n")
++
++
[email protected](
++    "target",
++    (
++        b"https:///protected",
++        b"https:////protected",
++        b"https://:80/protected",
++        b"https://user@/protected",
++    ),
++    ids=("empty-host", "empty-host-extra-slash", "port-only", "userinfo-only"),
++)
++def test_url_absolute_form_empty_host_rejected(
++    parser: HttpRequestParser, target: bytes
++) -> None:
++    # https://www.rfc-editor.org/rfc/rfc9110#section-4.2.2-4
++    with pytest.raises(http_exceptions.InvalidURLError):
++        parser.feed_data(b"GET " + target + b" HTTP/1.1\r\nHost: a\r\n\r\n")
++
++
++def test_url_absolute_form_invalid_port_rejected(parser: HttpRequestParser) -> None:
++    # yarl raises ValueError for an out-of-range port; that must surface as
++    # a 400, not escape the parser as a bare ValueError.
++    with pytest.raises(http_exceptions.InvalidURLError):
++        parser.feed_data(b"GET http://example.com:65536/x HTTP/1.1\r\nHost: a\r\n\r\n")
++
++
++def test_url_connect_invalid_port_rejected(parser: HttpRequestParser) -> None:
++    with pytest.raises(http_exceptions.InvalidURLError):
++        parser.feed_data(b"CONNECT example.com:65536 HTTP/1.1\r\nHost: a\r\n\r\n")
++
++
++def test_url_connect_empty_host_rejected(parser: HttpRequestParser) -> None:
++    with pytest.raises(http_exceptions.InvalidURLError):
++        parser.feed_data(b"CONNECT :80 HTTP/1.1\r\nHost: a\r\n\r\n")
++
++
++def test_url_origin_form_bare_slash(parser: HttpRequestParser) -> None:
++    messages, upgrade, tail = parser.feed_data(b"GET / HTTP/1.1\r\nHost: a\r\n\r\n")
++    assert messages[0][0].url == URL("/")
++
++
++def test_url_asterisk_form_options(parser: HttpRequestParser) -> None:
++    # https://www.rfc-editor.org/rfc/rfc9112#section-3.2.4
++    messages, upgrade, tail = parser.feed_data(b"OPTIONS * HTTP/1.1\r\nHost: a\r\n\r\n")
++    assert messages[0][0].url == URL("*")
++
++
++def test_url_asterisk_form_only_options(parser: HttpRequestParser) -> None:
++    # asterisk-form is only valid for OPTIONS; for other methods "*" is
++    # neither origin-form nor a valid absolute-form target.
++    with pytest.raises(http_exceptions.InvalidURLError):
++        parser.feed_data(b"GET * HTTP/1.1\r\nHost: a\r\n\r\n")
++
++
+ def test_headers_old_websocket_key1(parser: Any) -> None:
+     text = b"GET /test HTTP/1.1\r\n" b"SEC-WEBSOCKET-KEY1: line\r\n\r\n"
+ 
+diff --git a/tests/test_web_functional.py b/tests/test_web_functional.py
+index a0e3a8ea..262257b8 100644
+--- a/tests/test_web_functional.py
++++ b/tests/test_web_functional.py
+@@ -1863,8 +1863,50 @@ async def test_unread_compressed_body_drain_is_bounded(
+     assert max(drain_reads) < decompressed_size
+ 
+ 
+-async def test_app_max_client_size(aiohttp_client) -> None:
+-    async def handler(request):
++async def test_absolute_form_target_does_not_spoof_scheme(
++    aiohttp_server: AiohttpServer,
++) -> None:
++    """A plaintext absolute-form target with https must not look secure."""
++
++    async def handler(request: web.Request) -> web.Response:
++        return web.json_response(
++            {
++                "scheme": request.scheme,
++                "secure": request.secure,
++                "url": str(request.url),
++                "host": request.host,
++            }
++        )
++
++    app = web.Application()
++    app.router.add_get("/probe", handler)
++    server = await aiohttp_server(app)
++
++    reader, writer = await asyncio.open_connection(server.host, server.port)
++    try:
++        writer.write(
++            b"GET https://trusted.example/probe HTTP/1.1\r\n"
++            b"Host: trusted.example\r\n"
++            b"Connection: close\r\n\r\n"
++        )
++        await writer.drain()
++        raw = await asyncio.wait_for(reader.read(), 5)
++    finally:
++        writer.close()
++        with suppress(ConnectionResetError, BrokenPipeError):
++            await writer.wait_closed()
++
++    assert raw.startswith(b"HTTP/1.1 200 ")
++    assert json.loads(raw.split(b"\r\n\r\n", 1)[1]) == {
++        "scheme": "http",
++        "secure": False,
++        "url": "http://trusted.example/probe",
++        "host": "trusted.example",
++    }
++
++
++async def test_app_max_client_size(aiohttp_client: AiohttpClient) -> None:
++    async def handler(request: web.Request) -> NoReturn:
+         await request.post()
+         return web.Response(body=b"ok")
+ 
+diff --git a/tests/test_web_request.py b/tests/test_web_request.py
+index c1d61f89..79ddcdeb 100644
+--- a/tests/test_web_request.py
++++ b/tests/test_web_request.py
+@@ -9,13 +9,15 @@ import pytest
+ from multidict import CIMultiDict, CIMultiDictProxy, MultiDict
+ from yarl import URL
+ 
+-from aiohttp import HttpVersion
++from aiohttp import HttpVersion, web
++from aiohttp.abc import AbstractStreamWriter
+ from aiohttp.base_protocol import BaseProtocol
+ from aiohttp.http_exceptions import BadHttpMessage, LineTooLong
+ from aiohttp.http_parser import RawRequestMessage
+ from aiohttp.streams import StreamReader
+ from aiohttp.test_utils import make_mocked_request
+-from aiohttp.web import BaseRequest, HTTPRequestEntityTooLarge
++from aiohttp.web import HTTPRequestEntityTooLarge
++from aiohttp.web_protocol import RequestHandler
+ from aiohttp.web_request import ETag
+ 
+ 
+@@ -24,6 +26,19 @@ def protocol():
+     return mock.Mock(_reading_paused=False)
+ 
+ 
++def make_base_request(
++    message: RawRequestMessage, protocol: RequestHandler
++) -> web.BaseRequest:
++    return web.BaseRequest(
++        message,
++        mock.create_autospec(StreamReader, spec_set=True, instance=True),
++        protocol,
++        mock.create_autospec(AbstractStreamWriter, spec_set=True, instance=True),
++        mock.create_autospec(asyncio.Task, spec_set=True, instance=True),
++        mock.create_autospec(asyncio.AbstractEventLoop, spec_set=True, instance=True),
++    )
++
++
+ def test_base_ctor() -> None:
+     message = RawRequestMessage(
+         "GET",
+@@ -38,9 +53,10 @@ def test_base_ctor() -> None:
+         URL("/path/to?a=1&b=2"),
+     )
+ 
+-    req = BaseRequest(
+-        message, mock.Mock(), mock.Mock(), mock.Mock(), mock.Mock(), mock.Mock()
+-    )
++    protocol = mock.create_autospec(RequestHandler, spec_set=True, instance=True)
++    protocol.transport = mock.Mock()
++    protocol.transport.get_extra_info.return_value = None
++    req = make_base_request(message, protocol)
+ 
+     assert "GET" == req.method
+     assert HttpVersion(1, 1) == req.version
+@@ -165,12 +181,34 @@ def test_non_ascii_raw_path() -> None:
+ 
+ def test_absolute_url() -> None:
+     req = make_mocked_request("GET", "https://example.com/path/to?a=1")
+-    assert req.url == URL("https://example.com/path/to?a=1")
+-    assert req.scheme == "https"
++    assert req.url == URL("http://example.com/path/to?a=1")
++    # The scheme of an absolute-form target is peer-controlled and must not
++    # override the transport-derived scheme.
++    assert req.scheme == "http"
++    assert not req.secure
+     assert req.host == "example.com"
+     assert req.rel_url == URL.build(path="/path/to", query={"a": "1"})
+ 
+ 
++def test_clone_absolute_scheme() -> None:
++    req = make_mocked_request("GET", "https://example.com/path/to?a=1")
++    assert req.scheme == "http"
++    req2 = req.clone(scheme="https")
++    assert req2.scheme == "https"
++    assert req2.url.scheme == "https"
++    req3 = req2.clone(scheme="http")
++    assert req3.scheme == "http"
++    assert req3.url.scheme == "http"
++
++
++def test_clone_absolute_host() -> None:
++    req = make_mocked_request("GET", "https://example.com/path/to?a=1")
++    assert req.host == "example.com"
++    req2 = req.clone(host="foo.test")
++    assert req2.host == "foo.test"
++    assert req2.url.host == "foo.test"
++
++
+ def test_content_length() -> None:
+     req = make_mocked_request("Get", "/", CIMultiDict([("CONTENT-LENGTH", "123")]))
+ 
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111748_p2.patch new file +259 -0

259 lines not on this page · raw message

meta-python/recipes-devtools/python/python3-aiohttp_3.9.5.bb +2 -0
index 90475a5aff..db40e59a6b 100644
@@ -38,6 +38,8 @@ SRC_URI += "file://CVE-2024-52304.patch \
            file://CVE-2026-54273_p2.patch \
            file://CVE-2026-111750.patch \
            file://CVE-2026-111749.patch \
+           file://CVE-2026-111748_p1.patch \
+           file://CVE-2026-111748_p2.patch \
            "
 
 CVE_STATUS[CVE-2026-34515] = "not-applicable-platform: Vulnerability only affects applications running on Windows"
Signature · 1 line
2.35.6
#4 lore raw

PATCH 4/9 python3-aiohttp: fix CVE-2026-111066

In reply to Darsh Kelaiya -X (dkelaiya - E INFOCHIPS PRIVATE LIMITED at Cisco)

From: Darsh Kelaiya <[email protected]>

Backport the multipart descriptor-exhaustion fix [1] to aiohttp 3.9.5. Spool small file parts in memory and count raw multipart bytes, including headers, against client_max_size.

Include the upstream descriptor-test correction [2] so unrelated file descriptors do not make the regression test unreliable. Use synchronous BodyPartReader.decode(), retain the existing 64 KiB reads, and adapt the HTTP 413 constructor and raw-size assertion. The vulnerability and fixed release are documented in [3].

[1] https://github.com/aio-libs/aiohttp/commit/2d94633b7f1b4c1ba07d647b629a8440652b2d09
[2] https://github.com/aio-libs/aiohttp/commit/011c08204197beba8281911907b59ffcecea1413
[3] https://github.com/aio-libs/aiohttp/security/advisories/GHSA-9xw5-w5jj-pvcg

---
 .../python3-aiohttp/CVE-2026-111066_p1.patch  | 397 ++++++++++++++++++
 .../python3-aiohttp/CVE-2026-111066_p2.patch  |  59 +++
 .../python/python3-aiohttp_3.9.5.bb           |   2 +
 3 files changed, 458 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111066_p1.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111066_p2.patch
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111066_p1.patch new file +397 -0
new file mode 100644
index 0000000000..69bdbbec99
@@ -0,0 +1,397 @@
+From 2d94633b7f1b4c1ba07d647b629a8440652b2d09 Mon Sep 17 00:00:00 2001
+From: Sam Bull <[email protected]>
+Date: Tue, 18 Aug 2026 21:54:45 +0100
+Subject: [PATCH] Reduce number of file descriptors needed in multipart
+ messages (#13426) (#13475)
+
+CVE: CVE-2026-111066
+Upstream-Status: Backport [https://github.com/aio-libs/aiohttp/commit/2d94633b7f1b4c1ba07d647b629a8440652b2d09]
+
+Backport Changes:
+- Use synchronous BodyPartReader.decode() and 64 KiB reads in place
+  of the newer decode_iter()/DEFAULT_CHUNK_SIZE APIs.
+- Pass payload.total_bytes to the older HTTP 413 constructor and
+  adjust the existing size-limit test for raw multipart accounting.
+- Omit the cleanup-comment hunk because BaseRequest._finish() is
+  absent from aiohttp 3.9.5.
+
+(cherry picked from commit c92ed4c48dafd40d5ed4c86587af9e081ac7d971)
+Signed-off-by: Darsh Kelaiya <[email protected]>
+---
+ CHANGES/13426.bugfix.rst     |   1 +
+ aiohttp/web_request.py       |  95 ++++++++++++++-----
+ tests/test_web_functional.py | 171 +++++++++++++++++++++++++++++++++--
+ 3 files changed, 240 insertions(+), 27 deletions(-)
+ create mode 100644 CHANGES/13426.bugfix.rst
+
+diff --git a/CHANGES/13426.bugfix.rst b/CHANGES/13426.bugfix.rst
+new file mode 100644
+index 0000000..8b9ee29
+--- /dev/null
++++ b/CHANGES/13426.bugfix.rst
+@@ -0,0 +1 @@
++Switched multipart handling to use spooled temporary files to reduce number of file descriptors needed -- by :user:`Dreamsorcerer`.
+diff --git a/aiohttp/web_request.py b/aiohttp/web_request.py
+index f9de595..26279d5 100644
+--- a/aiohttp/web_request.py
++++ b/aiohttp/web_request.py
+@@ -4,12 +4,13 @@ import io
+ import re
+ import socket
+ import string
+-import tempfile
++import sys
+ import types
+ import warnings
+ from http.cookies import SimpleCookie
+ from types import MappingProxyType
+ from typing import (
++    IO,
+     TYPE_CHECKING,
+     Any,
+     Dict,
+@@ -64,6 +65,30 @@ from .typedefs import (
+ from .web_exceptions import HTTPRequestEntityTooLarge
+ from .web_response import StreamResponse
+ 
++if sys.version_info >= (3, 11):
++    from tempfile import SpooledTemporaryFile
++else:
++    import tempfile
++
++    class SpooledTemporaryFile(tempfile.SpooledTemporaryFile[bytes], io.IOBase):
++        """Make the spooled file satisfy the documented `FileField.file` type.
++
++        `tempfile.SpooledTemporaryFile` only became an `io.IOBase` subclass in
++        3.11 (python/cpython#70363), and never grew the three capability
++        predicates before then. Both underlying files (`io.BytesIO` before
++        rollover, a `w+b` temp file after) are readable, writable and seekable.
++        """
++
++        def readable(self) -> bool:
++            return True
++
++        def writable(self) -> bool:
++            return True
++
++        def seekable(self) -> bool:
++            return True
++
++
+ __all__ = ("BaseRequest", "FileField", "Request")
+ 
+ 
+@@ -73,11 +98,18 @@ if TYPE_CHECKING:
+     from .web_urldispatcher import UrlMappingMatchInfo
+ 
+ 
++# Multipart file parts are buffered in memory and only spilled to a temporary
++# file once they outgrow this size. A temp file per part would let a body made
++# of many tiny parts exhaust the process's file descriptors; spooling bounds
++# that at ``client_max_size // _FILE_SPOOL_MAX_SIZE`` descriptors per request.
++_FILE_SPOOL_MAX_SIZE: Final[int] = 1024**2
++
++
+ @attr.s(auto_attribs=True, frozen=True, slots=True)
+ class FileField:
+     name: str
+     filename: str
+-    file: io.BufferedReader
++    file: IO[bytes]
+     content_type: str
+     headers: "CIMultiDictProxy[str]"
+ 
+@@ -717,8 +749,15 @@ class BaseRequest(MutableMapping[str, Any], HeadersMixin):
+             multipart = await self.multipart()
+             max_size = self._client_max_size
+ 
+-            size = 0
++            payload = self._payload
+             while (field := await multipart.next()) is not None:
++                # This check is needed for empty payloads, which still add
++                # overhead without entering the loop and the check below.
++                if 0 < max_size < payload.total_bytes:
++                    raise HTTPRequestEntityTooLarge(
++                        max_size=max_size, actual_size=payload.total_bytes
++                    )
++
+                 field_ct = field.headers.get(hdrs.CONTENT_TYPE)
+ 
+                 if isinstance(field, BodyPartReader):
+@@ -730,22 +769,37 @@ class BaseRequest(MutableMapping[str, Any], HeadersMixin):
+                     # present.
+                     # https://tools.ietf.org/html/rfc7578#section-4.4
+                     if field.filename:
+-                        # store file in temp file
+-                        tmp = await self._loop.run_in_executor(
+-                            None, tempfile.TemporaryFile
+-                        )
+-                        chunk = await field.read_chunk(size=2**16)
+-                        while chunk:
+-                            chunk = field.decode(chunk)
+-                            await self._loop.run_in_executor(None, tmp.write, chunk)
+-                            size += len(chunk)
+-                            if 0 < max_size < size:
+-                                await self._loop.run_in_executor(None, tmp.close)
++                        tmp = SpooledTemporaryFile(_FILE_SPOOL_MAX_SIZE)
++                        # rolled means the temp file now uses the disk, at
++                        # which point we want to run in the executor.
++                        rolled = False
++                        while chunk := await field.read_chunk(size=2**16):
++                            # Bounds one part, mid-read.
++                            if 0 < max_size < payload.total_bytes:
++                                if rolled:
++                                    await self._loop.run_in_executor(None, tmp.close)
++                                else:
++                                    tmp.close()
+                                 raise HTTPRequestEntityTooLarge(
+-                                    max_size=max_size, actual_size=size
++                                    max_size=max_size, actual_size=payload.total_bytes
++                                )
++                            decoded_chunk = field.decode(chunk)
++                            # Update before writing, so we know if next
++                            # write is going to hit the disk.
++                            rolled = rolled or (
++                                tmp.tell() + len(decoded_chunk)
++                                > _FILE_SPOOL_MAX_SIZE
++                            )
++                            if rolled:
++                                await self._loop.run_in_executor(
++                                    None, tmp.write, decoded_chunk
+                                 )
+-                            chunk = await field.read_chunk(size=2**16)
+-                        await self._loop.run_in_executor(None, tmp.seek, 0)
++                            else:
++                                tmp.write(decoded_chunk)
++                        if rolled:
++                            await self._loop.run_in_executor(None, tmp.seek, 0)
++                        else:
++                            tmp.seek(0)
+ 
+                         if field_ct is None:
+                             field_ct = "application/octet-stream"
+@@ -753,7 +807,7 @@ class BaseRequest(MutableMapping[str, Any], HeadersMixin):
+                         ff = FileField(
+                             field.name,
+                             field.filename,
+-                            cast(io.BufferedReader, tmp),
++                            tmp,
+                             field_ct,
+                             field.headers,
+                         )
+@@ -762,10 +816,9 @@ class BaseRequest(MutableMapping[str, Any], HeadersMixin):
+                         # deal with ordinary data
+                         raw_data = bytearray()
+                         while chunk := await field.read_chunk():
+-                            size += len(chunk)
+-                            if 0 < max_size < size:
++                            if 0 < max_size < payload.total_bytes:
+                                 raise HTTPRequestEntityTooLarge(
+-                                    max_size=max_size, actual_size=size
++                                    max_size=max_size, actual_size=payload.total_bytes
+                                 )
+                             raw_data.extend(chunk)
+ 
+diff --git a/tests/test_web_functional.py b/tests/test_web_functional.py
+index a0e3a8e..78bd265 100644
+--- a/tests/test_web_functional.py
++++ b/tests/test_web_functional.py
+@@ -1,6 +1,8 @@
+ import asyncio
++import base64
+ import io
+ import json
++import os
+ import pathlib
+ import socket
+ import zlib
+@@ -28,6 +30,7 @@ from aiohttp.streams import StreamReader
+ from aiohttp.test_utils import make_mocked_coro
+ from aiohttp.typedefs import Handler
+ from aiohttp.web_protocol import MAX_MSG_QUEUE_SIZE, RequestHandler
++from aiohttp.web_request import _FILE_SPOOL_MAX_SIZE
+ 
+ try:
+     import brotlicffi as brotli
+@@ -1964,10 +1967,7 @@ async def test_post_max_client_size(aiohttp_client) -> None:
+ 
+         assert 413 == resp.status
+         resp_text = await resp.text()
+-        assert (
+-            "Maximum request body size 10 exceeded, "
+-            "actual body size 1024" in resp_text
+-        )
++        assert "Maximum request body size 10 exceeded" in resp_text
+         data["file"].close()
+ 
+         await resp.release()
+@@ -1991,8 +1991,167 @@ async def test_post_max_client_size_for_file(aiohttp_client) -> None:
+     await resp.release()
+ 
+ 
+-async def test_response_with_bodypart(aiohttp_client) -> None:
+-    async def handler(request):
++def _multipart_file_parts(count: int, body: bytes = b"") -> bytes:
++    """Raw multipart/form-data body of ``count`` file parts, boundary ``b``."""
++    return (
++        b"".join(
++            b'--b\r\nContent-Disposition: form-data; name="f%d"; '
++            b'filename="x"\r\n\r\n' % index + body + b"\r\n"
++            for index in range(count)
++        )
++        + b"--b--\r\n"
++    )
++
++
++async def test_post_max_client_size_counts_multipart_headers(
++    aiohttp_client: AiohttpClient,
++) -> None:
++    async def handler(request: web.Request) -> NoReturn:
++        await request.post()
++        assert False
++
++    app = web.Application(client_max_size=1)
++    app.router.add_post("/", handler)
++    client = await aiohttp_client(app)
++
++    body = _multipart_file_parts(55)
++    assert len(body) > 1
++    async with client.post(
++        "/", data=body, headers={CONTENT_TYPE: "multipart/form-data; boundary=b"}
++    ) as resp:
++        assert resp.status == 413
++
++
[email protected](
++    "max_size",
++    (_FILE_SPOOL_MAX_SIZE, 2 * _FILE_SPOOL_MAX_SIZE),
++    ids=("spooled", "rolled-over"),
++)
++async def test_post_max_client_size_within_single_part(
++    aiohttp_client: AiohttpClient, max_size: int
++) -> None:
++    async def handler(request: web.Request) -> NoReturn:
++        await request.post()
++        assert False
++
++    app = web.Application(client_max_size=max_size)
++    app.router.add_post("/", handler)
++    client = await aiohttp_client(app)
++
++    # A sole oversized part is never followed by a boundary, so only the
++    # per-chunk check can reject it, and it must do so before buffering. The
++    # larger limit lets the part reach the disk first, so the spool is then
++    # closed off the event loop too.
++    data = FormData()
++    with io.BytesIO(b"x" * (3 * _FILE_SPOOL_MAX_SIZE)) as file_handle:
++        data.add_field("file", file_handle, filename="x.bin")
++        async with client.post("/", data=data) as resp:
++            assert resp.status == 413
++
++
[email protected]("filename", (b"", b'; filename="x"'), ids=("field", "file"))
++async def test_post_max_client_size_counts_undecoded_bytes(
++    aiohttp_client: AiohttpClient, filename: bytes
++) -> None:
++    async def handler(request: web.Request) -> NoReturn:
++        await request.post()
++        assert False
++
++    limit = 64 * 1024
++    app = web.Application(client_max_size=limit)
++    app.router.add_post("/", handler)
++    client = await aiohttp_client(app)
++
++    # base64 decodes to exactly the limit but arrives 4/3 larger. The limit is
++    # on the request body, so both kinds of part must reject it alike.
++    encoded = base64.b64encode(b"A" * limit)
++    assert len(encoded) > limit
++    body = (
++        b'--b\r\nContent-Disposition: form-data; name="f"' + filename + b"\r\n"
++        b"Content-Transfer-Encoding: base64\r\n\r\n" + encoded + b"\r\n--b--\r\n"
++    )
++    async with client.post(
++        "/", data=body, headers={CONTENT_TYPE: "multipart/form-data; boundary=b"}
++    ) as resp:
++        assert resp.status == 413
++
++
[email protected](not os.path.isdir("/dev/fd"), reason="needs /dev/fd to count fds")
[email protected](
++    ("parts", "part_body", "expected_fds"),
++    (
++        (55, b"payload", 0),
++        (1, b"x" * (_FILE_SPOOL_MAX_SIZE + 1), 1),
++    ),
++    ids=("many-small-parts", "one-oversized-part"),
++)
++async def test_post_file_fields_descriptor_cost(
++    aiohttp_client: AiohttpClient, parts: int, part_body: bytes, expected_fds: int
++) -> None:
++    """Only a part past the spool size may cost a descriptor."""
++
++    async def handler(request: web.Request) -> web.Response:
++        before = set(await asyncio.to_thread(os.listdir, "/dev/fd"))
++        data = await request.post()
++        after = set(await asyncio.to_thread(os.listdir, "/dev/fd"))
++        assert len(data) == parts
++        return web.Response(text=str(len(after - before)))
++
++    app = web.Application(client_max_size=8 * 1024**2)
++    app.router.add_post("/", handler)
++    client = await aiohttp_client(app)
++
++    with io.BytesIO(_multipart_file_parts(parts, part_body)) as body:
++        async with client.post(
++            "/",
++            data=body,
++            headers={CONTENT_TYPE: "multipart/form-data; boundary=b"},
++        ) as resp:
++            assert resp.status == 200
++            assert await resp.text() == str(expected_fds)
++
++
[email protected](
++    "size",
++    (
++        0,
++        1,
++        _FILE_SPOOL_MAX_SIZE - 1,
++        _FILE_SPOOL_MAX_SIZE,
++        _FILE_SPOOL_MAX_SIZE + 1,
++    ),
++)
++async def test_post_file_field_spool_rollover(
++    aiohttp_client: AiohttpClient, size: int
++) -> None:
++    """A part is byte-identical either side of the spool/temp-file boundary."""
++    payload = (b"0123456789abcdef" * (size // 16 + 1))[:size]
++
++    async def handler(request: web.Request) -> web.Response:
++        field = (await request.post())["file"]
++        assert isinstance(field, aiohttp.web_request.FileField)
++        assert isinstance(field.file, io.IOBase)
++        assert field.file.readable()
++        assert field.file.writable()
++        assert field.file.seekable()
++        content = await asyncio.to_thread(field.file.read)
++        assert len(content) == size
++        assert content == payload
++        return web.Response()
++
++    app = web.Application(client_max_size=8 * 1024**2)
++    app.router.add_post("/", handler)
++    client = await aiohttp_client(app)
++
++    data = FormData()
++    with io.BytesIO(payload) as file_handle:
++        data.add_field("file", file_handle, filename="x.bin")
++        async with client.post("/", data=data) as resp:
++            assert resp.status == 200
++
++
++async def test_response_with_bodypart(aiohttp_client: AiohttpClient) -> None:
++    async def handler(request: web.Request) -> web.Response:
+         reader = await request.multipart()
+         part = await reader.next()
+         return web.Response(body=part)
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111066_p2.patch new file +59 -0

59 lines not on this page · raw message

meta-python/recipes-devtools/python/python3-aiohttp_3.9.5.bb +2 -0
index db40e59a6b..59e9f74e89 100644
@@ -40,6 +40,8 @@ SRC_URI += "file://CVE-2024-52304.patch \
            file://CVE-2026-111749.patch \
            file://CVE-2026-111748_p1.patch \
            file://CVE-2026-111748_p2.patch \
+           file://CVE-2026-111066_p1.patch \
+           file://CVE-2026-111066_p2.patch \
            "
 
 CVE_STATUS[CVE-2026-34515] = "not-applicable-platform: Vulnerability only affects applications running on Windows"
Signature · 1 line
2.35.6
#5 lore raw

PATCH 5/9 python3-aiohttp: fix CVE-2026-111065

In reply to Darsh Kelaiya -X (dkelaiya - E INFOCHIPS PRIVATE LIMITED at Cisco)

From: Darsh Kelaiya <[email protected]>

Backport the upstream cookie overflow and response cleanup fix [1] to aiohttp 3.9.5, as identified by [2]. Clamp positive Max-Age values before float conversion and expire nonpositive values immediately.

Close a received response if subsequent processing fails so a malformed cookie cannot exhaust the connection pool. Include the upstream extreme Max-Age and connection-release regression tests. Adapt the response annotation, cookie-update test hook and root-path keys to 3.9.5. Raise the test error only for nonempty cookies because this client invokes update_cookies() even for clean responses.

[1] https://github.com/aio-libs/aiohttp/commit/9dd8eaf4e31f1237ef2c1574a8c82a739fca5805
[2] https://github.com/aio-libs/aiohttp/security/advisories/GHSA-6cjc-53gc-5rqm

---
 .../python3-aiohttp/CVE-2026-111065.patch     | 171 ++++++++++++++++++
 .../python/python3-aiohttp_3.9.5.bb           |   1 +
 2 files changed, 172 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111065.patch
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111065.patch new file +171 -0
new file mode 100644
index 0000000000..916afb87ca
@@ -0,0 +1,171 @@
+From 9dd8eaf4e31f1237ef2c1574a8c82a739fca5805 Mon Sep 17 00:00:00 2001
+From: "patchback[bot]" <45432694+patchback[bot]@users.noreply.github.com>
+Date: Wed, 9 Sep 2026 14:43:30 +0100
+Subject: [PATCH] [PR #13677/9e08ba02 backport][3.14] Fix cookie overflow
+ (#13679)
+
+**This is a backport of PR #13677 as merged into master
+(9e08ba02abe573ce9e4cc541d4e3c3646adb43a7).**
+
+---------
+
+Co-authored-by: Sam Bull <[email protected]>
+
+CVE: CVE-2026-111065
+Upstream-Status: Backport [https://github.com/aio-libs/aiohttp/commit/9dd8eaf4e31f1237ef2c1574a8c82a739fca5805]
+
+Backport Changes:
+- Use the existing Optional spelling for the response variable.
+- Use update_cookies() and SimpleCookie() in the regression tests,
+  retaining the older "/" expiration key.
+- Raise the test cookie error only for nonempty cookies; this client
+  invokes update_cookies() even when a response has no Set-Cookie.
+
+Signed-off-by: Darsh Kelaiya <[email protected]>
+---
+ CHANGES/13677.bugfix.rst        |  1 +
+ aiohttp/client.py               |  5 ++++
+ aiohttp/cookiejar.py            | 10 ++++++-
+ tests/test_client_functional.py | 46 +++++++++++++++++++++++++++++++++
+ tests/test_cookiejar.py         | 22 ++++++++++++++++
+ 5 files changed, 83 insertions(+), 1 deletion(-)
+ create mode 100644 CHANGES/13677.bugfix.rst
+
+diff --git a/CHANGES/13677.bugfix.rst b/CHANGES/13677.bugfix.rst
+new file mode 100644
+index 0000000..bea67cb
+--- /dev/null
++++ b/CHANGES/13677.bugfix.rst
+@@ -0,0 +1 @@
++Fixed a possible ``OverflowError`` on cookies and a connection not being closed properly -- by :user:`Dreamsorcerer`.
+diff --git a/aiohttp/client.py b/aiohttp/client.py
+index 4674b19..2e88917 100644
+--- a/aiohttp/client.py
++++ b/aiohttp/client.py
+@@ -509,6 +509,7 @@ class ClientSession:
+             await trace.send_request_start(method, url.update_query(params), headers)
+ 
+         timer = tm.timer()
++        resp: Optional[ClientResponse] = None
+         try:
+             with timer:
+                 while True:
+@@ -727,6 +728,10 @@ class ClientSession:
+                 handle.cancel()
+                 handle = None
+ 
++            if resp is not None:
++                # A failure occurred after the response was received.
++                resp.close()
++
+             for trace in traces:
+                 await trace.send_request_exception(
+                     method, url.update_query(params), headers, e
+diff --git a/aiohttp/cookiejar.py b/aiohttp/cookiejar.py
+index 4f694b6..b69e9e2 100644
+--- a/aiohttp/cookiejar.py
++++ b/aiohttp/cookiejar.py
+@@ -340,7 +340,15 @@ class CookieJar(AbstractCookieJar):
+             if max_age:
+                 try:
+                     delta_seconds = int(max_age)
+-                    max_age_expiration = min(time.time() + delta_seconds, self.MAX_TIME)
++                    # https://datatracker.ietf.org/doc/html/rfc6265#section-5.2.2
++                    if delta_seconds <= 0:
++                        max_age_expiration = 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)
+                 except ValueError:
+                     cookie["max-age"] = ""
+diff --git a/tests/test_client_functional.py b/tests/test_client_functional.py
+index 649e766..d695638 100644
+--- a/tests/test_client_functional.py
++++ b/tests/test_client_functional.py
+@@ -2400,6 +2400,52 @@ async def test_set_cookies_max_age_overflow(aiohttp_client) -> None:
+                 assert int(cookie["max-age"]) == int(overflow)
+ 
+ 
++async def test_connection_released_when_cookie_processing_fails(
++    aiohttp_client: AiohttpClient,
++) -> None:
++    class EvilJar(aiohttp.CookieJar):
++        def update_cookies(
++            self, cookies: Any, response_url: URL = URL()
++        ) -> None:
++            if cookies:
++                raise RuntimeError("boom")
++            super().update_cookies(cookies, response_url)
++
++    hold = asyncio.Event()
++
++    async def hostile(request: web.Request) -> web.StreamResponse:
++        ret = web.StreamResponse()
++        ret.content_length = 2
++        ret.set_cookie("sid", "x")
++        await ret.prepare(request)
++        await ret.write(b"x")
++        await hold.wait()
++        assert False
++
++    async def clean(request: web.Request) -> web.Response:
++        return web.Response()
++
++    app = web.Application()
++    app.router.add_get("/hostile", hostile)
++    app.router.add_get("/clean", clean)
++    connector = aiohttp.TCPConnector(limit=1)
++    client = await aiohttp_client(app, connector=connector, cookie_jar=EvilJar())
++
++    try:
++        for _ in range(2):
++            with pytest.raises(RuntimeError, match="boom") as excinfo:
++                await client.get("/hostile")
++            assert not connector._acquired
++            del excinfo
++
++        # The single connector slot is free again: an unaffected request
++        # succeeds instead of waiting forever for a connection.
++        async with client.get("/clean") as resp:
++            assert resp.status == 200
++    finally:
++        hold.set()
++
++
+ async def test_request_conn_error() -> None:
+     client = aiohttp.ClientSession()
+     with pytest.raises(aiohttp.ClientConnectionError):
+diff --git a/tests/test_cookiejar.py b/tests/test_cookiejar.py
+index df59759..3c9933b 100644
+--- a/tests/test_cookiejar.py
++++ b/tests/test_cookiejar.py
+@@ -1176,3 +1176,25 @@ async def test_save_load_json_secure_cookies(tmp_path: Path) -> None:
+     assert cookie["secure"] is True
+     assert cookie["httponly"] is True
+     assert cookie["domain"] == "example.com"
++
++
++async def test_update_cookies_max_age_beyond_float_range_is_clamped() -> None:
++    """A hostile Max-Age larger than float max must clamp, not raise OverflowError."""
++    url = URL("https://example.com/")
++    jar = CookieJar()
++
++    jar.update_cookies(SimpleCookie(f"sid=x; Max-Age={'9' * 309}"), url)
++
++    assert "sid" in jar.filter_cookies(url)
++    assert jar._expirations[("example.com", "/", "sid")] == CookieJar.MAX_TIME
++
++
++async def test_update_cookies_negative_max_age_beyond_float_range_expires() -> None:
++    """A negative Max-Age below float min must expire the cookie, not raise."""
++    url = URL("https://example.com/")
++    jar = CookieJar()
++
++    jar.update_cookies(SimpleCookie(f"sid=x; Max-Age=-{'9' * 309}"), url)
++
++    assert "sid" not in jar.filter_cookies(url)
++    assert len(jar) == 0
meta-python/recipes-devtools/python/python3-aiohttp_3.9.5.bb +1 -0
index 59e9f74e89..8d7fe9f8dd 100644
@@ -42,6 +42,7 @@ SRC_URI += "file://CVE-2024-52304.patch \
            file://CVE-2026-111748_p2.patch \
            file://CVE-2026-111066_p1.patch \
            file://CVE-2026-111066_p2.patch \
+           file://CVE-2026-111065.patch \
            "
 
 CVE_STATUS[CVE-2026-34515] = "not-applicable-platform: Vulnerability only affects applications running on Windows"
Signature · 1 line
2.35.6
#6 lore raw

PATCH 6/9 python3-aiohttp: fix CVE-2026-111064

In reply to Darsh Kelaiya -X (dkelaiya - E INFOCHIPS PRIVATE LIMITED at Cisco)

From: Darsh Kelaiya <[email protected]>

Backport the idle-connection timeout fix [1] to aiohttp 3.9.5, as identified by [2]. Start the keepalive deadline when the connection is established and use the existing timeout to bound the wait for the first request headers.

[1] https://github.com/aio-libs/aiohttp/commit/be846822b4b3a5a54b6163e794b42dc06fba54a3
[2] https://github.com/aio-libs/aiohttp/security/advisories/GHSA-5wr8-gcqf-gqf3

---
 .../python3-aiohttp/CVE-2026-111064.patch     | 398 ++++++++++++++++++
 .../python/python3-aiohttp_3.9.5.bb           |   1 +
 2 files changed, 399 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111064.patch
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111064.patch new file +398 -0
new file mode 100644
index 0000000..7caf9c3
@@ -0,0 +1,398 @@
+From be846822b4b3a5a54b6163e794b42dc06fba54a3 Mon Sep 17 00:00:00 2001
+From: Sam Bull <[email protected]>
+Date: Tue, 29 Sep 2026 00:08:22 +0100
+Subject: [PATCH] Close idle connections (#13681) (#13838)
+
+CVE: CVE-2026-111064
+Upstream-Status: Backport [https://github.com/aio-libs/aiohttp/commit/be846822b4b3a5a54b6163e794b42dc06fba54a3]
+
+Backport Changes:
+- Use 3.9.5's _keepalive_time and task creation, preserve None as
+  disabled, and reuse the existing 75-second default.
+- Replace the old periodic timer check using the stored start time.
+  An early callback rearms at the deadline. A finished waiter stays
+  open.
+- Document that the initial deadline covers only request headers.
+  Omit the 3.14.4 version marker and already-correct default update.
+- Cover timer setup, rearming, and waiter states with mocked loops
+  and transports. Use the 3.9.5 raw-server fixture to check idle,
+  partial-header and post-request expiry on loopback. Synchronize the
+  slow handler with the initial deadline and check its response.
+  Adapt the WebSocket fixture signature and omit unrelated typing.
+
+(cherry picked from commit e07684ef9056183bbefba1ae3f717a23f243631e)
+Signed-off-by: Darsh Kelaiya <[email protected]>
+---
+ CHANGES/13681.bugfix.rst               |    1 
+ aiohttp/web_protocol.py                |   38 +++++-----
+ docs/web_reference.rst                 |    5 +
+ tests/test_web_protocol.py             |   76 +++++++++++++++++++++
+ tests/test_web_server.py               |  118 ++++++++++++++++++++++++++++++++
+ tests/test_web_websocket_functional.py |   30 ++++++++
+ 6 files changed, 250 insertions(+), 18 deletions(-)
+ create mode 100644 CHANGES/13681.bugfix.rst
+
+diff --git a/CHANGES/13681.bugfix.rst b/CHANGES/13681.bugfix.rst
+new file mode 100644
+index 0000000000000000000000000000000000000000..e39b73a91fa2833b1492054e31b18fea9e265029
+--- /dev/null
++++ b/CHANGES/13681.bugfix.rst
+@@ -0,0 +1 @@
++Fixed idle connections not being closed if no request was received -- by :user:`Dreamsorcerer`.
+diff --git a/aiohttp/web_protocol.py b/aiohttp/web_protocol.py
+index 39a1b68502fb48b8d0640c8fd4ebd6e7308512d6..314c5c79274aee2fffaf17afb91ae0349ac8a798 100644
+--- a/aiohttp/web_protocol.py
++++ b/aiohttp/web_protocol.py
+@@ -109,8 +109,7 @@ class RequestHandler(BaseProtocol):
+     status line, bad headers or incomplete payload. If any error occurs,
+     connection gets closed.
+ 
+-    keepalive_timeout -- number of seconds before closing
+-                         keep-alive connection
++    keepalive_timeout -- number of seconds before closing an idle connection.
+ 
+     tcp_keepalive -- TCP keep-alive is on, default is on
+ 
+@@ -138,8 +137,6 @@ class RequestHandler(BaseProtocol):
+ 
+     """
+ 
+-    KEEPALIVE_RESCHEDULE_DELAY = 1
+-
+     __slots__ = (
+         "max_field_size",
+         "max_headers",
+@@ -206,7 +203,7 @@ class RequestHandler(BaseProtocol):
+         super().__init__(loop)
+ 
+         self._request_count = 0
+-        self._keepalive = False
++        self._keepalive = True
+         self._current_request: Optional[BaseRequest] = None
+         self._manager: Optional[Server] = manager
+         self._request_handler: Optional[_RequestHandler] = manager.request_handler
+@@ -310,7 +307,15 @@ class RequestHandler(BaseProtocol):
+         if self._tcp_keepalive:
+             tcp_keepalive(real_transport)
+ 
+-        self._task_handler = self._loop.create_task(self.start())
++        loop = self._loop
++        # Need to enable keepalive timeout at start of connection, as there's no other
++        # protection against a dead connection that doesn't send a request at all.
++        if self._keepalive_timeout is not None and self._keepalive_timeout > 0:
++            self._keepalive_time = loop.time()
++            close_time = self._keepalive_time + self._keepalive_timeout
++            self._keepalive_handle = loop.call_at(close_time, self._process_keepalive)
++
++        self._task_handler = loop.create_task(self.start())
+         assert self._manager is not None
+         self._manager.connection_made(self, real_transport)
+ 
+@@ -483,23 +488,20 @@ class RequestHandler(BaseProtocol):
+         self.logger.exception(*args, **kw)
+ 
+     def _process_keepalive(self) -> None:
++        self._keepalive_handle = None
+         if self._force_close or not self._keepalive:
+             return
+ 
+-        next = self._keepalive_time + self._keepalive_timeout
++        loop = self._loop
++        close_time = self._keepalive_time + self._keepalive_timeout
++        if loop.time() < close_time:
++            # Keep alive close check fired too early, reschedule
++            self._keepalive_handle = loop.call_at(close_time, self._process_keepalive)
++            return
+ 
+         # handler in idle state
+-        if self._waiter:
+-            if self._loop.time() > next:
+-                self.force_close()
+-                return
+-
+-        # not all request handlers are done,
+-        # reschedule itself to next second
+-        self._keepalive_handle = self._loop.call_later(
+-            self.KEEPALIVE_RESCHEDULE_DELAY,
+-            self._process_keepalive,
+-        )
++        if self._waiter and not self._waiter.done():
++            self.force_close()
+ 
+     async def _handle_request(
+         self,
+diff --git a/docs/web_reference.rst b/docs/web_reference.rst
+index cc6201b42c09e36c993bd387af028bdd632cdaea..1f934021d7a44a0a66f7ed1e890e5cdc25ed00bf 100644
+--- a/docs/web_reference.rst
++++ b/docs/web_reference.rst
+@@ -2988,6 +2988,11 @@ Utilities
+    :param float keepalive_timeout: a delay before a TCP connection is
+                                    closed after a HTTP request. The delay
+                                    allows for reuse of a TCP connection.
++                                   The same delay bounds how long a newly
++                                   accepted connection may take to deliver
++                                   its first complete request headers;
++                                   connections that stay idle or send
++                                   incomplete headers are closed.
+ 
+       .. versionadded:: 3.8
+ 
+diff --git a/tests/test_web_protocol.py b/tests/test_web_protocol.py
+index dcda53965fb85711a2c9a6b573e554e73f2fcbd9..084b72edba0301dc17fc951f114b3751afae0934 100644
+--- a/tests/test_web_protocol.py
++++ b/tests/test_web_protocol.py
+@@ -1,4 +1,5 @@
+ import asyncio
++from typing import Optional, Tuple
+ from unittest import mock
+ 
+ import pytest
+@@ -17,6 +18,81 @@ def dummy_manager() -> Server:
+     )  # type: ignore[no-any-return]
+ 
+ 
++def _connect_with_keepalive(
++    dummy_manager: Server, timeout: Optional[float]
++) -> Tuple[RequestHandler, mock.Mock, mock.Mock]:
++    loop = mock.Mock(spec=asyncio.AbstractEventLoop)
++    loop.time.return_value = 10.0
++    transport = mock.Mock(spec=asyncio.Transport)
++    transport.get_extra_info.return_value = None
++    handler = RequestHandler(
++        dummy_manager,
++        loop=loop,
++        keepalive_timeout=timeout,  # type: ignore[arg-type]
++        tcp_keepalive=False,
++    )
++
++    with mock.patch.object(RequestHandler, "start", new=mock.Mock()):
++        handler.connection_made(transport)
++
++    return handler, loop, transport
++
++
[email protected]("timeout", [2.0, 0.0, None])
++def test_connection_made_schedules_initial_keepalive(
++    dummy_manager: Server, timeout: Optional[float]
++) -> None:
++    handler, loop, _ = _connect_with_keepalive(dummy_manager, timeout)
++
++    if timeout:
++        loop.call_at.assert_called_once_with(12.0, handler._process_keepalive)
++        assert handler._keepalive_handle is loop.call_at.return_value
++    else:
++        loop.call_at.assert_not_called()
++        assert handler._keepalive_handle is None
++
++
++def test_initial_keepalive_rearms_if_called_early(dummy_manager: Server) -> None:
++    handler, loop, transport = _connect_with_keepalive(dummy_manager, 2.0)
++    handler._waiter = mock.Mock(spec=asyncio.Future)
++    handler._waiter.done.return_value = False
++    callback = loop.call_at.call_args.args[1]
++    loop.call_at.reset_mock()
++    loop.time.return_value = 11.0
++    loop.call_at.return_value = mock.sentinel.rearmed
++
++    callback()
++
++    loop.call_at.assert_called_once_with(12.0, callback)
++    assert handler._keepalive_handle is mock.sentinel.rearmed
++    transport.close.assert_not_called()
++
++
[email protected](
++    "waiter_done", [False, True, None], ids=["pending", "resolved", "dispatched"]
++)
++def test_initial_keepalive_deadline(
++    dummy_manager: Server, waiter_done: Optional[bool]
++) -> None:
++    handler, loop, transport = _connect_with_keepalive(dummy_manager, 2.0)
++    if waiter_done is not None:
++        waiter = mock.Mock(spec=asyncio.Future)
++        waiter.done.return_value = waiter_done
++        handler._waiter = waiter
++    callback = loop.call_at.call_args.args[1]
++    loop.call_at.reset_mock()
++    loop.time.return_value = 12.0
++
++    callback()
++
++    assert handler._keepalive_handle is None
++    loop.call_at.assert_not_called()
++    if waiter_done is False:
++        transport.close.assert_called_once_with()
++    else:
++        transport.close.assert_not_called()
++
++
+ def test_pause_msg_queue_reading_without_transport(
+     loop: asyncio.AbstractEventLoop,
+     dummy_manager: Server,
+diff --git a/tests/test_web_server.py b/tests/test_web_server.py
+index d0fd95acdb4b17fcf8dc1a390e2a48d6ae68441c..6442224d86efe24be82c75969afe384329378c2b 100644
+--- a/tests/test_web_server.py
++++ b/tests/test_web_server.py
+@@ -253,3 +253,121 @@ async def test_no_handler_cancellation(aiohttp_unused_port) -> None:
+         assert done_event.is_set()
+     finally:
+         await asyncio.gather(runner.shutdown(), site.stop())
++
++
++async def test_initial_keepalive_is_armed_on_loopback(
++    aiohttp_raw_server, aiohttp_client
++) -> None:
++    keepalive_timeout = 30.0
++    connection_made = web.Server.connection_made
++    opened = []
++    handled = []
++
++    def observe_connection(
++        server: web.Server,
++        protocol: web.RequestHandler,
++        transport: asyncio.Transport,
++    ) -> None:
++        connection_made(server, protocol, transport)
++        opened.append((protocol, protocol._keepalive_handle, protocol._keepalive_time))
++
++    async def handler(request: web.BaseRequest) -> web.Response:
++        handled.append(request.protocol)
++        return web.Response(text="ok")
++
++    server = await aiohttp_raw_server(handler, keepalive_timeout=keepalive_timeout)
++    cli = await aiohttp_client(server, timeout=client.ClientTimeout(total=10))
++    with mock.patch.object(web.Server, "connection_made", observe_connection):
++        async with cli.get("/") as response:
++            assert response.status == 200
++            assert await response.text() == "ok"
++
++    [(protocol, timer, connection_time)] = opened
++    assert handled == [protocol]
++    assert isinstance(timer, asyncio.TimerHandle)
++    assert not timer.cancelled()
++    assert timer.when() == connection_time + keepalive_timeout
++
++
[email protected](
++    "send_headers", [False, True], ids=["idle", "partial-headers"]
++)
++async def test_initial_keepalive_closes_on_loopback(
++    aiohttp_raw_server, send_headers: bool
++) -> None:
++    handler = mock.AsyncMock()
++    server = await aiohttp_raw_server(handler, keepalive_timeout=1.0)
++    reader, writer = await asyncio.open_connection(server.host, server.port)
++
++    try:
++        if send_headers:
++            writer.write(b"GET / HTTP/1.1\r\nHost: localhost\r\n")
++            await writer.drain()
++
++        assert await asyncio.wait_for(reader.read(1), timeout=5) == b""
++        handler.assert_not_awaited()
++    finally:
++        writer.close()
++        await writer.wait_closed()
++
++
++async def test_keepalive_expires_on_loopback_after_complete_request(
++    aiohttp_raw_server, monkeypatch: pytest.MonkeyPatch
++) -> None:
++    expired = False
++    process_keepalive = web.RequestHandler._process_keepalive
++
++    def observe_expiry(protocol: web.RequestHandler) -> None:
++        nonlocal expired
++        was_open = not protocol._force_close
++        process_keepalive(protocol)
++        if was_open and protocol._force_close:
++            expired = True
++
++    monkeypatch.setattr(web.RequestHandler, "_process_keepalive", observe_expiry)
++
++    async def handler(request: web.BaseRequest) -> web.Response:
++        return web.Response(body=b"ok")
++
++    server = await aiohttp_raw_server(handler, keepalive_timeout=0.5)
++    reader, writer = await asyncio.open_connection(server.host, server.port)
++    try:
++        writer.write(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
++        await writer.drain()
++        headers = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), timeout=5)
++        assert headers.startswith(b"HTTP/1.1 200 ")
++        assert b"connection: close" not in headers.lower()
++        assert await asyncio.wait_for(reader.readexactly(2), timeout=5) == b"ok"
++
++        # Keep the client open so EOF comes from the server's keepalive timer.
++        assert await asyncio.wait_for(reader.read(1), timeout=5) == b""
++        assert expired
++    finally:
++        writer.close()
++        await writer.wait_closed()
++
++
++async def test_handler_slower_than_first_request_deadline(
++    aiohttp_raw_server, aiohttp_client, monkeypatch: pytest.MonkeyPatch
++) -> None:
++    """The initial deadline can expire while a complete request is handled."""
++    deadline_processed = asyncio.Event()
++    process_keepalive = web.RequestHandler._process_keepalive
++
++    def observe_deadline(protocol: web.RequestHandler) -> None:
++        process_keepalive(protocol)
++        if protocol._current_request is not None and protocol._keepalive_handle is None:
++            deadline_processed.set()
++
++    monkeypatch.setattr(web.RequestHandler, "_process_keepalive", observe_deadline)
++
++    async def handler(request: web.BaseRequest) -> web.Response:
++        await asyncio.wait_for(deadline_processed.wait(), timeout=5)
++        assert not request.protocol._force_close
++        return web.Response(text="ok")
++
++    server = await aiohttp_raw_server(handler, keepalive_timeout=0.5)
++    cli = await aiohttp_client(server, timeout=client.ClientTimeout(total=10))
++    async with cli.get("/") as response:
++        assert response.status == 200
++        assert await response.text() == "ok"
+diff --git a/tests/test_web_websocket_functional.py b/tests/test_web_websocket_functional.py
+index b471b131c1ef704d46712476b11a16693c862559..686845ce9964f1aa04f810181a4852153950c0f0 100644
+--- a/tests/test_web_websocket_functional.py
++++ b/tests/test_web_websocket_functional.py
+@@ -776,6 +776,36 @@ async def test_websocket_disable_keepalive(loop, aiohttp_client) -> None:
+     assert data == "OK"
+ 
+ 
++async def test_websocket_disable_keepalive_no_armed_handle(
++    aiohttp_server, aiohttp_client
++) -> None:
++    """keep_alive(False) when no keepalive timer was armed (keepalive_timeout=0)."""
++
++    async def handler(request: web.Request) -> web.StreamResponse:
++        ws = web.WebSocketResponse()
++        assert ws.can_prepare(request)
++        # A zero timeout arms no deadline at connection_made().
++        assert request.protocol._keepalive_handle is None
++        await ws.prepare(request)
++        assert not request.protocol._keepalive
++        assert request.protocol._keepalive_handle is None
++
++        await ws.send_str("OK")
++        await ws.close()
++        return ws
++
++    app = web.Application()
++    app.router.add_route("GET", "/", handler)
++    server = await aiohttp_server(app, keepalive_timeout=0)
++    client = await aiohttp_client(server)
++
++    ws = await client.ws_connect("/")
++    data = await ws.receive_str()
++    assert data == "OK"
++
++    await ws.receive()  # Handle close
++
++
+ async def test_bug3380(loop, aiohttp_client) -> None:
+     async def handle_null(request):
+         return aiohttp.web.json_response({"err": None})
meta-python/recipes-devtools/python/python3-aiohttp_3.9.5.bb +1 -0
index 8d7fe9f..16ec0a6 100644
@@ -43,6 +43,7 @@ SRC_URI += "file://CVE-2024-52304.patch \
            file://CVE-2026-111066_p1.patch \
            file://CVE-2026-111066_p2.patch \
            file://CVE-2026-111065.patch \
+           file://CVE-2026-111064.patch \
            "
 
 CVE_STATUS[CVE-2026-34515] = "not-applicable-platform: Vulnerability only affects applications running on Windows"
Signature · 1 line
2.35.6
#7 lore raw

PATCH 7/9 python3-aiohttp: fix CVE-2026-111063

In reply to Darsh Kelaiya -X (dkelaiya - E INFOCHIPS PRIVATE LIMITED at Cisco)

From: Darsh Kelaiya <[email protected]>

Backport the Secure shared-cookie fix [1] to aiohttp 3.9.5, as identified by [3]. Check Secure before the shared-cookie branch adds the cookie to the outgoing set.

Include the trusted-origin correction [2] so per-request cookies honor the session jar's treat_as_secure_origin policy. Keep the existing constructor defaults for the temporary cookie jar.

[1] https://github.com/aio-libs/aiohttp/commit/999c356d61e966faffa97b06ab0d0455226d36c5
[2] https://github.com/aio-libs/aiohttp/commit/95081f8a353be2873643ab6dd74904ca413e45e0
[3] https://github.com/aio-libs/aiohttp/security/advisories/GHSA-494j-54xm-rwp3

---
 .../python3-aiohttp/CVE-2026-111063_p1.patch  | 122 +++++++++
 .../python3-aiohttp/CVE-2026-111063_p2.patch  | 257 ++++++++++++++++++
 .../python/python3-aiohttp_3.9.5.bb           |   2 +
 3 files changed, 381 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111063_p1.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111063_p2.patch
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111063_p1.patch new file +122 -0
new file mode 100644
index 0000000000..417103af7a
@@ -0,0 +1,122 @@
+From 999c356d61e966faffa97b06ab0d0455226d36c5 Mon Sep 17 00:00:00 2001
+From: "patchback[bot]" <45432694+patchback[bot]@users.noreply.github.com>
+Date: Sun, 27 Sep 2026 21:27:34 +0100
+Subject: [PATCH] [PR #13830/e11d2836 backport][3.14] Fix secure shared cookie
+ (#13832)
+
+**This is a backport of PR #13830 as merged into master
+(e11d2836203a21bec59095498e578d37801027e7).**
+
+Co-authored-by: Sam Bull <[email protected]>
+
+CVE: CVE-2026-111063
+Upstream-Status: Backport [https://github.com/aio-libs/aiohttp/commit/999c356d61e966faffa97b06ab0d0455226d36c5]
+
+Backport Changes:
+- Guard the existing shared-cookie branch in filter_cookies();
+  aiohttp 3.9.5 does not have a morsel cache.
+- Omit the upstream cache regression because aiohttp 3.9.5 has no
+  morsel cache. This also drops its ordinary HTTPS delivery check.
+
+Signed-off-by: Darsh Kelaiya <[email protected]>
+---
+ CHANGES/13830.bugfix.rst        |  1 +
+ aiohttp/cookiejar.py            |  2 ++
+ docs/client_reference.rst       |  3 ++-
+ docs/spelling_wordlist.txt      |  1 +
+ tests/test_client_functional.py |  9 +++++++--
+ tests/test_cookiejar.py         | 10 ++++++++++
+ 6 files changed, 23 insertions(+), 3 deletions(-)
+ create mode 100644 CHANGES/13830.bugfix.rst
+
+diff --git a/CHANGES/13830.bugfix.rst b/CHANGES/13830.bugfix.rst
+new file mode 100644
+index 0000000..2a39769
+--- /dev/null
++++ b/CHANGES/13830.bugfix.rst
+@@ -0,0 +1 @@
++Fixed ``CookieJar.filter_cookies()`` sending shared cookies (cookies without a ``Domain`` attribute) marked ``Secure`` over unencrypted connections -- by :user:`Dreamsorcerer`.
+diff --git a/aiohttp/cookiejar.py b/aiohttp/cookiejar.py
+index cb5593c..59ace3a 100644
+--- a/aiohttp/cookiejar.py
++++ b/aiohttp/cookiejar.py
+@@ -398,6 +398,8 @@ class CookieJar(AbstractCookieJar):
+ 
+             # Send shared cookies
+             if not domain:
++                if is_not_secure and cookie["secure"]:
++                    continue
+                 filtered[name] = cookie.value
+                 continue
+ 
+diff --git a/docs/client_reference.rst b/docs/client_reference.rst
+index 49a2dfe..38b0833 100644
+--- a/docs/client_reference.rst
++++ b/docs/client_reference.rst
+@@ -1924,7 +1924,8 @@ Utilities
+       :param ~yarl.URL response_url: URL of response, ``None`` for *shared
+          cookies*.  Regular cookies are coupled with server's URL and
+          are sent only to this server, shared ones are sent in every
+-         client request.
++         client request (except that shared cookies marked ``Secure``
++         are only sent over encrypted connections).
+ 
+    .. method:: filter_cookies(request_url)
+ 
+diff --git a/docs/spelling_wordlist.txt b/docs/spelling_wordlist.txt
+index 3fb6d35..e0703d9 100644
+--- a/docs/spelling_wordlist.txt
++++ b/docs/spelling_wordlist.txt
+@@ -331,6 +331,7 @@ UI
+ un
+ unawaited
+ unclosed
++unencrypted
+ unhandled
+ unicode
+ unittest
+diff --git a/tests/test_client_functional.py b/tests/test_client_functional.py
+index d695638..e18348d 100644
+--- a/tests/test_client_functional.py
++++ b/tests/test_client_functional.py
+@@ -2290,12 +2290,17 @@ async def test_morsel_with_attributes(aiohttp_client) -> None:
+     c = http.cookies.Morsel()
+     c.set("test3", "456", "456")
+     c["httponly"] = True
+-    c["secure"] = True
+     c["max-age"] = 1000
+ 
++    # A Secure shared cookie must be withheld entirely: the test server
++    # is plain http, so it must not reach the handler at all.
++    c2: http.cookies.Morsel[str] = http.cookies.Morsel()
++    c2.set("test4", "789", "789")
++    c2["secure"] = True
++
+     app = web.Application()
+     app.router.add_get("/", handler)
+-    client = await aiohttp_client(app, cookies={"test2": c})
++    client = await aiohttp_client(app, cookies={"test2": c, "test4": c2})
+ 
+     async with client.get("/") as resp:
+         assert 200 == resp.status
+diff --git a/tests/test_cookiejar.py b/tests/test_cookiejar.py
+index d9cb5b2..8f852eb 100644
+--- a/tests/test_cookiejar.py
++++ b/tests/test_cookiejar.py
+@@ -1018,6 +1018,16 @@ async def test_save_load_json_roundtrip(
+     assert saved_cookies == loaded_cookies
+ 
+ 
++async def test_treat_as_secure_origin_sends_secure_shared_cookie() -> None:
++    endpoint = URL("http://127.0.0.1/")
++
++    jar = CookieJar(unsafe=True, treat_as_secure_origin=[endpoint])
++    jar.update_cookies(SimpleCookie("shared-secure-cookie=first; Secure;"))
++
++    filtered_cookies = jar.filter_cookies(request_url=endpoint)
++    assert "shared-secure-cookie" in filtered_cookies
++
++
+ async def test_save_load_json_preserves_host_only_scope(tmp_path: Path) -> None:
+     """Verify save/load keeps host-only cookies off subdomains."""
+     file_path = tmp_path / "host_only.json"
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-111063_p2.patch new file +257 -0

257 lines not on this page · raw message

meta-python/recipes-devtools/python/python3-aiohttp_3.9.5.bb +2 -0
index 16ec0a603b..f86a594669 100644
@@ -44,6 +44,8 @@ SRC_URI += "file://CVE-2024-52304.patch \
            file://CVE-2026-111066_p2.patch \
            file://CVE-2026-111065.patch \
            file://CVE-2026-111064.patch \
+           file://CVE-2026-111063_p1.patch \
+           file://CVE-2026-111063_p2.patch \
            "
 
 CVE_STATUS[CVE-2026-34515] = "not-applicable-platform: Vulnerability only affects applications running on Windows"
Signature · 1 line
2.35.6
#8 lore raw

PATCH 8/9 python3-aiohttp: fix CVE-2026-69243 and CVE-2026-128129

In reply to Darsh Kelaiya -X (dkelaiya - E INFOCHIPS PRIVATE LIMITED at Cisco)

From: Darsh Kelaiya <[email protected]>

Backport the upgrade framing fix [1] to aiohttp 3.9.5, as identified by [4]. Both HTTP parsers must finish reading a framed request body before handing back an upgraded connection.

Include the declined-upgrade follow-up [2] so the server returns to HTTP parsing at the correct request boundary. Include the tail limit and error-handling correction [3] so replay uses the normal HTTP error path and resumes reads after the buffer drains.
The tail limit also fixes CVE-2026-128129, documented in [5].

[1] https://github.com/aio-libs/aiohttp/commit/6ae358f0983c3f4d6f67692b2f8e65dc8e091c98
[2] https://github.com/aio-libs/aiohttp/commit/716c83d2b697e56fd74f95a1aa3a451fd2fb02e8
[3] https://github.com/aio-libs/aiohttp/commit/3d850ee9b92573c7e913821cbcb96005beb3f4df
[4] https://github.com/aio-libs/aiohttp/security/advisories/GHSA-mfx4-hv73-q22v
[5] https://github.com/aio-libs/aiohttp/security/advisories/GHSA-pw86-h8fm-j323

---
 .../CVE-2026-69243_CVE-2026-128129.patch      | 673 ++++++++++++++++++
 .../python3-aiohttp/CVE-2026-69243_p1.patch   | 300 ++++++++
 .../python3-aiohttp/CVE-2026-69243_p2.patch   |  93 +++
 .../python/python3-aiohttp_3.9.5.bb           |   3 +
 4 files changed, 1069 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-69243_CVE-2026-128129.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-69243_p1.patch
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-69243_p2.patch
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-69243_CVE-2026-128129.patch new file +673 -0
new file mode 100644
index 0000000..20de364
@@ -0,0 +1,673 @@
+From 3d850ee9b92573c7e913821cbcb96005beb3f4df 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)
+
+CVE: CVE-2026-69243 CVE-2026-128129
+Upstream-Status: Backport [https://github.com/aio-libs/aiohttp/commit/3d850ee9b92573c7e913821cbcb96005beb3f4df]
+
+Backport Changes:
+- Reuse Scarthgap's HTTP receive path to replay a declined upgrade
+  after the request body drains and queue the usual 400 on errors.
+- Check the tail limit on its first read, later reads and refills.
+  Leave reads paused while a queued parse error is awaiting its 400.
+- Adapt upstream flow-control tests to 3.9.5's _upgrade flag and
+  mock reader. Keep checks at and below the limit, with an empty
+  tail at a zero limit, and after a reader is set. Also check the
+  first tail fill and refills on the older HTTP receive path.
+- Exercise drain before replay with a real payload from a normal
+  POST in both parsers. Inject pending state and replay errors to
+  check request ordering, read resumption and the queued HTTP 400.
+- Adapt raw HTTP regressions to 3.9.5's server fixture. Check
+  Content-Length and chunked upgrades with a pipelined request on
+  one loopback connection using both parsers. Cover combined and
+  fragmented sends, with bodies read by the handler or left for
+  the protocol to finish before replaying the following request.
+- Keep client-driven WebSocket acceptance and connection reuse.
+  Use injected-state checks for isolated flow-control transitions.
+
+(cherry picked from commit c207cadb257e0959b192ffca0548eca8c71eb96a)
+Signed-off-by: Darsh Kelaiya <[email protected]>
+---
+ CHANGES/13501.bugfix.rst              |    1 
+ aiohttp/web_protocol.py               |   56 ++++----
+ tests/test_web_protocol.py            |  238 +++++++++++++++++++++++++++++++++
+ tests/test_web_upgrade_integration.py |  236 +++++++++++++++++++++++++++++++++
+ 4 files changed, 504 insertions(+), 27 deletions(-)
+ create mode 100644 CHANGES/13501.bugfix.rst
+ create mode 100644 tests/test_web_upgrade_integration.py
+
+diff --git a/CHANGES/13501.bugfix.rst b/CHANGES/13501.bugfix.rst
+new file mode 100644
+index 0000000..4c45225
+--- /dev/null
++++ b/CHANGES/13501.bugfix.rst
+@@ -0,0 +1 @@
++Fixed a limit on message tail after an upgrade request -- by :user:`Dreamsorcerer`.
+diff --git a/aiohttp/web_protocol.py b/aiohttp/web_protocol.py
+index 2a48feb..2c2c8ca 100644
+--- a/aiohttp/web_protocol.py
++++ b/aiohttp/web_protocol.py
+@@ -156,6 +156,7 @@ class RequestHandler(BaseProtocol):
+         "_msg_queue_resume_size",
+         "_msg_queue_paused",
+         "_message_tail",
++        "_read_bufsize",
+         "_waiter",
+         "_task_handler",
+         "_upgrade",
+@@ -196,6 +197,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
+         # Set before super().__init__ so _reading_paused_for_msg_queue() is safe
+         # if BaseProtocol ever triggers a resume during init.
+         self._msg_queue_paused = False
+@@ -365,6 +367,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
+ 
+@@ -393,21 +398,18 @@ class RequestHandler(BaseProtocol):
+                 # don't set result twice
+                 waiter.set_result(None)
+ 
+-            # Queue full: pause the transport (the parser already stopped
+-            # emitting). start() resumes as it drains the queue.
+-            if (
+-                not self._msg_queue_paused
+-                and len(self._messages) >= self._max_msg_queue_size
+-            ):
+-                self._pause_msg_queue_reading()
+-
+             self._upgrade = upgraded
+             if upgraded and tail:
+                 self._message_tail = tail
+ 
++            if not self._msg_queue_paused and self._msg_queue_needs_pause():
++                self._pause_msg_queue_reading()
++
+         # 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 self._msg_queue_needs_pause():
++                self._pause_msg_queue_reading()
+ 
+         # feed payload
+         elif data:
+@@ -418,6 +420,15 @@ class RequestHandler(BaseProtocol):
+     def _reading_paused_for_msg_queue(self) -> bool:
+         return self._msg_queue_paused
+ 
++    def _msg_queue_needs_pause(self) -> bool:
++        # Leave reads paused until a queued parse error sends its 400 response.
++        if self._messages and isinstance(self._messages[-1][0], _ErrInfo):
++            return True
++        # An empty tail must allow reads to resume even with read_bufsize=0.
++        return len(self._messages) >= self._max_msg_queue_size or (
++            bool(self._message_tail) and len(self._message_tail) >= self._read_bufsize
++        )
++
+     def _pause_msg_queue_reading(self) -> None:
+         self._msg_queue_paused = True
+         if self.transport is not None:
+@@ -429,12 +440,15 @@ class RequestHandler(BaseProtocol):
+                 pass
+ 
+     def _resume_msg_queue_reading(self) -> None:
++        if self._msg_queue_needs_pause():
++            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
+             # transport; only resume below once it stayed under the limit.
+             self.data_received(b"")
+-            if len(self._messages) >= self._max_msg_queue_size:
++            if self._msg_queue_needs_pause():
+                 return
+         self._msg_queue_paused = False
+         if not self._reading_paused and self.transport is not None:
+@@ -582,6 +596,7 @@ class RequestHandler(BaseProtocol):
+                 self._request_parser.message_consumed()
+             if (
+                 self._msg_queue_paused
++                and not isinstance(message, _ErrInfo)
+                 and len(self._messages) <= self._msg_queue_resume_size
+             ):
+                 self._resume_msg_queue_reading()
+@@ -655,24 +670,11 @@ class RequestHandler(BaseProtocol):
+                     self._request_parser.set_upgraded(False)
+                     self._upgrade = False
+                     if self._message_tail:
+-                        messages, upgraded, tail = self._request_parser.feed_data(
+-                            self._message_tail
+-                        )
+-                        # 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
+-                        ):
+-                            self._pause_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
++                        tail, self._message_tail = self._message_tail, b""
++                        # Reuse HTTP parsing, including its 400 error handling.
++                        self.data_received(tail)
++                    if self._msg_queue_paused:
++                        self._resume_msg_queue_reading()
+ 
+                 set_exception(payload, PayloadAccessError())
+ 
+diff --git a/tests/test_web_protocol.py b/tests/test_web_protocol.py
+index 084b72edba0301dc17fc951f114b3751afae0934..fb0dfc92fcc6f0c854d4903fa01a2dba567082f1 100644
+--- a/tests/test_web_protocol.py
++++ b/tests/test_web_protocol.py
+@@ -4,7 +4,11 @@ from unittest import mock
+ 
+ import pytest
+ 
++from aiohttp.http_exceptions import HttpProcessingError
++from aiohttp.http_parser import HttpRequestParser, HttpRequestParserPy
++from aiohttp.streams import StreamReader
+ from aiohttp.web_protocol import RequestHandler
++from aiohttp.web_response import Response, StreamResponse
+ from aiohttp.web_server import Server
+ 
+ 
+@@ -141,6 +145,240 @@ 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() or declined-upgrade replay, 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,
++) -> 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
++
++    reader = mock.Mock()
++    handler.set_parser(reader)
++
++    reader.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()
++
++
[email protected](
++    "chunks", [(b"tail", b""), (b"ta", b"il")], ids=["parser-return", "later-read"]
++)
++def test_received_upgrade_tail_pauses_at_read_limit(
++    loop: asyncio.AbstractEventLoop,
++    dummy_manager: Server,
++    chunks: tuple[bytes, bytes],
++) -> None:
++    handler = RequestHandler(dummy_manager, loop=loop, read_bufsize=4)
++    transport = mock.Mock(spec=asyncio.Transport)
++    handler.transport = transport
++    parser = mock.Mock()
++    handler._request_parser = parser
++    initial, later = chunks
++    parser.feed_data.return_value = ((), True, initial)
++
++    handler.data_received(b"event")
++    if later:
++        transport.pause_reading.assert_not_called()
++        handler.data_received(later)
++
++    parser.feed_data.assert_called_once_with(b"event")
++    assert handler._message_tail == b"tail"
++    transport.pause_reading.assert_called_once_with()
++
++
++def test_refill_keeps_reads_paused_for_full_upgrade_tail(
++    loop: asyncio.AbstractEventLoop,
++    dummy_manager: Server,
++) -> None:
++    handler = RequestHandler(dummy_manager, loop=loop, read_bufsize=4)
++    transport = mock.Mock(spec=asyncio.Transport)
++    handler.transport = transport
++    handler._msg_queue_paused = True
++    parser = mock.Mock()
++    handler._request_parser = parser
++    parser.feed_data.return_value = ((), True, b"tail")
++
++    handler._resume_msg_queue_reading()
++
++    parser.feed_data.assert_called_once_with(b"")
++    assert handler._message_tail == b"tail"
++    assert handler._msg_queue_paused
++    transport.resume_reading.assert_not_called()
++
++
[email protected]("replay_fails", [False, True])
[email protected](
++    "request_parser_cls",
++    tuple(dict.fromkeys((HttpRequestParserPy, HttpRequestParser))),
++    ids=lambda parser_cls: "python" if parser_cls is HttpRequestParserPy else "c",
++)
++async def test_declined_upgrade_replays_after_body_drains(
++    loop: asyncio.AbstractEventLoop,
++    dummy_manager: Server,
++    replay_fails: bool,
++    request_parser_cls: type[HttpRequestParser],
++    monkeypatch: pytest.MonkeyPatch,
++) -> None:
++    events: list[str] = []
++
++    async def respond(_request: object) -> Response:
++        return Response()
++
++    dummy_manager.request_handler = respond
++    dummy_manager.requests_count = 0
++    request = mock.Mock()
++    request.writer.output_size = 0
++    dummy_manager.request_factory.return_value = request
++    handler = RequestHandler(dummy_manager, loop=loop, read_bufsize=4)
++    transport = mock.Mock(spec=asyncio.Transport)
++    handler.transport = transport
++    http_parser = request_parser_cls(handler, loop, 2**16)
++    parser = mock.Mock(wraps=http_parser)
++    handler._request_parser = parser
++    headers = (
++        b"POST /submit HTTP/1.1\r\n"
++        b"Host: example.test\r\n"
++        b"Content-Length: 4\r\n\r\n"
++    )
++    messages, upgraded, tail = http_parser.feed_data(headers)
++    [(message, body)] = messages
++    assert message.method == "POST"
++    assert not upgraded and not tail and not body.is_eof()
++
++    readany = StreamReader.readany
++
++    async def drain(payload: StreamReader) -> bytes:
++        assert payload is body
++        assert not body.is_eof()
++        # Supply the remaining bytes of the ordinary HTTP body when the
++        # protocol starts draining it.
++        messages, upgraded, tail = http_parser.feed_data(b"body")
++        assert not messages and not upgraded and not tail
++        data = await readany(payload)
++        assert data == b"body"
++        events.append("drain")
++        return data
++
++    monkeypatch.setattr(StreamReader, "readany", drain)
++
++    def receive(data: bytes) -> tuple[tuple[tuple[object, object], ...], bool, bytes]:
++        if data == b"event":
++            # Seed the upgrade state separately from the real HTTP parsing.
++            return ((message, body),), True, b"tail"
++        if data == b"tail":
++            events.append("replay")
++            assert body.at_eof()
++            if replay_fails:
++                raise HttpProcessingError(message="mock failure")
++            messages, upgraded, tail = http_parser.feed_data(
++                b"GET /next HTTP/1.1\r\nHost: example.test\r\n\r\n"
++            )
++            [(next_message, next_body)] = messages
++            assert next_message.path == "/next"
++            assert not upgraded and not tail and next_body.at_eof()
++            return tuple(messages), upgraded, tail
++        assert data == b""
++        return (), False, b""
++
++    parser.feed_data.side_effect = receive
++    handler.data_received(b"event")
++
++    async def finish(
++        _handler: RequestHandler,
++        _request: object,
++        response: StreamResponse,
++        _start: float,
++    ) -> bool:
++        response._keep_alive = not events
++        events.append(f"status {response.status}")
++        return False
++
++    with mock.patch.object(RequestHandler, "finish_response", new=finish):
++        task = handler._task_handler = loop.create_task(handler.start())
++        try:
++            await asyncio.wait_for(task, timeout=2)
++        finally:
++            if handler._keepalive_handle is not None:
++                handler._keepalive_handle.cancel()
++
++    assert not handler._messages
++    transport.pause_reading.assert_called_once_with()
++    parser.set_upgraded.assert_called_once_with(False)
++    expected_status = 400 if replay_fails else 200
++    assert events == ["status 200", "drain", "replay", f"status {expected_status}"]
++    if replay_fails:
++        transport.resume_reading.assert_not_called()
++    else:
++        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_upgrade_integration.py b/tests/test_web_upgrade_integration.py
+new file mode 100644
+index 0000000000000000000000000000000000000000..7a4798a05c2fc23bb841edcab752a8459e8166f6
+--- /dev/null
++++ b/tests/test_web_upgrade_integration.py
+@@ -0,0 +1,236 @@
++from asyncio import Event, Transport, open_connection, wait_for
++from base64 import b64encode
++from typing import List, Optional
++
++import pytest
++
++from aiohttp import ClientTimeout, hdrs, web, web_protocol
++from aiohttp.http_parser import HttpRequestParser, HttpRequestParserPy
++from aiohttp.pytest_plugin import AiohttpClient, AiohttpServer
++
++
[email protected]("framing", ["empty", "content-length", "chunked"])
++async def test_declined_websocket_upgrade_keeps_http_connection(
++    aiohttp_client: AiohttpClient, framing: str,
++) -> None:
++    transports: List[Optional[Transport]] = []
++    upgrade_pending_at_prepare: List[bool] = []
++    body = b"example body" if framing != "empty" else b""
++
++    async def decline(request: web.Request) -> web.Response:
++        transports.append(request.transport)
++        assert await request.read() == body
++        if framing == "content-length":
++            assert request.content_length == len(body)
++        elif framing == "chunked":
++            assert request.headers[hdrs.TRANSFER_ENCODING] == "chunked"
++        return web.Response(text="upgrade declined")
++
++    async def normal(request: web.Request) -> web.Response:
++        transports.append(request.transport)
++        return web.Response(text="http response")
++
++    async def record_upgrade_state(
++        request: web.Request, response: web.StreamResponse
++    ) -> None:
++        if request.path == "/upgrade":
++            upgrade_pending_at_prepare.append(request.protocol._upgrade)
++
++    app = web.Application()
++    app.router.add_get("/upgrade", decline)
++    app.router.add_get("/", normal)
++    app.on_response_prepare.append(record_upgrade_state)
++    client = await aiohttp_client(app, timeout=ClientTimeout(total=5))
++
++    headers = {
++        hdrs.CONNECTION: "Upgrade",
++        hdrs.UPGRADE: "websocket",
++        hdrs.SEC_WEBSOCKET_KEY: b64encode(b"test upgrade key").decode("ascii"),
++        hdrs.SEC_WEBSOCKET_VERSION: "13",
++    }
++    async with client.get(
++        "/upgrade",
++        headers=headers,
++        data=body or None,
++        chunked=True if framing == "chunked" else None,
++    ) as response:
++        assert response.status == 200
++        assert await response.text() == "upgrade declined"
++
++    assert upgrade_pending_at_prepare == [True]
++
++    async with client.get("/") as response:
++        assert response.status == 200
++        assert await response.text() == "http response"
++
++    assert len(transports) == 2
++    assert transports[0] is not None
++    assert transports[0] is transports[1]
++
++
++async def test_accepted_websocket_upgrade_delivers_message(
++    aiohttp_client: AiohttpClient,
++) -> None:
++    async def upgrade(request: web.Request) -> web.WebSocketResponse:
++        websocket = web.WebSocketResponse()
++        await websocket.prepare(request)
++        await websocket.send_str("ready")
++        return websocket
++
++    app = web.Application()
++    app.router.add_get("/upgrade", upgrade)
++    client = await aiohttp_client(app, timeout=ClientTimeout(total=5))
++
++    async with client.ws_connect("/upgrade") as websocket:
++        assert await websocket.receive_str(timeout=5) == "ready"
++
++
[email protected](
++    "parser_class",
++    tuple(dict.fromkeys((HttpRequestParserPy, HttpRequestParser))),
++    ids=lambda cls: "python" if cls is HttpRequestParserPy else "c",
++)
[email protected]("chunked", [False, True], ids=["content-length", "chunked"])
[email protected]("fragmented", [False, True], ids=["combined", "split-body"])
[email protected]("read_body", [False, True], ids=["unread-body", "read-body"])
++async def test_body_upgrade_and_pipelined_request_on_loopback(
++    aiohttp_server: AiohttpServer,
++    monkeypatch: pytest.MonkeyPatch,
++    parser_class,
++    chunked: bool,
++    fragmented: bool,
++    read_body: bool,
++) -> None:
++    monkeypatch.setattr(web_protocol, "HttpRequestParser", parser_class)
++    body = b"request-body\r\n"
++    started = Event()
++    following_request = Event()
++    requests: List[web.Request] = []
++
++    async def decline(request: web.Request) -> web.Response:
++        assert request.headers[hdrs.UPGRADE] == "websocket"
++        assert isinstance(request.protocol._request_parser, parser_class)
++        requests.append(request)
++        started.set()
++        if read_body:
++            assert await request.read() == body
++        return web.Response(body=b"declined")
++
++    async def next_request(request: web.Request) -> web.Response:
++        assert len(requests) == 1
++        assert request.transport is requests[0].transport
++        assert requests[0].content.is_eof()
++        requests.append(request)
++        following_request.set()
++        return web.Response(body=b"next response")
++
++    app = web.Application()
++    app.router.add_get("/upgrade", decline)
++    app.router.add_get("/next", next_request)
++    server = await aiohttp_server(app, read_bufsize=32)
++    reader, writer = await open_connection(server.host, server.port)
++    if chunked:
++        framing = b"Transfer-Encoding: chunked\r\n"
++        wire_body = b"%x\r\n%s\r\n0\r\n\r\n" % (len(body), body)
++    else:
++        framing = b"Content-Length: %d\r\n" % len(body)
++        wire_body = body
++    headers = (
++        b"GET /upgrade HTTP/1.1\r\n"
++        b"Host: localhost\r\n"
++        b"Connection: Upgrade\r\n"
++        b"Upgrade: websocket\r\n"
++        b"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
++        b"Sec-WebSocket-Version: 13\r\n"
++        + framing
++        + b"\r\n"
++    )
++    tail = b"GET /next HTTP/1.1\r\nHost: localhost\r\n\r\n"
++
++    async def read_response(expected: bytes) -> None:
++        response_headers = await reader.readuntil(b"\r\n\r\n")
++        assert response_headers.startswith(b"HTTP/1.1 200 ")
++        assert b"content-length: " + str(len(expected)).encode() in response_headers.lower()
++        assert await reader.readexactly(len(expected)) == expected
++
++    async def exchange() -> None:
++        if fragmented:
++            writer.write(headers + wire_body[:-1])
++            await writer.drain()
++            await started.wait()
++            assert not requests[0].content.is_eof()
++            assert not following_request.is_set()
++            writer.write(wire_body[-1:] + tail)
++        else:
++            writer.write(headers + wire_body + tail)
++        await writer.drain()
++        await read_response(b"declined")
++        await read_response(b"next response")
++        assert following_request.is_set()
++        assert [request.path for request in requests] == ["/upgrade", "/next"]
++
++    try:
++        await wait_for(exchange(), timeout=5)
++    finally:
++        writer.close()
++        await writer.wait_closed()
++
++
++async def test_injected_upgrade_tail_replays_and_resumes_reads(
++    aiohttp_server: AiohttpServer,
++) -> None:
++    tail = b"GET /replay HTTP/1.1\r\nHost: localhost\r\n\r\n"
++    transports: List[Transport] = []
++
++    async def seed_pending_state(request: web.Request) -> web.Response:
++        transport = request.transport
++        assert transport is not None
++        transports.append(transport)
++        protocol = request.protocol
++        assert transport.is_reading()
++        assert protocol._message_tail == b""
++
++        # Seed the pending flag after the ordinary GET reached its handler.
++        # Pass a complete request to the receive callback without a socket send.
++        protocol._upgrade = True
++        protocol.data_received(tail)
++        assert protocol._message_tail == tail
++        assert not transport.is_reading()
++        return web.Response(body=b"first")
++
++    async def replay(request: web.Request) -> web.Response:
++        assert request.transport is transports[0]
++        assert transports[0].is_reading()
++        assert not request.protocol._message_tail
++        return web.Response(body=b"replayed")
++
++    async def normal(request: web.Request) -> web.Response:
++        assert request.transport is transports[0]
++        return web.Response(body=b"normal")
++
++    app = web.Application()
++    app.router.add_get("/seed", seed_pending_state)
++    app.router.add_get("/replay", replay)
++    app.router.add_get("/", normal)
++    server = await aiohttp_server(app, read_bufsize=len(tail))
++    reader, writer = await open_connection(server.host, server.port)
++
++    async def read_response(body: bytes) -> None:
++        headers = await reader.readuntil(b"\r\n\r\n")
++        assert headers.startswith(b"HTTP/1.1 200 ")
++        assert await reader.readexactly(len(body)) == body
++
++    async def exchange() -> None:
++        writer.write(b"GET /seed HTTP/1.1\r\nHost: localhost\r\n\r\n")
++        await writer.drain()
++        await read_response(b"first")
++        await read_response(b"replayed")
++        writer.write(b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n")
++        await writer.drain()
++        await read_response(b"normal")
++
++    try:
++        await wait_for(exchange(), timeout=5)
++    finally:
++        writer.close()
++        await writer.wait_closed()
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-69243_p1.patch new file +300 -0

300 lines not on this page · raw message

meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-69243_p2.patch new file +93 -0

93 lines not on this page · raw message

meta-python/recipes-devtools/python/python3-aiohttp_3.9.5.bb +3 -0
index f86a594..bbd7b27 100644
@@ -46,6 +46,9 @@ SRC_URI += "file://CVE-2024-52304.patch \
            file://CVE-2026-111064.patch \
            file://CVE-2026-111063_p1.patch \
            file://CVE-2026-111063_p2.patch \
+           file://CVE-2026-69243_p1.patch \
+           file://CVE-2026-69243_p2.patch \
+           file://CVE-2026-69243_CVE-2026-128129.patch \
            "
 
 CVE_STATUS[CVE-2026-34515] = "not-applicable-platform: Vulnerability only affects applications running on Windows"
Signature · 1 line
2.35.6
#9 lore raw

PATCH 9/9 python3-aiohttp: fix CVE-2026-69244

In reply to Darsh Kelaiya -X (dkelaiya - E INFOCHIPS PRIVATE LIMITED at Cisco)

From: Darsh Kelaiya <[email protected]>

Backport the bounded parser diagnostic fix [1] to aiohttp 3.9.5, as identified by [2]. Build error snippets from bounded slices of the current input buffer. The recipe regenerates the C parser from the patched Cython source during configuration.

[1] https://github.com/aio-libs/aiohttp/commit/49f65d54150397892f7bcc4aae887767d51c322d
[2] https://github.com/aio-libs/aiohttp/security/advisories/GHSA-cq5v-8q36-5273

---
 .../python3-aiohttp/CVE-2026-69244.patch      | 248 ++++++++++++++++++
 .../python/python3-aiohttp_3.9.5.bb           |   1 +
 2 files changed, 249 insertions(+)
 create mode 100644 meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-69244.patch
meta-python/recipes-devtools/python/python3-aiohttp/CVE-2026-69244.patch new file +248 -0
new file mode 100644
index 0000000..73dfafa
@@ -0,0 +1,248 @@
+From 49f65d54150397892f7bcc4aae887767d51c322d Mon Sep 17 00:00:00 2001
+From: "J. Nick Koston" <[email protected]>
+Date: Wed, 22 Jul 2026 11:14:50 -1000
+Subject: [PATCH] [PR #13222/f4866933 backport][3.14] Build C parser error
+ message from bounded buffer slice (#13223)
+
+CVE: CVE-2026-69244
+Upstream-Status: Backport [https://github.com/aio-libs/aiohttp/commit/49f65d54150397892f7bcc4aae887767d51c322d]
+
+Backport Changes:
+- Keep the bounded slice and caret in a private Cython helper so the
+  diagnostic can be tested with ordinary byte strings.
+- Adapt upstream malformed-input tests to a fresh C parser with an
+  invalid status code and check the rejected line in its diagnostic.
+  Check empty, start, middle-line and end-of-buffer offsets in the
+  private helper.
+- Exercise the compiled parser with a valid response and verify its
+  header-limit exception on the same response under a lower limit.
+  This covers the header callback error path.
+- Force a native llhttp error on a valid response in a Linux child
+  process to exercise the bounded fallback diagnostic. Pin the child
+  import to the same compiled parser loaded by the parent.
+
+Signed-off-by: Darsh Kelaiya <[email protected]>
+---
+ CHANGES/13222.bugfix.rst           |    1 
+ aiohttp/_http_parser.pyx           |   17 +++-
+ tests/llhttp_diagnostic_fault.c    |   10 ++
+ tests/test_c_parser_diagnostics.py |  150 ++++++++++++++++++++++++++++++++++++
+ 4 files changed, 172 insertions(+), 6 deletions(-)
+ create mode 100644 CHANGES/13222.bugfix.rst
+ create mode 100644 tests/llhttp_diagnostic_fault.c
+ create mode 100644 tests/test_c_parser_diagnostics.py
+
+diff --git a/CHANGES/13222.bugfix.rst b/CHANGES/13222.bugfix.rst
+new file mode 100644
+index 0000000000000000000000000000000000000000..dcdda17051ca720c81703ec846e5be06d17025f8
+--- /dev/null
++++ b/CHANGES/13222.bugfix.rst
+@@ -0,0 +1 @@
++Fixed error message construction in the C HTTP parser -- by :user:`bdraco`.
+diff --git a/aiohttp/_http_parser.pyx b/aiohttp/_http_parser.pyx
+index 6f5975b7833643f1c4f3deb0efd80afaf035cdea..3c4506e5bc5b5ca95cc51790f16f31de94456df3 100644
+--- a/aiohttp/_http_parser.pyx
++++ b/aiohttp/_http_parser.pyx
+@@ -634,12 +634,9 @@ cdef class HttpParser:
+                     ex = self._last_error
+                     self._last_error = None
+                 else:
+-                    after = cparser.llhttp_get_error_pos(self._cparser)
+-                    before = data[:after - base]
+-                    after_b = after.split(b"\r\n", 1)[0]
+-                    before = before.rsplit(b"\r\n", 1)[-1]
+-                    data = before + after_b
+-                    pointer = " " * (len(repr(before))-1) + "^"
++                    error_pos = cparser.llhttp_get_error_pos(self._cparser)
++                    error_off = error_pos - base
++                    data, pointer = _format_error_context(data, error_off)
+                     ex = parser_error_from_errno(self._cparser, data, pointer)
+                 self._payload = None
+                 raise ex
+@@ -929,6 +926,14 @@ cdef int cb_on_chunk_complete(cparser.llhttp_t* parser) except -1:
+         return 0
+ 
+ 
++def _format_error_context(bytes data not None, Py_ssize_t error_off):
++    """Return the bounded diagnostic line and the pointer to the error."""
++    before = data[:error_off].rsplit(b"\r\n", 1)[-1]
++    after = data[error_off:].split(b"\r\n", 1)[0]
++    pointer = " " * (len(repr(before)) - 1) + "^"
++    return before + after, pointer
++
++
+ cdef parser_error_from_errno(cparser.llhttp_t* parser, data, pointer):
+     cdef cparser.llhttp_errno_t errno = cparser.llhttp_get_errno(parser)
+     cdef bytes desc = cparser.llhttp_get_error_reason(parser)
+diff --git a/tests/llhttp_diagnostic_fault.c b/tests/llhttp_diagnostic_fault.c
+new file mode 100644
+index 0000000000000000000000000000000000000000..44a63c4f866b2246fddc5f78300541ab6978f691
+--- /dev/null
++++ b/tests/llhttp_diagnostic_fault.c
+@@ -0,0 +1,10 @@
++#include "llhttp.h"
++
++/* Fault injection for the isolated Linux parser diagnostic test. */
++llhttp_errno_t llhttp_execute(llhttp_t *parser, const char *data, size_t len)
++{
++    parser->error = HPE_USER;
++    parser->reason = "Injected diagnostic test error";
++    parser->error_pos = data + (len > 2 ? 2 : 0);
++    return HPE_USER;
++}
+diff --git a/tests/test_c_parser_diagnostics.py b/tests/test_c_parser_diagnostics.py
+new file mode 100644
+index 0000000000000000000000000000000000000000..555c25d64bdf365e8caa9e9437eff40b3dde892a
+--- /dev/null
++++ b/tests/test_c_parser_diagnostics.py
+@@ -0,0 +1,150 @@
++import asyncio
++import os
++import shutil
++import subprocess
++import sys
++from asyncio import AbstractEventLoop
++from pathlib import Path
++
++import pytest
++
++from aiohttp.base_protocol import BaseProtocol
++from aiohttp.http_exceptions import BadHttpMessage, BadStatusLine, LineTooLong
++
++
++_RESPONSE = (
++    b"HTTP/1.1 200 OK\r\n"
++    b"Content-Length: 5\r\n"
++    b"X-Sample: example header value\r\n"
++    b"\r\n"
++    b"hello"
++)
++
++
[email protected](
++    ("data", "offset", "expected"),
++    [
++        (b"", 0, (b"", "  ^")),
++        (b"sample", 0, (b"sample", "  ^")),
++        (b"north\r\ncenter\r\nsouth", 10, (b"center", "     ^")),
++        (b"north\r\ncenter\r\nsouth", 20, (b"south", "       ^")),
++        (b"end\r\n", 5, (b"", "  ^")),
++    ],
++    ids=["empty", "start", "middle-line", "buffer-end", "empty-last-line"],
++)
++def test_c_parser_error_context(
++    data: bytes, offset: int, expected: tuple[bytes, str]
++) -> None:
++    parser = pytest.importorskip("aiohttp._http_parser")
++    assert parser._format_error_context(data, offset) == expected
++
++
++def test_c_parser_reads_complete_response(loop: AbstractEventLoop) -> None:
++    parser_module = pytest.importorskip("aiohttp._http_parser")
++    parser = parser_module.HttpResponseParser(BaseProtocol(loop), loop, 2**16)
++
++    messages, upgraded, tail = parser.feed_data(_RESPONSE)
++
++    (message, payload), = messages
++    assert message.code == 200
++    assert message.headers["X-Sample"] == "example header value"
++    assert not upgraded
++    assert tail == b""
++    assert payload.read_nowait() == b"hello"
++    assert payload.at_eof()
++
++
++def test_c_parser_enforces_response_header_limit(loop: AbstractEventLoop) -> None:
++    parser_module = pytest.importorskip("aiohttp._http_parser")
++    parser = parser_module.HttpResponseParser(
++        BaseProtocol(loop), loop, 2**16, max_field_size=20
++    )
++
++    with pytest.raises(LineTooLong, match="Got more than 20 bytes"):
++        parser.feed_data(_RESPONSE)
++
++
++def test_c_parser_rejects_invalid_status_line(loop: AbstractEventLoop) -> None:
++    parser_module = pytest.importorskip("aiohttp._http_parser")
++    parser = parser_module.HttpResponseParser(BaseProtocol(loop), loop, 2**16)
++
++    with pytest.raises(BadStatusLine) as caught:
++        parser.feed_data(b"HTTP/1.1 ABC Invalid\r\n\r\n")
++
++    assert caught.value.code == 400
++    assert "HTTP/1.1 ABC Invalid" in caught.value.message
++
++
++def _assert_c_parser_fallback_diagnostic(expected_parser: Path) -> None:
++    from aiohttp import _http_parser
++
++    assert Path(_http_parser.__file__).resolve() == expected_parser
++    captured: list[tuple[bytes, int]] = []
++    format_error_context = _http_parser._format_error_context
++
++    def record_context(data: bytes, offset: int) -> tuple[bytes, str]:
++        captured.append((data, offset))
++        return format_error_context(data, offset)
++
++    _http_parser._format_error_context = record_context
++    loop = asyncio.new_event_loop()
++    try:
++        parser = _http_parser.HttpResponseParser(BaseProtocol(loop), loop, 2**16)
++        with pytest.raises(BadHttpMessage) as caught:
++            parser.feed_data(_RESPONSE)
++    finally:
++        loop.close()
++
++    assert captured == [(_RESPONSE, 2)]
++    assert caught.value.message == (
++        "Injected diagnostic test error:\n\n  b'HTTP/1.1 200 OK'\n      ^"
++    )
++
++
[email protected]
[email protected](sys.platform != "linux", reason="requires Linux LD_PRELOAD")
++def test_c_parser_formats_injected_llhttp_error(tmp_path: Path) -> None:
++    parser = pytest.importorskip("aiohttp._http_parser")
++    parser_path = Path(parser.__file__).resolve()
++    compiler = shutil.which("cc")
++    if compiler is None:
++        pytest.skip("requires a C compiler for the test-only llhttp shim")
++
++    test_file = Path(__file__).resolve()
++    llhttp_include = test_file.parent.parent / "vendor" / "llhttp" / "build"
++    if not (llhttp_include / "llhttp.h").is_file():
++        pytest.skip("requires the bundled llhttp headers")
++
++    shim = tmp_path / "llhttp_diagnostic_fault.so"
++    subprocess.run(
++        [
++            compiler,
++            "-shared",
++            "-fPIC",
++            "-I", str(llhttp_include),
++            str(test_file.with_name("llhttp_diagnostic_fault.c")),
++            "-o", str(shim),
++        ],
++        check=True,
++        timeout=15,
++    )
++    # Restrict symbol interposition to the subprocess that sends one valid
++    # response. The shim causes feed_data() to take the native fallback path.
++    env = dict(os.environ)
++    preload = env.get("LD_PRELOAD")
++    env["LD_PRELOAD"] = f"{preload}:{shim}" if preload else str(shim)
++    child = (
++        "import runpy, sys\n"
++        "from pathlib import Path\n"
++        "parser_path = Path(sys.argv[2])\n"
++        "sys.path.insert(0, str(parser_path.parent.parent))\n"
++        "namespace = runpy.run_path(sys.argv[1])\n"
++        "namespace['_assert_c_parser_fallback_diagnostic'](parser_path)\n"
++    )
++    subprocess.run(
++        [sys.executable, "-c", child, str(test_file), str(parser_path)],
++        cwd=test_file.parent.parent,
++        env=env,
++        check=True,
++        timeout=15,
++    )
meta-python/recipes-devtools/python/python3-aiohttp_3.9.5.bb +1 -0
index bbd7b27..e880c61 100644
@@ -49,6 +49,7 @@ SRC_URI += "file://CVE-2024-52304.patch \
            file://CVE-2026-69243_p1.patch \
            file://CVE-2026-69243_p2.patch \
            file://CVE-2026-69243_CVE-2026-128129.patch \
+           file://CVE-2026-69244.patch \
            "
 
 CVE_STATUS[CVE-2026-34515] = "not-applicable-platform: Vulnerability only affects applications running on Windows"
Signature · 1 line
2.35.6