diff --git a/CHANGES/14124.bugfix.rst b/CHANGES/14124.bugfix.rst new file mode 100644 index 00000000000..625a8308382 --- /dev/null +++ b/CHANGES/14124.bugfix.rst @@ -0,0 +1,3 @@ +Fixed ``FileResponse`` answering a well-formed multi-range request with +``416 Range Not Satisfiable`` instead of ignoring ``Range`` and returning the +full file -- by :user:`vyrnsynx`. diff --git a/CONTRIBUTORS.txt b/CONTRIBUTORS.txt index 44b0649a814..0b20ab4fffc 100644 --- a/CONTRIBUTORS.txt +++ b/CONTRIBUTORS.txt @@ -433,6 +433,7 @@ Vladimir Zakharov Vladyslav Bohaichuk Vladyslav Bondar Vojtěch Boček +Vyrn Synx W. Trevor King Wei Lin Weiwei Wang diff --git a/aiohttp/web_fileresponse.py b/aiohttp/web_fileresponse.py index 5cc9d886a57..d6398a19b4b 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 @@ -42,6 +43,14 @@ NOSENDFILE: Final[bool] = bool(os.environ.get("AIOHTTP_NOSENDFILE")) +# Well-formed multi-range set (RFC 9110 §14.1). FileResponse only serves a +# single range; a satisfiable multi-range must not become 416 (RFC 9110 §14.2 +# allows ignoring Range and returning 200 with the full representation). +_MULTI_BYTE_RANGE_RE = re.compile( + r"^bytes=(?:\d+-\d*|-\d+)(?:,(?:\d+-\d*|-\d+))+$", + re.ASCII | re.IGNORECASE, +) + CONTENT_TYPES: Final[MimeTypes] = MimeTypes() # File extension to IANA encodings map that will be checked in the order defined. @@ -339,6 +348,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 @@ -367,20 +377,29 @@ async def _prepare_open_file( try: rng = request.http_range start = rng.start - end: int | None = rng.stop + end = rng.stop except ValueError: - # https://tools.ietf.org/html/rfc7233: - # A server generating a 416 (Range Not Satisfiable) response to - # a byte-range request SHOULD send a Content-Range header field - # with an unsatisfied-range value. - # The complete-length in a 416 response indicates the current - # length of the selected representation. - # - # Will do the same below. Many servers ignore this and do not - # send a Content-Range header with HTTP 416 - self._headers[hdrs.CONTENT_RANGE] = f"bytes */{file_size}" - self.set_status(HTTPRequestRangeNotSatisfiable.status_code) - return await super().prepare(request) + # http_range only accepts a single byte range. A well-formed + # multi-range set (e.g. bytes=0-1,4-5) is still a valid Range + # per RFC 9110; answering 416 would be wrong for a satisfiable + # set. Ignore the header and fall through to a full 200 instead + # (RFC 9110 §14.2 / RFC 7233). Malformed ranges keep 416. + range_hdr = request.headers.get(hdrs.RANGE) + if range_hdr is not None and _MULTI_BYTE_RANGE_RE.fullmatch(range_hdr): + pass + else: + # https://tools.ietf.org/html/rfc7233: + # A server generating a 416 (Range Not Satisfiable) response to + # a byte-range request SHOULD send a Content-Range header field + # with an unsatisfied-range value. + # The complete-length in a 416 response indicates the current + # length of the selected representation. + # + # Will do the same below. Many servers ignore this and do not + # send a Content-Range header with HTTP 416 + self._headers[hdrs.CONTENT_RANGE] = f"bytes */{file_size}" + self.set_status(HTTPRequestRangeNotSatisfiable.status_code) + return await super().prepare(request) # If a range request has been made, convert start, end slice # notation into file pointer offset and count diff --git a/tests/test_web_sendfile_functional.py b/tests/test_web_sendfile_functional.py index 70d25398148..d896acca1b3 100644 --- a/tests/test_web_sendfile_functional.py +++ b/tests/test_web_sendfile_functional.py @@ -1032,6 +1032,45 @@ async def handler(request: web.Request) -> web.FileResponse: await client.close() +async def test_static_file_multi_range_ignored( + aiohttp_client: AiohttpClient, sender: _Sender +) -> None: + """A well-formed multi-range request gets 200 with the full file. + + FileResponse only implements a single byte range. Per RFC 9110 §14.2 a + server may ignore Range; answering 416 for a satisfiable multi-range set + is incorrect (see #14124). + """ + filepath = pathlib.Path(__file__).parent / "aiohttp.png" + body = filepath.read_bytes() + + 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) + + resp = await client.get("/", headers={"Range": "bytes=0-1,4-5"}) + assert resp.status == 200 + assert "Content-Range" not in resp.headers + assert await resp.read() == body + resp.release() + + # Still a multi-range set (suffix + open range); ignore rather than 416. + resp = await client.get("/", headers={"Range": "bytes=-3,0-"}) + assert resp.status == 200 + assert await resp.read() == body + resp.release() + + # Malformed ranges that happen to contain a comma stay 416. + resp = await client.get("/", headers={"Range": "bytes=0-1,a-b"}) + assert resp.status == 416 + resp.release() + + await client.close() + + async def test_static_file_if_unmodified_since_past_with_range( aiohttp_client: AiohttpClient, app_with_static_route: web.Application ) -> None: