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

@@ -1,6 +1,7 @@
package middleware
import (
"errors"
"net/http"
"strings"
@@ -11,22 +12,24 @@ import (
var corsConfig = config.CORSConfig{
AllowedOrigins: []string{}, // 默认为空,必须显式配置
AllowCredentials: false, // 默认关闭凭证,必须显式启用
AllowCredentials: false, // 默认关闭凭证,必须显式启用
}
// init 在包初始化时检测危险的 CORS 配置组合
func init() {
// 检测危险的通配符 + Credentials 组合
for _, origin := range corsConfig.AllowedOrigins {
if origin == "*" && corsConfig.AllowCredentials {
panic("CORS 配置错误: AllowedOrigins 包含 '*' 且 AllowCredentials 为 true 是危险组合")
func validateCORSConfig(cfg config.CORSConfig) error {
for _, origin := range cfg.AllowedOrigins {
if origin == "*" && cfg.AllowCredentials {
return errors.New("CORS 配置错误: AllowedOrigins 包含 '*' 时不能启用 AllowCredentials")
}
}
return nil
}
func SetCORSConfig(cfg config.CORSConfig) {
// 注意显式配置危险组合时不会panic但生产环境应避免使用
func SetCORSConfig(cfg config.CORSConfig) error {
if err := validateCORSConfig(cfg); err != nil {
return err
}
corsConfig = cfg
return nil
}
func CORS() gin.HandlerFunc {