Skip to content

Commit 5eea054

Browse files
authored
Merge pull request #270 from doringeman/cors
fix(cors): validate Origin header
2 parents 0f68b49 + 291bfe5 commit 5eea054

File tree

2 files changed

+11
-9
lines changed

2 files changed

+11
-9
lines changed

pkg/middleware/cors.go

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,6 @@ func CorsMiddleware(allowedOrigins []string, next http.Handler) http.Handler {
1515
allowedOrigins = getAllowedOrigins()
1616
}
1717

18-
// Explicitly disable all origins.
19-
if allowedOrigins == nil {
20-
return next
21-
}
22-
2318
allowAll := len(allowedOrigins) == 1 && allowedOrigins[0] == "*"
2419
allowedSet := make(map[string]struct{}, len(allowedOrigins))
2520
for _, o := range allowedOrigins {
@@ -29,16 +24,23 @@ func CorsMiddleware(allowedOrigins []string, next http.Handler) http.Handler {
2924
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
3025
origin := r.Header.Get("Origin")
3126

27+
allowed := allowAll || originAllowed(origin, allowedSet)
28+
29+
if origin != "" && !allowed {
30+
http.Error(w, "Origin not allowed", http.StatusForbidden)
31+
return
32+
}
33+
3234
// Set CORS headers if origin is allowed
33-
if origin != "" && (allowAll || originAllowed(origin, allowedSet)) {
35+
if origin != "" && allowed {
3436
w.Header().Set("Access-Control-Allow-Origin", origin)
3537
}
3638

3739
// Handle OPTIONS requests with origin validation.
3840
// Only intercept OPTIONS if the origin is valid to prevent unauthorized preflight requests.
3941
if r.Method == http.MethodOptions {
4042
// Require valid Origin header for OPTIONS requests
41-
if origin == "" || !(allowAll || originAllowed(origin, allowedSet)) {
43+
if origin == "" || !allowed {
4244
// No origin or invalid origin - pass to router for proper 405/404 response
4345
next.ServeHTTP(w, r)
4446
return

pkg/middleware/cors_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ func TestCorsMiddleware(t *testing.T) {
3838
allowedOrigins: []string{"http://foo.com"},
3939
method: "GET",
4040
origin: "http://bar.com",
41-
wantStatus: http.StatusOK,
41+
wantStatus: http.StatusForbidden,
4242
wantHeaders: map[string]string{"Access-Control-Allow-Origin": ""},
4343
},
4444
{
@@ -74,7 +74,7 @@ func TestCorsMiddleware(t *testing.T) {
7474
allowedOrigins: nil,
7575
method: "GET",
7676
origin: "http://foo.com",
77-
wantStatus: http.StatusOK,
77+
wantStatus: http.StatusForbidden,
7878
wantHeaders: map[string]string{"Access-Control-Allow-Origin": ""},
7979
},
8080
}

0 commit comments

Comments
 (0)