Skip to content

Commit b761023

Browse files
authored
Use weak comparison and accept lists and * in Plug.Static If-None-Match (#1338)
1 parent 5afec8c commit b761023

2 files changed

Lines changed: 41 additions & 1 deletion

File tree

‎lib/plug/static.ex‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -391,7 +391,7 @@ defmodule Plug.Static do
391391
|> put_resp_header("cache-control", et_cache)
392392
|> put_resp_header("etag", etag)
393393

394-
if etag in get_req_header(conn, "if-none-match") do
394+
if etag_matches?(get_req_header(conn, "if-none-match"), etag) do
395395
{:fresh, conn}
396396
else
397397
{:stale, conn}
@@ -402,6 +402,20 @@ defmodule Plug.Static do
402402
{:stale, conn}
403403
end
404404

405+
# If-None-Match is "*" or a list of ETags, compared with the weak comparison
406+
# function, so the W/ prefix is ignored. See RFC 9110, 13.1.2.
407+
defp etag_matches?(if_none_match, etag) do
408+
opaque_tag = strip_weak(etag)
409+
410+
Enum.any?(if_none_match, fn value ->
411+
value == etag or
412+
Enum.any?(Plug.Conn.Utils.list(value), &(&1 == "*" or strip_weak(&1) == opaque_tag))
413+
end)
414+
end
415+
416+
defp strip_weak("W/" <> etag), do: etag
417+
defp strip_weak(etag), do: etag
418+
405419
defp etag_for_path(file_info, et_generation, path) do
406420
case et_generation do
407421
{module, function, args} ->

‎test/plug/static_test.exs‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,32 @@ defmodule Plug.StaticTest do
127127
assert get_resp_header(conn, "etag") == [etag]
128128
end
129129

130+
test "performs etag negotiation with weak etags, lists and *" do
131+
conn = call(conn(:get, "/public/fixtures/static.txt"))
132+
assert [etag] = get_resp_header(conn, "etag")
133+
134+
for if_none_match <- ["W/" <> etag, ~s("other", ) <> etag, ~s("other",W/) <> etag, "*"] do
135+
conn =
136+
conn(:get, "/public/fixtures/static.txt", nil)
137+
|> put_req_header("if-none-match", if_none_match)
138+
|> call()
139+
140+
assert conn.status == 304, "expected 304 for #{if_none_match}"
141+
assert conn.resp_body == ""
142+
assert get_resp_header(conn, "etag") == [etag]
143+
end
144+
145+
for if_none_match <- [~s("other"), ~s("other", W/"another")] do
146+
conn =
147+
conn(:get, "/public/fixtures/static.txt", nil)
148+
|> put_req_header("if-none-match", if_none_match)
149+
|> call()
150+
151+
assert conn.status == 200, "expected 200 for #{if_none_match}"
152+
assert conn.resp_body == "HELLO"
153+
end
154+
end
155+
130156
defmodule EtagGenerator do
131157
def generate(path, a, b) do
132158
{:ok, contents} = :prim_file.read_file(path)

0 commit comments

Comments
 (0)