]> git.ipfire.org Git - thirdparty/starlette.git/commitdiff
Use ETag from headers when parsing If-Range in FileResponse (#2761)
authorVictor Westerhuis <viccie30@users.noreply.github.com>
Tue, 3 Dec 2024 07:07:22 +0000 (08:07 +0100)
committerGitHub <noreply@github.com>
Tue, 3 Dec 2024 07:07:22 +0000 (08:07 +0100)
starlette/responses.py
tests/test_responses.py

index fd156f84120cd582be7189f0e017250775f5c22e..c711dfa39b28cd880b3983ce68c5af928b7dc869 100644 (file)
@@ -353,7 +353,7 @@ class FileResponse(Response):
         http_range = headers.get("range")
         http_if_range = headers.get("if-range")
 
-        if http_range is None or (http_if_range is not None and not self._should_use_range(http_if_range, stat_result)):
+        if http_range is None or (http_if_range is not None and not self._should_use_range(http_if_range)):
             await self._handle_simple(send, send_header_only)
         else:
             try:
@@ -438,11 +438,8 @@ class FileResponse(Response):
                     }
                 )
 
-    @classmethod
-    def _should_use_range(cls, http_if_range: str, stat_result: os.stat_result) -> bool:
-        etag_base = str(stat_result.st_mtime) + "-" + str(stat_result.st_size)
-        etag = f'"{md5_hexdigest(etag_base.encode(), usedforsecurity=False)}"'
-        return http_if_range == formatdate(stat_result.st_mtime, usegmt=True) or http_if_range == etag
+    def _should_use_range(self, http_if_range: str) -> bool:
+        return http_if_range == self.headers["last-modified"] or http_if_range == self.headers["etag"]
 
     @staticmethod
     def _parse_range_header(http_range: str, file_size: int) -> list[tuple[int, int]]:
index 298bc3b0bbd6708dc1de63864b35ba7fe7ee08cd..f22b43b0195a41552e8ef084881d4f3f63d7ff65 100644 (file)
@@ -336,6 +336,22 @@ def test_file_response_with_method_warns(tmp_path: Path) -> None:
         FileResponse(path=tmp_path, filename="example.png", method="GET")
 
 
+def test_file_response_with_range_header(tmp_path: Path, test_client_factory: TestClientFactory) -> None:
+    content = b"file content"
+    filename = "hello.txt"
+    path = tmp_path / filename
+    path.write_bytes(content)
+    etag = '"a_non_autogenerated_etag"'
+    app = FileResponse(path=path, filename=filename, headers={"etag": etag})
+    client = test_client_factory(app)
+    response = client.get("/", headers={"range": "bytes=0-4", "if-range": etag})
+    assert response.status_code == status.HTTP_206_PARTIAL_CONTENT
+    assert response.content == content[:5]
+    assert response.headers["etag"] == etag
+    assert response.headers["content-length"] == "5"
+    assert response.headers["content-range"] == f"bytes 0-4/{len(content)}"
+
+
 def test_set_cookie(test_client_factory: TestClientFactory, monkeypatch: pytest.MonkeyPatch) -> None:
     # Mock time used as a reference for `Expires` by stdlib `SimpleCookie`.
     mocked_now = dt.datetime(2037, 1, 22, 12, 0, 0, tzinfo=dt.timezone.utc)