Skip to content

Commit bab09db

Browse files
committed
CORS middleware should compile allowOrigin regexp at creation.
Note: this changes MW behaviour - previously invalid regexps would cause allow origin check to fail, but now if there is a invalid AllowOrigin regexp panic will be raised during middleware creation.
1 parent 5d98929 commit bab09db

File tree

3 files changed

+19
-5
lines changed

3 files changed

+19
-5
lines changed

Makefile

+2-2
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,6 @@ benchmark: ## Run benchmarks
3131
help: ## Display this help screen
3232
@grep -h -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
3333

34-
goversion ?= "1.19"
35-
test_version: ## Run tests inside Docker with given version (defaults to 1.19 oldest supported). Example: make test_version goversion=1.19
34+
goversion ?= "1.20"
35+
test_version: ## Run tests inside Docker with given version (defaults to 1.20 oldest supported). Example: make test_version goversion=1.20
3636
@docker run --rm -it -v $(shell pwd):/project golang:$(goversion) /bin/sh -c "cd /project && make init check"

middleware/cors.go

+9-3
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
package middleware
55

66
import (
7+
"fmt"
78
"net/http"
89
"regexp"
910
"strconv"
@@ -147,13 +148,18 @@ func CORSWithConfig(config CORSConfig) echo.MiddlewareFunc {
147148
config.AllowMethods = DefaultCORSConfig.AllowMethods
148149
}
149150

150-
allowOriginPatterns := []string{}
151+
allowOriginPatterns := make([]*regexp.Regexp, 0, len(config.AllowOrigins))
151152
for _, origin := range config.AllowOrigins {
152153
pattern := regexp.QuoteMeta(origin)
153154
pattern = strings.ReplaceAll(pattern, "\\*", ".*")
154155
pattern = strings.ReplaceAll(pattern, "\\?", ".")
155156
pattern = "^" + pattern + "$"
156-
allowOriginPatterns = append(allowOriginPatterns, pattern)
157+
158+
re, err := regexp.Compile(pattern)
159+
if err != nil {
160+
panic(fmt.Errorf("echo: invalid AllowOrigins regexp, err: %w", err))
161+
}
162+
allowOriginPatterns = append(allowOriginPatterns, re)
157163
}
158164

159165
allowMethods := strings.Join(config.AllowMethods, ",")
@@ -239,7 +245,7 @@ func CORSWithConfig(config CORSConfig) echo.MiddlewareFunc {
239245
}
240246
if checkPatterns {
241247
for _, re := range allowOriginPatterns {
242-
if match, _ := regexp.MatchString(re, origin); match {
248+
if match := re.MatchString(origin); match {
243249
allowOrigin = origin
244250
break
245251
}

middleware/cors_test.go

+8
Original file line numberDiff line numberDiff line change
@@ -671,3 +671,11 @@ func Test_allowOriginFunc(t *testing.T) {
671671
}
672672
}
673673
}
674+
675+
func TestInvalidAllowOriginsAtCreationPanics(t *testing.T) {
676+
assert.Panics(t, func() {
677+
CORSWithConfig(CORSConfig{
678+
AllowOrigins: []string{"\xff"}, // Invalid UTF-8
679+
})
680+
})
681+
}

0 commit comments

Comments
 (0)