package cors import ( "net/http" "net/http/httptest" "strings" "testing" "github.com/gin-gonic/gin" ) // TestCredentialedPreflightAndVary 验证真实预检凭据协议、方法/头白名单和已有 Vary 合并。 func TestCredentialedPreflightAndVary(t *testing.T) { for _, item := range []struct { name, origin, method, headers string want int }{ {"allowed", "https://app.example.test", "POST", "Authorization,Last-Event-ID", 204}, {"origin denied", "https://other.example.test", "POST", "Authorization", 403}, {"method denied", "https://app.example.test", "DELETE", "Authorization", 403}, {"header denied", "https://app.example.test", "POST", "X-Unknown", 403}, } { t.Run(item.name, func(t *testing.T) { middleware, err := New(Config{AllowOrigins: []string{"https://app.example.test"}, AllowMethods: []string{"GET", "POST"}, AllowHeaders: []string{"Authorization", "Last-Event-ID"}, AllowCredentials: true}, Options{}) if err != nil { t.Fatal(err) } engine := gin.New() engine.Use(func(ctx *gin.Context) { ctx.Header("Vary", "Accept-Encoding"); ctx.Next() }, middleware) engine.OPTIONS("/api", func(*gin.Context) { t.Error("preflight reached application handler") }) request := httptest.NewRequest(http.MethodOptions, "/api", nil) request.Header.Set("Origin", item.origin) request.Header.Set("Access-Control-Request-Method", item.method) request.Header.Set("Access-Control-Request-Headers", item.headers) recorder := httptest.NewRecorder() engine.ServeHTTP(recorder, request) if recorder.Code != item.want { t.Fatalf("status=%d, want %d", recorder.Code, item.want) } if item.want == 204 { if recorder.Header().Get("Access-Control-Allow-Origin") != item.origin || recorder.Header().Get("Access-Control-Allow-Credentials") != "true" || recorder.Header().Get("Access-Control-Allow-Headers") != item.headers { t.Fatal("credential preflight headers changed") } vary := strings.Join(recorder.Header().Values("Vary"), ",") for _, token := range []string{"Accept-Encoding", "Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"} { if !strings.Contains(vary, token) { t.Fatalf("lost Vary %s", token) } } } }) } } // TestCORSRejectsInvalidConfig 凭据和全来源互斥,静态来源不接受文件协议或未声明通配符。 func TestCORSRejectsInvalidConfig(t *testing.T) { for _, cfg := range []Config{{}, {AllowAllOrigins: true, AllowCredentials: true}, {AllowOrigins: []string{"*"}, AllowCredentials: true}, {AllowOrigins: []string{"file://local"}}, {AllowOrigins: []string{"https://*.example.test"}}, {AllowOrigins: []string{"https://app.example.test/path"}}} { if _, err := New(cfg, Options{}); err == nil { t.Fatalf("invalid policy accepted: %#v", cfg) } } } // TestCORSRuntimePolicyAndFrozenConfig 验证应用回调处理扩展拒绝响应,配置切片不会被调用方后续修改。 func TestCORSRuntimePolicyAndFrozenConfig(t *testing.T) { cfg := Config{AllowOrigins: []string{"https://app.example.test"}, AllowMethods: []string{"GET"}} middleware, err := New(cfg, Options{AllowOrigin: func(_ *gin.Context, origin string) bool { return origin == "chrome-extension://registered" }, OnOriginDenied: func(ctx *gin.Context) { ctx.JSON(http.StatusUnauthorized, gin.H{"denied": true}) }}) if err != nil { t.Fatal(err) } cfg.AllowOrigins[0] = "https://attacker.example.test" engine := gin.New() engine.Use(middleware) engine.GET("/api", func(ctx *gin.Context) { ctx.Status(http.StatusNoContent) }) for _, item := range []struct { origin string want int }{{"https://app.example.test", 204}, {"https://attacker.example.test", 401}, {"chrome-extension://registered", 204}} { request := httptest.NewRequest(http.MethodGet, "/api", nil) request.Header.Set("Origin", item.origin) recorder := httptest.NewRecorder() engine.ServeHTTP(recorder, request) if recorder.Code != item.want { t.Fatalf("origin %s status=%d", item.origin, recorder.Code) } } } // TestCredentialWildcardEchoesPreflight 验证显式动态来源授权下的方法和请求头通配符回显。 func TestCredentialWildcardEchoesPreflight(t *testing.T) { middleware, err := New(Config{AllowMethods: []string{"*"}, AllowHeaders: []string{"*"}, AllowCredentials: true}, Options{AllowOrigin: func(*gin.Context, string) bool { return true }}) if err != nil { t.Fatal(err) } engine := gin.New() engine.Use(middleware) request := httptest.NewRequest(http.MethodOptions, "/api", nil) request.Header.Set("Origin", "https://client.example.test") request.Header.Set("Access-Control-Request-Method", "PATCH") request.Header.Set("Access-Control-Request-Headers", "Authorization,X-Custom") recorder := httptest.NewRecorder() engine.ServeHTTP(recorder, request) if recorder.Code != 204 || recorder.Header().Get("Access-Control-Allow-Methods") != "PATCH" || recorder.Header().Get("Access-Control-Allow-Headers") != "Authorization,X-Custom" { t.Fatal("credential wildcard was not echoed") } } // TestCORSWildcardMatchesOriginsOnly 防止 URL 路径被当作主机通配来源匹配。 func TestCORSWildcardMatchesOriginsOnly(t *testing.T) { handler, err := New(Config{AllowOrigins: []string{"https://*.example.test"}, AllowWildcard: true, AllowMethods: []string{"GET"}}, Options{}) if err != nil { t.Fatal(err) } engine := gin.New() engine.Use(handler) engine.GET("/", func(ctx *gin.Context) { ctx.Status(http.StatusNoContent) }) for _, item := range []struct { origin string want int }{{"https://client.example.test", 204}, {"https://evil.test/path.example.test", 403}, {"https://client.example.test?x=.example.test", 403}} { request := httptest.NewRequest(http.MethodGet, "/", nil) request.Header.Set("Origin", item.origin) recorder := httptest.NewRecorder() engine.ServeHTTP(recorder, request) if recorder.Code != item.want { t.Fatalf("origin %s status=%d", item.origin, recorder.Code) } } }