Files
ginframework/http/cors/cors.go
T
2026-11-28 02:28:13 -08:00

205 lines
8.6 KiB
Go

// Package cors 提供独立于业务身份的来源匹配、预检和跨域响应头。
package cors
import (
"errors"
"net/http"
"net/url"
"strconv"
"strings"
"time"
failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure"
"github.com/gin-gonic/gin"
)
const (
codeOrigins = 900801
codeCredentials = 900802
codeOriginPattern = 900803
codeMaxAge = 900804
)
// Config 只保存跨域策略数据;零 MaxAge 不缓存预检,名单不会隐式扩展。
type Config struct {
AllowAllOrigins bool `json:"allow_all_origins" yaml:"allow_all_origins" dc:"允许任意来源,与凭据模式互斥"`
AllowOrigins []string `json:"allow_origins" yaml:"allow_origins" dc:"明确的 HTTP/HTTPS 来源名单"`
AllowMethods []string `json:"allow_methods" yaml:"allow_methods" dc:"预检允许的方法,星号允许任意方法"`
AllowHeaders []string `json:"allow_headers" yaml:"allow_headers" dc:"预检允许的请求头,星号允许任意请求头"`
ExposeHeaders []string `json:"expose_headers" yaml:"expose_headers" dc:"允许浏览器读取的响应头"`
AllowCredentials bool `json:"allow_credentials" yaml:"allow_credentials" dc:"允许请求携带凭据,必须回显明确来源"`
AllowWildcard bool `json:"allow_wildcard" yaml:"allow_wildcard" dc:"允许名单中出现单个星号来源规则"`
CheckActualMethod bool `json:"check_actual_method" yaml:"check_actual_method" dc:"除预检外也拒绝名单之外的实际跨域方法"`
MaxAge time.Duration `json:"max_age" yaml:"max_age" dc:"预检缓存时长,零不缓存,拒绝负值"`
}
// Options 显式提供应用自己的动态来源授权和拒绝响应,不进入配置解码。
type Options struct {
AllowOrigin func(*gin.Context, string) bool `json:"-" dc:"静态名单未匹配时的可信来源授权,可处理扩展等来源"`
OnOriginDenied gin.HandlerFunc `json:"-" dc:"来源拒绝时的可选业务响应,缺省为 403;框架始终终止处理"`
}
// DefaultConfig 返回标准方法和基础请求头、十二小时缓存;调用方仍须声明来源。
func DefaultConfig() Config {
return Config{AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}, AllowHeaders: []string{"Origin", "Content-Length", "Content-Type"}, MaxAge: 12 * time.Hour}
}
// New 校验一次策略并复制名单,返回可注册到 Gin/框架 Use 的处理器。
// 入参:cfg 为数据,options 为应用运行函数;静态来源只接受 HTTP/HTTPS origin 和显式单星号规则。
// 返回:构造失败保留内部原因链,不使用 panic;无 Origin 或同源请求直接通过,预检成功返回 204。
// 隐式逻辑:凭据模式禁止星号 Origin,方法和头的星号按请求回显;已有 Vary 会合并保留。
func New(cfg Config, options Options) (gin.HandlerFunc, error) {
cfg.AllowOrigins = normalize(cfg.AllowOrigins)
cfg.AllowMethods = normalize(cfg.AllowMethods)
cfg.AllowHeaders = normalize(cfg.AllowHeaders)
cfg.ExposeHeaders = normalize(cfg.ExposeHeaders)
if cfg.MaxAge < 0 {
return nil, failure.Wrap(codeMaxAge, "validate CORS preflight lifetime failed", errors.New("negative preflight lifetime"))
}
if contains(cfg.AllowOrigins, "*") {
cfg.AllowAllOrigins = true
}
if cfg.AllowAllOrigins && cfg.AllowCredentials {
return nil, failure.Wrap(codeCredentials, "validate CORS credential policy failed", errors.New("credentials require explicit origins"))
}
if cfg.AllowAllOrigins && (options.AllowOrigin != nil || len(cfg.AllowOrigins) > 1 || len(cfg.AllowOrigins) == 1 && cfg.AllowOrigins[0] != "*") {
return nil, failure.Wrap(codeOrigins, "validate CORS origin policy failed", errors.New("wildcard origin conflicts with explicit origin rules"))
}
if !cfg.AllowAllOrigins && len(cfg.AllowOrigins) == 0 && options.AllowOrigin == nil {
return nil, failure.Wrap(codeOrigins, "validate CORS origin policy failed", errors.New("origin rule is required"))
}
for _, origin := range cfg.AllowOrigins {
if origin == "*" {
continue
}
if !webOrigin(origin) || strings.Count(origin, "*") > 1 || strings.Contains(origin, "*") && !cfg.AllowWildcard {
return nil, failure.Wrap(codeOriginPattern, "validate CORS origin pattern failed", errors.New("invalid origin scheme, shape or wildcard declaration"))
}
}
return func(ctx *gin.Context) {
origin := strings.TrimSpace(ctx.GetHeader("Origin"))
if origin == "" || origin == "http://"+ctx.Request.Host || origin == "https://"+ctx.Request.Host {
return
}
allowed := cfg.AllowAllOrigins
for _, rule := range cfg.AllowOrigins {
if strings.EqualFold(rule, origin) {
allowed = true
break
}
if cfg.AllowWildcard && strings.Contains(rule, "*") && webOrigin(origin) {
before, after, _ := strings.Cut(rule, "*")
candidate := strings.ToLower(origin)
if strings.HasPrefix(candidate, before) && strings.HasSuffix(candidate, after) && len(candidate) >= len(before)+len(after) {
allowed = true
break
}
}
}
if !allowed && options.AllowOrigin != nil {
allowed = options.AllowOrigin(ctx, origin)
}
if !allowed {
if options.OnOriginDenied != nil {
options.OnOriginDenied(ctx)
ctx.Abort()
} else {
ctx.AbortWithStatus(http.StatusForbidden)
}
return
}
if cfg.CheckActualMethod && ctx.Request.Method != http.MethodOptions && !contains(cfg.AllowMethods, ctx.Request.Method) && !contains(cfg.AllowMethods, "*") {
ctx.AbortWithStatus(http.StatusForbidden)
return
}
header := ctx.Writer.Header()
if cfg.AllowAllOrigins {
header.Set("Access-Control-Allow-Origin", "*")
} else {
header.Set("Access-Control-Allow-Origin", origin)
appendVary(header, "Origin")
}
if cfg.AllowCredentials {
header.Set("Access-Control-Allow-Credentials", "true")
}
if ctx.Request.Method != http.MethodOptions {
if len(cfg.ExposeHeaders) > 0 {
header.Set("Access-Control-Expose-Headers", strings.Join(cfg.ExposeHeaders, ","))
}
return
}
method := strings.ToUpper(strings.TrimSpace(ctx.GetHeader("Access-Control-Request-Method")))
if !contains(cfg.AllowMethods, "*") && !contains(cfg.AllowMethods, method) {
ctx.AbortWithStatus(http.StatusForbidden)
return
}
requested := strings.TrimSpace(ctx.GetHeader("Access-Control-Request-Headers"))
if !contains(cfg.AllowHeaders, "*") {
for _, name := range strings.Split(requested, ",") {
if strings.TrimSpace(name) != "" && !contains(cfg.AllowHeaders, name) {
ctx.AbortWithStatus(http.StatusForbidden)
return
}
}
}
methods := strings.ToUpper(strings.Join(cfg.AllowMethods, ", "))
if contains(cfg.AllowMethods, "*") && cfg.AllowCredentials {
methods = method
}
header.Set("Access-Control-Allow-Methods", methods)
if requested != "" {
if cfg.AllowCredentials || contains(cfg.AllowHeaders, "*") {
header.Set("Access-Control-Allow-Headers", requested)
} else {
header.Set("Access-Control-Allow-Headers", strings.Join(cfg.AllowHeaders, ","))
}
}
if cfg.MaxAge > 0 {
header.Set("Access-Control-Max-Age", strconv.FormatInt(int64(cfg.MaxAge/time.Second), 10))
}
appendVary(header, "Access-Control-Request-Method")
appendVary(header, "Access-Control-Request-Headers")
ctx.AbortWithStatus(http.StatusNoContent)
}, nil
}
// normalize 复制并规范化构造期名单,避免请求读取调用方的可变切片。
func normalize(values []string) []string {
result := make([]string, 0, len(values))
for _, value := range values {
value = strings.ToLower(strings.TrimSpace(value))
if value != "" && !contains(result, value) {
result = append(result, value)
}
}
return result
}
// contains 对方法、来源和请求头执行大小写不敏感的完整项匹配。
func contains(values []string, value string) bool {
for _, entry := range values {
if strings.EqualFold(entry, strings.TrimSpace(value)) {
return true
}
}
return false
}
// appendVary 保留既有协商条件,合并同名项时不重复输出。
func appendVary(header http.Header, value string) {
for _, existing := range header.Values("Vary") {
for _, item := range strings.Split(existing, ",") {
if strings.EqualFold(strings.TrimSpace(item), value) {
return
}
}
}
header.Add("Vary", value)
}
// webOrigin 检查来源 URL 的 origin 形状,拒绝凭据、路径、查询和片段参与通配匹配。
func webOrigin(origin string) bool {
parsed, err := url.Parse(origin)
return err == nil && (parsed.Scheme == "http" || parsed.Scheme == "https") && parsed.Host != "" && parsed.User == nil && parsed.Path == "" && parsed.RawQuery == "" && parsed.Fragment == "" && parsed.Opaque == ""
}