From 2e43518bb4269fc4a803b20371333c6369dd3205 Mon Sep 17 00:00:00 2001 From: Gani Georgiev Date: Fri, 22 Nov 2024 23:18:50 +0200 Subject: [PATCH] synced ported cors middleware --- apis/middlewares_cors.go | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/apis/middlewares_cors.go b/apis/middlewares_cors.go index ef9ff8e2..a3424167 100644 --- a/apis/middlewares_cors.go +++ b/apis/middlewares_cors.go @@ -134,13 +134,25 @@ func CORS(config CORSConfig) *hook.Handler[*core.RequestEvent] { config.AllowMethods = DefaultCORSConfig.AllowMethods } - allowOriginPatterns := []string{} + allowOriginPatterns := make([]*regexp.Regexp, 0, len(config.AllowOrigins)) for _, origin := range config.AllowOrigins { + if origin == "*" { + continue // "*" is handled differently and does not need regexp + } + pattern := regexp.QuoteMeta(origin) pattern = strings.ReplaceAll(pattern, "\\*", ".*") pattern = strings.ReplaceAll(pattern, "\\?", ".") pattern = "^" + pattern + "$" - allowOriginPatterns = append(allowOriginPatterns, pattern) + + re, err := regexp.Compile(pattern) + if err != nil { + // This is to preserve previous behaviour - invalid patterns were just ignored. + // If we would turn this to panic, users with invalid patterns + // would have applications crashing in production due unrecovered panic. + continue + } + allowOriginPatterns = append(allowOriginPatterns, re) } allowMethods := strings.Join(config.AllowMethods, ",") @@ -210,7 +222,7 @@ func CORS(config CORSConfig) *hook.Handler[*core.RequestEvent] { } if checkPatterns { for _, re := range allowOriginPatterns { - if match, _ := regexp.MatchString(re, origin); match { + if match := re.MatchString(origin); match { allowOrigin = origin break }