From 1b592a46fde695536c859b0fa735d84f9bc15326 Mon Sep 17 00:00:00 2001 From: Emad Date: Mon, 26 Oct 2026 01:12:31 +0200 Subject: [PATCH 1/4] Handle satisfiable multi-range requests in FileResponse --- CHANGES/14124.bugfix.rst | 2 + CONTRIBUTORS.txt | 1 + aiohttp/web_fileresponse.py | 38 ++++++++++++- docs/web_reference.rst | 4 ++ tests/test_web_sendfile_functional.py | 82 +++++++++++++++++++++++++++ 5 files changed, 124 insertions(+), 3 deletions(-) create mode 100644 CHANGES/14124.bugfix.rst diff --git a/CHANGES/14124.bugfix.rst b/CHANGES/14124.bugfix.rst new file mode 100644 index 00000000000..0d0df3a41a3 --- /dev/null +++ b/CHANGES/14124.bugfix.rst @@ -0,0 +1,2 @@ +Fixed :class:`aiohttp.web.FileResponse` returning HTTP 416 for valid, satisfiable +requests for multiple byte ranges by serving the entire file instead -- by :user:`emadleo13`. diff --git a/CONTRIBUTORS.txt b/CONTRIBUTORS.txt index 494ab59ebda..6140fffe03a 100644 --- a/CONTRIBUTORS.txt +++ b/CONTRIBUTORS.txt @@ -135,6 +135,7 @@ Earle Lowe Eduard Iskandarov Eli Ribble Elizabeth Leddy +Emad Bashari Emil Melnikov Enrique Saez Eric Sheng diff --git a/aiohttp/web_fileresponse.py b/aiohttp/web_fileresponse.py index e30bff091e6..7dd61d52790 100644 --- a/aiohttp/web_fileresponse.py +++ b/aiohttp/web_fileresponse.py @@ -3,6 +3,7 @@ import math import os import pathlib +import re import sys from collections.abc import Awaitable, Callable from contextlib import suppress @@ -160,6 +161,30 @@ def _etag_match(etag_value: str, etags: tuple[ETag, ...], *, weak: bool) -> bool etag.value == etag_value for etag in etags if weak or not etag.is_weak ) + @staticmethod + def _is_satisfiable_multi_range(range_header: str, file_size: int) -> bool: + unit, _, ranges = range_header.partition("=") + if unit.lower() != "bytes" or "," not in ranges: + return False + + satisfiable = False + for byte_range in ranges.split(","): + match = re.fullmatch(r"([0-9]*)-([0-9]*)", byte_range.strip(" \t")) + if match is None: + return False + first, last = match.groups() + if first: + start = int(first) + if last and start > int(last): + return False + satisfiable |= start < file_size + elif last: + satisfiable |= int(last) > 0 and file_size > 0 + else: + return False + + return satisfiable + async def _not_modified( self, request: "BaseRequest", etag_value: str, last_modified: float ) -> AbstractStreamWriter | None: @@ -310,6 +335,7 @@ async def _prepare_open_file( file_mtime: float = st.st_mtime count: int = file_size start: int | None = None + end: int | None = None etag_value = f"{st.st_mtime_ns:x}-{st.st_size:x}" # https://www.rfc-editor.org/info/rfc9110/#name-if-range @@ -336,9 +362,15 @@ async def _prepare_open_file( # if True but Range header missing # return 200 try: - rng = request.http_range - start = rng.start - end: int | None = rng.stop + if self._is_satisfiable_multi_range( + request.headers.get(hdrs.RANGE, ""), file_size + ): + # Multipart responses are unsupported, so ignore valid ranges. + start = end = None + else: + rng = request.http_range + start = rng.start + end = rng.stop except ValueError: # https://tools.ietf.org/html/rfc7233: # A server generating a 416 (Range Not Satisfiable) response to diff --git a/docs/web_reference.rst b/docs/web_reference.rst index 5701acfe5cf..59c2db05933 100644 --- a/docs/web_reference.rst +++ b/docs/web_reference.rst @@ -979,6 +979,10 @@ and :ref:`aiohttp-web-signals` handlers:: Supports the ``Content-Range`` and ``If-Range`` HTTP Headers in requests. + Valid requests for multiple byte ranges are ignored and the entire file is + served when at least one range is satisfiable. Malformed or wholly + unsatisfiable range sets receive a ``416`` response. + The actual :attr:`body` sending happens in overridden :meth:`~StreamResponse.prepare`. :param path: Path to file. Accepts both :class:`str` and :class:`pathlib.Path`. diff --git a/tests/test_web_sendfile_functional.py b/tests/test_web_sendfile_functional.py index 178995d8d1d..fbf73fdd65d 100644 --- a/tests/test_web_sendfile_functional.py +++ b/tests/test_web_sendfile_functional.py @@ -981,6 +981,88 @@ async def handler(request: web.Request) -> web.FileResponse: await client.close() +@pytest.mark.parametrize( + "range_header", + [ + "bytes=0-1,4-5", + "bytes=0-1, 4-5", + "bytes=0-1,\t4-5", + "BYTES=0-1,4-5", + "bytes=100-200,0-1", + "bytes=0-1,100-200", + "bytes=100-,4-", + "bytes=100-,-2", + "bytes=-0,0-1", + ], +) +async def test_static_file_multiple_ranges_fall_back_to_full_response( + aiohttp_client: AiohttpClient, + sender: _Sender, + tmp_path: pathlib.Path, + range_header: str, +) -> None: + filepath = tmp_path / "ten.bin" + filepath.write_bytes(b"0123456789") + + async def handler(request: web.Request) -> web.FileResponse: + return sender(filepath, chunk_size=16) + + app = web.Application() + app.router.add_get("/", handler) + client = await aiohttp_client(app) + + async with client.get("/", headers={"Range": range_header}) as response: + assert response.status == 200 + assert "Content-Range" not in response.headers + assert response.headers["Content-Length"] == "10" + assert await response.read() == b"0123456789" + + await client.close() + + +@pytest.mark.parametrize( + "range_header", + [ + "blocks=0-1,4-5", + "bytes=0-1,a-b", + "bytes=0-1,5-4", + "bytes=0-1,0--1", + "bytes=0-1,-", + "bytes=0-1,", + "bytes=,0-1", + "bytes=0-1,,4-5", + "bytes=0-1, 4 -5", + "bytes=0-1,+4-5", + "bytes=0-1,\u0664-\u0665", + "bytes=10-11,20-21", + "bytes=10-,20-", + "bytes=-0,10-", + "bytes=-0,-0", + ], +) +async def test_static_file_invalid_multiple_ranges( + aiohttp_client: AiohttpClient, + sender: _Sender, + tmp_path: pathlib.Path, + range_header: str, +) -> None: + filepath = tmp_path / "ten.bin" + filepath.write_bytes(b"0123456789") + + async def handler(request: web.Request) -> web.FileResponse: + return sender(filepath, chunk_size=16) + + app = web.Application() + app.router.add_get("/", handler) + client = await aiohttp_client(app) + + async with client.get("/", headers={"Range": range_header}) as response: + assert response.status == 416 + assert response.headers["Content-Range"] == "bytes */10" + + await client.close() + + async def test_static_file_invalid_range( aiohttp_client: AiohttpClient, sender: _Sender ) -> None: From 008fbfbd597431c8dd569b8bfd992fdf3989fa03 Mon Sep 17 00:00:00 2001 From: Emad Date: Mon, 26 Oct 2026 23:57:31 +0200 Subject: [PATCH 2/4] Avoid regex in multi-range validation --- aiohttp/web_fileresponse.py | 36 ++++++++++++++++++++++++------------ 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/aiohttp/web_fileresponse.py b/aiohttp/web_fileresponse.py index 7dd61d52790..a58edea5b0c 100644 --- a/aiohttp/web_fileresponse.py +++ b/aiohttp/web_fileresponse.py @@ -3,7 +3,6 @@ import math import os import pathlib -import re import sys from collections.abc import Awaitable, Callable from contextlib import suppress @@ -163,25 +162,38 @@ def _etag_match(etag_value: str, etags: tuple[ETag, ...], *, weak: bool) -> bool @staticmethod def _is_satisfiable_multi_range(range_header: str, file_size: int) -> bool: - unit, _, ranges = range_header.partition("=") - if unit.lower() != "bytes" or "," not in ranges: + unit, separator, ranges = range_header.partition("=") + if separator != "=" or unit.lower() != "bytes" or "," not in ranges: return False + def is_ascii_digits(value: str) -> bool: + return value.isascii() and value.isdecimal() + + def less_than(left: str, right: str) -> bool: + left = left.lstrip("0") or "0" + right = right.lstrip("0") or "0" + return (len(left), left) < (len(right), right) + satisfiable = False + file_size_text = str(file_size) + for byte_range in ranges.split(","): - match = re.fullmatch(r"([0-9]*)-([0-9]*)", byte_range.strip(" \t")) - if match is None: + first, dash, last = byte_range.strip(" \t").partition("-") + + if not dash or "-" in last or not (first or last): return False - first, last = match.groups() + + if (first and not is_ascii_digits(first)) or ( + last and not is_ascii_digits(last) + ): + return False + if first: - start = int(first) - if last and start > int(last): + if last and less_than(last, first): return False - satisfiable |= start < file_size - elif last: - satisfiable |= int(last) > 0 and file_size > 0 + satisfiable |= less_than(first, file_size_text) else: - return False + satisfiable |= file_size > 0 and bool(last.lstrip("0")) return satisfiable From 1f31a1f7e4f463c3fec5135f78ff518821302a86 Mon Sep 17 00:00:00 2001 From: Emad Date: Tue, 27 Oct 2026 00:42:00 +0200 Subject: [PATCH 3/4] Link PR changelog fragment --- CHANGES/14174.bugfix.rst | 1 + 1 file changed, 1 insertion(+) create mode 120000 CHANGES/14174.bugfix.rst diff --git a/CHANGES/14174.bugfix.rst b/CHANGES/14174.bugfix.rst new file mode 120000 index 00000000000..e876103aa3e --- /dev/null +++ b/CHANGES/14174.bugfix.rst @@ -0,0 +1 @@ +14124.bugfix.rst \ No newline at end of file From 60c91a629de26a8aabf0a914bdd7b00de16dc24b Mon Sep 17 00:00:00 2001 From: Emad Date: Wed, 28 Oct 2026 12:00:46 +0200 Subject: [PATCH 4/4] Handle empty members in multi-range requests --- aiohttp/web_fileresponse.py | 11 ++++++++++- docs/web_reference.rst | 1 + tests/test_web_sendfile_functional.py | 13 ++++++++++--- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/aiohttp/web_fileresponse.py b/aiohttp/web_fileresponse.py index baebc242008..469af001ece 100644 --- a/aiohttp/web_fileresponse.py +++ b/aiohttp/web_fileresponse.py @@ -177,8 +177,17 @@ def less_than(left: str, right: str) -> bool: satisfiable = False file_size_text = str(file_size) + empty_members = 0 for byte_range in ranges.split(","): - first, dash, last = byte_range.strip(" \t").partition("-") + byte_range = byte_range.strip(" \t") + if not byte_range: + # RFC 9110 permits a reasonable number of empty list members. + empty_members += 1 + if empty_members > 8: + return False + continue + + first, dash, last = byte_range.partition("-") if not dash or "-" in last or not (first or last): return False diff --git a/docs/web_reference.rst b/docs/web_reference.rst index 38c0db28188..803bc5bec68 100644 --- a/docs/web_reference.rst +++ b/docs/web_reference.rst @@ -982,6 +982,7 @@ and :ref:`aiohttp-web-signals` handlers:: Valid requests for multiple byte ranges are ignored and the entire file is served when at least one range is satisfiable. Malformed or wholly unsatisfiable range sets receive a ``416`` response. + A limited number of empty range-list members are ignored. The actual :attr:`body` sending happens in overridden :meth:`~StreamResponse.prepare`. diff --git a/tests/test_web_sendfile_functional.py b/tests/test_web_sendfile_functional.py index fbf73fdd65d..a347b8576e3 100644 --- a/tests/test_web_sendfile_functional.py +++ b/tests/test_web_sendfile_functional.py @@ -985,6 +985,12 @@ async def handler(request: web.Request) -> web.FileResponse: "range_header", [ "bytes=0-1,4-5", + "bytes=0-1,", + "bytes=,0-1", + "bytes=0-1,,4-5", + "bytes=0-1, \t ,4-5", + "bytes=0-1,4-5,", + "bytes=0-1,,,,,,,,,4-5", "bytes=0-1, 4-5", "bytes=0-1,\t4-5", "BYTES=0-1,4-5", @@ -1028,9 +1034,10 @@ async def handler(request: web.Request) -> web.FileResponse: "bytes=0-1,5-4", "bytes=0-1,0--1", "bytes=0-1,-", - "bytes=0-1,", - "bytes=,0-1", - "bytes=0-1,,4-5", + "bytes=,,", + "bytes=0-1,,a-b", + "bytes=0-1,,,,,,,,,,4-5", + "bytes=10-11,,20-21", "bytes=0-1, 4 -5", "bytes=0-1,+4-5", "bytes=0-1,\u0664-\u0665",