Skip to content

Commit

Permalink
Use ETag from headers when parsing If-Range in FileResponse (#2761)
Browse files Browse the repository at this point in the history
  • Loading branch information
viccie30 authored Dec 3, 2024
1 parent eee4cdc commit ca1f45d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
9 changes: 3 additions & 6 deletions starlette/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
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:
Expand Down Expand Up @@ -438,11 +438,8 @@ async def _handle_multiple_ranges(
}
)

@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]]:
Expand Down
16 changes: 16 additions & 0 deletions tests/test_responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit ca1f45d

Please sign in to comment.