fix(prod): 后端生产级 A 类硬伤全清(7 项:授权/崩溃点/全表扫/限流/鉴权/限额)

部署前生产级审计(可靠性/数据层/安全三路)后,清掉 7 处代码级硬伤:

A1 后台定时器 goroutine 无 panic recover → 单个 DB panic 崩整个 gateway。加 safeGo/
   safeCall,包住订阅/掉单补偿/微信推送/探针 goroutine,单轮 tick 再兜一层。
A2 提示词控制面(建/激活/停用,热广播全服务)只 RequireAuth → 任意登录用户改全局提示词。
   三写端点+列表挂 RequireAdmin。
A3 HITL 审批端点无角色门 → viewer 可放行烧钱执行。加 RequireTenantRole(member)。
A4 审计/护栏列表 limit 无校验,limit=-1 让 gorm 取消 LIMIT 全表扫。加 clampLimit/
   clampOffset,AdminTasks/AdminSpaces 补上界。
A5 限流 Redis 一挂就完全放行(fail-open)。加进程内固定窗口兜底(fail-safe) + 登录/注册
   按 IP 专用严限流(10/min)。
A6 公开 by-id 端点(stream/exec/report导出/kb导入流)无鉴权无租户过滤。加
   AuthFromHeaderOrQuery(从 ?token= 取 JWT) + task/report 按 owner 归属校验;桌面端
   5 处 EventSource/下载 URL 经 tokenQuery 附 JWT。
A7 文件上传无大小上限(整文件进内存 OOM 面) → 50MB 闸(KB_MAX_UPLOAD_BYTES)+ LimitReader;
   http.Server 加 ReadHeaderTimeout/ReadTimeout/MaxHeaderBytes(不设 WriteTimeout 保 SSE)。

带单测:clampLimit/safeCall/procLimiter/AuthFromHeaderOrQuery/TaskOwner。
build+vet+全量 test 绿;desktop tsc 绿。B(迁移工具/实时探针/出网韧性/登录锁定/leader选举)
与 C(TLS/PG HA/K8s/备份自动化/可观测)分期后做,参照 production_readiness.md。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Blizzard
2026-07-21 15:04:47 +08:00
parent ce7cca657e
commit ac38d5e663
20 changed files with 443 additions and 100 deletions
@@ -0,0 +1,37 @@
package middleware
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/sundynix/sundynix-gateway/internal/auth"
)
// AuthFromHeaderOrQuery 是给「公开 by-id」端点(SSE 流 / 报告下载)用的强制鉴权。
// 这些端点由 EventSource / <a download> 发起,**带不了 Authorization 头**——此前只靠随机
// task_id 寻址、无 authz、无租户过滤(capability-URL,泄露即无第二道门)。
// 本中间件先读 Bearer 头、没有再读 `?token=` / `?access_token=` 查询参数(EventSource 能带 query),
// 校验通过注入 CtxUserID(同 Auth),失败即 401。归属校验由各 handler 用 uid 再做(见 requireTaskOwner)。
func AuthFromHeaderOrQuery() gin.HandlerFunc {
return func(c *gin.Context) {
tok := ""
if h := c.GetHeader("Authorization"); strings.HasPrefix(h, "Bearer ") {
tok = strings.TrimSpace(h[len("Bearer "):])
}
if tok == "" {
tok = c.Query("token")
}
if tok == "" {
tok = c.Query("access_token")
}
uid, err := auth.Parse(tok)
if err != nil || uid == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "需要登录"})
return
}
c.Set(CtxUserID, uid)
c.Next()
}
}
@@ -71,9 +71,9 @@ func recordGuardrail(c *gin.Context, db *store.Postgres, kind, reason string, si
// RateLimit 基于 Redis 的会话级限流(每分钟上限)。
// 限流键:**已认证用户优先按 uid,未认证按客户端 IP** —— 企业网多人共享出口 IP 不再互相拖累,
// 单用户换 IP 也绕不过。须挂在 Auth 之后(否则取不到 uid)。上限经 RATE_LIMIT_PER_MIN 配置
// (缺省 120);压测可调高。Redis 降级时始终放行,不阻断业务。
// (缺省 120);压测可调高。**Redis 降级时回落进程内兜底限流(fail-safe),不再完全放行。**
func RateLimit(cache *store.Redis) gin.HandlerFunc {
perMinute := int64(envInt("RATE_LIMIT_PER_MIN", 120))
perMinute := envInt("RATE_LIMIT_PER_MIN", 120)
return func(c *gin.Context) {
key := "ip:" + c.ClientIP()
if v, ok := c.Get(CtxUserID); ok {
@@ -81,8 +81,7 @@ func RateLimit(cache *store.Redis) gin.HandlerFunc {
key = "u:" + uid
}
}
ok, _ := cache.Allow(c.Request.Context(), key, perMinute, time.Minute)
if !ok {
if !allowWithFallback(cache, c.Request.Context(), key, perMinute) {
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "rate limit exceeded"})
return
}
@@ -0,0 +1,78 @@
package middleware
import (
"context"
"net/http"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/sundynix/sundynix-gateway/internal/store"
)
// 限流的 fail-safe 兜底。Redis 是限流的主后端,但它一挂(或降级)时,此前 `Allow` 直接放行
// = fail-open:爆破/洪泛防护随 Redis 一起消失。这里加一个**进程内**固定窗口兜底限流,让
// Redis 不可用时仍有每实例的宽松限流(fail-safe),不牺牲整体可用性(本地限流很快、无外部依赖)。
// procLimiter 是进程内固定窗口计数器(每实例独立,不追求精确——兜底而已)。
type procLimiter struct {
mu sync.Mutex
counts map[string]*winCount
window time.Duration
}
type winCount struct {
n int
reset time.Time
}
func newProcLimiter(window time.Duration) *procLimiter {
return &procLimiter{counts: make(map[string]*winCount), window: window}
}
// allow 固定窗口内对 key 累加,超 limit 拒绝。顺带惰性清理过期项防 map 无界增长。
func (l *procLimiter) allow(key string, limit int, now time.Time) bool {
l.mu.Lock()
defer l.mu.Unlock()
if len(l.counts) > 10000 {
for k, wc := range l.counts {
if now.After(wc.reset) {
delete(l.counts, k)
}
}
}
wc := l.counts[key]
if wc == nil || now.After(wc.reset) {
l.counts[key] = &winCount{n: 1, reset: now.Add(l.window)}
return true
}
wc.n++
return wc.n <= limit
}
// 全局兜底器(1 分钟窗口,与 Redis 限流同窗口口径)。
var fallbackLimiter = newProcLimiter(time.Minute)
// allowWithFallback 优先用 Redis 限流;Redis 降级/故障(!Enabled 或 Allow 出错)时回落进程内兜底。
// 返回 true=放行。这是把 fail-open 改成 fail-safe 的关键接缝。
func allowWithFallback(cache *store.Redis, ctx context.Context, key string, limit int) bool {
ok, err := cache.Allow(ctx, key, int64(limit), time.Minute)
if !cache.Enabled() || err != nil {
return fallbackLimiter.allow(key, limit, time.Now())
}
return ok
}
// RateLimitN 对某类端点施加更严的独立限流(按 IP + prefix 分桶),用于登录/注册等爆破面大的
// 公开端点。与全局 RateLimit 叠加(两道桶都过才放行)。Redis 故障时走进程内兜底。
func RateLimitN(cache *store.Redis, perMinute int, prefix string) gin.HandlerFunc {
return func(c *gin.Context) {
key := prefix + ":" + c.ClientIP()
if !allowWithFallback(cache, c.Request.Context(), key, perMinute) {
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "请求过于频繁,请稍后再试"})
return
}
c.Next()
}
}
@@ -0,0 +1,56 @@
package middleware
import (
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/sundynix/sundynix-gateway/internal/auth"
)
// A5:进程内兜底限流——固定窗口内超限即拒,过窗后恢复。Redis 挂时靠它 fail-safe。
func TestProcLimiter(t *testing.T) {
l := newProcLimiter(time.Minute)
now := time.Now()
for i := 0; i < 3; i++ {
if !l.allow("k", 3, now) {
t.Fatalf("前 3 次应放行(第 %d 次被拒)", i+1)
}
}
if l.allow("k", 3, now) {
t.Fatal("超限第 4 次应拒")
}
if !l.allow("k", 3, now.Add(2*time.Minute)) {
t.Fatal("新窗口应恢复放行")
}
}
// A6AuthFromHeaderOrQuery——?token= 有效则注入 uid、无 token 则 401。
func TestAuthFromHeaderOrQuery(t *testing.T) {
gin.SetMode(gin.TestMode)
tok, err := auth.Issue("u1")
if err != nil {
t.Fatalf("签发失败: %v", err)
}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET", "/x?token="+tok, nil)
AuthFromHeaderOrQuery()(c)
if c.IsAborted() {
t.Fatal("有效 query token 不该被拦")
}
if v, _ := c.Get(CtxUserID); v != "u1" {
t.Fatalf("应注入 uid=u1,得 %v", v)
}
w2 := httptest.NewRecorder()
c2, _ := gin.CreateTestContext(w2)
c2.Request = httptest.NewRequest("GET", "/x", nil)
AuthFromHeaderOrQuery()(c2)
if !c2.IsAborted() || w2.Code != 401 {
t.Fatalf("无 token 应 401,得 aborted=%v code=%d", c2.IsAborted(), w2.Code)
}
}