feat(gateway): 安全收口 —— CORS 生产收紧 + 限流按用户(T4.F)

- CORS:开发期缺省仍放行 *(便利);生产(APP_ENV=prod/GIN_MODE=release)未显式配
  CORS_ALLOW_ORIGIN 则不发 ACAO 头(浏览器按同源拦截),逼运维显式配置允许的源
- 限流键改「已认证按 uid、未认证按 IP」:企业网多人共享出口 IP 不再互相拖累,
  单用户换 IP 也绕不过;中间件顺序调整 Auth 前置于 RateLimit(否则取不到 uid)
- isProd() 判定与 middleware.RequireAdmin 同口径
- live 冒烟:登录/认证请求正常(重排未破链),dev CORS 仍 *

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Blizzard
2026-07-02 13:55:20 +08:00
parent 6095bc71d2
commit 23b8fa5e8a
3 changed files with 43 additions and 16 deletions
@@ -68,12 +68,20 @@ func recordGuardrail(c *gin.Context, db *store.Postgres, kind, reason string, si
_ = db.AppendGuardrailEvent(ctx, e)
}
// RateLimit 基于 Redis 的会话级限流(按客户端 IP每分钟上限)。
// 上限经 RATE_LIMIT_PER_MIN 配置(缺省 120);压测可调高。Redis 降级时始终放行,不阻断业务。
// RateLimit 基于 Redis 的会话级限流(每分钟上限)。
// 限流键:**已认证用户优先按 uid,未认证按客户端 IP** —— 企业网多人共享出口 IP 不再互相拖累,
// 单用户换 IP 也绕不过。须挂在 Auth 之后(否则取不到 uid)。上限经 RATE_LIMIT_PER_MIN 配置
// (缺省 120);压测可调高。Redis 降级时始终放行,不阻断业务。
func RateLimit(cache *store.Redis) gin.HandlerFunc {
perMinute := int64(envInt("RATE_LIMIT_PER_MIN", 120))
return func(c *gin.Context) {
ok, _ := cache.Allow(c.Request.Context(), c.ClientIP(), perMinute, time.Minute)
key := "ip:" + c.ClientIP()
if v, ok := c.Get(CtxUserID); ok {
if uid, _ := v.(string); uid != "" {
key = "u:" + uid
}
}
ok, _ := cache.Allow(c.Request.Context(), key, perMinute, time.Minute)
if !ok {
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "rate limit exceeded"})
return