Files
sundynix-agentix/sundynix-gateway/internal/middleware/ratelimit.go
T
Blizzard ac38d5e663 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>
2026-07-21 15:04:47 +08:00

79 lines
2.6 KiB
Go

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()
}
}