mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-11-24 23:21:18 +00:00
用户可高频刷面板接口(usage/dashboard 等重聚合查询)直接打爆数据库:
现有限流器只覆盖登录/注册等公开认证入口,登录后的全部面板端点无任何限流。
三层防护(阈值均可在后台可视化配置,panel_rate_limit_settings):
1. 认证面板接口按「用户 ID」限流,与来源 IP 无关——反向代理/NAT 共享出口
(所有请求源地址坍缩为 127.0.0.1 等)不会互相误伤:
- Global 档(默认 240 rpm/账号):user/auth/payment/admin 全部登录后路由
- Heavy 档(默认 60 rpm/账号):/usage、/usage/dashboard/*、
/user/api-keys/:id/usage/daily 等重 SQL 聚合端点叠加计数
- 管理员默认豁免(可关闭)
2. 无认证公开接口(/api/v1/settings/*,每次请求都查 DB)按安全客户端 IP
限流(默认 300 rpm/IP);回环/私网/链路本地地址(反代内部转发地址)
一律跳过计数,杜绝把整条反代链路合并进同一个桶造成大面积误拦截。
3. 修复既有隐患:auth 入口限流的 IP 取值从 c.ClientIP() 切换到与审计日志/
会话绑定/API Key ACL 同源的安全客户端 IP 解析(尊重后台「信任反代转发
IP」开关快照)。原实现下默认反代部署(未配置 server.trusted_proxies)
所有用户共享同一个登录限流桶,既会全员误拦也可被单人恶意占满形成登录
DoS;开关关闭时行为与原来完全一致。
工程约束:
- 配置热路径走进程内缓存(atomic.Value + singleflight,60s TTL),
限流中间件零 DB 访问;保存后当前节点立即生效
- 面板限流 Redis 故障 fail-open(auth 入口保持原有 fail-close)
- 429 响应携带 Retry-After;错误码 RATE_LIMITED
- 支付 webhook / 公开支付回调有意不挂限流
- 新增 GET/PUT /api/v1/admin/settings/panel-rate-limit;设置页安全 tab
新增「面板接口限流」卡片(zh/en i18n 全量)
测试:rate_limiter/panel_rate_limit/setting_panel_rate_limit 单测全绿;
routes、handler/admin、-tags unit 契约测试通过;前端 vue-tsc/ESLint/
SettingsView spec(26/26,含新增交互用例)/i18n 守卫全部通过。
139 lines
5.4 KiB
Go
139 lines
5.4 KiB
Go
package routes
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"sort"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/Wei-Shaw/sub2api/internal/handler"
|
|
"github.com/Wei-Shaw/sub2api/internal/securityaudit"
|
|
servermiddleware "github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func TestEveryGatewayPOSTRouteIsClassifiedForPromptAuditCoverage(t *testing.T) {
|
|
routeSource, err := os.ReadFile("gateway.go")
|
|
require.NoError(t, err)
|
|
pattern := regexp.MustCompile(`(?:gateway|gemini|r|codexDirect|antigravityV1|antigravityV1Beta)\.POST\("([^"]+)"`)
|
|
matches := pattern.FindAllStringSubmatch(string(routeSource), -1)
|
|
actual := map[string]struct{}{}
|
|
for _, match := range matches {
|
|
actual[match[1]] = struct{}{}
|
|
}
|
|
|
|
audited := map[string][]string{
|
|
"/messages": {"gateway_handler.go", "openai_gateway_handler.go"},
|
|
"/responses": {"gateway_handler_responses.go", "openai_gateway_handler.go"},
|
|
"/responses/*subpath": {"gateway_handler_responses.go", "openai_gateway_handler.go"},
|
|
"/chat/completions": {"gateway_handler_chat_completions.go", "openai_chat_completions.go"},
|
|
"/embeddings": {"openai_embeddings.go"},
|
|
"/alpha/search": {"openai_alpha_search.go"},
|
|
"/live": {"openai_live.go"},
|
|
"/realtime/calls": {"openai_live.go"},
|
|
"/images/generations": {"openai_images.go", "grok_media.go"},
|
|
"/images/edits": {"openai_images.go", "grok_media.go"},
|
|
"/images/generations/async": {"image_task_handler.go"},
|
|
"/images/edits/async": {"image_task_handler.go"},
|
|
"/images/batches": {"batch_image_handler.go"},
|
|
"/videos/generations": {"grok_media.go"},
|
|
"/videos/edits": {"grok_media.go"},
|
|
"/videos/extensions": {"grok_media.go"},
|
|
"/models/*modelAction": {"gemini_v1beta_handler.go"},
|
|
}
|
|
excluded := map[string]string{
|
|
"/messages/count_tokens": "tokenization only; it does not execute a model request",
|
|
"/images/batches/:id/cancel": "control-plane cancellation with no user prompt",
|
|
}
|
|
|
|
unclassified := make([]string, 0)
|
|
for route := range actual {
|
|
if _, ok := audited[route]; ok {
|
|
continue
|
|
}
|
|
if _, ok := excluded[route]; ok {
|
|
continue
|
|
}
|
|
unclassified = append(unclassified, route)
|
|
}
|
|
sort.Strings(unclassified)
|
|
require.Empty(t, unclassified, "new gateway POST routes must be audited or explicitly classified with a no-prompt reason")
|
|
|
|
for route, files := range audited {
|
|
_, exists := actual[route]
|
|
require.Truef(t, exists, "stale prompt-audit route manifest entry %s", route)
|
|
for _, filename := range files {
|
|
source, readErr := os.ReadFile(filepath.Join("..", "..", "handler", filename))
|
|
require.NoError(t, readErr)
|
|
require.Containsf(t, string(source), "checkSecurityAudit", "%s route handler %s bypasses Coordinator", route, filename)
|
|
}
|
|
}
|
|
|
|
for route, reason := range excluded {
|
|
require.NotEmpty(t, strings.TrimSpace(reason))
|
|
_, exists := actual[route]
|
|
require.Truef(t, exists, "stale excluded route %s", route)
|
|
}
|
|
}
|
|
|
|
func TestResponsesWebSocketHasFirstAndSubsequentTurnPromptGates(t *testing.T) {
|
|
routeSource, err := os.ReadFile("gateway.go")
|
|
require.NoError(t, err)
|
|
require.GreaterOrEqual(t, strings.Count(string(routeSource), `.GET("/responses"`), 2)
|
|
handlerSource, err := os.ReadFile(filepath.Join("..", "..", "handler", "openai_gateway_handler.go"))
|
|
require.NoError(t, err)
|
|
require.Contains(t, string(handlerSource), `checkSecurityAuditStage`)
|
|
require.Contains(t, string(handlerSource), `"first_turn"`)
|
|
require.Contains(t, string(handlerSource), `"subsequent_turn"`)
|
|
wsStart := strings.Index(string(handlerSource), `func (h *OpenAIGatewayHandler) ResponsesWebSocket`)
|
|
require.NotEqual(t, -1, wsStart)
|
|
wsSource := string(handlerSource)[wsStart:]
|
|
require.Less(t,
|
|
strings.Index(wsSource, `"first_turn"`),
|
|
strings.Index(wsSource, `TryAcquireUserSlotForAPIKey`),
|
|
"the first response.create gate must precede per-request user/account slots",
|
|
)
|
|
}
|
|
|
|
func TestPromptAuditAdminRoutesRejectUnauthenticatedAndNonAdminRequests(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
router := gin.New()
|
|
handlers := &handler.Handlers{Admin: &handler.AdminHandlers{
|
|
PromptAudit: securityaudit.NewPromptAdminHandler(nil),
|
|
}}
|
|
adminAuth := servermiddleware.AdminAuthMiddleware(func(c *gin.Context) {
|
|
if c.GetHeader("Authorization") == "" {
|
|
servermiddleware.AbortWithError(c, http.StatusUnauthorized, "UNAUTHORIZED", "Authorization required")
|
|
return
|
|
}
|
|
servermiddleware.AbortWithError(c, http.StatusForbidden, "FORBIDDEN", "Admin access required")
|
|
})
|
|
auditLog := servermiddleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() })
|
|
stepUp := servermiddleware.StepUpAuthMiddleware(func(c *gin.Context) { c.Next() })
|
|
RegisterAdminRoutes(router.Group("/api/v1"), handlers, adminAuth, auditLog, stepUp, nil, nil)
|
|
|
|
for _, tc := range []struct {
|
|
name string
|
|
auth string
|
|
wantStatus int
|
|
}{
|
|
{name: "unauthenticated", wantStatus: http.StatusUnauthorized},
|
|
{name: "non-admin", auth: "Bearer user-token", wantStatus: http.StatusForbidden},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
recorder := httptest.NewRecorder()
|
|
request := httptest.NewRequest(http.MethodGet, "/api/v1/admin/prompt-audit/config", nil)
|
|
if tc.auth != "" {
|
|
request.Header.Set("Authorization", tc.auth)
|
|
}
|
|
router.ServeHTTP(recorder, request)
|
|
require.Equal(t, tc.wantStatus, recorder.Code)
|
|
})
|
|
}
|
|
}
|