Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions internal/strategy/apiv1.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"maps"
"net/http"
"os"
"strings"
"time"

"github.com/alecthomas/errors"
Expand Down Expand Up @@ -223,14 +224,28 @@ func (d *APIV1) httpError(w http.ResponseWriter, code int, err error, message st
// preconditions pass, otherwise the HTTP status code to send (304 or 412).
func checkConditionals(r *http.Request, etag string) int {
if ifMatch := r.Header.Get("If-Match"); ifMatch != "" {
if etag == "" || (ifMatch != "*" && ifMatch != etag) {
if etag == "" || !etagListMatches(ifMatch, etag) {
return http.StatusPreconditionFailed
}
}
if ifNoneMatch := r.Header.Get("If-None-Match"); ifNoneMatch != "" {
if (ifNoneMatch == "*" && etag != "") || ifNoneMatch == etag {
if etag != "" && etagListMatches(ifNoneMatch, etag) {
return http.StatusNotModified
}
}
return 0
}

// etagListMatches reports whether etag matches an RFC 7232 If-Match /
// If-None-Match header value, which may be a comma-separated list of ETags or
// the "*" wildcard. Stored ETags are always strong, so weak comparison is not
// required.
func etagListMatches(headerValue, etag string) bool {
for candidate := range strings.SplitSeq(headerValue, ",") {
candidate = strings.TrimSpace(candidate)
if candidate == "*" || candidate == etag {
return true
}
}
return false
}
4 changes: 4 additions & 0 deletions internal/strategy/apiv1_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@ func TestConditionalGetIfNoneMatch(t *testing.T) {
{name: "Matching", ifNoneMatch: etag, expectedStatus: http.StatusNotModified},
{name: "NonMatching", ifNoneMatch: `"wrong"`, expectedStatus: http.StatusOK},
{name: "Wildcard", ifNoneMatch: "*", expectedStatus: http.StatusNotModified},
{name: "ListMatching", ifNoneMatch: `"a", ` + etag + `, "b"`, expectedStatus: http.StatusNotModified},
{name: "ListNonMatching", ifNoneMatch: `"a", "b"`, expectedStatus: http.StatusOK},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down Expand Up @@ -134,6 +136,8 @@ func TestConditionalGetIfMatch(t *testing.T) {
{name: "Matching", ifMatch: etag, expectedStatus: http.StatusOK},
{name: "NonMatching", ifMatch: `"wrong"`, expectedStatus: http.StatusPreconditionFailed},
{name: "Wildcard", ifMatch: "*", expectedStatus: http.StatusOK},
{name: "ListMatching", ifMatch: `"a", ` + etag + `, "b"`, expectedStatus: http.StatusOK},
{name: "ListNonMatching", ifMatch: `"a", "b"`, expectedStatus: http.StatusPreconditionFailed},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down