Skip to content

Commit

Permalink
Take weak ETags in consideration on StaticFiles (#2334)
Browse files Browse the repository at this point in the history
Co-authored-by: Kar Petrosyan <[email protected]>
Co-authored-by: Marcelo Trylesinski <[email protected]>
  • Loading branch information
3 people authored Dec 16, 2023
1 parent efa03eb commit 3c8ab8e
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 2 deletions.
2 changes: 1 addition & 1 deletion starlette/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ def set_stat_headers(self, stat_result: os.stat_result) -> None:
content_length = str(stat_result.st_size)
last_modified = formatdate(stat_result.st_mtime, usegmt=True)
etag_base = str(stat_result.st_mtime) + "-" + str(stat_result.st_size)
etag = md5_hexdigest(etag_base.encode(), usedforsecurity=False)
etag = f'"{md5_hexdigest(etag_base.encode(), usedforsecurity=False)}"'

self.headers.setdefault("content-length", content_length)
self.headers.setdefault("last-modified", last_modified)
Expand Down
2 changes: 1 addition & 1 deletion starlette/staticfiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ def is_not_modified(
try:
if_none_match = request_headers["if-none-match"]
etag = response_headers["etag"]
if if_none_match == etag:
if etag in [tag.strip(" W/") for tag in if_none_match.split(",")]:
return True
except KeyError:
pass
Expand Down
5 changes: 5 additions & 0 deletions tests/test_staticfiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,11 @@ def test_staticfiles_304_with_etag_match(tmpdir, test_client_factory):
second_resp = client.get("/example.txt", headers={"if-none-match": last_etag})
assert second_resp.status_code == 304
assert second_resp.content == b""
second_resp = client.get(
"/example.txt", headers={"if-none-match": f'W/{last_etag}, "123"'}
)
assert second_resp.status_code == 304
assert second_resp.content == b""


def test_staticfiles_304_with_last_modified_compare_last_req(
Expand Down

0 comments on commit 3c8ab8e

Please sign in to comment.