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/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 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 9c581a6c690..469af001ece 100644 --- a/aiohttp/web_fileresponse.py +++ b/aiohttp/web_fileresponse.py @@ -160,6 +160,52 @@ 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, 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) + + empty_members = 0 + for byte_range in ranges.split(","): + 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 + + if (first and not is_ascii_digits(first)) or ( + last and not is_ascii_digits(last) + ): + return False + + if first: + if last and less_than(last, first): + return False + satisfiable |= less_than(first, file_size_text) + else: + satisfiable |= file_size > 0 and bool(last.lstrip("0")) + + return satisfiable + async def _not_modified( self, request: "BaseRequest", etag_value: str, last_modified: float ) -> AbstractStreamWriter | None: @@ -310,6 +356,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 +383,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 2090def6c23..24f6e74ff88 100644 --- a/docs/web_reference.rst +++ b/docs/web_reference.rst @@ -986,6 +986,11 @@ 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. + A limited number of empty range-list members are ignored. + 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..a347b8576e3 100644 --- a/tests/test_web_sendfile_functional.py +++ b/tests/test_web_sendfile_functional.py @@ -981,6 +981,95 @@ async def handler(request: web.Request) -> web.FileResponse: await client.close() +@pytest.mark.parametrize( + "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", + "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=,,", + "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", + "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: