From 3915a70ca5686d8cd7ff9d66a0d2e16730220637 Mon Sep 17 00:00:00 2001 From: Twiink Date: Sun, 22 Nov 2026 13:46:13 +0800 Subject: [PATCH] =?UTF-8?q?fix(cors):=20=E8=BF=94=E5=9B=9E=E5=8C=B9?= =?UTF-8?q?=E9=85=8D=E8=AF=B7=E6=B1=82=E7=9A=84=E5=8E=9F=E5=A7=8B=E6=9D=A5?= =?UTF-8?q?=E6=BA=90=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware/cors.go | 2 +- middleware/cors_origin_case_test.go | 37 +++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 middleware/cors_origin_case_test.go diff --git a/middleware/cors.go b/middleware/cors.go index b4ddbd7f9..8b31df701 100644 --- a/middleware/cors.go +++ b/middleware/cors.go @@ -305,7 +305,7 @@ func (config CORSConfig) starAllowOriginFunc(c *echo.Context, origin string) (st func (config CORSConfig) defaultAllowOriginFunc(c *echo.Context, origin string) (string, bool, error) { for _, allowedOrigin := range config.AllowOrigins { if strings.EqualFold(allowedOrigin, origin) { - return allowedOrigin, true, nil + return origin, true, nil } } return "", false, nil diff --git a/middleware/cors_origin_case_test.go b/middleware/cors_origin_case_test.go new file mode 100644 index 000000000..e092e95c9 --- /dev/null +++ b/middleware/cors_origin_case_test.go @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT +// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors + +package middleware + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/labstack/echo/v5" + "github.com/stretchr/testify/assert" +) + +func TestCORSReflectsMatchedOrigin(t *testing.T) { + for _, method := range []string{http.MethodGet, http.MethodOptions} { + t.Run(method, func(t *testing.T) { + e := echo.New() + e.Use(CORSWithConfig(CORSConfig{ + AllowOrigins: []string{"https://EXAMPLE.com"}, + AllowCredentials: true, + })) + e.GET("/", func(c *echo.Context) error { + return c.String(http.StatusOK, "allowed") + }) + req := httptest.NewRequest(method, "/", nil) + req.Header.Set(echo.HeaderOrigin, "https://example.com") + if method == http.MethodOptions { + req.Header.Set(echo.HeaderAccessControlRequestMethod, http.MethodGet) + } + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + assert.Equal(t, req.Header.Get(echo.HeaderOrigin), rec.Header().Get(echo.HeaderAccessControlAllowOrigin)) + assert.Equal(t, "true", rec.Header().Get(echo.HeaderAccessControlAllowCredentials)) + }) + } +}