Skip to content

Commit

Permalink
simplify logic for methods
Browse files Browse the repository at this point in the history
  • Loading branch information
jub0bs committed Jan 8, 2025
1 parent 391faea commit f8429c7
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 9 deletions.
13 changes: 7 additions & 6 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package cors

import (
"errors"
"maps"
"net/http"
"slices"
"strconv"
Expand Down Expand Up @@ -627,6 +626,12 @@ func (icfg *internalConfig) validateMethods(names []string) error {
errs = append(errs, err)
continue
}
name = methods.Normalize(name)
if methods.IsSafelisted(name) {
// Safelisted methods need not be explicitly allowed;
// see https://stackoverflow.com/a/71429784/2541573.
continue
}
if methods.IsForbidden(name) {
err := &cfgerrors.UnacceptableMethodError{
Value: name,
Expand All @@ -635,12 +640,8 @@ func (icfg *internalConfig) validateMethods(names []string) error {
errs = append(errs, err)
continue
}
allowedMethods.Add(methods.Normalize(name))
allowedMethods.Add(name)
}
// Because safelisted methods need not be explicitly allowed
// (see https://stackoverflow.com/a/71429784/2541573),
// let's remove them silently.
maps.DeleteFunc(allowedMethods, methods.IsSafelisted)
if len(errs) != 0 {
return errors.Join(errs...)
}
Expand Down
2 changes: 1 addition & 1 deletion internal/methods/methods.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ var byteLowercasedForbiddenMethods = util.NewSet(
// [per the Fetch standard].
//
// [per the Fetch standard]: https://fetch.spec.whatwg.org/#cors-safelisted-method
func IsSafelisted(name string, _ struct{}) bool {
func IsSafelisted(name string) bool {
return safelistedMethods.Contains(name)
}

Expand Down
2 changes: 1 addition & 1 deletion internal/methods/methods_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ func TestIsSafelisted(t *testing.T) {
}
for _, tc := range cases {
f := func(t *testing.T) {
got := IsSafelisted(tc.name, struct{}{})
got := IsSafelisted(tc.name)
if got != tc.want {
const tmpl = "%q: got %t; want %t"
t.Errorf(tmpl, tc.name, got, tc.want)
Expand Down
2 changes: 1 addition & 1 deletion middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ func (icfg *internalConfig) processACRM(
acrm string,
acrmSgl []string,
) bool {
if methods.IsSafelisted(acrm, struct{}{}) {
if methods.IsSafelisted(acrm) {
// CORS-safelisted methods get a free pass; see
// https://fetch.spec.whatwg.org/#ref-for-cors-safelisted-method%E2%91%A2.
// Therefore, no need to set the ACAM header in this case.
Expand Down

0 comments on commit f8429c7

Please sign in to comment.