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
9 changes: 4 additions & 5 deletions middleware/cors/cors.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package cors

import (
"slices"
"strconv"
"strings"

Expand Down Expand Up @@ -53,9 +52,9 @@ func New(config ...Config) fiber.Handler {
log.Warn("[CORS] Both 'AllowOrigins' and 'AllowOriginsFunc' have been defined.")
}

// allowOrigins is a slice of strings that contains the allowed origins
// allowOrigins is a set of strings that contains the allowed origins
// defined in the 'AllowOrigins' configuration.
allowOrigins := []string{}
allowOrigins := make(map[string]struct{}, len(cfg.AllowOrigins))
allowSubOrigins := []subdomain{}

// Validate and normalize static AllowOrigins
Expand Down Expand Up @@ -84,7 +83,7 @@ func New(config ...Config) fiber.Handler {
if !isValid {
panic("[CORS] Invalid origin format in configuration: " + maskValue(trimmedOrigin))
}
allowOrigins = append(allowOrigins, normalizedOrigin)
allowOrigins[normalizedOrigin] = struct{}{}
}
}

Expand Down Expand Up @@ -141,7 +140,7 @@ func New(config ...Config) fiber.Handler {
allowOrigin = "*"
} else {
// Check if the origin is in the list of allowed origins
if slices.Contains(allowOrigins, originHeader) {
if _, ok := allowOrigins[originHeader]; ok {
allowOrigin = originHeaderRaw
}

Expand Down
17 changes: 17 additions & 0 deletions middleware/cors/cors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,23 @@ func Test_CORS_Preserve_Origin_Case(t *testing.T) {
require.Equal(t, origin, string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowOrigin)))
}

func Test_CORS_AllowOrigins_NormalizedExactLookup(t *testing.T) {
t.Parallel()

app := fiber.New()
app.Use(New(Config{AllowOrigins: []string{" HTTP://EXAMPLE.COM/ "}}))

origin := "http://example.com"

ctx := &fasthttp.RequestCtx{}
ctx.Request.Header.SetMethod(fiber.MethodOptions)
ctx.Request.Header.Set(fiber.HeaderAccessControlRequestMethod, fiber.MethodGet)
ctx.Request.Header.Set(fiber.HeaderOrigin, origin)
app.Handler()(ctx)

require.Equal(t, origin, string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowOrigin)))
}

func testDefaultOrEmptyConfig(t *testing.T, app *fiber.App) {
t.Helper()

Expand Down
Loading