fix: fail closed on invalid cors config

This commit is contained in:
Your Name
2026-05-28 16:53:33 +08:00
parent 547fdab0b2
commit 7eb5f9c7d4
3 changed files with 49 additions and 16 deletions

View File

@@ -14,15 +14,16 @@ import (
func TestCORS_UsesConfiguredOrigins(t *testing.T) {
gin.SetMode(gin.TestMode)
SetCORSConfig(config.CORSConfig{
if err := SetCORSConfig(config.CORSConfig{
AllowedOrigins: []string{"https://app.example.com"},
AllowCredentials: true,
})
}); err != nil {
t.Fatalf("SetCORSConfig should accept explicit origin with credentials: %v", err)
}
t.Cleanup(func() {
SetCORSConfig(config.CORSConfig{
AllowedOrigins: []string{"*"},
AllowCredentials: true,
})
if err := SetCORSConfig(config.CORSConfig{}); err != nil {
t.Fatalf("reset cors config failed: %v", err)
}
})
recorder := httptest.NewRecorder()
@@ -44,6 +45,33 @@ func TestCORS_UsesConfiguredOrigins(t *testing.T) {
}
}
func TestSetCORSConfig_RejectsWildcardWithCredentials(t *testing.T) {
gin.SetMode(gin.TestMode)
if err := SetCORSConfig(config.CORSConfig{}); err != nil {
t.Fatalf("failed to initialize baseline cors config: %v", err)
}
err := SetCORSConfig(config.CORSConfig{
AllowedOrigins: []string{"*"},
AllowCredentials: true,
})
if err == nil {
t.Fatal("expected wildcard+credentials cors config to be rejected")
}
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodOptions, "/api/v1/users", nil)
c.Request.Header.Set("Origin", "https://evil.example.com")
c.Request.Header.Set("Access-Control-Request-Headers", "Authorization")
CORS()(c)
if recorder.Code != http.StatusForbidden {
t.Fatalf("expected previous safe config to remain active and reject origin, got %d", recorder.Code)
}
}
func TestSanitizeQuery_MasksSensitiveValues(t *testing.T) {
raw := "token=abc123&foo=bar&access_token=xyz&secret=s1"
sanitized := sanitizeQuery(raw)