From 6b2fdfcac262ec826be24c9ca857f39e40ef7119 Mon Sep 17 00:00:00 2001 From: Shumin <332587268@qq.com> Date: Fri, 9 Oct 2026 14:29:01 -0400 Subject: [PATCH 001/297] fix(openai): return JSON for non-stream OAuth passthrough /v1/responses OAuth passthrough forces stream=true for the ChatGPT internal API and then overwrote reqStream from the rewritten body, so clients sending stream=false received the raw upstream SSE stream. Keep the client's original stream flag (compact requests stay non-streaming) so the non-streaming branch aggregates SSE into a single Responses object. Also set Content-Type explicitly when the SSE-to-JSON handlers write the aggregated body: the upstream text/event-stream header was already copied into the response and gin's c.Data does not override an existing Content-Type. Applies to both passthrough and non-passthrough paths. Fixes #7978 --- .../service/openai_gateway_passthrough.go | 10 +- .../openai_gateway_response_handling.go | 3 + ...penai_oauth_passthrough_non_stream_test.go | 99 +++++++++++++++++++ 3 files changed, 111 insertions(+), 1 deletion(-) create mode 100644 backend/internal/service/openai_oauth_passthrough_non_stream_test.go diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index bf74b242d9..57e6cb9cdb 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -178,7 +178,12 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( if normalized { body = normalizedBody } - reqStream = gjson.GetBytes(body, "stream").Bool() + // 上游 ChatGPT internal API 要求 stream=true,但下游响应形态必须遵循 + // 客户端原始的 stream 标志:stream=false 时由非流式分支把上游 SSE + // 聚合为单个 JSON(#7978)。compact 请求始终为非流式。 + if isOpenAIResponsesCompactPath(c) { + reqStream = false + } accountScopedBody, accountScoped, scopeErr := applyCodexAccountIdentityClientMetadataRaw(body, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c)) if scopeErr != nil { @@ -2433,6 +2438,9 @@ func (s *OpenAIGatewayService) handlePassthroughSSEToJSON(resp *http.Response, c } } if !writeOpenAICompactSSEBridge(c, resp.StatusCode, body) { + // 上游的 Content-Type(text/event-stream)已复制到响应头,而 c.Data + // 不会覆盖已存在的 Content-Type,这里需显式设置为聚合后的类型。 + c.Writer.Header().Set("Content-Type", contentType) c.Data(resp.StatusCode, contentType, body) } diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index d4c8f723b6..763f2ebb4f 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -1787,6 +1787,9 @@ func (s *OpenAIGatewayService) handleSSEToJSON(resp *http.Response, c *gin.Conte } } if !writeOpenAICompactSSEBridge(c, resp.StatusCode, body) { + // 上游的 Content-Type(text/event-stream)已复制到响应头,而 c.Data + // 不会覆盖已存在的 Content-Type,这里需显式设置为聚合后的类型。 + c.Writer.Header().Set("Content-Type", contentType) c.Data(resp.StatusCode, contentType, body) } diff --git a/backend/internal/service/openai_oauth_passthrough_non_stream_test.go b/backend/internal/service/openai_oauth_passthrough_non_stream_test.go new file mode 100644 index 0000000000..a9ca12f674 --- /dev/null +++ b/backend/internal/service/openai_oauth_passthrough_non_stream_test.go @@ -0,0 +1,99 @@ +package service + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// Regression tests for #7978: /v1/responses with stream=false must return a +// single JSON Responses object even though the ChatGPT OAuth upstream is +// always called with stream=true and answers with SSE. + +const openAINonStreamRegressionSSE = "event: response.created\n" + + `data: {"type":"response.created","response":{"id":"resp_7978","status":"in_progress","output":[]}}` + "\n\n" + + "event: response.completed\n" + + `data: {"type":"response.completed","response":{"id":"resp_7978","object":"response","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"OK"}]}],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}` + "\n\n" + +func runOpenAIOAuthNonStreamRegression(t *testing.T, passthrough bool, requestBody string) (*httptest.ResponseRecorder, *httpUpstreamRecorder, *OpenAIForwardResult) { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil)) + c.Request.Header.Set("Accept", "application/json") + + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid_7978"}}, + Body: io.NopCloser(strings.NewReader(openAINonStreamRegressionSSE)), + }} + cfg := &config.Config{} + svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: upstream, responseHeaderFilter: compileResponseHeaderFilter(cfg)} + account := &Account{ + ID: 7978, + Name: "acc", + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Concurrency: 1, + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-acc"}, + Extra: map[string]any{"openai_passthrough": passthrough}, + Status: StatusActive, + Schedulable: true, + RateMultiplier: f64p(1), + } + + result, err := svc.Forward(context.Background(), c, account, []byte(requestBody)) + require.NoError(t, err) + require.NotNil(t, result) + return rec, upstream, result +} + +func requireSingleJSONResponsesObject(t *testing.T, rec *httptest.ResponseRecorder) { + t.Helper() + require.True(t, strings.HasPrefix(rec.Header().Get("Content-Type"), "application/json"), "Content-Type=%q", rec.Header().Get("Content-Type")) + var obj map[string]any + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &obj), "body=%s", rec.Body.String()) + require.Equal(t, "resp_7978", obj["id"]) + require.Equal(t, "completed", obj["status"]) + require.Equal(t, "OK", gjson.GetBytes(rec.Body.Bytes(), "output.0.content.0.text").String()) +} + +func TestOpenAIGatewayService_OAuthPassthrough_StreamFalseReturnsJSON(t *testing.T) { + rec, upstream, result := runOpenAIOAuthNonStreamRegression(t, true, + `{"model":"gpt-5.4","instructions":"x","input":"Reply with exactly OK.","stream":false}`) + + // Upstream still requires stream=true. + require.True(t, gjson.GetBytes(upstream.lastBody, "stream").Bool()) + require.False(t, result.Stream) + requireSingleJSONResponsesObject(t, rec) +} + +func TestOpenAIGatewayService_OAuthPassthrough_StreamTrueStillStreams(t *testing.T) { + rec, upstream, result := runOpenAIOAuthNonStreamRegression(t, true, + `{"model":"gpt-5.4","instructions":"x","input":"Reply with exactly OK.","stream":true}`) + + require.True(t, gjson.GetBytes(upstream.lastBody, "stream").Bool()) + require.True(t, result.Stream) + require.True(t, strings.HasPrefix(rec.Header().Get("Content-Type"), "text/event-stream"), "Content-Type=%q", rec.Header().Get("Content-Type")) + require.Contains(t, rec.Body.String(), "event: response.completed") +} + +func TestOpenAIGatewayService_OAuthLegacy_StreamFalseReturnsJSONContentType(t *testing.T) { + rec, upstream, result := runOpenAIOAuthNonStreamRegression(t, false, + `{"model":"gpt-5.4","instructions":"x","input":"Reply with exactly OK.","stream":false}`) + + require.True(t, gjson.GetBytes(upstream.lastBody, "stream").Bool()) + require.False(t, result.Stream) + requireSingleJSONResponsesObject(t, rec) +} From 9b5407449c8d0b8f41abba4756da3bab47a67945 Mon Sep 17 00:00:00 2001 From: Shumin <332587268@qq.com> Date: Fri, 9 Oct 2026 17:01:53 -0400 Subject: [PATCH 002/297] fix(openai): return JSON for incomplete/cancelled non-stream Responses When a non-streaming /v1/responses request is aggregated from upstream SSE and the stream ends with response.incomplete (e.g. max_output_tokens) or response.cancelled instead of response.completed, the SSE-to-JSON handlers fell back to relaying the raw SSE body. Use the terminal event's response object as the final JSON (keeping status/incomplete_details) in both handlePassthroughSSEToJSON and handleSSEToJSON. Usage is still recorded. extractCodexFinalResponse is unchanged. Refs #7978 --- .../service/openai_gateway_passthrough.go | 3 ++ .../openai_gateway_response_handling.go | 18 ++++++++ ...penai_oauth_passthrough_non_stream_test.go | 46 ++++++++++++++++++- 3 files changed, 65 insertions(+), 2 deletions(-) diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index 57e6cb9cdb..3c1428540b 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -2392,6 +2392,9 @@ func (s *OpenAIGatewayService) handlePassthroughSSEToJSON(resp *http.Response, c return nil, s.writeOpenAINonStreamingProtocolError(resp, c, msg) } finalResponse, ok := extractCodexFinalResponse(bodyText) + if !ok && terminalOK { + finalResponse, ok = extractOpenAINonCompletedTerminalResponse(terminalType, terminalPayload) + } usage := s.parseSSEUsageFromBody(bodyText) if ok { diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index 763f2ebb4f..47e3753bbe 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -1731,6 +1731,9 @@ func (s *OpenAIGatewayService) handleSSEToJSON(resp *http.Response, c *gin.Conte return nil, s.writeOpenAINonStreamingProtocolError(resp, c, msg) } finalResponse, ok := extractCodexFinalResponse(bodyText) + if !ok && terminalOK { + finalResponse, ok = extractOpenAINonCompletedTerminalResponse(terminalType, terminalPayload) + } usage := s.parseSSEUsageFromBody(bodyText) if ok { @@ -1965,6 +1968,21 @@ func (s *OpenAIGatewayService) writeOpenAINonStreamingProtocolError(resp *http.R return fmt.Errorf("non-streaming openai protocol error: %s", message) } +// extractOpenAINonCompletedTerminalResponse 在没有 response.completed/done 时, +// 从 response.incomplete / response.cancelled 终止事件中取出 response 对象, +// 使非流式客户端拿到带 status/incomplete_details 的单个 JSON,而不是原始 SSE。 +func extractOpenAINonCompletedTerminalResponse(terminalType string, payload []byte) ([]byte, bool) { + switch terminalType { + case "response.incomplete", "response.cancelled", "response.canceled": + default: + return nil, false + } + if response := gjson.GetBytes(payload, "response"); response.Exists() && response.IsObject() { + return []byte(response.Raw), true + } + return nil, false +} + func extractCodexFinalResponse(body string) ([]byte, bool) { var finalResponse []byte forEachOpenAISSEFrame(body, func(eventType string, data []byte) { diff --git a/backend/internal/service/openai_oauth_passthrough_non_stream_test.go b/backend/internal/service/openai_oauth_passthrough_non_stream_test.go index a9ca12f674..cb17e74a2b 100644 --- a/backend/internal/service/openai_oauth_passthrough_non_stream_test.go +++ b/backend/internal/service/openai_oauth_passthrough_non_stream_test.go @@ -25,7 +25,7 @@ const openAINonStreamRegressionSSE = "event: response.created\n" + "event: response.completed\n" + `data: {"type":"response.completed","response":{"id":"resp_7978","object":"response","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"OK"}]}],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}` + "\n\n" -func runOpenAIOAuthNonStreamRegression(t *testing.T, passthrough bool, requestBody string) (*httptest.ResponseRecorder, *httpUpstreamRecorder, *OpenAIForwardResult) { +func runOpenAIOAuthNonStreamRegression(t *testing.T, passthrough bool, requestBody string, upstreamSSE ...string) (*httptest.ResponseRecorder, *httpUpstreamRecorder, *OpenAIForwardResult) { t.Helper() gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() @@ -33,10 +33,14 @@ func runOpenAIOAuthNonStreamRegression(t *testing.T, passthrough bool, requestBo c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil)) c.Request.Header.Set("Accept", "application/json") + sseBody := openAINonStreamRegressionSSE + if len(upstreamSSE) > 0 { + sseBody = upstreamSSE[0] + } upstream := &httpUpstreamRecorder{resp: &http.Response{ StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid_7978"}}, - Body: io.NopCloser(strings.NewReader(openAINonStreamRegressionSSE)), + Body: io.NopCloser(strings.NewReader(sseBody)), }} cfg := &config.Config{} svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: upstream, responseHeaderFilter: compileResponseHeaderFilter(cfg)} @@ -97,3 +101,41 @@ func TestOpenAIGatewayService_OAuthLegacy_StreamFalseReturnsJSONContentType(t *t require.False(t, result.Stream) requireSingleJSONResponsesObject(t, rec) } + +const openAINonStreamIncompleteSSE = "event: response.created\n" + + `data: {"type":"response.created","response":{"id":"resp_7978","status":"in_progress","output":[]}}` + "\n\n" + + "event: response.output_text.delta\n" + + `data: {"type":"response.output_text.delta","delta":"Hel"}` + "\n\n" + + "event: response.incomplete\n" + + `data: {"type":"response.incomplete","response":{"id":"resp_7978","object":"response","status":"incomplete","incomplete_details":{"reason":"max_output_tokens"},"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Hel"}]}],"usage":{"input_tokens":5,"output_tokens":16,"total_tokens":21}}}` + "\n\n" + +func TestOpenAIGatewayService_OAuthStreamFalseIncompleteReturnsJSON(t *testing.T) { + for _, passthrough := range []bool{true, false} { + rec, _, result := runOpenAIOAuthNonStreamRegression(t, passthrough, + `{"model":"gpt-5.4","instructions":"x","input":"hi","max_output_tokens":16,"stream":false}`, + openAINonStreamIncompleteSSE) + + require.False(t, result.Stream) + require.True(t, strings.HasPrefix(rec.Header().Get("Content-Type"), "application/json"), "passthrough=%v Content-Type=%q", passthrough, rec.Header().Get("Content-Type")) + var obj map[string]any + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &obj), "passthrough=%v body=%s", passthrough, rec.Body.String()) + require.Equal(t, "resp_7978", obj["id"]) + require.Equal(t, "incomplete", obj["status"]) + require.Equal(t, "max_output_tokens", gjson.GetBytes(rec.Body.Bytes(), "incomplete_details.reason").String()) + require.Equal(t, "Hel", gjson.GetBytes(rec.Body.Bytes(), "output.0.content.0.text").String()) + require.Equal(t, 5, result.Usage.InputTokens) + require.Equal(t, 16, result.Usage.OutputTokens) + } +} + +func TestOpenAIGatewayService_OAuthStreamFalseCancelledReturnsJSON(t *testing.T) { + cancelledSSE := "event: response.cancelled\n" + + `data: {"type":"response.cancelled","response":{"id":"resp_7978","object":"response","status":"cancelled","output":[],"usage":{"input_tokens":5,"output_tokens":0,"total_tokens":5}}}` + "\n\n" + for _, passthrough := range []bool{true, false} { + rec, _, _ := runOpenAIOAuthNonStreamRegression(t, passthrough, + `{"model":"gpt-5.4","instructions":"x","input":"hi","stream":false}`, cancelledSSE) + + require.True(t, strings.HasPrefix(rec.Header().Get("Content-Type"), "application/json"), "passthrough=%v Content-Type=%q", passthrough, rec.Header().Get("Content-Type")) + require.Equal(t, "cancelled", gjson.GetBytes(rec.Body.Bytes(), "status").String(), "passthrough=%v body=%s", passthrough, rec.Body.String()) + } +} From 5db2d6956ba60fb5c9401823561a166d38295095 Mon Sep 17 00:00:00 2001 From: Yuan Liu <3638888+Yukinoshita-Yukino@users.noreply.github.com> Date: Sat, 10 Oct 2026 20:01:39 +0800 Subject: [PATCH 003/297] fix(billing): retain DeepSeek V4 Pro pricing after September 14 --- backend/internal/service/billing_service.go | 47 +++++-------------- .../internal/service/deepseek_pricing_test.go | 45 +++++++++--------- 2 files changed, 34 insertions(+), 58 deletions(-) diff --git a/backend/internal/service/billing_service.go b/backend/internal/service/billing_service.go index 449acf1597..e2ae9845d9 100644 --- a/backend/internal/service/billing_service.go +++ b/backend/internal/service/billing_service.go @@ -267,9 +267,8 @@ var ErrModelPricingUnavailable = errors.New("pricing not found") // ---- DeepSeek 官方低谷价($/token)---- // 2026-09-10 官方公告:DeepSeek-V4.1-Flash(新名 deepseek-flash)大幅降价, // Flash 低谷价降为 $0.15/$0.60/$0.003 per MTok(输入缓存未命中/输出/缓存命中); -// deepseek-v4-pro 名义价格暂不变,但自北京时间 2026-09-14 12:00(04:00 UTC)起 -// 其请求被上游路由到 V4.1-Flash 并按 Flash 价计费(见 deepseekProBilledAsFlash)。 -// Source: https://api-docs.deepseek.com/news/news260910 +// 官方后续确认 2026-09-14 后继续提供 deepseek-v4-pro,计费方式保持不变。 +// Source: https://api-docs.deepseek.com/updates/ // // https://api-docs.deepseek.com/quick_start/pricing // @@ -311,21 +310,6 @@ func deepseekPeakMultiplierAt(now time.Time) float64 { return 1.0 } -// deepseekProRoutesToFlashAt:官方公告自北京时间 2026-09-14 12:00(04:00 UTC)起, -// 所有 deepseek-v4-pro 请求被上游路由到 V4.1-Flash 并按 Flash 价计费(直至未来 -// V4.1 Pro 上线)。Source: https://api-docs.deepseek.com/news/news260910 -var deepseekProRoutesToFlashAt = time.Date(2026, 9, 14, 4, 0, 0, 0, time.UTC) - -// deepseekProBilledAsFlash 报告指定计费时点 deepseek-v4-pro 是否已按 Flash 价 -// 计费:计费时点到达或晚于切换时点返回 true;零值时点回退当前时刻(与峰谷 -// 倍率的取时点方式一致,见 calculateTokenCost)。 -func deepseekProBilledAsFlash(pricingAt time.Time) bool { - if pricingAt.IsZero() { - pricingAt = timezone.Now() - } - return !pricingAt.Before(deepseekProRoutesToFlashAt) -} - // isDeepSeekProModel 判断模型名是否归入 deepseek-v4-pro 档(含版本化名称, // 如 deepseek-v4-pro-0813)。 func isDeepSeekProModel(model string) bool { @@ -1321,13 +1305,11 @@ func (s *BillingService) HasIdentifiedTokenPricing(model string) bool { // GetModelPricing 获取模型价格配置 func (s *BillingService) GetModelPricing(model string) (*ModelPricing, error) { - // 无显式计费时点,DeepSeek pro→Flash 切换按当前时刻判定。 return s.getModelPricingAt(model, timezone.Now()) } -// getModelPricingAt 是 GetModelPricing 的带计费时点内部变体:pricingAt 显式 -// 驱动 DeepSeek pro→Flash 切换判定(切换点前 Pro 价、之后 Flash 价),使 -// 展示/估算路径可与历史补账同刻复算,测试也能用固定时点钉住断言。 +// getModelPricingAt 保留带计费时点的内部调用接口。DeepSeek 默认低谷价 +// 仅由模型决定,峰谷倍率由统一计费入口按请求时点处理。 func (s *BillingService) getModelPricingAt(model string, pricingAt time.Time) (*ModelPricing, error) { // 标准化模型名称(转小写) model = strings.ToLower(model) @@ -1552,8 +1534,7 @@ func (s *BillingService) calculateTokenCost(resolved *ResolvedPricing, input Cos return nil, fmt.Errorf("no pricing available for model: %s: %w", input.Model, ErrModelPricingUnavailable) } - // 计费时点:优先请求级 PricingAt(历史补账与 DeepSeek pro→Flash 切换判定 - // 同源),零值回退当前时刻。 + // 峰谷计费时点:优先请求级 PricingAt,零值回退当前时刻。 pricingAt := input.PricingAt if pricingAt.IsZero() { pricingAt = timezone.Now() @@ -1829,17 +1810,15 @@ func (s *BillingService) calculateCostInternalWithPolicy( // 强制覆盖;GPT-5.6 缺 cache_write 价时按官方规则补 1.25 倍输入价;Fast/priority // 档按业务倍率改写(本地/远程目录的 priority 价可能沿用官方旧口径)。长上下文 // 阶梯不在此处补齐:一律由目录数据(above_XXXk 折算或显式 long_context_* 字段) -// 驱动。强制 DeepSeek 官方价且无显式计费时点(pro→Flash 切换按当前时刻判定), -// 供无既有时点的策略修正场景与测试使用;计费/展示主路径分别经 -// calculateTokenCost 与 getModelPricingAt 显式传时点,分组/渠道自定义定价 -// 用 applyModelSpecificPricingPolicyEx 关闭强制,保留运营者配置。 +// 驱动。分组/渠道自定义定价用 applyModelSpecificPricingPolicyEx 关闭 +// DeepSeek 官方价强制覆盖,保留运营者配置。 func (s *BillingService) applyModelSpecificPricingPolicy(model string, pricing *ModelPricing) *ModelPricing { return s.applyModelSpecificPricingPolicyEx(model, pricing, true, time.Time{}) } // applyModelSpecificPricingPolicyEx 与 applyModelSpecificPricingPolicy 相同, -// 但由调用方控制是否强制 DeepSeek 官方价(forceDeepSeekRates),并显式传入 -// 计费时点 pricingAt(零值表示按当前时刻判定)。 +// 但由调用方控制是否强制 DeepSeek 官方价(forceDeepSeekRates)。 +// 保留计费时点参数以兼容现有调用;模型价卡不再按日期切换。 // calculateTokenCost 对分组/渠道自定义定价(Source 非 LiteLLM)传 false: // 强制覆盖会把运营者配置的售价盖回官方价,违反自定义定价语义。 func (s *BillingService) applyModelSpecificPricingPolicyEx(model string, pricing *ModelPricing, forceDeepSeekRates bool, pricingAt time.Time) *ModelPricing { @@ -1852,20 +1831,18 @@ func (s *BillingService) applyModelSpecificPricingPolicyEx(model string, pricing // 共享 fallbackPrices 指针。 // 档位判定:含 "deepseek-v4-pro" 的版本化名称(如 deepseek-v4-pro-0813)归 pro 档, // 其余 deepseek-*(含已停服的 chat/reasoner 与未知型号)统一归 flash 档。 - // 2026-09-14 04:00 UTC 起上游把 pro 请求路由到 V4.1-Flash,pro 档改按 - // Flash 三档价计费;历史时点(早于切换时刻)仍按 Pro 价。 + // 官方后续保留了 Pro 服务及其计费方式,Pro 不按日期切换成 Flash 价。 // 高峰时段倍率不在本函数处理,由 calculateTokenCost 按 deepseekPeakMultiplierAt // 对默认价卡另行叠加(分组/渠道自定义定价不叠加)。 if forceDeepSeekRates && isDeepSeekModel(model) { cloned := *pricing - if isDeepSeekProModel(model) && !deepseekProBilledAsFlash(pricingAt) { + if isDeepSeekProModel(model) { cloned.InputPricePerToken = deepseekProOffPeakInputPrice cloned.OutputPricePerToken = deepseekProOffPeakOutputPrice cloned.CacheReadPricePerToken = deepseekProOffPeakCacheRead } else { // deepseek-flash(= V4.1-Flash)、deepseek-v4-flash / - // deepseek-v4-flash-vision-exp 与其余 deepseek-* 共用 flash 价; - // 切换时点之后的 pro 请求同样按 flash 价计费。 + // deepseek-v4-flash-vision-exp 与其余 deepseek-* 共用 flash 价。 cloned.InputPricePerToken = deepseekFlashOffPeakInputPrice cloned.OutputPricePerToken = deepseekFlashOffPeakOutputPrice cloned.CacheReadPricePerToken = deepseekFlashOffPeakCacheRead diff --git a/backend/internal/service/deepseek_pricing_test.go b/backend/internal/service/deepseek_pricing_test.go index 7862d82e0e..4f7f8b6f49 100644 --- a/backend/internal/service/deepseek_pricing_test.go +++ b/backend/internal/service/deepseek_pricing_test.go @@ -262,13 +262,13 @@ func TestGetModelPricing_DeepseekForcesOfficialRatesOverJSON(t *testing.T) { } for _, tt := range tests { t.Run(tt.model, func(t *testing.T) { - // flash 档三档价与 pro→Flash 切换无关,GetModelPricing 断言不随时间翻转。 + // Flash 默认价格不随日期切换。 pricing, err := bs.GetModelPricing(tt.model) require.NoError(t, err) require.InDelta(t, tt.input, pricing.InputPricePerToken, 1e-15) require.InDelta(t, tt.output, pricing.OutputPricePerToken, 1e-15) require.InDelta(t, tt.cacheRead, pricing.CacheReadPricePerToken, 1e-15) - // 固定时点(切换点之后的 2026-10-01)复核:仍走 Flash 新价。 + // 固定时点 2026-10-01 复核:仍走 Flash 新价。 atPricing, err := bs.getModelPricingAt(tt.model, time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)) require.NoError(t, err) require.InDelta(t, tt.input, atPricing.InputPricePerToken, 1e-15) @@ -279,10 +279,10 @@ func TestGetModelPricing_DeepseekForcesOfficialRatesOverJSON(t *testing.T) { } // pro 档(含版本化名称):断言经固定时点的 getModelPricingAt,不依赖墙上时钟。 - // 2026-08-01 早于切换点 2026-09-14 04:00 UTC → Pro 价。 + // 官方确认 2026-09-14 后继续提供 Pro,计费方式保持不变。 for _, model := range []string{"deepseek-v4-pro", "deepseek-v4-pro-0813"} { - t.Run(model+"/before-cutoff", func(t *testing.T) { - pricing, err := bs.getModelPricingAt(model, time.Date(2026, 8, 1, 0, 0, 0, 0, time.UTC)) + t.Run(model+"/after-september-14", func(t *testing.T) { + pricing, err := bs.getModelPricingAt(model, time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)) require.NoError(t, err) require.InDelta(t, 6.6e-7, pricing.InputPricePerToken, 1e-15) require.InDelta(t, 1.98e-6, pricing.OutputPricePerToken, 1e-15) @@ -290,7 +290,7 @@ func TestGetModelPricing_DeepseekForcesOfficialRatesOverJSON(t *testing.T) { }) } - // 半开边界钉死:2026-09-14 03:59:59 仍 Pro 价,04:00:00 整起 Flash 新价。 + // 原计划切换时点前后均保持 Pro 价。 proBefore, err := bs.getModelPricingAt("deepseek-v4-pro", time.Date(2026, 9, 14, 3, 59, 59, 0, time.UTC)) require.NoError(t, err) require.InDelta(t, 6.6e-7, proBefore.InputPricePerToken, 1e-15) @@ -298,12 +298,12 @@ func TestGetModelPricing_DeepseekForcesOfficialRatesOverJSON(t *testing.T) { require.InDelta(t, 2.2e-8, proBefore.CacheReadPricePerToken, 1e-15) proAtCutoff, err := bs.getModelPricingAt("deepseek-v4-pro", time.Date(2026, 9, 14, 4, 0, 0, 0, time.UTC)) require.NoError(t, err) - require.InDelta(t, 1.5e-7, proAtCutoff.InputPricePerToken, 1e-15) - require.InDelta(t, 6e-7, proAtCutoff.OutputPricePerToken, 1e-15) - require.InDelta(t, 3e-9, proAtCutoff.CacheReadPricePerToken, 1e-15) + require.InDelta(t, 6.6e-7, proAtCutoff.InputPricePerToken, 1e-15) + require.InDelta(t, 1.98e-6, proAtCutoff.OutputPricePerToken, 1e-15) + require.InDelta(t, 2.2e-8, proAtCutoff.CacheReadPricePerToken, 1e-15) // 版本化名称(不在 JSON / fallbackPrices 精确表中):按子串归档计价。 - // flash-0731 归 flash 档,三档价与切换无关,GetModelPricing 断言稳定。 + // flash-0731 归 flash 档,GetModelPricing 断言稳定。 versioned := []struct { model string input, output, cacheRead float64 @@ -381,7 +381,7 @@ func TestDeepseekPricingFileMatchesOfficialRates(t *testing.T) { // --------------------------------------------------------------------------- // 2026-09-10 官方降价:deepseek-flash(V4.1-Flash 新名)与旧名同价; -// 2026-09-14 04:00 UTC 起 deepseek-v4-pro 按上游路由改按 Flash 价计费 +// 官方确认 2026-09-14 后 deepseek-v4-pro 继续按 Pro 价计费 // --------------------------------------------------------------------------- func TestCalculateCostUnified_DeepseekFlashAndLegacyFlashShareNewRates(t *testing.T) { @@ -393,7 +393,7 @@ func TestCalculateCostUnified_DeepseekFlashAndLegacyFlashShareNewRates(t *testin offPeakTotal := 1000*1.5e-7 + 500*6e-7 + 1000*3e-9 // deepseek-flash 与 deepseek-v4-flash 都取 Flash 新价。 - // 时点取切换日 2026-09-14(周一)12:00 UTC 低谷,峰谷倍率不影响断言。 + // 时点取 2026-09-14(周一)12:00 UTC 低谷,峰谷倍率不影响断言。 for _, model := range []string{"deepseek-flash", "deepseek-v4-flash"} { cost, err := bs.CalculateCostUnified(CostInput{ Ctx: context.Background(), Model: model, Tokens: tokens, @@ -405,15 +405,14 @@ func TestCalculateCostUnified_DeepseekFlashAndLegacyFlashShareNewRates(t *testin } } -func TestCalculateCostUnified_DeepseekProRoutesToFlashAtCutoff(t *testing.T) { +func TestCalculateCostUnified_DeepseekProRetainsRatesAfterSeptember14(t *testing.T) { bs := newTestBillingService() resolver := NewModelPricingResolver(nil, bs) tokens := UsageTokens{InputTokens: 1000, OutputTokens: 500, CacheReadTokens: 1000} - proTotal := 1000*6.6e-7 + 500*1.98e-6 + 1000*2.2e-8 // 切换前 Pro 价 - flashTotal := 1000*1.5e-7 + 500*6e-7 + 1000*3e-9 // 切换后 Flash 价 + proTotal := 1000*6.6e-7 + 500*1.98e-6 + 1000*2.2e-8 - // 切换时点之前(2026-09-13 周日,北京周末全天低谷):仍按 Pro 价。 + // 原计划切换时点之前(2026-09-13 周日,北京周末全天低谷):按 Pro 价。 before, err := bs.CalculateCostUnified(CostInput{ Ctx: context.Background(), Model: "deepseek-v4-pro", Tokens: tokens, RateMultiplier: 1.0, Resolver: resolver, @@ -421,25 +420,25 @@ func TestCalculateCostUnified_DeepseekProRoutesToFlashAtCutoff(t *testing.T) { }) require.NoError(t, err) require.InDelta(t, proTotal, before.TotalCost, 1e-10, - "deepseek-v4-pro must use Pro rates before the 2026-09-14 04:00 UTC cutoff") + "deepseek-v4-pro must use Pro rates before September 14") - // 到达切换时点(2026-09-14 04:00 UTC 整,周一低谷窗口边界外):按 Flash 价。 + // 到达原计划切换时点(2026-09-14 04:00 UTC 整,周一低谷):仍按 Pro 价。 after, err := bs.CalculateCostUnified(CostInput{ Ctx: context.Background(), Model: "deepseek-v4-pro", Tokens: tokens, RateMultiplier: 1.0, Resolver: resolver, PricingAt: time.Date(2026, 9, 14, 4, 0, 0, 0, time.UTC), }) require.NoError(t, err) - require.InDelta(t, flashTotal, after.TotalCost, 1e-10, - "deepseek-v4-pro must use Flash rates at/after the 2026-09-14 04:00 UTC cutoff") + require.InDelta(t, proTotal, after.TotalCost, 1e-10, + "deepseek-v4-pro must retain Pro rates on September 14") - // 版本化名称同口径:切换后 deepseek-v4-pro-0813 也按 Flash 价。 + // 版本化名称同口径:deepseek-v4-pro-0813 也保持 Pro 价。 versioned, err := bs.CalculateCostUnified(CostInput{ Ctx: context.Background(), Model: "deepseek-v4-pro-0813", Tokens: tokens, RateMultiplier: 1.0, Resolver: resolver, PricingAt: time.Date(2026, 9, 14, 4, 0, 0, 0, time.UTC), }) require.NoError(t, err) - require.InDelta(t, flashTotal, versioned.TotalCost, 1e-10, - "versioned pro names must also route to Flash rates after the cutoff") + require.InDelta(t, proTotal, versioned.TotalCost, 1e-10, + "versioned pro names must retain Pro rates on September 14") } From c01b2cb817663e79c3ce1db1d611ffe33f2d589a Mon Sep 17 00:00:00 2001 From: Shumin Date: Wed, 14 Oct 2026 03:12:15 -0400 Subject: [PATCH 004/297] ci: retrigger CI (previous run hit Docker Hub rate limit) From e068c3d02ff8664c1142d5f7c51a05a82f75ad3d Mon Sep 17 00:00:00 2001 From: zeng gang Date: Fri, 16 Oct 2026 11:17:44 +0800 Subject: [PATCH 005/297] fix(openai): preserve overload retries after queued and metadata events --- backend/internal/service/openai_capacity_shed_test.go | 8 ++++++++ backend/internal/service/openai_gateway_passthrough.go | 4 +++- backend/internal/service/openai_ws_http_bridge_test.go | 4 ++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/backend/internal/service/openai_capacity_shed_test.go b/backend/internal/service/openai_capacity_shed_test.go index 7d2f8c8dd2..086f7380e3 100644 --- a/backend/internal/service/openai_capacity_shed_test.go +++ b/backend/internal/service/openai_capacity_shed_test.go @@ -124,6 +124,8 @@ func TestOpenAIStreamErrorFrameDoesNotStartClientOutput(t *testing.T) { {`{"type":"error","error":{"type":"invalid_request_error","code":"content_policy_violation","message":"blocked"}}`, "error", true}, {`{"type":"response.failed","response":{"error":{"code":"server_is_overloaded"}}}`, "response.failed", false}, {`{"type":"response.created","response":{"id":"resp_1"}}`, "response.created", false}, + {`{"type":"response.queued","response":{"id":"resp_1","status":"queued"}}`, "response.queued", false}, + {`{"type":"response.metadata","response_id":"resp_1","metadata":{"openai_chatgpt_moderation_metadata":{"prompt":{}}}}`, "response.metadata", false}, {`{"type":"response.in_progress","response":{"id":"resp_1"}}`, "response.in_progress", false}, {`{"type":"keepalive"}`, "keepalive", false}, {`{"type":"unknown_event"}`, "unknown_event", true}, @@ -147,6 +149,12 @@ func TestOpenAIStreamMetadataAndKeepaliveBeforeOverloadFailOver(t *testing.T) { "event: response.created", `data: {"type":"response.created","response":{"id":"resp_1","metadata":{"padding":"` + largeMetadata + `"}}}`, "", + "event: response.queued", + `data: {"type":"response.queued","response":{"id":"resp_1","status":"queued"}}`, + "", + "event: response.metadata", + `data: {"type":"response.metadata","response_id":"resp_1","metadata":{"openai_chatgpt_moderation_metadata":{"prompt":{}}}}`, + "", "event: response.output_item.added", `data: {"type":"response.output_item.added","item":{"type":"reasoning","summary":[]}}`, "", diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index 6feadb8fb6..170830ae4f 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -1087,7 +1087,9 @@ func openAIStreamClientOutputStarted(c *gin.Context, localStarted bool) bool { // Lifecycle metadata and transport heartbeats are not model output. func openAIStreamEventIsMetadata(eventType string) bool { switch strings.TrimSpace(eventType) { - case "response.created", "response.in_progress", "keepalive": + // Queuing and moderation metadata do not commit model output or disarm the + // first-output timeout; a following overload must remain safe to retry. + case "response.created", "response.queued", "response.in_progress", "response.metadata", "keepalive": return true default: return false diff --git a/backend/internal/service/openai_ws_http_bridge_test.go b/backend/internal/service/openai_ws_http_bridge_test.go index 12f08c655a..c8c654e6c6 100644 --- a/backend/internal/service/openai_ws_http_bridge_test.go +++ b/backend/internal/service/openai_ws_http_bridge_test.go @@ -1192,6 +1192,10 @@ func TestProxyOpenAIWSHTTPBridgeTurnStagesMetadataAndRelaysKeepaliveBeforeCapaci preamble := strings.Join([]string{ `data: {"type":"response.created","response":{"id":"resp_shed"}}`, "", + `data: {"type":"response.queued","response":{"id":"resp_shed","status":"queued"}}`, + "", + `data: {"type":"response.metadata","response_id":"resp_shed","metadata":{"openai_chatgpt_moderation_metadata":{"prompt":{}}}}`, + "", `data: {"type":"response.in_progress","response":{"id":"resp_shed"}}`, "", `data: {"type":"keepalive"}`, From 7fcaa32db4940ff9ca42b961b00c453b496d8d25 Mon Sep 17 00:00:00 2001 From: ahe <53739884+qhmhyp@users.noreply.github.com> Date: Fri, 16 Oct 2026 11:54:50 +0800 Subject: [PATCH 006/297] fix(accounts): persist platform and status filters --- frontend/src/views/admin/AccountsView.vue | 41 +++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/frontend/src/views/admin/AccountsView.vue b/frontend/src/views/admin/AccountsView.vue index 2502f2db8c..6d71337fdd 100644 --- a/frontend/src/views/admin/AccountsView.vue +++ b/frontend/src/views/admin/AccountsView.vue @@ -496,6 +496,7 @@ import { useI18n } from 'vue-i18n' import { useAppStore } from '@/stores/app' import { useAuthStore } from '@/stores/auth' import { adminAPI } from '@/api/admin' +import { CONCRETE_PLATFORM_OPTIONS } from '@/constants/platforms' import { useTableLoader } from '@/composables/useTableLoader' import { useSwipeSelect, type SwipeSelectVirtualContext } from '@/composables/useSwipeSelect' import { useTableSelection } from '@/composables/useTableSelection' @@ -653,6 +654,31 @@ const HIDDEN_COLUMNS_KEY = 'account-hidden-columns' const HIDDEN_COLUMNS_VERSION_KEY = 'account-hidden-columns-version' const HIDDEN_COLUMNS_CURRENT_VERSION = 'scheduler-score-hidden-by-default' +// Account filter settings +const ACCOUNT_FILTER_STORAGE_KEY = 'account-filter-values' +type AccountFilterValues = { + platform: string + status: string +} +const loadInitialAccountFilterValues = (): AccountFilterValues => { + const fallback: AccountFilterValues = { platform: '', status: '' } + try { + const raw = localStorage.getItem(ACCOUNT_FILTER_STORAGE_KEY) + if (!raw) return fallback + const parsed: unknown = JSON.parse(raw) + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return fallback + const values = parsed as Record + return { + platform: typeof values.platform === 'string' && CONCRETE_PLATFORM_OPTIONS.some(option => option.value === values.platform) + ? values.platform : '', + status: typeof values.status === 'string' && ['active', 'inactive', 'error', 'rate_limited', 'temp_unschedulable', 'unschedulable'].includes(values.status) + ? values.status : '' + } + } catch { + return fallback + } +} + // Sorting settings const ACCOUNT_SORT_STORAGE_KEY = 'account-table-sort' type AccountSortOrder = 'asc' | 'desc' @@ -1084,9 +1110,8 @@ const { } = useTableLoader({ fetchFn: adminAPI.accounts.list, initialParams: { - platform: '', + ...loadInitialAccountFilterValues(), type: '', - status: '', privacy_mode: '', group: '', search: '', @@ -1292,7 +1317,19 @@ const refreshUpstreamBillingSortedList = async (force = false) => { useIntervalFn(() => { void refreshUpstreamBillingRates() }, 5 * 60_000, { immediate: false }) +const saveAccountFilterValues = () => { + try { + localStorage.setItem(ACCOUNT_FILTER_STORAGE_KEY, JSON.stringify({ + platform: params.platform, + status: params.status + })) + } catch { + // Filtering must remain available when browser storage is unavailable. + } +} + const debouncedReload = () => { + saveAccountFilterValues() clearSelection() syncAccountListDerivedParams() hasPendingListSync.value = false From eb4ccd173e35b459661fff4a4f079f6f96fccc56 Mon Sep 17 00:00:00 2001 From: wucm667 Date: Fri, 16 Oct 2026 20:32:00 +0800 Subject: [PATCH 007/297] fix(openai): apply reasoning mappings to synthesized effort --- .../internal/handler/composite_platform.go | 7 ---- .../handler/composite_platform_test.go | 36 ++++++++++++++----- 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/backend/internal/handler/composite_platform.go b/backend/internal/handler/composite_platform.go index 6e613aa3e4..764a6a7f9d 100644 --- a/backend/internal/handler/composite_platform.go +++ b/backend/internal/handler/composite_platform.go @@ -163,13 +163,6 @@ func bindOpenAIReasoningEffortPolicyForMessagesRequest(c *gin.Context, apiKey *s return } bindRequestedReasoningEffort(c, body, strings.TrimSpace(gjson.GetBytes(body, "model").String())) - // The Messages bridge synthesizes a default OpenAI effort when - // output_config.effort is omitted. Bind the group policy only for an - // explicit client value so the ceiling does not alter that default. - effort := gjson.GetBytes(body, "output_config.effort") - if !effort.Exists() || effort.Type != gjson.String || strings.TrimSpace(effort.String()) == "" { - return - } maxEffort, mappings, overLimit, ok := openAIReasoningEffortPolicyForRequest(c, apiKey) if !ok { return diff --git a/backend/internal/handler/composite_platform_test.go b/backend/internal/handler/composite_platform_test.go index 7704a129a0..4dc504e6c3 100644 --- a/backend/internal/handler/composite_platform_test.go +++ b/backend/internal/handler/composite_platform_test.go @@ -133,14 +133,34 @@ func TestOpenAIReasoningEffortPolicyForCompositeTarget(t *testing.T) { require.True(t, changed) require.JSONEq(t, `{"reasoning":{"effort":"medium"}}`, string(bound)) - omittedCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) - omittedCtx.Request = httptest.NewRequest("POST", "/v1/messages", nil) - omittedCtx.Request = omittedCtx.Request.WithContext(service.WithResolvedTargetPlatform(omittedCtx.Request.Context(), service.PlatformOpenAI)) - bindOpenAIReasoningEffortPolicyForMessagesRequest(omittedCtx, apiKey, []byte(`{"model":"gpt-5"}`)) - omitted, changed, err := service.ApplyOpenAIReasoningEffortPolicyFromContext(omittedCtx.Request.Context(), body) - require.NoError(t, err) - require.False(t, changed) - require.Equal(t, body, omitted) + synthesizedGroup := &service.Group{ + Platform: service.PlatformComposite, + ReasoningEffortMappings: []service.ReasoningEffortMapping{ + {From: "medium", To: "low"}, + {From: "none", To: "low"}, + }, + } + synthesizedAPIKey := &service.APIKey{Group: synthesizedGroup} + for _, tc := range []struct { + name string + request string + response string + want string + }{ + {name: "default medium", request: `{"model":"gpt-5"}`, response: `{"reasoning":{"effort":"medium"}}`, want: "low"}, + {name: "disabled thinking none", request: `{"model":"gpt-5","thinking":{"type":"disabled"}}`, response: `{"reasoning":{"effort":"none"}}`, want: "low"}, + } { + t.Run(tc.name, func(t *testing.T) { + omittedCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + omittedCtx.Request = httptest.NewRequest("POST", "/v1/messages", nil) + omittedCtx.Request = omittedCtx.Request.WithContext(service.WithResolvedTargetPlatform(omittedCtx.Request.Context(), service.PlatformOpenAI)) + bindOpenAIReasoningEffortPolicyForMessagesRequest(omittedCtx, synthesizedAPIKey, []byte(tc.request)) + got, changed, err := service.ApplyOpenAIReasoningEffortPolicyFromContext(omittedCtx.Request.Context(), []byte(tc.response)) + require.NoError(t, err) + require.True(t, changed) + require.Equal(t, tc.want, gjson.GetBytes(got, "reasoning.effort").String()) + }) + } denyGroup := *group denyGroup.MaxReasoningEffortOverLimit = service.ReasoningEffortOverLimitDeny From 1cdecf4a88f016115392033bdbe0662d7ff92e81 Mon Sep 17 00:00:00 2001 From: haruka <1628615876@qq.com> Date: Fri, 16 Oct 2026 20:13:58 -0400 Subject: [PATCH 008/297] =?UTF-8?q?fix(billing):=20Grok=204.7=20Fast=20?= =?UTF-8?q?=E6=8C=89=E5=AE=98=E6=96=B9=20Fast=20=E4=BB=B7=E5=8D=A1?= =?UTF-8?q?=E8=AE=A1=E8=B4=B9=20(#8119)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit grok-4.7-fast 没有专属价格,落入「未知 Grok 文本模型」兜底按 grok-4.6 价卡计费,与普通 grok-4.7 同价($2 / $0.50 / $6),少收一半。 - 内置兜底价新增 grok-4.7-fast:<200k 为 $4 输入 / $1 缓存读取 / $12 输出 (每百万 token,标准价 2 倍);>=200k 整次请求为 $6 / $1.50 / $18, 即 Fast 基础价 1.5 倍,阈值口径与其它 xAI 价卡一致(达到即进高档) - grok-4.7-build-fast(Grok Build 侧的 Fast ID,见 #7502)同样命中该价卡 - 本地价格快照新增 grok-4.7-fast 条目,带 xai/ 前缀的写法也能识别 价格来源:https://docs.x.ai/developers/pricing(Grok 4.7 Fast,仅 Cursor 与 Grok Build 提供)。 Co-Authored-By: Claude Opus 5.5 --- backend/internal/service/billing_service.go | 19 +++++++ .../internal/service/billing_service_test.go | 52 +++++++++++++++++++ .../internal/service/pricing_service_test.go | 37 +++++++++++++ .../model_prices_and_context_window.json | 12 +++++ 4 files changed, 120 insertions(+) diff --git a/backend/internal/service/billing_service.go b/backend/internal/service/billing_service.go index 7341fb123d..bd639ebfab 100644 --- a/backend/internal/service/billing_service.go +++ b/backend/internal/service/billing_service.go @@ -978,6 +978,20 @@ func (s *BillingService) initFallbackPricing() { LongContextOutputMultiplier: 2, } + // xAI Grok 4.7 Fast (Cursor and Grok Build only): the same model on faster + // infrastructure at $4 input / $1 cached input / $12 output below 200k; + // long-context rates are $6 / $1.50 / $18 (1.5x of the Fast base card). + s.fallbackPrices["grok-4.7-fast"] = &ModelPricing{ + InputPricePerToken: 4e-6, + OutputPricePerToken: 12e-6, + CacheReadPricePerToken: 1e-6, + SupportsCacheBreakdown: false, + LongContextInputThreshold: 200000, + LongContextThresholdInclusive: true, + LongContextInputMultiplier: 1.5, + LongContextOutputMultiplier: 1.5, + } + // xAI Grok 4.3: $1.25 input / $0.20 cached / $2.50 output below 200k; // long-context rates are $2.50 / $0.40 / $5. s.fallbackPrices["grok-4.3"] = &ModelPricing{ @@ -1274,6 +1288,11 @@ func (s *BillingService) getFallbackPricing(model string) *ModelPricing { return s.fallbackPrices["grok-4.6"] case "grok-4.7", "grok-4.7-latest": return s.fallbackPrices["grok-4.7"] + // Grok 4.7 Fast IDs (grok-4.7-fast, and the Grok Build ID + // grok-4.7-build-fast). Without these cases both fall into the unknown-Grok + // family card and bill at the standard 4.7 rate (#8119). + case "grok-4.7-fast", "grok-4.7-build-fast": + return s.fallbackPrices["grok-4.7-fast"] case "grok-4.5", "grok-4.5-latest": return s.fallbackPrices["grok-4.5"] case "grok-3-mini": diff --git a/backend/internal/service/billing_service_test.go b/backend/internal/service/billing_service_test.go index 45544508ec..d02c942cb3 100644 --- a/backend/internal/service/billing_service_test.go +++ b/backend/internal/service/billing_service_test.go @@ -1203,6 +1203,58 @@ func TestGetModelPricing_Grok47OfficialFallback(t *testing.T) { } } +func TestGetModelPricing_Grok47FastOfficialFallback(t *testing.T) { + svc := newTestBillingService() + + for _, model := range []string{"grok-4.7-fast", "grok-4.7-build-fast", "GROK-4.7-FAST"} { + model := model + t.Run(model, func(t *testing.T) { + pricing, err := svc.GetModelPricing(model) + require.NoError(t, err) + require.InDelta(t, 4e-6, pricing.InputPricePerToken, 1e-12) + require.InDelta(t, 12e-6, pricing.OutputPricePerToken, 1e-12) + require.InDelta(t, 1e-6, pricing.CacheReadPricePerToken, 1e-12) + require.Equal(t, 200000, pricing.LongContextInputThreshold) + require.True(t, pricing.LongContextThresholdInclusive) + require.InDelta(t, 1.5, pricing.LongContextInputMultiplier, 1e-12) + require.InDelta(t, 1.5, pricing.LongContextOutputMultiplier, 1e-12) + require.False(t, pricing.SupportsCacheBreakdown) + }) + } + require.True(t, svc.HasIdentifiedTokenPricing("grok-4.7-fast")) +} + +// Issue #8119: Grok 4.7 Fast used to inherit the unknown-Grok card and bill at +// the standard grok-4.7 rate. +func TestCalculateCost_Grok47FastUsesFastCard(t *testing.T) { + svc := newTestBillingService() + + short := UsageTokens{InputTokens: 100_000, CacheReadTokens: 50_000, OutputTokens: 10_000} + standard, err := svc.CalculateCost("grok-4.7", short, 1) + require.NoError(t, err) + fast, err := svc.CalculateCost("grok-4.7-fast", short, 1) + require.NoError(t, err) + require.InDelta(t, 0.4, fast.InputCost, 1e-12) + require.InDelta(t, 0.05, fast.CacheReadCost, 1e-12) + require.InDelta(t, 0.12, fast.OutputCost, 1e-12) + require.False(t, fast.LongContextBillingApplied) + // Below 200k the Fast card is exactly twice the standard card. + require.InDelta(t, standard.TotalCost*2, fast.TotalCost, 1e-12) + + // Reaching 200k prompt tokens moves the whole request to $6 / $1.50 / $18. + long := UsageTokens{InputTokens: 150_000, CacheReadTokens: 50_000, OutputTokens: 10_000} + standardLong, err := svc.CalculateCost("grok-4.7", long, 1) + require.NoError(t, err) + fastLong, err := svc.CalculateCost("grok-4.7-fast", long, 1) + require.NoError(t, err) + require.True(t, fastLong.LongContextBillingApplied) + require.InDelta(t, 0.9, fastLong.InputCost, 1e-12) + require.InDelta(t, 0.075, fastLong.CacheReadCost, 1e-12) + require.InDelta(t, 0.18, fastLong.OutputCost, 1e-12) + // Long-context Fast is 1.5x the standard long-context card. + require.InDelta(t, standardLong.TotalCost*1.5, fastLong.TotalCost, 1e-12) +} + func TestGetModelPricing_GrokOfficialFamilyCards(t *testing.T) { svc := newTestBillingService() for _, tc := range []struct { diff --git a/backend/internal/service/pricing_service_test.go b/backend/internal/service/pricing_service_test.go index 08f5171a7c..d72e2f1214 100644 --- a/backend/internal/service/pricing_service_test.go +++ b/backend/internal/service/pricing_service_test.go @@ -819,6 +819,43 @@ func TestDefaultPricingIncludesGemini4ArgonRates(t *testing.T) { require.Contains(t, pricingSvc.ListModelNamesByProvider("gemini"), "gemini-4-argon") } +func TestDefaultPricingIncludesGrok47FastRates(t *testing.T) { + data, err := os.ReadFile(filepath.Join("..", "..", "resources", "model-pricing", "model_prices_and_context_window.json")) + require.NoError(t, err) + + pricingSvc := &PricingService{} + pricingData, err := pricingSvc.parsePricingData(data) + require.NoError(t, err) + pricingSvc.pricingData = pricingData + + for _, model := range []string{"grok-4.7-fast", "xai/grok-4.7-fast"} { + t.Run(model, func(t *testing.T) { + pricing := pricingSvc.GetModelPricing(model) + require.NotNil(t, pricing) + require.Equal(t, "xai", pricing.LiteLLMProvider) + require.InDelta(t, 4e-6, pricing.InputCostPerToken, 1e-15) + require.InDelta(t, 12e-6, pricing.OutputCostPerToken, 1e-15) + require.InDelta(t, 1e-6, pricing.CacheReadInputTokenCost, 1e-15) + // Long-context Fast is $6 / $1.50 / $18, i.e. 1.5x the Fast base card. + require.Equal(t, 200000, pricing.LongContextInputTokenThreshold) + require.InDelta(t, 1.5, pricing.LongContextInputCostMultiplier, 1e-12) + require.InDelta(t, 1.5, pricing.LongContextOutputCostMultiplier, 1e-12) + }) + } + // The Fast entry must not shadow the standard grok-4.7 card. + standard := pricingSvc.GetModelPricing("grok-4.7") + require.NotNil(t, standard) + require.InDelta(t, 2e-6, standard.InputCostPerToken, 1e-15) + + billing := NewBillingService(&config.Config{}, pricingSvc) + cost, err := billing.CalculateCost("grok-4.7-fast", UsageTokens{InputTokens: 150_000, CacheReadTokens: 50_000, OutputTokens: 10_000}, 1) + require.NoError(t, err) + require.True(t, cost.LongContextBillingApplied) + require.InDelta(t, 0.9, cost.InputCost, 1e-12) + require.InDelta(t, 0.075, cost.CacheReadCost, 1e-12) + require.InDelta(t, 0.18, cost.OutputCost, 1e-12) +} + func TestDefaultPricingUsesCurrentCodexAutoReviewBaseRates(t *testing.T) { data, err := os.ReadFile(filepath.Join("..", "..", "resources", "model-pricing", "model_prices_and_context_window.json")) require.NoError(t, err) diff --git a/backend/resources/model-pricing/model_prices_and_context_window.json b/backend/resources/model-pricing/model_prices_and_context_window.json index 5e0f608d2f..c9a5c3fb48 100644 --- a/backend/resources/model-pricing/model_prices_and_context_window.json +++ b/backend/resources/model-pricing/model_prices_and_context_window.json @@ -64,6 +64,18 @@ "output_cost_per_token_above_200k_tokens": 1.2e-05, "supports_prompt_caching": true }, + "grok-4.7-fast": { + "cache_read_input_token_cost": 1e-06, + "cache_read_input_token_cost_above_200k_tokens": 1.5e-06, + "input_cost_per_token": 4e-06, + "input_cost_per_token_above_200k_tokens": 6e-06, + "litellm_provider": "xai", + "max_input_tokens": 500000, + "mode": "chat", + "output_cost_per_token": 1.2e-05, + "output_cost_per_token_above_200k_tokens": 1.8e-05, + "supports_prompt_caching": true + }, "gpt-6-sol": { "cache_creation_input_token_cost": 2.5e-06, "cache_creation_input_token_cost_batches": 1.25e-06, From c7bfcd93aa206065238b67757d5d8fae81cf697b Mon Sep 17 00:00:00 2001 From: wucm667 Date: Sun, 18 Oct 2026 04:40:42 +0800 Subject: [PATCH 009/297] fix(tools): normalize parameter constants and annotations --- .../service/gemini_messages_compat_service.go | 82 ++++++- .../gemini_messages_compat_service_test.go | 220 ++++++++++++++++++ 2 files changed, 298 insertions(+), 4 deletions(-) diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index 48b095fb36..98c0cbf159 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -3765,12 +3765,24 @@ func isClaudeWebSearchToolMap(tool map[string]any) bool { // cleanToolSchema 清理工具的 JSON Schema,移除 Gemini 不支持的字段 func cleanToolSchema(schema any) any { + return cleanToolSchemaNode(schema, true) +} + +func cleanToolSchemaNode(schema any, schemaNode bool) any { if schema == nil { return nil } switch v := schema.(type) { case map[string]any: + if !schemaNode { + cleaned := make(map[string]any, len(v)) + for key, value := range v { + cleaned[key] = cleanToolSchemaNode(value, false) + } + return cleaned + } + cleaned := make(map[string]any) for key, value := range v { // 跳过不支持的字段 @@ -3778,11 +3790,73 @@ func cleanToolSchema(schema any) any { key == "$defs" || key == "definitions" || key == "additionalProperties" || key == "patternProperties" || key == "minLength" || key == "maxLength" || key == "minItems" || key == "maxItems" || key == "exclusiveMinimum" || - key == "deprecated" { + key == "deprecated" || key == "examples" { continue } - // 递归清理嵌套对象 - cleaned[key] = cleanToolSchema(value) + + switch key { + case "properties", "dependentSchemas": + if propertySchemas, ok := value.(map[string]any); ok { + cleanedProperties := make(map[string]any, len(propertySchemas)) + for propertyName, propertySchema := range propertySchemas { + cleanedProperties[propertyName] = cleanToolSchemaNode(propertySchema, true) + } + cleaned[key] = cleanedProperties + } else { + cleaned[key] = cleanToolSchemaNode(value, false) + } + case "items", "contains", "propertyNames", "if", "then", "else", "not", "contentSchema", + "additionalItems", "unevaluatedItems", "unevaluatedProperties": + cleaned[key] = cleanToolSchemaNode(value, true) + case "dependencies": + if dependencies, ok := value.(map[string]any); ok { + cleanedDependencies := make(map[string]any, len(dependencies)) + for propertyName, dependency := range dependencies { + if dependencySchema, ok := dependency.(map[string]any); ok { + cleanedDependencies[propertyName] = cleanToolSchemaNode(dependencySchema, true) + } else { + cleanedDependencies[propertyName] = cleanToolSchemaNode(dependency, false) + } + } + cleaned[key] = cleanedDependencies + } else { + cleaned[key] = cleanToolSchemaNode(value, false) + } + case "anyOf", "allOf", "oneOf", "prefixItems": + if schemas, ok := value.([]any); ok { + cleanedSchemas := make([]any, len(schemas)) + for i, childSchema := range schemas { + cleanedSchemas[i] = cleanToolSchemaNode(childSchema, true) + } + cleaned[key] = cleanedSchemas + } else { + cleaned[key] = cleanToolSchemaNode(value, false) + } + default: + cleaned[key] = cleanToolSchemaNode(value, false) + } + } + if constValue, exists := v["const"]; exists { + if stringValue, ok := constValue.(string); ok { + if originalEnum, hasEnum := v["enum"].([]any); hasEnum { + intersection := make([]any, 0, 1) + for _, value := range originalEnum { + if enumString, ok := value.(string); ok && enumString == stringValue { + intersection = append(intersection, stringValue) + break + } + } + cleaned["enum"] = intersection + } else { + cleaned["enum"] = []any{stringValue} + } + if _, hasType := cleaned["type"]; !hasType { + cleaned["type"] = "STRING" + } + } + // Non-string constants are unsupported: omit the constant, retain the + // original type, and do not stringify the constant or infer a type. + delete(cleaned, "const") } if enum, ok := cleaned["enum"].([]any); ok { if normalized, ok := normalizeGeminiEnum(enum); ok { @@ -3817,7 +3891,7 @@ func cleanToolSchema(schema any) any { case []any: cleaned := make([]any, len(v)) for i, item := range v { - cleaned[i] = cleanToolSchema(item) + cleaned[i] = cleanToolSchemaNode(item, schemaNode) } return cleaned default: diff --git a/backend/internal/service/gemini_messages_compat_service_test.go b/backend/internal/service/gemini_messages_compat_service_test.go index 3e6c3539d9..64399e01d5 100644 --- a/backend/internal/service/gemini_messages_compat_service_test.go +++ b/backend/internal/service/gemini_messages_compat_service_test.go @@ -509,6 +509,226 @@ func TestCleanToolSchema_DropsEnumWithNonScalarValue(t *testing.T) { require.NotContains(t, cleaned, "enum") } +func TestCleanToolSchema_PreservesSchemaKeywordNamedProperties(t *testing.T) { + schema := map[string]any{ + "type": "object", + "examples": []any{"root example"}, + "properties": map[string]any{ + "const": map[string]any{ + "type": "string", + "const": "property const", + }, + "enum": map[string]any{ + "type": "string", + "const": "property enum", + }, + "examples": map[string]any{ + "type": "string", + }, + "type": map[string]any{ + "type": "string", + }, + }, + } + + cleaned, ok := cleanToolSchema(schema).(map[string]any) + require.True(t, ok) + require.NotContains(t, cleaned, "examples") + + properties, ok := cleaned["properties"].(map[string]any) + require.True(t, ok) + require.Contains(t, properties, "const") + require.Contains(t, properties, "enum") + require.Contains(t, properties, "examples") + require.Contains(t, properties, "type") + + constSchema, ok := properties["const"].(map[string]any) + require.True(t, ok) + require.Equal(t, []any{"property const"}, constSchema["enum"]) + + enumPropertySchema, ok := properties["enum"].(map[string]any) + require.True(t, ok) + require.Equal(t, []any{"property enum"}, enumPropertySchema["enum"]) +} + +func TestCleanToolSchema_NormalizesConstAndExamplesAtNestedSchemaNodes(t *testing.T) { + schema := map[string]any{ + "type": "object", + "properties": map[string]any{ + "values": map[string]any{ + "type": "array", + "items": map[string]any{ + "type": "string", + "examples": []any{"item example"}, + "anyOf": []any{ + map[string]any{"type": "string", "const": "a"}, + map[string]any{"type": "string", "examples": []any{"branch example"}}, + }, + }, + }, + }, + } + + cleaned, ok := cleanToolSchema(schema).(map[string]any) + require.True(t, ok) + properties, ok := cleaned["properties"].(map[string]any) + require.True(t, ok) + values, ok := properties["values"].(map[string]any) + require.True(t, ok) + items, ok := values["items"].(map[string]any) + require.True(t, ok) + require.NotContains(t, items, "examples") + anyOf, ok := items["anyOf"].([]any) + require.True(t, ok) + require.Len(t, anyOf, 2) + firstBranch, ok := anyOf[0].(map[string]any) + require.True(t, ok) + require.Equal(t, []any{"a"}, firstBranch["enum"]) + secondBranch, ok := anyOf[1].(map[string]any) + require.True(t, ok) + require.NotContains(t, secondBranch, "examples") +} + +func TestCleanToolSchema_TraversesRetainedSchemaValuedKeywords(t *testing.T) { + schema := map[string]any{ + "type": "object", + "additionalItems": map[string]any{ + "type": "string", + "const": "additional", + "examples": []any{"additional example"}, + }, + "unevaluatedItems": map[string]any{ + "type": "string", + "const": "unevaluated item", + "examples": []any{"item example"}, + }, + "unevaluatedProperties": map[string]any{ + "type": "string", + "const": "unevaluated property", + "examples": []any{"property example"}, + }, + "dependencies": map[string]any{ + "schema dependency": map[string]any{ + "type": "string", + "const": "dependency", + "examples": []any{"dependency example"}, + }, + "required dependency": []any{"first", "second"}, + }, + } + + cleaned, ok := cleanToolSchema(schema).(map[string]any) + require.True(t, ok) + expectedEnums := map[string][]any{ + "additionalItems": {"additional"}, + "unevaluatedItems": {"unevaluated item"}, + "unevaluatedProperties": {"unevaluated property"}, + } + for keyword, expectedEnum := range expectedEnums { + child, ok := cleaned[keyword].(map[string]any) + require.True(t, ok) + require.Equal(t, expectedEnum, child["enum"]) + require.NotContains(t, child, "const") + require.NotContains(t, child, "examples") + } + + dependencies, ok := cleaned["dependencies"].(map[string]any) + require.True(t, ok) + dependencySchema, ok := dependencies["schema dependency"].(map[string]any) + require.True(t, ok) + require.Equal(t, []any{"dependency"}, dependencySchema["enum"]) + require.NotContains(t, dependencySchema, "const") + require.NotContains(t, dependencySchema, "examples") + require.Equal(t, []any{"first", "second"}, dependencies["required dependency"]) +} + +func TestCleanToolSchema_IntersectsStringConstWithEnum(t *testing.T) { + tests := []struct { + name string + constValue string + enum []any + expected []any + }{ + {name: "matching", constValue: "browser", enum: []any{"browser", "shell"}, expected: []any{"browser"}}, + {name: "contradictory", constValue: "browser", enum: []any{"shell"}, expected: []any{}}, + {name: "numeric string collision", constValue: "7", enum: []any{float64(7)}, expected: []any{}}, + {name: "empty string", constValue: "", enum: []any{"", "shell"}, expected: []any{""}}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + schema := map[string]any{ + "type": "string", + "const": test.constValue, + "enum": test.enum, + } + + cleaned, ok := cleanToolSchema(schema).(map[string]any) + require.True(t, ok) + require.NotContains(t, cleaned, "const") + require.Equal(t, test.expected, cleaned["enum"]) + }) + } + + cleaned, ok := cleanToolSchema(map[string]any{"const": "browser"}).(map[string]any) + require.True(t, ok) + require.Equal(t, "STRING", cleaned["type"]) + require.Equal(t, []any{"browser"}, cleaned["enum"]) +} + +func TestCleanToolSchema_DropsNonStringConstWithoutInferringType(t *testing.T) { + for _, constValue := range []any{true, float64(7), map[string]any{"value": "x"}} { + cleaned, ok := cleanToolSchema(map[string]any{"const": constValue}).(map[string]any) + require.True(t, ok) + require.NotContains(t, cleaned, "const") + require.NotContains(t, cleaned, "type") + require.NotContains(t, cleaned, "enum") + } +} + +func TestCleanToolSchema_DropsNonStringConstAndRetainsExistingTypeAndEnum(t *testing.T) { + schema := map[string]any{ + "type": "integer", + "const": float64(7), + "enum": []any{float64(8)}, + } + + cleaned, ok := cleanToolSchema(schema).(map[string]any) + require.True(t, ok) + require.NotContains(t, cleaned, "const") + require.Equal(t, "INTEGER", cleaned["type"]) + require.Equal(t, []any{"8"}, cleaned["enum"]) +} + +func TestCleanToolSchema_PreservesNestedOneOfCombinator(t *testing.T) { + schema := map[string]any{ + "type": "object", + "properties": map[string]any{ + "value": map[string]any{ + "oneOf": []any{ + map[string]any{"const": "a"}, + map[string]any{"type": "string", "const": "b"}, + }, + }, + }, + } + + cleaned, ok := cleanToolSchema(schema).(map[string]any) + require.True(t, ok) + properties, ok := cleaned["properties"].(map[string]any) + require.True(t, ok) + valueSchema, ok := properties["value"].(map[string]any) + require.True(t, ok) + oneOf, ok := valueSchema["oneOf"].([]any) + require.True(t, ok) + require.Len(t, oneOf, 2) + firstBranch, ok := oneOf[0].(map[string]any) + require.True(t, ok) + secondBranch, ok := oneOf[1].(map[string]any) + require.True(t, ok) + require.Equal(t, []any{"a"}, firstBranch["enum"]) + require.Equal(t, []any{"b"}, secondBranch["enum"]) +} + func TestConvertClaudeToolsToGeminiTools_PreservesWebSearchAlongsideFunctions(t *testing.T) { tools := []any{ map[string]any{ From 94c7d6b025a4074efe34b444e7ea218c85409dd6 Mon Sep 17 00:00:00 2001 From: feeeei Date: Mon, 19 Oct 2026 12:27:57 +0800 Subject: [PATCH 010/297] =?UTF-8?q?fix(gateway):=20Anthropic=20=E8=B4=A6?= =?UTF-8?q?=E5=8F=B7=20chat/responses=20=E5=85=BC=E5=AE=B9=E6=B5=81?= =?UTF-8?q?=E5=BC=8F=E5=AE=A2=E6=88=B7=E7=AB=AF=E6=96=AD=E5=BC=80=E5=90=8E?= =?UTF-8?q?=E8=AF=BB=E5=AE=8C=E4=B8=8A=E6=B8=B8=E5=86=8D=E8=AE=A1=E8=B4=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit handleCCStreamingFromAnthropic 与 handleResponsesStreamingResponse 写客户端失败时 立即返回,message_delta 的 output_tokens 未合并,usage 记为 0。改为断开后停止向 下游写入、继续读完上游合并 usage,与原生 /v1/messages 路径一致;ForwardResult 标记 ClientDisconnect。 两条路径改用 anthropicNativeLinePump 读上游,按 gateway.stream_data_interval_timeout 限制逐行读间隔,上游挂住时关闭 body 并按已累计 usage 收尾。 --- .../gateway_forward_as_chat_completions.go | 114 +++++++--- ...y_forward_as_chat_completions_ping_test.go | 5 +- .../service/gateway_forward_as_responses.go | 65 +++--- ...y_forward_compat_client_disconnect_test.go | 204 ++++++++++++++++++ 4 files changed, 328 insertions(+), 60 deletions(-) create mode 100644 backend/internal/service/gateway_forward_compat_client_disconnect_test.go diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index 83d82e6ed0..bb96b28a6b 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -381,6 +381,8 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( var usage ClaudeUsage var firstTokenMs *int firstChunk := true + // 客户端断开后停止向下游写入,继续读完上游以合并 message_delta 的最终 usage。 + clientDisconnected := false scanner := bufio.NewScanner(resp.Body) maxLineSize := defaultMaxLineSize @@ -388,21 +390,35 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( maxLineSize = s.cfg.Gateway.MaxLineSize } scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) + streamInterval := s.anthropicCompatStreamInterval() + pump := newAnthropicNativeLinePump(scanner, streamInterval) + defer pump.stop() + nextLine := func() (string, bool) { + return nextAnthropicCompatLine(pump, resp.Body, streamInterval, "forward_as_cc", requestID, clientDisconnected) + } resultWithUsage := func() *ForwardResult { return &ForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: usage, - Model: originalModel, - UpstreamModel: mappedModel, - ReasoningEffort: reasoningEffort, - Stream: true, - Duration: time.Since(startTime), - FirstTokenMs: firstTokenMs, + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: usage, + Model: originalModel, + UpstreamModel: mappedModel, + ReasoningEffort: reasoningEffort, + Stream: true, + Duration: time.Since(startTime), + FirstTokenMs: firstTokenMs, + ClientDisconnect: clientDisconnected, } } + markClientDisconnected := func() { + clientDisconnected = true + logger.L().Info("forward_as_cc stream: client disconnected, continuing to drain upstream for billing", + zap.String("request_id", requestID), + ) + } + writeChunk := func(chunk apicompat.ChatCompletionsChunk) bool { sse, err := apicompat.ChatChunkToSSE(chunk) if err != nil { @@ -417,16 +433,20 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( return false } - processAnthropicEvent := func(event *apicompat.AnthropicStreamEvent) bool { + processAnthropicEvent := func(event *apicompat.AnthropicStreamEvent) { if event == nil { - return false + return } if event.Type == "ping" { + if clientDisconnected { + return + } if _, err := fmt.Fprint(c.Writer, ": ping\n\n"); err != nil { - return true + markClientDisconnected() + return } c.Writer.Flush() - return false + return } if firstChunk { firstChunk = false @@ -442,6 +462,9 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( if event.Type == "message_start" && event.Message != nil { mergeAnthropicUsage(&usage, event.Message.Usage) } + if clientDisconnected { + return + } // Keep the outward Responses/Chat usage on the same normalized buckets used // for billing, including converter handlers that consume event usage. @@ -454,25 +477,29 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( ccChunks := apicompat.ResponsesEventToChatChunks(&resEvt, ccState) for _, chunk := range ccChunks { if disconnected := writeChunk(chunk); disconnected { - return true + markClientDisconnected() + return } } } c.Writer.Flush() - return false } - for scanner.Scan() { - line := scanner.Text() + for { + line, ok := nextLine() + if !ok { + break + } // 与缓冲路径一致:接受 SSE 紧凑格式(冒号后无空格,#4653 同根因)。 if _, ok := extractOpenAISSEEventLine(line); !ok { continue } - if !scanner.Scan() { + dataLine, ok := nextLine() + if !ok { break } - payload, ok := extractOpenAISSEDataLine(scanner.Text()) + payload, ok := extractOpenAISSEDataLine(dataLine) if !ok { continue } @@ -486,18 +513,11 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( // The intermediate Responses converter synthesizes usage even when absent. ccState.IncludeUsage = ccState.IncludeUsage || anthropicChatStreamHasUsage(&event, payload) - if processAnthropicEvent(&event) { - return resultWithUsage(), nil - } + processAnthropicEvent(&event) } - if err := scanner.Err(); err != nil { - if !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) { - logger.L().Warn("forward_as_cc stream: read error", - zap.Error(err), - zap.String("request_id", requestID), - ) - } + if clientDisconnected { + return resultWithUsage(), nil } // Finalize both state machines @@ -532,6 +552,42 @@ func writeGatewayCCError(c *gin.Context, statusCode int, errType, message string }) } +// anthropicCompatStreamInterval 返回 Anthropic 上游协议转换流的逐行读间隔上限, +// gateway.stream_data_interval_timeout <= 0 时不限。 +func (s *GatewayService) anthropicCompatStreamInterval() time.Duration { + if s.cfg != nil && s.cfg.Gateway.StreamDataIntervalTimeout > 0 { + return time.Duration(s.cfg.Gateway.StreamDataIntervalTimeout) * time.Second + } + return 0 +} + +// nextAnthropicCompatLine 从行泵取下一行;ok=false 表示上游流已结束(EOF、读错误 +// 或读间隔超时),调用方按已累计的 usage 收尾。读间隔超时时关闭 body,解除泵 +// goroutine 阻塞中的读并释放上游连接。 +func nextAnthropicCompatLine(pump *anthropicNativeLinePump, body io.Closer, interval time.Duration, logPrefix, requestID string, clientDisconnected bool) (string, bool) { + line, err := pump.next() + if err == nil { + return line, true + } + switch { + case errors.Is(err, errAnthropicNativeStreamIdle): + _ = body.Close() + logger.L().Warn(logPrefix+" stream: data interval timeout", + zap.String("request_id", requestID), + zap.Duration("interval", interval), + zap.Bool("client_disconnected", clientDisconnected), + ) + case errors.Is(err, io.EOF), errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded): + // 正常收流或取消:不记日志。 + default: + logger.L().Warn(logPrefix+" stream: read error", + zap.Error(err), + zap.String("request_id", requestID), + ) + } + return "", false +} + // anthropicChatStreamHasUsage distinguishes an explicit zero-valued usage object // from omitted/null usage before the Anthropic→Responses conversion loses that distinction. func anthropicChatStreamHasUsage(event *apicompat.AnthropicStreamEvent, payload string) bool { diff --git a/backend/internal/service/gateway_forward_as_chat_completions_ping_test.go b/backend/internal/service/gateway_forward_as_chat_completions_ping_test.go index df08d20f78..7eda0f90d9 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions_ping_test.go +++ b/backend/internal/service/gateway_forward_as_chat_completions_ping_test.go @@ -190,15 +190,16 @@ func TestHandleCCStreamingFromAnthropic_PingWriteFailureStopsDownstream(t *testi ) require.NoError(t, err) require.True(t, writer.failed) + require.True(t, result.ClientDisconnect) require.Zero(t, writer.writesAfterError) require.Zero(t, writer.flushesAfterError) require.NotContains(t, writer.Body.String(), "[DONE]") - require.Zero(t, result.Usage.OutputTokens) + require.Equal(t, 7, result.Usage.OutputTokens) + require.NotNil(t, result.FirstTokenMs) if withUsage { require.Equal(t, 10, result.Usage.InputTokens) } else { require.Zero(t, result.Usage.InputTokens) - require.Nil(t, result.FirstTokenMs) } }) } diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index 189c086192..fa2d601a05 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -545,6 +545,8 @@ func (s *GatewayService) handleResponsesStreamingResponse( var usage ClaudeUsage var firstTokenMs *int firstChunk := true + // 客户端断开后停止向下游写入,继续读完上游以合并 message_delta 的最终 usage。 + clientDisconnected := false scanner := bufio.NewScanner(resp.Body) maxLineSize := defaultMaxLineSize @@ -552,23 +554,30 @@ func (s *GatewayService) handleResponsesStreamingResponse( maxLineSize = s.cfg.Gateway.MaxLineSize } scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) + streamInterval := s.anthropicCompatStreamInterval() + pump := newAnthropicNativeLinePump(scanner, streamInterval) + defer pump.stop() + nextLine := func() (string, bool) { + return nextAnthropicCompatLine(pump, resp.Body, streamInterval, "forward_as_responses", requestID, clientDisconnected) + } resultWithUsage := func() *ForwardResult { return &ForwardResult{ - RequestID: requestID, - UpstreamHeaders: resp.Header, - Usage: usage, - Model: originalModel, - UpstreamModel: mappedModel, - ReasoningEffort: reasoningEffort, - Stream: true, - Duration: time.Since(startTime), - FirstTokenMs: firstTokenMs, + RequestID: requestID, + UpstreamHeaders: resp.Header, + Usage: usage, + Model: originalModel, + UpstreamModel: mappedModel, + ReasoningEffort: reasoningEffort, + Stream: true, + Duration: time.Since(startTime), + FirstTokenMs: firstTokenMs, + ClientDisconnect: clientDisconnected, } } // processEvent handles a single parsed Anthropic SSE event. - processEvent := func(event *apicompat.AnthropicStreamEvent) bool { + processEvent := func(event *apicompat.AnthropicStreamEvent) { if firstChunk { firstChunk = false ms := int(time.Since(startTime).Milliseconds()) @@ -583,6 +592,9 @@ func (s *GatewayService) handleResponsesStreamingResponse( if event.Type == "message_start" && event.Message != nil { mergeAnthropicUsage(&usage, event.Message.Usage) } + if clientDisconnected { + return + } // Keep the terminal Responses usage aligned with the normalized billing // buckets. Normalize the converter input too, so message handlers cannot @@ -613,20 +625,23 @@ func (s *GatewayService) handleResponsesStreamingResponse( for _, restored := range payloads { eventType := gjson.GetBytes(restored, "type").String() if _, err := fmt.Fprintf(c.Writer, "event: %s\ndata: %s\n\n", eventType, restored); err != nil { - logger.L().Info("forward_as_responses stream: client disconnected", + clientDisconnected = true + logger.L().Info("forward_as_responses stream: client disconnected, continuing to drain upstream for billing", zap.String("request_id", requestID), ) - return true // client disconnected + return } } } if len(events) > 0 { c.Writer.Flush() } - return false } finalizeStream := func() (*ForwardResult, error) { + if clientDisconnected { + return resultWithUsage(), nil + } if finalEvents := apicompat.FinalizeAnthropicResponsesStream(state); len(finalEvents) > 0 { for _, evt := range finalEvents { sse, err := apicompat.ResponsesEventToSSE(evt) @@ -642,18 +657,21 @@ func (s *GatewayService) handleResponsesStreamingResponse( } // Read Anthropic SSE events - for scanner.Scan() { - line := scanner.Text() + for { + line, ok := nextLine() + if !ok { + break + } eventType, ok := parseAnthropicSSEField(line, "event") if !ok { continue } // Read data line - if !scanner.Scan() { + dataLine, ok := nextLine() + if !ok { break } - dataLine := scanner.Text() payload, ok := parseAnthropicSSEField(dataLine, "data") if !ok { continue @@ -669,18 +687,7 @@ func (s *GatewayService) handleResponsesStreamingResponse( continue } - if processEvent(&event) { - return resultWithUsage(), nil - } - } - - if err := scanner.Err(); err != nil { - if !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) { - logger.L().Warn("forward_as_responses stream: read error", - zap.Error(err), - zap.String("request_id", requestID), - ) - } + processEvent(&event) } return finalizeStream() diff --git a/backend/internal/service/gateway_forward_compat_client_disconnect_test.go b/backend/internal/service/gateway_forward_compat_client_disconnect_test.go new file mode 100644 index 0000000000..cfa55a0f0a --- /dev/null +++ b/backend/internal/service/gateway_forward_compat_client_disconnect_test.go @@ -0,0 +1,204 @@ +//go:build unit + +package service + +import ( + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// disconnectOnMarkerResponseWriter 在首次写入包含 marker 的数据时返回错误,模拟客户端中途断开。 +type disconnectOnMarkerResponseWriter struct { + *httptest.ResponseRecorder + marker string + failed bool + writesAfterError int + flushesAfterError int +} + +func (writer *disconnectOnMarkerResponseWriter) Write(data []byte) (int, error) { + if writer.failed { + writer.writesAfterError++ + return 0, errors.New("client disconnected") + } + if strings.Contains(string(data), writer.marker) { + writer.failed = true + return 0, errors.New("client disconnected") + } + return writer.ResponseRecorder.Write(data) +} + +func (writer *disconnectOnMarkerResponseWriter) WriteString(data string) (int, error) { + return writer.Write([]byte(data)) +} + +func (writer *disconnectOnMarkerResponseWriter) Flush() { + if writer.failed { + writer.flushesAfterError++ + } + writer.ResponseRecorder.Flush() +} + +func anthropicStreamWithMidStreamText() string { + return strings.Join([]string{ + `event: message_start`, + `data: {"type":"message_start","message":{"id":"msg_disc","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4-6","usage":{"input_tokens":20,"cache_read_input_tokens":11,"cache_creation_input_tokens":4,"output_tokens":1}}}`, + ``, + `event: content_block_start`, + `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + ``, + `event: content_block_delta`, + `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"first"}}`, + ``, + `event: content_block_delta`, + `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"second"}}`, + ``, + `event: ping`, + `data: {"type":"ping"}`, + ``, + `event: content_block_stop`, + `data: {"type":"content_block_stop","index":0}`, + ``, + `event: message_delta`, + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":42}}`, + ``, + `event: message_stop`, + `data: {"type":"message_stop"}`, + ``, + }, "\n") +} + +// stallingAnthropicUpstream 写完 stream 后保持连接不关闭,模拟上游挂住。 +func stallingAnthropicUpstream(t *testing.T, stream string) (*http.Response, *io.PipeWriter) { + t.Helper() + pr, pw := io.Pipe() + go func() { + _, _ = io.WriteString(pw, stream) + }() + t.Cleanup(func() { + _ = pw.Close() + _ = pr.Close() + }) + return &http.Response{Header: http.Header{}, Body: pr}, pw +} + +func newCompatStreamIdleTestService(intervalSec int) *GatewayService { + return &GatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{StreamDataIntervalTimeout: intervalSec}}} +} + +func TestAnthropicCompatStreaming_IdleUpstreamEndsWithinInterval(t *testing.T) { + handlers := map[string]func(*GatewayService, *http.Response, *gin.Context) (*ForwardResult, error){ + "chat_completions": func(svc *GatewayService, resp *http.Response, c *gin.Context) (*ForwardResult, error) { + return svc.handleCCStreamingFromAnthropic(resp, c, "claude-sonnet-4-6", "claude-sonnet-4-6", nil, time.Now()) + }, + "responses": func(svc *GatewayService, resp *http.Response, c *gin.Context) (*ForwardResult, error) { + return svc.handleResponsesStreamingResponse(resp, c, "claude-sonnet-4-6", "claude-sonnet-4-6", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) + }, + } + stream := strings.TrimSuffix(anthropicStreamWithMidStreamText(), "event: message_stop\ndata: {\"type\":\"message_stop\"}\n") + for name, handle := range handlers { + for _, disconnect := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/client_disconnected=%t", name, disconnect), func(t *testing.T) { + gin.SetMode(gin.TestMode) + marker := "\x00never-written" + if disconnect { + marker = "second" + } + writer := &disconnectOnMarkerResponseWriter{ResponseRecorder: httptest.NewRecorder(), marker: marker} + c, _ := gin.CreateTestContext(writer) + resp, pw := stallingAnthropicUpstream(t, stream) + + type outcome struct { + result *ForwardResult + err error + } + done := make(chan outcome, 1) + go func() { + result, err := handle(newCompatStreamIdleTestService(1), resp, c) + done <- outcome{result: result, err: err} + }() + var got outcome + select { + case got = <-done: + case <-time.After(5 * time.Second): + t.Fatal("stream did not end after upstream idle interval") + } + + require.NoError(t, got.err) + require.Equal(t, disconnect, got.result.ClientDisconnect) + require.Equal(t, disconnect, writer.failed) + require.Equal(t, 42, got.result.Usage.OutputTokens) + require.Zero(t, writer.writesAfterError) + _, werr := io.WriteString(pw, "event: ping\n") + require.Error(t, werr, "upstream body must be closed after idle timeout") + }) + } + } +} + +func TestHandleCCStreamingFromAnthropic_ClientDisconnectDrainsUpstreamUsage(t *testing.T) { + gin.SetMode(gin.TestMode) + writer := &disconnectOnMarkerResponseWriter{ResponseRecorder: httptest.NewRecorder(), marker: "second"} + c, _ := gin.CreateTestContext(writer) + + result, err := (&GatewayService{}).handleCCStreamingFromAnthropic( + &http.Response{Header: http.Header{}, Body: io.NopCloser(strings.NewReader(anthropicStreamWithMidStreamText()))}, + c, "claude-sonnet-4-6", "claude-sonnet-4-6", nil, time.Now(), + ) + require.NoError(t, err) + require.NotNil(t, result) + require.True(t, writer.failed) + require.True(t, result.ClientDisconnect) + require.Zero(t, writer.writesAfterError) + require.Zero(t, writer.flushesAfterError) + + body := writer.Body.String() + require.Contains(t, body, `"content":"first"`) + require.NotContains(t, body, "second") + require.NotContains(t, body, "[DONE]") + + require.Equal(t, 20, result.Usage.InputTokens) + require.Equal(t, 42, result.Usage.OutputTokens) + require.Equal(t, 11, result.Usage.CacheReadInputTokens) + require.Equal(t, 4, result.Usage.CacheCreationInputTokens) + require.NotNil(t, result.FirstTokenMs) +} + +func TestHandleResponsesStreamingResponse_ClientDisconnectDrainsUpstreamUsage(t *testing.T) { + gin.SetMode(gin.TestMode) + writer := &disconnectOnMarkerResponseWriter{ResponseRecorder: httptest.NewRecorder(), marker: "second"} + c, _ := gin.CreateTestContext(writer) + + result, err := (&GatewayService{}).handleResponsesStreamingResponse( + &http.Response{Header: http.Header{}, Body: io.NopCloser(strings.NewReader(anthropicStreamWithMidStreamText()))}, + c, "claude-sonnet-4-6", "claude-sonnet-4-6", nil, time.Now(), apicompat.ResponsesClientToolMapping{}, + ) + require.NoError(t, err) + require.NotNil(t, result) + require.True(t, writer.failed) + require.True(t, result.ClientDisconnect) + require.Zero(t, writer.writesAfterError) + require.Zero(t, writer.flushesAfterError) + + body := writer.Body.String() + require.Contains(t, body, `"delta":"first"`) + require.NotContains(t, body, "second") + require.NotContains(t, body, "response.completed") + + require.Equal(t, 20, result.Usage.InputTokens) + require.Equal(t, 42, result.Usage.OutputTokens) + require.Equal(t, 11, result.Usage.CacheReadInputTokens) + require.Equal(t, 4, result.Usage.CacheCreationInputTokens) + require.NotNil(t, result.FirstTokenMs) +} From afbef7c8cca571660d6ca66a211d36ad83ea46ff Mon Sep 17 00:00:00 2001 From: wucm667 Date: Mon, 19 Oct 2026 20:15:37 +0800 Subject: [PATCH 011/297] fix(deepseek): avoid duplicate image payloads --- ...penai_gateway_deepseek_input_image_test.go | 24 ++++++++++++------- .../service/openai_gateway_request_body.go | 20 +++++++--------- 2 files changed, 25 insertions(+), 19 deletions(-) diff --git a/backend/internal/service/openai_gateway_deepseek_input_image_test.go b/backend/internal/service/openai_gateway_deepseek_input_image_test.go index 61f75c1939..b95d75cf37 100644 --- a/backend/internal/service/openai_gateway_deepseek_input_image_test.go +++ b/backend/internal/service/openai_gateway_deepseek_input_image_test.go @@ -63,7 +63,7 @@ func TestNormalizeDeepSeekResponsesRequestBodyAliasesInputImageURL(t *testing.T) got := normalizeDeepSeekResponsesRequestBody(mapped, body) require.Equal(t, "input_image", gjson.GetBytes(got, "input.0.content.1.type").String()) require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.0.content.1.image_url").String()) - require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.0.content.1.url").String()) + require.False(t, gjson.GetBytes(got, "input.0.content.1.url").Exists()) require.Equal(t, "what is this?", gjson.GetBytes(got, "input.0.content.0.text").String()) require.True(t, gjson.GetBytes(got, "store").Bool(), "mapped openai 账号不应被无状态适配改掉 store") }) @@ -73,7 +73,7 @@ func TestNormalizeDeepSeekResponsesRequestBodyAliasesInputImageURL(t *testing.T) got := normalizeDeepSeekResponsesRequestBody(native, body) require.Equal(t, gjson.String, gjson.GetBytes(got, "input.0.content.1.image_url").Type) require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.0.content.1.image_url").String()) - require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.0.content.1.url").String()) + require.False(t, gjson.GetBytes(got, "input.0.content.1.url").Exists()) }) t.Run("chat_completions_image_url_part_converted", func(t *testing.T) { @@ -81,7 +81,7 @@ func TestNormalizeDeepSeekResponsesRequestBodyAliasesInputImageURL(t *testing.T) got := normalizeDeepSeekResponsesRequestBody(mapped, body) require.Equal(t, "input_image", gjson.GetBytes(got, "input.0.content.1.type").String()) require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.0.content.1.image_url").String()) - require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.0.content.1.url").String()) + require.False(t, gjson.GetBytes(got, "input.0.content.1.url").Exists()) }) t.Run("anthropic_source_becomes_data_uri", func(t *testing.T) { @@ -89,16 +89,24 @@ func TestNormalizeDeepSeekResponsesRequestBodyAliasesInputImageURL(t *testing.T) got := normalizeDeepSeekResponsesRequestBody(native, body) require.Equal(t, "input_image", gjson.GetBytes(got, "input.0.content.1.type").String()) require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.0.content.1.image_url").String()) - require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.0.content.1.url").String()) + require.False(t, gjson.GetBytes(got, "input.0.content.1.url").Exists()) }) - t.Run("lifted_tool_output_image_gets_url", func(t *testing.T) { + t.Run("lifted_tool_output_image_keeps_image_url_only", func(t *testing.T) { body := []byte(`{"model":"deepseek-flash","input":[{"type":"function_call","call_id":"call_image","name":"view_image","arguments":"{}"},{"type":"function_call_output","call_id":"call_image","output":[{"type":"input_image","image_url":"` + deepSeekInputImageDataURI + `"}]}]}`) got := normalizeDeepSeekResponsesRequestBody(mapped, body) require.Equal(t, gjson.String, gjson.GetBytes(got, "input.1.output").Type) require.Equal(t, "input_image", gjson.GetBytes(got, "input.2.content.1.type").String()) require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.2.content.1.image_url").String()) - require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.2.content.1.url").String()) + require.False(t, gjson.GetBytes(got, "input.2.content.1.url").Exists()) + }) + + t.Run("dual_field_input_drops_duplicate_url", func(t *testing.T) { + body := deepSeekUserImageBody(`{"type":"input_image","image_url":"` + deepSeekInputImageDataURI + `","url":"` + deepSeekInputImageDataURI + `"}`) + got := normalizeDeepSeekResponsesRequestBody(native, body) + require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(got, "input.0.content.1.image_url").String()) + require.False(t, gjson.GetBytes(got, "input.0.content.1.url").Exists()) + require.Equal(t, string(got), string(normalizeDeepSeekResponsesRequestBody(native, got))) }) t.Run("file_id_only_does_not_gain_empty_url", func(t *testing.T) { @@ -144,7 +152,7 @@ func TestForwardResponses_OpenAIMappedDeepSeekAliasesInputImageURL(t *testing.T) require.NotNil(t, result) require.Contains(t, upstream.lastReq.URL.String(), "/responses") require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(upstream.lastBody, "input.0.content.1.image_url").String()) - require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(upstream.lastBody, "input.0.content.1.url").String()) + require.False(t, gjson.GetBytes(upstream.lastBody, "input.0.content.1.url").Exists()) } func TestForwardResponses_NativeDeepSeekAliasesInputImageURL(t *testing.T) { @@ -167,5 +175,5 @@ func TestForwardResponses_NativeDeepSeekAliasesInputImageURL(t *testing.T) { require.NotNil(t, result) require.Equal(t, "https://api.deepseek.com/responses", upstream.lastReq.URL.String()) require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(upstream.lastBody, "input.0.content.1.image_url").String()) - require.Equal(t, deepSeekInputImageDataURI, gjson.GetBytes(upstream.lastBody, "input.0.content.1.url").String()) + require.False(t, gjson.GetBytes(upstream.lastBody, "input.0.content.1.url").Exists()) } diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index 52ca1d57b4..38cc743d9d 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -133,9 +133,8 @@ func deleteOpenAIResponsesNoneReasoningEffortFromObject(account *Account, body m // 强制 store=false 并清除 previous_response_id(DeepSeek / Kimi 官方 // Responses 均不支持服务端状态存储,携带这些字段会被拒绝)。 // -// DeepSeek 另需把 Codex/OpenAI 的 input_image.image_url 写成线上 serde -// 要求的 url 字段;openai 平台但 base_url 指向 api.deepseek.com 的映射 -// 账号同样走这条出站改写(Codex 贴图会 422 missing field url)。 +// DeepSeek 另需把兼容格式的图片输入归一化为官方 image_url 字段;openai +// 平台但 base_url 指向 api.deepseek.com 的映射账号同样走这条出站改写。 // 非 CN / 非 DeepSeek 上游原样返回。 func normalizeDeepSeekResponsesRequestBody(account *Account, body []byte) []byte { if account == nil { @@ -194,10 +193,9 @@ func shouldAliasDeepSeekResponsesInputImages(account *Account) bool { return targetsDeepSeekAPIHost(account) } -// aliasDeepSeekResponsesInputImages 把图片 part 改写成 DeepSeek 能反序列化 -// 的形状:type=input_image,同时带字符串字段 image_url 与 url。 -// 文档与部分 400 提 image_url;线上 serde 要求 url。只发其中一个都会踩坑。 -// 仅有 file_id、没有可用 URL 的 part 原样保留。 +// aliasDeepSeekResponsesInputImages 把图片 part 改写成 DeepSeek 官方形状: +// type=input_image,同时只保留字符串字段 image_url。仅有 file_id、没有可用 +// URL 的 part 原样保留。 func aliasDeepSeekResponsesInputImages(input any) (any, bool) { items, ok := asDeepSeekResponsesSlice(input) if !ok { @@ -279,18 +277,18 @@ func aliasDeepSeekResponsesImagePart(part map[string]any) bool { part["image_url"] = imageURL changed = true } - if current, ok := part["url"].(string); !ok || strings.TrimSpace(current) != imageURL { - part["url"] = imageURL + if _, exists := part["url"]; exists { + delete(part, "url") changed = true } return changed } func extractDeepSeekResponsesImageURL(part map[string]any) string { - if imageURL := deepSeekResponsesURLValue(part["url"]); imageURL != "" { + if imageURL := deepSeekResponsesURLValue(part["image_url"]); imageURL != "" { return imageURL } - if imageURL := deepSeekResponsesURLValue(part["image_url"]); imageURL != "" { + if imageURL := deepSeekResponsesURLValue(part["url"]); imageURL != "" { return imageURL } if imageURL := deepSeekResponsesURLValue(part["image"]); imageURL != "" { From d6120b5d8e05fe4edf54f1575c4dd6e5c7beb856 Mon Sep 17 00:00:00 2001 From: feeeei Date: Mon, 19 Oct 2026 23:31:46 +0800 Subject: [PATCH 012/297] =?UTF-8?q?feat(account):=20Vertex=20=E8=B4=A6?= =?UTF-8?q?=E5=8F=B7=E6=94=AF=E6=8C=81=E9=85=8D=E9=A2=9D=E4=B8=8A=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 AccountTypeSupportsQuota / SupportsAccountQuota(apikey/bedrock/service_account) 作为配额账号类型的唯一判定,累加、超限停调度、额度通知、接口输出与计费仓储统一改用; 池模式等其它特性仍只看 IsAPIKeyOrBedrock - service_account 配额语义与 apikey 一致:配置了任一上限才累加,用满停调度,跨阈值发额度通知 - 计费事务中账号已删除时跳过账号配额计数,与 API Key 对称,用户扣费不再整笔回滚 - 账号额度通知只对配置了上限的账号做检查 - 前端创建/编辑弹窗对 Vertex 开放配额设置,设上限后用量列显示配额进度条; 账号类型判断收敛到 supportsAccountQuota --- .../dto/account_quota_service_account_test.go | 78 +++++++ backend/internal/handler/dto/mappers.go | 4 +- .../internal/repository/usage_billing_repo.go | 5 +- .../usage_billing_repo_integration_test.go | 102 +++++++++ .../usage_billing_repo_unit_test.go | 34 +++ backend/internal/service/account.go | 19 +- .../service/account_quota_schedulable_test.go | 42 ++++ .../account_quota_service_account_test.go | 204 ++++++++++++++++++ .../internal/service/gateway_scheduling.go | 4 +- .../internal/service/gateway_usage_billing.go | 11 +- .../account/AccountCapacityCell.vue | 3 +- .../components/account/AccountUsageCell.vue | 26 ++- .../components/account/CreateAccountModal.vue | 9 +- .../components/account/EditAccountModal.vue | 13 +- .../__tests__/AccountUsageCell.spec.ts | 65 ++++++ .../__tests__/EditAccountModal.spec.ts | 20 ++ .../admin/account/AccountActionMenu.vue | 3 +- frontend/src/utils/accountQuota.ts | 6 + 18 files changed, 624 insertions(+), 24 deletions(-) create mode 100644 backend/internal/handler/dto/account_quota_service_account_test.go create mode 100644 backend/internal/service/account_quota_service_account_test.go create mode 100644 frontend/src/utils/accountQuota.ts diff --git a/backend/internal/handler/dto/account_quota_service_account_test.go b/backend/internal/handler/dto/account_quota_service_account_test.go new file mode 100644 index 0000000000..1f6f1ae510 --- /dev/null +++ b/backend/internal/handler/dto/account_quota_service_account_test.go @@ -0,0 +1,78 @@ +package dto + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/Wei-Shaw/sub2api/internal/service" +) + +// service_account 与 apikey 同语义:设了总额度才输出 quota_limit / quota_used。 +func TestAccountFromServiceShallow_ServiceAccountQuota(t *testing.T) { + t.Run("no limit omits quota fields", func(t *testing.T) { + out := AccountFromServiceShallow(&service.Account{ + ID: 1, + Platform: service.PlatformGemini, + Type: service.AccountTypeServiceAccount, + Extra: map[string]any{"quota_used": 12.5}, + }) + require.Nil(t, out.QuotaUsed) + require.Nil(t, out.QuotaLimit) + require.Nil(t, out.QuotaDailyLimit) + require.Nil(t, out.QuotaWeeklyLimit) + + payload, err := json.Marshal(out) + require.NoError(t, err) + var decoded map[string]any + require.NoError(t, json.Unmarshal(payload, &decoded)) + require.NotContains(t, decoded, "quota_used") + require.NotContains(t, decoded, "quota_limit") + }) + + t.Run("with limits outputs limits and usage", func(t *testing.T) { + out := AccountFromServiceShallow(&service.Account{ + ID: 3, + Platform: service.PlatformGemini, + Type: service.AccountTypeServiceAccount, + Extra: map[string]any{ + "quota_used": 30.0, + "quota_limit": 100.0, + "quota_daily_limit": 10.0, + }, + }) + require.NotNil(t, out.QuotaLimit) + require.InDelta(t, 100.0, *out.QuotaLimit, 1e-9) + require.NotNil(t, out.QuotaUsed) + require.InDelta(t, 30.0, *out.QuotaUsed, 1e-9) + require.NotNil(t, out.QuotaDailyLimit) + require.NotNil(t, out.QuotaDailyUsed) + }) + + t.Run("lite list item keeps quota fields", func(t *testing.T) { + item := AccountListItemFromAccount(AccountFromServiceShallow(&service.Account{ + ID: 4, + Platform: service.PlatformGemini, + Type: service.AccountTypeServiceAccount, + Extra: map[string]any{"quota_used": 7.25, "quota_limit": 290.0}, + })) + payload, err := json.Marshal(item) + require.NoError(t, err) + var decoded map[string]any + require.NoError(t, json.Unmarshal(payload, &decoded)) + require.InDelta(t, 7.25, decoded["quota_used"], 1e-9) + require.InDelta(t, 290.0, decoded["quota_limit"], 1e-9) + }) +} + +// apikey 维持原语义:未设总额度时不输出 quota_used。 +func TestAccountFromServiceShallow_APIKeyWithoutLimitOmitsQuotaUsed(t *testing.T) { + out := AccountFromServiceShallow(&service.Account{ + ID: 5, + Type: service.AccountTypeAPIKey, + Extra: map[string]any{"quota_used": 5.0}, + }) + require.Nil(t, out.QuotaUsed) + require.Nil(t, out.QuotaLimit) +} diff --git a/backend/internal/handler/dto/mappers.go b/backend/internal/handler/dto/mappers.go index d0c7de939a..a84d493e52 100644 --- a/backend/internal/handler/dto/mappers.go +++ b/backend/internal/handler/dto/mappers.go @@ -341,8 +341,8 @@ func AccountFromServiceShallow(a *service.Account) *Account { } } - // 提取账号配额限制(apikey / bedrock 类型有效) - if a.IsAPIKeyOrBedrock() { + // 提取账号配额限制(apikey / bedrock / service_account 类型有效) + if a.SupportsAccountQuota() { if limit := a.GetQuotaLimit(); limit > 0 { out.QuotaLimit = &limit used := a.GetQuotaUsed() diff --git a/backend/internal/repository/usage_billing_repo.go b/backend/internal/repository/usage_billing_repo.go index bfb1bb0de5..01f5f857f5 100644 --- a/backend/internal/repository/usage_billing_repo.go +++ b/backend/internal/repository/usage_billing_repo.go @@ -202,9 +202,10 @@ func (r *usageBillingRepository) applyUsageBillingEffects(ctx context.Context, t } } - if cmd.AccountQuotaCost > 0 && (strings.EqualFold(cmd.AccountType, service.AccountTypeAPIKey) || strings.EqualFold(cmd.AccountType, service.AccountTypeBedrock)) { + // 账号已不存在时跳过其配额计数,其余结算项不受影响。 + if cmd.AccountQuotaCost > 0 && service.AccountTypeSupportsQuota(cmd.AccountType) { quotaState, err := incrementUsageBillingAccountQuota(ctx, tx, cmd.AccountID, cmd.AccountQuotaCost) - if err != nil { + if err != nil && !errors.Is(err, service.ErrAccountNotFound) { return err } result.QuotaState = quotaState diff --git a/backend/internal/repository/usage_billing_repo_integration_test.go b/backend/internal/repository/usage_billing_repo_integration_test.go index 9f2f0169dc..c7f2e6c528 100644 --- a/backend/internal/repository/usage_billing_repo_integration_test.go +++ b/backend/internal/repository/usage_billing_repo_integration_test.go @@ -217,6 +217,54 @@ func TestUsageBillingRepositoryApply_DeletedAPIKeyStillBillsBalance(t *testing.T require.Equal(t, 1, dedupCount) } +func TestUsageBillingRepositoryApply_DeletedAccountStillBillsBalance(t *testing.T) { + ctx := context.Background() + client := testEntClient(t) + repo := NewUsageBillingRepository(client, integrationDB) + + user := mustCreateUser(t, client, &service.User{ + Email: fmt.Sprintf("usage-billing-deleted-account-user-%d@example.com", time.Now().UnixNano()), + PasswordHash: "hash", + Balance: 100, + }) + apiKey := mustCreateApiKey(t, client, &service.APIKey{ + UserID: user.ID, + Key: "sk-usage-billing-deleted-account-" + uuid.NewString(), + Name: "billing-deleted-account", + }) + account := mustCreateAccount(t, client, &service.Account{ + Name: "usage-billing-deleted-account-" + uuid.NewString(), + Platform: service.PlatformGemini, + Type: service.AccountTypeServiceAccount, + }) + + _, err := integrationDB.ExecContext(ctx, "UPDATE accounts SET deleted_at = NOW() WHERE id = $1", account.ID) + require.NoError(t, err) + + requestID := uuid.NewString() + result, err := repo.Apply(ctx, &service.UsageBillingCommand{ + RequestID: requestID, + APIKeyID: apiKey.ID, + UserID: user.ID, + AccountID: account.ID, + AccountType: service.AccountTypeServiceAccount, + BalanceCost: 1.25, + AccountQuotaCost: 1.25, + }) + require.NoError(t, err) + require.NotNil(t, result) + require.True(t, result.Applied) + require.Nil(t, result.QuotaState) + + var balance float64 + require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT balance FROM users WHERE id = $1", user.ID).Scan(&balance)) + require.InDelta(t, 98.75, balance, 0.000001) + + var dedupCount int + require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT COUNT(*) FROM usage_billing_dedup WHERE request_id = $1 AND api_key_id = $2", requestID, apiKey.ID).Scan(&dedupCount)) + require.Equal(t, 1, dedupCount) +} + func TestUsageBillingRepositoryApply_UpdatesAccountQuota(t *testing.T) { ctx := context.Background() client := testEntClient(t) @@ -254,6 +302,60 @@ func TestUsageBillingRepositoryApply_UpdatesAccountQuota(t *testing.T) { require.InDelta(t, 3.5, quotaUsed, 0.000001) } +// service_account 只设总上限:累加 quota_used;日/周用量只在设置了对应 limit 时累加,未跨越上限不入队调度 outbox。 +func TestUsageBillingRepositoryApply_UpdatesServiceAccountQuota(t *testing.T) { + ctx := context.Background() + client := testEntClient(t) + repo := NewUsageBillingRepository(client, integrationDB) + + user := mustCreateUser(t, client, &service.User{ + Email: fmt.Sprintf("usage-billing-sa-user-%d@example.com", time.Now().UnixNano()), + PasswordHash: "hash", + }) + apiKey := mustCreateApiKey(t, client, &service.APIKey{ + UserID: user.ID, + Key: "sk-usage-billing-sa-" + uuid.NewString(), + Name: "billing-sa", + }) + account := mustCreateAccount(t, client, &service.Account{ + Name: "usage-billing-sa-quota-" + uuid.NewString(), + Platform: service.PlatformGemini, + Type: service.AccountTypeServiceAccount, + Extra: map[string]any{ + "quota_limit": 100.0, + }, + }) + + for _, cost := range []float64{2.25, 1.5} { + _, err := repo.Apply(ctx, &service.UsageBillingCommand{ + RequestID: uuid.NewString(), + APIKeyID: apiKey.ID, + UserID: user.ID, + AccountID: account.ID, + AccountType: service.AccountTypeServiceAccount, + AccountQuotaCost: cost, + }) + require.NoError(t, err) + } + + var quotaUsed float64 + var hasDailyUsed, hasWeeklyUsed bool + require.NoError(t, integrationDB.QueryRowContext(ctx, + "SELECT COALESCE((extra->>'quota_used')::numeric, 0), extra ? 'quota_daily_used', extra ? 'quota_weekly_used' FROM accounts WHERE id = $1", + account.ID, + ).Scan("aUsed, &hasDailyUsed, &hasWeeklyUsed)) + require.InDelta(t, 3.75, quotaUsed, 0.000001) + require.False(t, hasDailyUsed) + require.False(t, hasWeeklyUsed) + + var outboxCount int + require.NoError(t, integrationDB.QueryRowContext(ctx, + "SELECT COUNT(*) FROM scheduler_outbox WHERE event_type = $1 AND account_id = $2", + service.SchedulerOutboxEventAccountChanged, account.ID, + ).Scan(&outboxCount)) + require.Zero(t, outboxCount, "service_account under its limit must not enqueue scheduler outbox") +} + func TestUsageBillingRepositoryApply_EnqueuesSchedulerOutboxOnQuotaCrossing(t *testing.T) { ctx := context.Background() client := testEntClient(t) diff --git a/backend/internal/repository/usage_billing_repo_unit_test.go b/backend/internal/repository/usage_billing_repo_unit_test.go index 40394d819c..a745eb8d73 100644 --- a/backend/internal/repository/usage_billing_repo_unit_test.go +++ b/backend/internal/repository/usage_billing_repo_unit_test.go @@ -22,6 +22,7 @@ const ( userExistsForBillingSQL = `(?s)SELECT 1\s+FROM users\s+WHERE id = \$1 AND deleted_at IS NULL` apiKeyQuotaIncrementSQL = `(?s)UPDATE api_keys\s+SET quota_used = quota_used \+ \$1,.*WHERE id = \$2 AND deleted_at IS NULL\s+RETURNING` apiKeyRateLimitIncrementSQL = `(?s)UPDATE api_keys SET\s+usage_5h = .*WHERE id = \$2 AND deleted_at IS NULL` + accountQuotaIncrementSQL = `(?s)UPDATE accounts SET extra = .*WHERE id = \$2 AND deleted_at IS NULL\s+RETURNING` ) func TestDeductUsageBillingBalance_UsesSufficientBalanceGuard(t *testing.T) { @@ -137,6 +138,39 @@ func TestApplyUsageBillingEffects_DeletedAPIKeyStillBillsBalance(t *testing.T) { require.NoError(t, mock.ExpectationsWereMet()) } +func TestApplyUsageBillingEffects_DeletedAccountStillBillsBalance(t *testing.T) { + ctx := context.Background() + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer func() { _ = db.Close() }() + + mock.ExpectBegin() + tx, err := db.BeginTx(ctx, nil) + require.NoError(t, err) + mock.ExpectQuery(conditionalBalanceDeductSQL). + WithArgs(10.0, int64(42)). + WillReturnRows(sqlmock.NewRows([]string{"balance"}).AddRow(90.0)) + mock.ExpectQuery(accountQuotaIncrementSQL). + WithArgs(4.0, int64(9)). + WillReturnRows(sqlmock.NewRows([]string{"quota_used", "quota_limit", "quota_daily_used", "quota_daily_limit", "quota_weekly_used", "quota_weekly_limit"})) + mock.ExpectCommit() + + result := &service.UsageBillingApplyResult{Applied: true} + err = (&usageBillingRepository{}).applyUsageBillingEffects(ctx, tx, &service.UsageBillingCommand{ + UserID: 42, + AccountID: 9, + AccountType: service.AccountTypeServiceAccount, + BalanceCost: 10, + AccountQuotaCost: 4, + }, result) + require.NoError(t, err) + require.NotNil(t, result.NewBalance) + require.InDelta(t, 90.0, *result.NewBalance, 0.000001) + require.Nil(t, result.QuotaState) + require.NoError(t, tx.Commit()) + require.NoError(t, mock.ExpectationsWereMet()) +} + func TestApplyUsageBillingEffects_APIKeyCounterErrorStillFails(t *testing.T) { ctx := context.Background() db, mock, err := sqlmock.New() diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 06b94b754e..ebc07b8c5c 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -206,7 +206,7 @@ func (a *Account) IsSchedulable() bool { if a.TempUnschedulableUntil != nil && now.Before(*a.TempUnschedulableUntil) { return false } - if a.IsAPIKeyOrBedrock() && a.IsQuotaExceeded() { + if a.SupportsAccountQuota() && a.IsQuotaExceeded() { return false } return true @@ -1378,11 +1378,26 @@ func (a *Account) IsBedrockAPIKey() bool { return a.IsBedrock() && a.GetCredential("auth_mode") == "apikey" } -// IsAPIKeyOrBedrock 返回账号类型是否支持配额和池模式等特性 +// IsAPIKeyOrBedrock 返回账号类型是否支持池模式等特性(账号配额判定见 SupportsAccountQuota) func (a *Account) IsAPIKeyOrBedrock() bool { return a.Type == AccountTypeAPIKey || a.Type == AccountTypeBedrock } +// AccountTypeSupportsQuota 返回账号类型是否支持账号配额(quota_limit 及日/周额度、quota_used 累加、超限停调度)。 +// 在 apikey/bedrock 之外额外放开 Vertex service_account;池模式等其它特性仍只看 IsAPIKeyOrBedrock。 +func AccountTypeSupportsQuota(accountType string) bool { + switch strings.ToLower(accountType) { + case AccountTypeAPIKey, AccountTypeBedrock, AccountTypeServiceAccount: + return true + } + return false +} + +// SupportsAccountQuota 返回账号是否支持账号配额,类型集合见 AccountTypeSupportsQuota。 +func (a *Account) SupportsAccountQuota() bool { + return AccountTypeSupportsQuota(a.Type) +} + func (a *Account) IsOpenAI() bool { return a.Platform == PlatformOpenAI } diff --git a/backend/internal/service/account_quota_schedulable_test.go b/backend/internal/service/account_quota_schedulable_test.go index 2895b34c88..dfe34c4fc5 100644 --- a/backend/internal/service/account_quota_schedulable_test.go +++ b/backend/internal/service/account_quota_schedulable_test.go @@ -113,6 +113,48 @@ func TestAccountIsSchedulable_QuotaExceeded(t *testing.T) { }, want: false, }, + { + name: "service_account total quota exceeded", + account: &Account{ + Status: StatusActive, + Schedulable: true, + Platform: PlatformGemini, + Type: AccountTypeServiceAccount, + Extra: map[string]any{ + "quota_limit": 50.0, + "quota_used": 50.0, + }, + }, + want: false, + }, + { + name: "service_account daily quota exceeded", + account: &Account{ + Status: StatusActive, + Schedulable: true, + Platform: PlatformGemini, + Type: AccountTypeServiceAccount, + Extra: map[string]any{ + "quota_daily_limit": 10.0, + "quota_daily_used": 12.0, + "quota_daily_start": now.Add(-1 * time.Hour).Format(time.RFC3339), + }, + }, + want: false, + }, + { + name: "service_account without limit stays schedulable regardless of quota_used", + account: &Account{ + Status: StatusActive, + Schedulable: true, + Platform: PlatformGemini, + Type: AccountTypeServiceAccount, + Extra: map[string]any{ + "quota_used": 9999.0, + }, + }, + want: true, + }, } for _, tt := range tests { diff --git a/backend/internal/service/account_quota_service_account_test.go b/backend/internal/service/account_quota_service_account_test.go new file mode 100644 index 0000000000..6358f32024 --- /dev/null +++ b/backend/internal/service/account_quota_service_account_test.go @@ -0,0 +1,204 @@ +package service + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestAccountSupportsAccountQuota(t *testing.T) { + tests := []struct { + accountType string + want bool + }{ + {AccountTypeAPIKey, true}, + {AccountTypeBedrock, true}, + {AccountTypeServiceAccount, true}, + {AccountTypeOAuth, false}, + {AccountTypeSetupToken, false}, + {AccountTypeUpstream, false}, + } + for _, tt := range tests { + t.Run(tt.accountType, func(t *testing.T) { + account := &Account{Type: tt.accountType} + require.Equal(t, tt.want, account.SupportsAccountQuota()) + }) + } +} + +// 配额专用判定放开 service_account,不能连带放开池模式等其它 IsAPIKeyOrBedrock 特性。 +func TestServiceAccountQuotaDoesNotWidenPoolMode(t *testing.T) { + account := &Account{ + Platform: PlatformGemini, + Type: AccountTypeServiceAccount, + Credentials: map[string]any{"pool_mode": true}, + } + require.True(t, account.SupportsAccountQuota()) + require.False(t, account.IsAPIKeyOrBedrock()) + require.False(t, account.IsPoolMode()) +} + +func TestShouldUpdateAccountQuota(t *testing.T) { + tests := []struct { + name string + account *Account + totalCost float64 + want bool + }{ + { + name: "apikey without limit does not accumulate", + account: &Account{Type: AccountTypeAPIKey, Extra: map[string]any{}}, + totalCost: 1.5, + want: false, + }, + { + name: "apikey with total limit accumulates", + account: &Account{Type: AccountTypeAPIKey, Extra: map[string]any{"quota_limit": 100.0}}, + totalCost: 1.5, + want: true, + }, + { + name: "bedrock with daily limit accumulates", + account: &Account{Type: AccountTypeBedrock, Extra: map[string]any{"quota_daily_limit": 10.0}}, + totalCost: 1.5, + want: true, + }, + { + name: "service_account without limit does not accumulate", + account: &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_used": 30.0}}, + totalCost: 1.5, + want: false, + }, + { + name: "service_account with limit accumulates", + account: &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_weekly_limit": 50.0}}, + totalCost: 1.5, + want: true, + }, + { + name: "service_account zero cost does not accumulate", + account: &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}}, + totalCost: 0, + want: false, + }, + { + name: "oauth with limit is not quota eligible", + account: &Account{Type: AccountTypeOAuth, Extra: map[string]any{"quota_limit": 100.0}}, + totalCost: 1.5, + want: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + p := &postUsageBillingParams{ + Cost: &CostBreakdown{TotalCost: tt.totalCost}, + Account: tt.account, + } + require.Equal(t, tt.want, p.shouldUpdateAccountQuota()) + }) + } +} + +func TestBuildUsageBillingCommandAccountQuotaCostForServiceAccount(t *testing.T) { + build := func(account *Account) *UsageBillingCommand { + return buildUsageBillingCommand("req-sa-quota", nil, &postUsageBillingParams{ + Cost: &CostBreakdown{TotalCost: 2, ActualCost: 3}, + User: &User{ID: 7}, + APIKey: &APIKey{ID: 13}, + Account: account, + AccountRateMultiplier: 1.5, + }) + } + + // service_account 设了上限:AccountQuotaCost = TotalCost × 账号倍率 + cmd := build(&Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}}) + require.NotNil(t, cmd) + require.Equal(t, AccountTypeServiceAccount, cmd.AccountType) + require.InDelta(t, 3.0, cmd.AccountQuotaCost, 1e-9) + + // service_account 不设上限:与 apikey 一致不累加 + cmd = build(&Account{ID: 10, Platform: PlatformGemini, Type: AccountTypeServiceAccount}) + require.NotNil(t, cmd) + require.Zero(t, cmd.AccountQuotaCost) +} + +type accountQuotaIncrementRepoStub struct { + AccountRepository + calls []float64 +} + +func (s *accountQuotaIncrementRepoStub) IncrementQuotaUsed(_ context.Context, _ int64, amount float64) error { + s.calls = append(s.calls, amount) + return nil +} + +func TestPostUsageBillingLegacyAccumulatesServiceAccountQuota(t *testing.T) { + repo := &accountQuotaIncrementRepoStub{} + postUsageBilling(context.Background(), &postUsageBillingParams{ + Cost: &CostBreakdown{TotalCost: 2}, + User: &User{ID: 7}, + APIKey: &APIKey{ID: 13}, + Account: &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}}, + AccountRateMultiplier: 1.25, + }, &billingDeps{accountRepo: repo}) + + require.Len(t, repo.calls, 1) + require.InDelta(t, 2.5, repo.calls[0], 1e-9) +} + +type settingGetValueCounter struct { + SettingRepository + calls int +} + +func (s *settingGetValueCounter) GetValue(context.Context, string) (string, error) { + s.calls++ + return "false", nil +} + +// 未设任何上限的账号没有可跨越的阈值,不应逐请求读取通知设置。 +func TestNotifyAccountQuotaSkipsAccountWithoutLimit(t *testing.T) { + tests := []struct { + name string + account *Account + wantCalls int + }{ + { + name: "service_account without limit", + account: &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount}, + wantCalls: 0, + }, + { + name: "service_account with total limit", + account: &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}}, + wantCalls: 1, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + settings := &settingGetValueCounter{} + notifyAccountQuota(&postUsageBillingParams{ + Cost: &CostBreakdown{TotalCost: 2}, + Account: tt.account, + AccountRateMultiplier: 1, + }, &billingDeps{ + balanceNotifyService: NewBalanceNotifyService(NewEmailService(settings, nil), settings, nil), + }, nil) + require.Equal(t, tt.wantCalls, settings.calls) + }) + } +} + +// 账号已删除时计数被跳过、无递增后状态,不应回退到快照做阈值判定。 +func TestNotifyAccountQuotaSkipsWhenQuotaIncrementSkipped(t *testing.T) { + settings := &settingGetValueCounter{} + notifyAccountQuota(&postUsageBillingParams{ + Cost: &CostBreakdown{TotalCost: 2}, + Account: &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}}, + AccountRateMultiplier: 1, + }, &billingDeps{ + balanceNotifyService: NewBalanceNotifyService(NewEmailService(settings, nil), settings, nil), + }, &UsageBillingApplyResult{Applied: true}) + require.Zero(t, settings.calls) +} diff --git a/backend/internal/service/gateway_scheduling.go b/backend/internal/service/gateway_scheduling.go index 059d7e2b2c..46df448245 100644 --- a/backend/internal/service/gateway_scheduling.go +++ b/backend/internal/service/gateway_scheduling.go @@ -1309,9 +1309,9 @@ func (s *GatewayService) withWindowCostPrefetch(ctx context.Context, accounts [] } // isAccountSchedulableForQuota 检查账号是否在配额限制内 -// 适用于配置了 quota_limit 的 apikey 和 bedrock 类型账号 +// 适用于配置了 quota_limit 的 apikey、bedrock 和 service_account 类型账号 func (s *GatewayService) isAccountSchedulableForQuota(account *Account) bool { - if !account.IsAPIKeyOrBedrock() { + if !account.SupportsAccountQuota() { return true } return !account.IsQuotaExceeded() diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index 84c604fd04..426209b296 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -137,7 +137,7 @@ func (p *postUsageBillingParams) shouldUpdateRateLimits() bool { } func (p *postUsageBillingParams) shouldUpdateAccountQuota() bool { - return p.Cost.TotalCost > 0 && p.Account.IsAPIKeyOrBedrock() && p.Account.HasAnyQuotaLimit() + return p.Cost.TotalCost > 0 && p.Account.SupportsAccountQuota() && p.Account.HasAnyQuotaLimit() } // postUsageBilling is the legacy fallback billing path used when the unified @@ -541,11 +541,12 @@ func notifyAccountQuota(p *postUsageBillingParams, deps *billingDeps, result *Us slog.Error("panic in notifyAccountQuota", "recover", r) } }() - if p.Cost.TotalCost <= 0 || p.Account == nil || !p.Account.IsAPIKeyOrBedrock() || deps.balanceNotifyService == nil { + if p.Cost.TotalCost <= 0 || p.Account == nil || !p.Account.SupportsAccountQuota() || !p.Account.HasAnyQuotaLimit() || deps.balanceNotifyService == nil { slog.Debug("notifyAccountQuota: skipped", "total_cost", p.Cost.TotalCost, "account_nil", p.Account == nil, - "is_apikey_or_bedrock", p.Account != nil && p.Account.IsAPIKeyOrBedrock(), + "supports_account_quota", p.Account != nil && p.Account.SupportsAccountQuota(), + "has_quota_limit", p.Account != nil && p.Account.HasAnyQuotaLimit(), "service_nil", deps.balanceNotifyService == nil, ) return @@ -554,6 +555,10 @@ func notifyAccountQuota(p *postUsageBillingParams, deps *billingDeps, result *Us var quotaState *AccountQuotaState if result != nil { quotaState = result.QuotaState + // 本应累加却无递增后状态(账号已删除,计数被跳过):没有新用量,不做阈值判定。 + if quotaState == nil && p.shouldUpdateAccountQuota() { + return + } } slog.Debug("notifyAccountQuota: calling CheckAccountQuotaAfterIncrement", "account_id", p.Account.ID, diff --git a/frontend/src/components/account/AccountCapacityCell.vue b/frontend/src/components/account/AccountCapacityCell.vue index 3df5b24b4f..4e89708d87 100644 --- a/frontend/src/components/account/AccountCapacityCell.vue +++ b/frontend/src/components/account/AccountCapacityCell.vue @@ -39,6 +39,7 @@ import { computed } from 'vue' import { useI18n } from 'vue-i18n' import type { Account } from '@/types' +import { supportsAccountQuota } from '@/utils/accountQuota' import CapacityBadge from '@/components/account/CapacityBadge.vue' import QuotaBadge from '@/components/account/QuotaBadge.vue' @@ -176,7 +177,7 @@ const formatCost = (value: number | null | undefined) => { } // ====== 配额 ====== -const isQuotaEligible = computed(() => props.account.type === 'apikey' || props.account.type === 'bedrock') +const isQuotaEligible = computed(() => supportsAccountQuota(props.account.type)) const showDailyQuota = computed(() => isQuotaEligible.value && props.account.quota_daily_limit != null && props.account.quota_daily_limit > 0 diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue index 6bf5f12af5..a12527b82b 100644 --- a/frontend/src/components/account/AccountUsageCell.vue +++ b/frontend/src/components/account/AccountUsageCell.vue @@ -554,6 +554,29 @@
+ +
@@ -684,6 +707,7 @@ import { buildOpenAIUsageRefreshKey } from '@/utils/accountUsageRefresh' import { enqueueUsageRequest } from '@/utils/usageLoadQueue' import { formatCompactNumber } from '@/utils/format' import { isOfficialGeminiBaseUrl } from '@/utils/geminiExplicitCache' +import { supportsAccountQuota } from '@/utils/accountQuota' import UsageProgressBar from './UsageProgressBar.vue' import AccountQuotaInfo from './AccountQuotaInfo.vue' import ClaudeResetCreditsCell from './ClaudeResetCreditsCell.vue' @@ -1572,7 +1596,7 @@ const makeQuotaBar = ( } const hasApiKeyQuota = computed(() => { - if (props.account.type !== 'apikey' && props.account.type !== 'bedrock') return false + if (!supportsAccountQuota(props.account.type)) return false return ( (props.account.quota_daily_limit ?? 0) > 0 || (props.account.quota_weekly_limit ?? 0) > 0 || diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index 93deb2f4c3..cb013a4dd3 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -2347,9 +2347,9 @@ />
- +
@@ -4203,6 +4203,7 @@ import { parseDateTimeLocalInput } from '@/utils/format' import { createStableObjectKeyResolver } from '@/utils/stableObjectKey' +import { supportsAccountQuota } from '@/utils/accountQuota' import { getAccountExpiryTimestamp } from '@/components/account/accountExpiry' import { VERTEX_LOCATION_OPTIONS } from '@/constants/account' import { @@ -6282,9 +6283,9 @@ const createAccountAndFinish = async ( if (!applyTempUnschedConfig(credentials)) { return } - // Inject quota limits for apikey/bedrock accounts + // Inject quota limits for apikey/bedrock/service_account accounts let finalExtra = withUpstreamRequestIdHeader(extra) - if (type === 'apikey' || type === 'bedrock') { + if (supportsAccountQuota(type)) { const quotaExtra: Record = { ...(finalExtra || {}) } if (editQuotaLimit.value != null && editQuotaLimit.value > 0) { quotaExtra.quota_limit = editQuotaLimit.value diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index bbddaaf44e..288abd793e 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -2319,9 +2319,9 @@ @update:quotaNotifyTotalThresholdType="quotaNotifyState.total.thresholdType = $event" />
- +
@@ -3316,6 +3316,7 @@ import { } from '@/utils/format' import { extractApiErrorMessage, extractI18nErrorMessage } from '@/utils/apiError' import { createStableObjectKeyResolver } from '@/utils/stableObjectKey' +import { supportsAccountQuota } from '@/utils/accountQuota' import { getAccountExpiryTimestamp } from '@/components/account/accountExpiry' import { allSelectedGroupsEnableLongContextPricing } from '@/components/account/longContextBilling' import { VERTEX_LOCATION_OPTIONS } from '@/constants/account' @@ -4438,8 +4439,8 @@ const syncFormFromAccount = (newAccount: Account | null) => { } } - // Load quota limit for apikey/bedrock accounts (bedrock quota is also loaded in its own branch above) - if (newAccount.type === 'apikey' || newAccount.type === 'bedrock') { + // Load quota limit for apikey/bedrock/service_account accounts (bedrock quota is also loaded in its own branch above) + if (supportsAccountQuota(newAccount.type)) { const quotaVal = extra?.quota_limit as number | undefined editQuotaLimit.value = (quotaVal && quotaVal > 0) ? quotaVal : null const dailyVal = extra?.quota_daily_limit as number | undefined @@ -6016,8 +6017,8 @@ const handleSubmit = async () => { updatePayload.extra = newExtra } - // For apikey/bedrock accounts, handle quota_limit in extra - if (props.account.type === 'apikey' || props.account.type === 'bedrock') { + // For apikey/bedrock/service_account accounts, handle quota_limit in extra + if (supportsAccountQuota(props.account.type)) { const currentExtra = (updatePayload.extra as Record) || (props.account.extra as Record) || {} const newExtra: Record = { ...currentExtra } diff --git a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts index d595102f66..acbf0884ca 100644 --- a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts +++ b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts @@ -1715,6 +1715,71 @@ describe('AccountUsageCell', () => { expect(getUsage).not.toHaveBeenCalled() }) + it('Vertex 账号不设上限时不显示配额进度条', async () => { + const wrapper = mount(AccountUsageCell, { + props: { + account: makeAccount({ + id: 4011, + platform: 'gemini', + type: 'service_account', + credentials: { tier_id: 'vertex', project_id: 'vertex-proj', location: 'global' }, + extra: {} + }), + todayStats: { + requests: 3, + tokens: 1200, + cost: 0.42, + standard_cost: 0.42, + user_cost: 0.5 + } + }, + global: { + stubs: { + UsageProgressBar: true, + AccountQuotaInfo: true + } + } + }) + + await flushPromises() + + expect(wrapper.text()).toContain('A $0.42') + expect(wrapper.findAll('usage-progress-bar-stub')).toHaveLength(0) + expect(getUsage).not.toHaveBeenCalled() + }) + + it('Vertex 账号设置了配额上限时显示配额进度条', async () => { + const wrapper = mount(AccountUsageCell, { + props: { + account: makeAccount({ + id: 4012, + platform: 'gemini', + type: 'service_account', + credentials: { tier_id: 'vertex', project_id: 'vertex-proj', location: 'global' }, + extra: { quota_daily_start: new Date().toISOString() }, + quota_used: 123.456, + quota_limit: 500, + quota_daily_limit: 50, + quota_daily_used: 12.5 + }), + todayStats: null, + todayStatsLoading: false + }, + global: { + stubs: { + UsageProgressBar: true, + AccountQuotaInfo: true + } + } + }) + + await flushPromises() + + const bars = wrapper.findAll('usage-progress-bar-stub') + expect(bars.map((bar) => bar.attributes('label'))).toEqual(['1d', 'total']) + expect(getUsage).not.toHaveBeenCalled() + }) + it('Gemini 第三方上游 API Key 按普通 Key 账号展示今日统计与额度,不显示 Gemini 徽章', async () => { const wrapper = mount(AccountUsageCell, { props: { diff --git a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts index 7061bc84d6..9e786042f2 100644 --- a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts @@ -1715,6 +1715,26 @@ describe('EditAccountModal', () => { expect(updateAccountMock).toHaveBeenCalledTimes(1) }) + it('shows quota limit card for Vertex SA account and keeps quota limits on save', async () => { + const account = buildVertexAccount() + account.extra = { quota_limit: 200, quota_daily_limit: 20, quota_used: 35.5 } + updateAccountMock.mockReset() + checkMixedChannelRiskMock.mockReset() + checkMixedChannelRiskMock.mockResolvedValue({ has_risk: false }) + updateAccountMock.mockResolvedValue(account) + + const wrapper = mountModal(account) + expect(wrapper.findComponent({ name: 'QuotaLimitCard' }).exists()).toBe(true) + + await wrapper.get('form#edit-account-form').trigger('submit.prevent') + + expect(updateAccountMock).toHaveBeenCalledTimes(1) + const extra = updateAccountMock.mock.calls[0]?.[1]?.extra + expect(extra?.quota_limit).toBe(200) + expect(extra?.quota_daily_limit).toBe(20) + expect(extra?.quota_weekly_limit).toBeUndefined() + }) + it('blocks Vertex SA save when neither credentials_status nor legacy json indicates existence', async () => { const account = buildVertexAccount() account.credentials = { diff --git a/frontend/src/components/admin/account/AccountActionMenu.vue b/frontend/src/components/admin/account/AccountActionMenu.vue index 0523dcad02..f376cce12d 100644 --- a/frontend/src/components/admin/account/AccountActionMenu.vue +++ b/frontend/src/components/admin/account/AccountActionMenu.vue @@ -68,6 +68,7 @@ import { useResizeObserver, useWindowSize } from '@vueuse/core' import { useI18n } from 'vue-i18n' import { Icon } from '@/components/icons' import type { Account } from '@/types' +import { supportsAccountQuota } from '@/utils/accountQuota' const props = defineProps<{ show: boolean; account: Account | null; anchorRect: DOMRect | null }>() const emit = defineEmits(['close', 'test', 'stats', 'schedule', 'duplicate', 'reauth', 'refresh-token', 'recover-state', 'reset-quota', 'set-privacy', 'create-spark-shadow']) @@ -135,7 +136,7 @@ const isShadow = computed(() => props.account?.parent_account_id != null) const isOpenAIOAuthParent = computed(() => isOpenAIOAuth.value && !isShadow.value) const supportsPrivacy = computed(() => (isAntigravityOAuth.value || isOpenAIOAuth.value) && !isShadow.value) const hasQuotaLimit = computed(() => { - return (props.account?.type === 'apikey' || props.account?.type === 'bedrock') && ( + return supportsAccountQuota(props.account?.type) && ( (props.account?.quota_limit ?? 0) > 0 || (props.account?.quota_daily_limit ?? 0) > 0 || (props.account?.quota_weekly_limit ?? 0) > 0 diff --git a/frontend/src/utils/accountQuota.ts b/frontend/src/utils/accountQuota.ts new file mode 100644 index 0000000000..22c54ccbe2 --- /dev/null +++ b/frontend/src/utils/accountQuota.ts @@ -0,0 +1,6 @@ +import type { AccountType } from '@/types' + +/** 支持账号配额(总/日/周上限、quota_used 累加、超限停调度)的账号类型,与后端 AccountTypeSupportsQuota 一致。 */ +export function supportsAccountQuota(type?: AccountType | null): boolean { + return type === 'apikey' || type === 'bedrock' || type === 'service_account' +} From 47cb84b8b047ff883d3ab6214151c96ff8b93584 Mon Sep 17 00:00:00 2001 From: feeeei Date: Sat, 17 Oct 2026 00:07:44 +0800 Subject: [PATCH 013/297] =?UTF-8?q?fix(gemini):=20=E5=88=86=E7=BB=84?= =?UTF-8?q?=E3=80=8C=E5=85=81=E8=AE=B8=E5=BD=93=E5=89=8D=E5=88=86=E7=BB=84?= =?UTF-8?q?=E7=94=9F=E5=9B=BE=E3=80=8D=E5=BC=80=E5=85=B3=E5=AF=B9=20Gemini?= =?UTF-8?q?=20=E7=B3=BB=E5=85=A5=E5=8F=A3=E7=94=9F=E6=95=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 门禁作用于展示该开关的 Gemini 系分组(gemini/antigravity/composite);无分组 Key、 anthropic 等其他平台分组不受影响,OpenAI/Grok 仍走各自门禁 - 生图判定:复用图片接口的 gemini-*-image 判定(isGeminiCompatibleImageModel),或请求体 generationConfig.responseModalities 含 IMAGE(camelCase/snake_case、字符串/整数枚举、 重复键逐个检查);countTokens 不拦 - 两道检查:/v1/messages、/v1/chat/completions、/v1/responses、/v1beta/models 入口在 选号前按客户端请求名与渠道映射名预检;Gemini 兼容与 Antigravity 的 6 个转发函数在 账号模型映射后再按上游模型名检查,覆盖账号级别名 - 拒绝统一返回 400(Gemini 原生 INVALID_ARGUMENT,其余 invalid_request_error), 不触发换号与账号处罚,下游 sub2api 把本实例当上游时不会因此停用账号; 请求标记为本地功能门禁 - 升级兼容:迁移 246 把存量 gemini/antigravity 分组的生图开关置为开启;新建分组与简易 模式默认分组对 gemini/antigravity 默认开启(与 grok 同为 OR 语义,创建时传 false 不生效), 前端创建表单同步默认值;composite 不回填(同一开关还控制 OpenAI 生图),未开启的 composite 分组升级后 Gemini 生图返回 400 - 未覆盖:最终模型名不符合 gemini-*-image 形态(如上游中转自定义的 nano-banana 别名) 且请求体未声明 IMAGE 模态;门禁按 Key 所属分组判断,Claude Code 专用分组降级到 其他分组时仍按原分组 --- backend/internal/handler/gateway_handler.go | 4 + .../gateway_handler_chat_completions.go | 4 + .../handler/gateway_handler_responses.go | 4 + .../handler/gemini_image_generation_gate.go | 17 ++ .../gemini_image_generation_gate_test.go | 168 +++++++++++ .../internal/handler/gemini_v1beta_handler.go | 14 +- .../repository/simple_mode_default_groups.go | 2 +- ...le_mode_default_groups_integration_test.go | 17 +- backend/internal/service/admin_group.go | 17 +- .../service/admin_service_group_test.go | 68 ++--- .../service/antigravity_gateway_claude.go | 3 + .../service/antigravity_gateway_compat.go | 3 + .../service/antigravity_gateway_gemini.go | 3 + .../gemini_chat_completions_compat_service.go | 3 + .../service/gemini_image_generation_gate.go | 94 +++++++ .../gemini_image_generation_gate_test.go | 263 ++++++++++++++++++ .../service/gemini_messages_compat_service.go | 6 + ..._enable_gemini_image_generation_groups.sql | 6 + ..._image_generation_groups_migration_test.go | 24 ++ frontend/src/views/admin/GroupsView.vue | 2 + .../__tests__/groupsImagePricing.spec.ts | 9 + .../src/views/admin/groupsImagePricing.ts | 6 + 22 files changed, 691 insertions(+), 46 deletions(-) create mode 100644 backend/internal/handler/gemini_image_generation_gate.go create mode 100644 backend/internal/handler/gemini_image_generation_gate_test.go create mode 100644 backend/internal/service/gemini_image_generation_gate.go create mode 100644 backend/internal/service/gemini_image_generation_gate_test.go create mode 100644 backend/migrations/246_enable_gemini_image_generation_groups.sql create mode 100644 backend/migrations/gemini_image_generation_groups_migration_test.go diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index e990e3dd0a..73eff575a6 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -228,6 +228,10 @@ func (h *GatewayHandler) Messages(c *gin.Context) { if rejectSystemOneOnlyPlatform(c, apiKey, h.errorResponse) { return } + if geminiImageGenerationRejected(c, apiKey, nil, reqModel, channelMapping.MappedModel) { + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", service.ImageGenerationPermissionMessage()) + return + } if decision := h.checkSecurityAudit(c, reqLog, apiKey, subject, service.ContentModerationProtocolAnthropicMessages, reqModel, body); decision != nil && !decision.AllowNextStage { h.anthropicSecurityAuditError(c, decision) diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 561ed1bca0..85fceffd75 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -113,6 +113,10 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { "This group is restricted to Claude Code clients (/v1/messages only)") return } + if geminiImageGenerationRejected(c, apiKey, nil, reqModel, channelMapping.MappedModel) { + h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", service.ImageGenerationPermissionMessage()) + return + } if decision := h.checkSecurityAudit(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIChat, reqModel, body); decision != nil && !decision.AllowNextStage { h.openAISecurityAuditError(c, decision) diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 5ef6bace91..c25d3cfa9d 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -117,6 +117,10 @@ func (h *GatewayHandler) Responses(c *gin.Context) { "This group is restricted to Claude Code clients (/v1/messages only)") return } + if geminiImageGenerationRejected(c, apiKey, nil, reqModel, channelMapping.MappedModel) { + h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", service.ImageGenerationPermissionMessage()) + return + } if decision := h.checkSecurityAudit(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, reqModel, body); decision != nil && !decision.AllowNextStage { h.responsesSecurityAuditError(c, decision) diff --git a/backend/internal/handler/gemini_image_generation_gate.go b/backend/internal/handler/gemini_image_generation_gate.go new file mode 100644 index 0000000000..f1667ee6d5 --- /dev/null +++ b/backend/internal/handler/gemini_image_generation_gate.go @@ -0,0 +1,17 @@ +package handler + +import ( + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" +) + +// geminiImageGenerationRejected 在选号之前按客户端请求名、渠道映射名与请求体 +// 执行 Gemini 系分组的生图门禁。命中时把请求标记为本地功能门禁并返回 true, +// 调用方按入口协议写出 400;账号级模型映射之后的判定由转发层负责。 +func geminiImageGenerationRejected(c *gin.Context, apiKey *service.APIKey, body []byte, models ...string) bool { + if apiKey == nil || !service.GeminiImageGenerationDenied(apiKey.Group, body, models...) { + return false + } + service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate) + return true +} diff --git a/backend/internal/handler/gemini_image_generation_gate_test.go b/backend/internal/handler/gemini_image_generation_gate_test.go new file mode 100644 index 0000000000..048a7a7dd9 --- /dev/null +++ b/backend/internal/handler/gemini_image_generation_gate_test.go @@ -0,0 +1,168 @@ +//go:build unit + +package handler + +import ( + "bytes" + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type geminiImageGateEndpoint struct { + name string + path string + body string + params gin.Params + forcePlatform string + call func(*GatewayHandler, *gin.Context) +} + +func geminiImageGateEndpoints(model string) []geminiImageGateEndpoint { + return []geminiImageGateEndpoint{ + { + name: "messages", path: "/v1/messages", + body: `{"model":"` + model + `","max_tokens":16,"messages":[{"role":"user","content":"draw a cat"}]}`, + call: (*GatewayHandler).Messages, + }, + { + name: "chat completions", path: "/v1/chat/completions", + body: `{"model":"` + model + `","messages":[{"role":"user","content":"draw a cat"}]}`, + call: (*GatewayHandler).ChatCompletions, + }, + { + name: "responses", path: "/v1/responses", + body: `{"model":"` + model + `","input":"draw a cat"}`, + call: (*GatewayHandler).Responses, + }, + { + name: "gemini native", path: "/v1beta/models/" + model + ":generateContent", + body: `{"contents":[{"role":"user","parts":[{"text":"draw a cat"}]}]}`, + params: gin.Params{{Key: "modelAction", Value: "/" + model + ":generateContent"}}, + call: (*GatewayHandler).GeminiV1BetaModels, + }, + } +} + +func runGeminiImageGateEndpoint(t *testing.T, ep geminiImageGateEndpoint, group *service.Group, accountPlatform string) (*httptest.ResponseRecorder, *gin.Context, *groupScopedSchedulerCache) { + t.Helper() + const accountID = int64(9411) + schedulerCache := &groupScopedSchedulerCache{fakeSchedulerCache: &fakeSchedulerCache{accounts: []*service.Account{{ + ID: accountID, Platform: accountPlatform, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, + AccountGroups: []service.AccountGroup{{AccountID: accountID, GroupID: group.ID}}, + }}}} + gatewayService := service.NewGatewayService( + nil, &groupMapRepo{fakeGroupRepo: &fakeGroupRepo{}, groups: map[int64]*service.Group{group.ID: group}}, + nil, nil, nil, nil, nil, nil, nil, + service.NewSchedulerSnapshotService(schedulerCache, nil, nil, nil, nil), + nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + ) + cfg := &config.Config{RunMode: config.RunModeSimple} + billingCacheService := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCacheService.Stop) + h := &GatewayHandler{ + gatewayService: gatewayService, + billingCacheService: billingCacheService, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0), + maxAccountSwitches: 1, + cfg: cfg, + } + + groupID := group.ID + apiKey := &service.APIKey{ + ID: 9420, UserID: 9430, GroupID: &groupID, Group: group, Status: service.StatusActive, + User: &service.User{ID: 9430, Concurrency: 10, Balance: 100}, + } + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + ctx := context.WithValue(context.Background(), ctxkey.Group, group) + req := httptest.NewRequest(http.MethodPost, ep.path, bytes.NewBufferString(ep.body)).WithContext(ctx) + req.Header.Set("Content-Type", "application/json") + c.Request = req + c.Params = ep.params + if ep.forcePlatform != "" { + c.Set(string(middleware.ContextKeyForcePlatform), ep.forcePlatform) + } + c.Set(string(middleware.ContextKeyAPIKey), apiKey) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.UserID, Concurrency: 10}) + + ep.call(h, c) + return recorder, c, schedulerCache +} + +func TestGatewayHandlers_GeminiImageGenerationDisabledGroupRejectsBeforeSelection(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, platform := range []string{service.PlatformGemini, service.PlatformAntigravity} { + for _, ep := range geminiImageGateEndpoints("gemini-3-pro-image") { + if platform == service.PlatformAntigravity && ep.params != nil { + ep.path = "/antigravity" + ep.path + ep.forcePlatform = service.PlatformAntigravity + } + t.Run(platform+"/"+ep.name, func(t *testing.T) { + group := &service.Group{ + ID: 9400, Hydrated: true, Platform: platform, Status: service.StatusActive, + AllowImageGeneration: false, + } + recorder, c, schedulerCache := runGeminiImageGateEndpoint(t, ep, group, platform) + + require.Equal(t, http.StatusBadRequest, recorder.Code) + require.Contains(t, recorder.Body.String(), service.ImageGenerationPermissionMessage()) + _, reachedSelection := c.Get(opsAccountIDKey) + require.False(t, reachedSelection) + require.Empty(t, schedulerCache.queriedGroupIDs()) + }) + } + } +} + +func TestGatewayHandlers_GeminiImageGenerationGateSkipsGroupsWithoutTheSwitch(t *testing.T) { + gin.SetMode(gin.TestMode) + // Anthropic 分组在后台不展示生图开关,混合调度 Antigravity 账号时不受门禁约束。 + for _, ep := range geminiImageGateEndpoints("gemini-3-pro-image")[:3] { + t.Run(ep.name, func(t *testing.T) { + group := &service.Group{ + ID: 9401, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive, + AllowImageGeneration: false, + } + recorder, _, schedulerCache := runGeminiImageGateEndpoint(t, ep, group, service.PlatformAnthropic) + + require.NotContains(t, recorder.Body.String(), service.ImageGenerationPermissionMessage()) + require.NotEmpty(t, schedulerCache.queriedGroupIDs()) + }) + } +} + +func TestGatewayHandlers_GeminiImageGenerationGateAllowsTextModelsAndEnabledGroups(t *testing.T) { + gin.SetMode(gin.TestMode) + cases := []struct { + name string + model string + allow bool + }{ + {name: "text model in disabled group", model: "gemini-3.7-flash", allow: false}, + {name: "image model in enabled group", model: "gemini-3-pro-image", allow: true}, + } + for _, tc := range cases { + for _, ep := range geminiImageGateEndpoints(tc.model)[:3] { + t.Run(tc.name+"/"+ep.name, func(t *testing.T) { + group := &service.Group{ + ID: 9402, Hydrated: true, Platform: service.PlatformGemini, Status: service.StatusActive, + AllowImageGeneration: tc.allow, + } + recorder, _, schedulerCache := runGeminiImageGateEndpoint(t, ep, group, service.PlatformGemini) + + require.NotContains(t, recorder.Body.String(), service.ImageGenerationPermissionMessage()) + require.NotEmpty(t, schedulerCache.queriedGroupIDs()) + }) + } + } +} diff --git a/backend/internal/handler/gemini_v1beta_handler.go b/backend/internal/handler/gemini_v1beta_handler.go index 95c550302e..0e2187c9cb 100644 --- a/backend/internal/handler/gemini_v1beta_handler.go +++ b/backend/internal/handler/gemini_v1beta_handler.go @@ -328,6 +328,7 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { googleError(c, http.StatusBadRequest, "Invalid model in URL") return } + urlModel := modelName if resolvedModel, ok := service.ResolvedUpstreamModelFromContext(c.Request.Context()); ok && strings.TrimSpace(resolvedModel) != "" { modelName = strings.TrimSpace(resolvedModel) } @@ -358,14 +359,19 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { pricingCtx, pricingAt := service.WithGatewayTokenRequestPricing(c.Request.Context()) c.Request = c.Request.WithContext(pricingCtx) - if decision := h.checkSecurityAudit(c, reqLog, apiKey, authSubject, service.ContentModerationProtocolGemini, modelName, body); decision != nil && !decision.AllowNextStage { + // 解析渠道级模型映射 + channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, modelName) + reqModel := modelName // 保存映射前的原始模型名 + if action != "countTokens" && geminiImageGenerationRejected(c, apiKey, body, urlModel, reqModel, channelMapping.MappedModel) { + googleError(c, http.StatusBadRequest, service.ImageGenerationPermissionMessage()) + return + } + + if decision := h.checkSecurityAudit(c, reqLog, apiKey, authSubject, service.ContentModerationProtocolGemini, reqModel, body); decision != nil && !decision.AllowNextStage { googleSecurityAuditError(c, decision) return } - // 解析渠道级模型映射 - channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, modelName) - reqModel := modelName // 保存映射前的原始模型名 if channelMapping.Mapped { modelName = channelMapping.MappedModel } diff --git a/backend/internal/repository/simple_mode_default_groups.go b/backend/internal/repository/simple_mode_default_groups.go index 2b9daa4d64..25f3d6df5f 100644 --- a/backend/internal/repository/simple_mode_default_groups.go +++ b/backend/internal/repository/simple_mode_default_groups.go @@ -77,7 +77,7 @@ func createGroupIfNotExists(ctx context.Context, client *dbent.Client, name, pla SetSubscriptionType(service.SubscriptionTypeStandard). SetRateMultiplier(1.0). SetIsExclusive(false). - SetAllowImageGeneration(platform == service.PlatformGrok). + SetAllowImageGeneration(service.DefaultAllowImageGenerationForPlatform(platform)). Save(ctx) if err != nil { if dbent.IsConstraintError(err) { diff --git a/backend/internal/repository/simple_mode_default_groups_integration_test.go b/backend/internal/repository/simple_mode_default_groups_integration_test.go index d6a96bbfa2..e21d1b0b4d 100644 --- a/backend/internal/repository/simple_mode_default_groups_integration_test.go +++ b/backend/internal/repository/simple_mode_default_groups_integration_test.go @@ -34,11 +34,18 @@ func TestEnsureSimpleModeDefaultGroups_CreatesMissingDefaults(t *testing.T) { assertGroupExists(service.PlatformAntigravity + "-default-1") assertGroupExists(service.PlatformAntigravity + "-default-2") - grokDefault, err := client.Group.Query(). - Where(group.NameEQ(service.PlatformGrok+"-default"), group.DeletedAtIsNil()). - Only(seedCtx) - require.NoError(t, err) - require.True(t, grokDefault.AllowImageGeneration) + for _, name := range []string{ + service.PlatformGrok + "-default", + service.PlatformGemini + "-default", + service.PlatformAntigravity + "-default-1", + service.PlatformAntigravity + "-default-2", + } { + imageDefault, err := client.Group.Query(). + Where(group.NameEQ(name), group.DeletedAtIsNil()). + Only(seedCtx) + require.NoError(t, err) + require.True(t, imageDefault.AllowImageGeneration, "expected group %s to allow image generation", name) + } } func TestEnsureSimpleModeDefaultGroups_BackfillsOnlyAutoCreatedGrokDefault(t *testing.T) { diff --git a/backend/internal/service/admin_group.go b/backend/internal/service/admin_group.go index 96c8092a8e..f2c06a9a83 100644 --- a/backend/internal/service/admin_group.go +++ b/backend/internal/service/admin_group.go @@ -311,10 +311,17 @@ func defaultModelsListCandidateIDs(platform string) []string { } } -func defaultAllowImageGenerationForPlatform(platform string) bool { - // Grok image and video generation routes share the legacy image-generation gate. - // Older clients send the false zero value, so Grok groups must default enabled. - return platform == PlatformGrok +// DefaultAllowImageGenerationForPlatform reports whether new groups on the platform allow +// image generation. CreateGroup ORs the requested value with it, so a false in the create +// request does not turn it off. Composite defaults disabled because the same switch also +// gates OpenAI image generation there. +func DefaultAllowImageGenerationForPlatform(platform string) bool { + switch platform { + case PlatformGrok, PlatformGemini, PlatformAntigravity: + return true + default: + return false + } } func compositeDefaultModelsListCandidateIDs() []string { @@ -525,7 +532,7 @@ func (s *adminServiceImpl) CreateGroup(ctx context.Context, input *CreateGroupIn mcpXMLInject = *input.MCPXMLInject } - allowImageGeneration := input.AllowImageGeneration || defaultAllowImageGenerationForPlatform(platform) + allowImageGeneration := input.AllowImageGeneration || DefaultAllowImageGenerationForPlatform(platform) allowBatchImageGeneration := input.AllowBatchImageGeneration && allowImageGeneration && platform == PlatformGemini // 如果指定了复制账号的源分组,先获取账号 ID 列表 diff --git a/backend/internal/service/admin_service_group_test.go b/backend/internal/service/admin_service_group_test.go index 56ef6d7e3d..af12cf0e4f 100644 --- a/backend/internal/service/admin_service_group_test.go +++ b/backend/internal/service/admin_service_group_test.go @@ -593,41 +593,47 @@ func TestAdminService_CreateGroup_DefaultsGrokMediaGenerationEnabled(t *testing. require.True(t, group.AllowImageGeneration) } -func TestAdminService_CreateGroup_PreservesNonGrokImageGenerationDisabled(t *testing.T) { - repo := &groupRepoStubForAdmin{} - svc := &adminServiceImpl{groupRepo: repo} +func TestAdminService_CreateGroup_DefaultsGeminiFamilyImageGenerationEnabled(t *testing.T) { + for _, platform := range []string{PlatformGemini, PlatformAntigravity} { + t.Run(platform, func(t *testing.T) { + repo := &groupRepoStubForAdmin{} + svc := &adminServiceImpl{groupRepo: repo} - group, err := svc.CreateGroup(context.Background(), &CreateGroupInput{ - Name: "anthropic-text", - Description: "Anthropic text group", - Platform: PlatformAnthropic, - RateMultiplier: 1.0, - }) - require.NoError(t, err) - require.NotNil(t, group) - require.NotNil(t, repo.created) - require.False(t, repo.created.AllowImageGeneration) - require.False(t, group.AllowImageGeneration) + group, err := svc.CreateGroup(context.Background(), &CreateGroupInput{ + Name: platform + "-images", + Description: "Gemini family group", + Platform: platform, + RateMultiplier: 1.0, + }) + require.NoError(t, err) + require.NotNil(t, group) + require.NotNil(t, repo.created) + require.True(t, repo.created.AllowImageGeneration) + require.True(t, group.AllowImageGeneration) + require.False(t, repo.created.AllowBatchImageGeneration) + }) + } } -func TestAdminService_CreateGroup_DisablesBatchImageWhenImageGenerationDisabled(t *testing.T) { - repo := &groupRepoStubForAdmin{} - svc := &adminServiceImpl{groupRepo: repo} +func TestAdminService_CreateGroup_PreservesImageGenerationDisabledWithoutPlatformDefault(t *testing.T) { + for _, platform := range []string{PlatformAnthropic, PlatformComposite} { + t.Run(platform, func(t *testing.T) { + repo := &groupRepoStubForAdmin{} + svc := &adminServiceImpl{groupRepo: repo} - group, err := svc.CreateGroup(context.Background(), &CreateGroupInput{ - Name: "gemini-no-image", - Description: "Gemini group without image generation", - Platform: PlatformGemini, - RateMultiplier: 1.0, - AllowImageGeneration: false, - AllowBatchImageGeneration: true, - }) - require.NoError(t, err) - require.NotNil(t, group) - require.NotNil(t, repo.created) - require.False(t, repo.created.AllowImageGeneration) - require.False(t, repo.created.AllowBatchImageGeneration) - require.False(t, group.AllowBatchImageGeneration) + group, err := svc.CreateGroup(context.Background(), &CreateGroupInput{ + Name: platform + "-text", + Description: "Group without image default", + Platform: platform, + RateMultiplier: 1.0, + }) + require.NoError(t, err) + require.NotNil(t, group) + require.NotNil(t, repo.created) + require.False(t, repo.created.AllowImageGeneration) + require.False(t, group.AllowImageGeneration) + }) + } } func TestAdminService_CreateGroup_DisablesBatchImageForNonGeminiPlatform(t *testing.T) { diff --git a/backend/internal/service/antigravity_gateway_claude.go b/backend/internal/service/antigravity_gateway_claude.go index 264cbe9980..70230dd488 100644 --- a/backend/internal/service/antigravity_gateway_claude.go +++ b/backend/internal/service/antigravity_gateway_claude.go @@ -61,6 +61,9 @@ func (s *AntigravityGatewayService) Forward(ctx context.Context, c *gin.Context, // 应用 thinking 模式自动后缀:如果 thinking 开启且目标是 claude-sonnet-4-5,自动改为 thinking 版本 thinkingEnabled := claudeReq.Thinking != nil && (claudeReq.Thinking.Type == "enabled" || claudeReq.Thinking.Type == "adaptive") mappedModel = applyThinkingModelSuffix(mappedModel, thinkingEnabled) + if geminiImageGenerationDenied(c, nil, originalModel, mappedModel) { + return nil, s.writeClaudeError(c, http.StatusBadRequest, "invalid_request_error", ImageGenerationPermissionMessage()) + } billingModel := mappedModel // 获取 access_token diff --git a/backend/internal/service/antigravity_gateway_compat.go b/backend/internal/service/antigravity_gateway_compat.go index 60ecd977ed..2869675449 100644 --- a/backend/internal/service/antigravity_gateway_compat.go +++ b/backend/internal/service/antigravity_gateway_compat.go @@ -225,6 +225,9 @@ func (s *AntigravityGatewayService) prepareAntigravityCompatCall( thinkingEnabled := claudeRequest.Thinking != nil && (claudeRequest.Thinking.Type == "enabled" || claudeRequest.Thinking.Type == "adaptive") mappedModel = applyThinkingModelSuffix(mappedModel, thinkingEnabled) + if geminiImageGenerationDenied(c, nil, request.originalModel, mappedModel) { + return nil, s.writeAntigravityCompatError(c, http.StatusBadRequest, "invalid_request_error", ImageGenerationPermissionMessage()) + } if s.tokenProvider == nil { return nil, s.writeAntigravityCompatError(c, http.StatusBadGateway, "api_error", "Antigravity token provider not configured") diff --git a/backend/internal/service/antigravity_gateway_gemini.go b/backend/internal/service/antigravity_gateway_gemini.go index b6396cb08a..0d12fe7759 100644 --- a/backend/internal/service/antigravity_gateway_gemini.go +++ b/backend/internal/service/antigravity_gateway_gemini.go @@ -96,6 +96,9 @@ func (s *AntigravityGatewayService) ForwardGemini(ctx context.Context, c *gin.Co MarkOpsClientBusinessLimited(c, OpsClientBusinessLimitedReasonLocalFeatureGate) return nil, s.writeGoogleError(c, http.StatusForbidden, fmt.Sprintf("model %s not in whitelist", originalModel)) } + if geminiImageGenerationDenied(c, body, originalModel, mappedModel) { + return nil, s.writeGoogleError(c, http.StatusBadRequest, ImageGenerationPermissionMessage()) + } forwardedModel := mappedModel // 获取 access_token diff --git a/backend/internal/service/gemini_chat_completions_compat_service.go b/backend/internal/service/gemini_chat_completions_compat_service.go index f85ac0577a..fbfcd4b179 100644 --- a/backend/internal/service/gemini_chat_completions_compat_service.go +++ b/backend/internal/service/gemini_chat_completions_compat_service.go @@ -100,6 +100,9 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( if err != nil { return nil, s.writeChatCompletionsError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) } + if geminiImageGenerationDenied(c, geminiReq, originalModel, req.Model, mappedModel) { + return nil, s.writeChatCompletionsError(c, http.StatusBadRequest, "invalid_request_error", ImageGenerationPermissionMessage()) + } geminiReq = ensureGeminiFunctionCallThoughtSignatures(geminiReq) geminiReq = applyGeminiCompatThinkingConfig(geminiReq, claudeBody, mappedModel, clientStream) diff --git a/backend/internal/service/gemini_image_generation_gate.go b/backend/internal/service/gemini_image_generation_gate.go new file mode 100644 index 0000000000..8923083685 --- /dev/null +++ b/backend/internal/service/gemini_image_generation_gate.go @@ -0,0 +1,94 @@ +package service + +import ( + "slices" + "strings" + + "github.com/gin-gonic/gin" + "github.com/tidwall/gjson" +) + +// geminiImageModalityEnum 是 proto JSON 中 Modality.IMAGE 的整数枚举值。 +const geminiImageModalityEnum = 2 + +// GeminiImageGenerationDenied 判断 Gemini 系请求是否因分组关闭生图而必须拒绝。 +// 门禁只作用于后台展示该开关的 Gemini 系分组(gemini / antigravity / composite); +// 无分组的 Key 与其他平台分组不受影响。models 中任一名字属于生图模型, +// 或请求体要求输出 IMAGE 模态,即视为生图请求。 +func GeminiImageGenerationDenied(group *Group, geminiBody []byte, models ...string) bool { + if group == nil || group.AllowImageGeneration { + return false + } + switch group.Platform { + case PlatformGemini, PlatformAntigravity, PlatformComposite: + default: + return false + } + return isGeminiImageGenerationIntent(geminiBody, models...) +} + +// geminiImageGenerationDenied 是转发层在账号模型映射之后的门禁:models 传入 +// 转发时可见的模型名(入参模型名与账号映射后的上游模型名)。命中时把请求标记为 +// 本地功能门禁,调用方负责按各自协议写出 400。 +func geminiImageGenerationDenied(c *gin.Context, geminiBody []byte, models ...string) bool { + if c == nil || !GeminiImageGenerationDenied(apiKeyGroup(getAPIKeyFromContext(c)), geminiBody, models...) { + return false + } + MarkOpsClientBusinessLimited(c, OpsClientBusinessLimitedReasonLocalFeatureGate) + return true +} + +func isGeminiImageGenerationIntent(geminiBody []byte, models ...string) bool { + return slices.ContainsFunc(models, isGeminiImageOutputModel) || geminiRequestAsksForImageOutput(geminiBody) +} + +// isGeminiImageOutputModel 匹配以图片为输出的 Gemini 模型名,与图片接口共用 +// isGeminiCompatibleImageModel 判定。 +func isGeminiImageOutputModel(model string) bool { + return isGeminiCompatibleImageModel(strings.TrimPrefix(strings.ToLower(strings.TrimSpace(model)), "models/")) +} + +// geminiRequestAsksForImageOutput 判断 generationConfig.responseModalities 是否包含 IMAGE。 +// Gemini REST 同时接受 camelCase 与 snake_case 字段名、字符串与整数枚举; +// 重复出现的键逐个检查。 +func geminiRequestAsksForImageOutput(body []byte) bool { + if len(body) == 0 || !gjson.ValidBytes(body) { + return false + } + found := false + gjson.ParseBytes(body).ForEach(func(key, config gjson.Result) bool { + if key.Str == "generationConfig" || key.Str == "generation_config" { + found = geminiGenerationConfigAsksForImage(config) + } + return !found + }) + return found +} + +func geminiGenerationConfigAsksForImage(config gjson.Result) bool { + if !config.IsObject() { + return false + } + found := false + config.ForEach(func(key, modalities gjson.Result) bool { + if key.Str == "responseModalities" || key.Str == "response_modalities" { + found = geminiModalitiesContainImage(modalities) + } + return !found + }) + return found +} + +func geminiModalitiesContainImage(modalities gjson.Result) bool { + found := false + modalities.ForEach(func(_, modality gjson.Result) bool { + switch modality.Type { + case gjson.String: + found = strings.EqualFold(strings.TrimSpace(modality.Str), "IMAGE") + case gjson.Number: + found = modality.Num == geminiImageModalityEnum + } + return !found + }) + return found +} diff --git a/backend/internal/service/gemini_image_generation_gate_test.go b/backend/internal/service/gemini_image_generation_gate_test.go new file mode 100644 index 0000000000..c384563127 --- /dev/null +++ b/backend/internal/service/gemini_image_generation_gate_test.go @@ -0,0 +1,263 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestIsGeminiImageGenerationIntent(t *testing.T) { + cases := []struct { + name string + body string + models []string + want bool + }{ + {name: "pro image", models: []string{"gemini-3-pro-image"}, want: true}, + {name: "flash image preview with prefix", models: []string{"models/gemini-3.1-flash-image-preview"}, want: true}, + {name: "image generation experimental", models: []string{"gemini-2.0-flash-exp-image-generation"}, want: true}, + {name: "imageless suffix", models: []string{"gemini-3-pro-imageless"}, want: false}, + {name: "image without gemini prefix", models: []string{"unknown-image", "my-image-chat"}, want: false}, + {name: "banana alias without resolved image model", models: []string{"nano-banana-2"}, want: false}, + {name: "any resolved name", models: []string{"my-alias", "gemini-2.5-flash-image"}, want: true}, + {name: "text model", models: []string{"gemini-3.7-flash", "gemini-3.1-pro-preview"}, want: false}, + {name: "empty", models: []string{"", " "}, want: false}, + {name: "camelCase modalities", body: `{"generationConfig":{"responseModalities":["TEXT","IMAGE"]}}`, models: []string{"gemini-3.7-flash"}, want: true}, + {name: "snake_case modalities", body: `{"generation_config":{"response_modalities":["image"]}}`, want: true}, + {name: "mixed case keys", body: `{"generationConfig":{"response_modalities":[" Image "]}}`, want: true}, + {name: "text only modalities", body: `{"generationConfig":{"responseModalities":["TEXT"]}}`, models: []string{"gemini-3.7-flash"}, want: false}, + {name: "modalities string not array", body: `{"generationConfig":{"responseModalities":"IMAGE"}}`, want: true}, + {name: "no generation config", body: `{"contents":[{"parts":[{"text":"IMAGE"}]}]}`, want: false}, + {name: "integer enum modalities", body: `{"generationConfig":{"responseModalities":[1,2]}}`, want: true}, + {name: "integer enum text only", body: `{"generationConfig":{"responseModalities":[1]}}`, want: false}, + {name: "duplicate generationConfig keys", body: `{"generationConfig":{"responseModalities":["TEXT"]},"generationConfig":{"responseModalities":["IMAGE"]}}`, want: true}, + {name: "duplicate modalities keys", body: `{"generationConfig":{"responseModalities":["TEXT"],"responseModalities":["IMAGE"]}}`, want: true}, + {name: "invalid json", body: `{"generationConfig":{"responseModalities":["IMAGE"]`, want: false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.want, isGeminiImageGenerationIntent([]byte(tc.body), tc.models...)) + }) + } +} + +func TestGeminiImageGenerationDenied_GroupScope(t *testing.T) { + cases := []struct { + name string + group *Group + want bool + }{ + {name: "ungrouped key", group: nil, want: false}, + {name: "gemini disabled", group: &Group{Platform: PlatformGemini}, want: true}, + {name: "antigravity disabled", group: &Group{Platform: PlatformAntigravity}, want: true}, + {name: "composite disabled", group: &Group{Platform: PlatformComposite}, want: true}, + {name: "gemini enabled", group: &Group{Platform: PlatformGemini, AllowImageGeneration: true}, want: false}, + {name: "anthropic group without the switch", group: &Group{Platform: PlatformAnthropic}, want: false}, + {name: "openai group gated elsewhere", group: &Group{Platform: PlatformOpenAI}, want: false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.want, GeminiImageGenerationDenied(tc.group, nil, "gemini-3-pro-image")) + }) + } +} + +func withGeminiImageGateAPIKey(c *gin.Context, group *Group) { + c.Set("api_key", &APIKey{ID: 1, Group: group}) +} + +func imageDisabledGroup() *Group { + return &Group{ID: 10, Platform: PlatformGemini, AllowImageGeneration: false} +} + +func requireGeminiImagePermissionError(t *testing.T, rec *httptest.ResponseRecorder, wantGoogleStatus string) { + t.Helper() + require.Equal(t, http.StatusBadRequest, rec.Code) + var payload map[string]any + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &payload)) + errObj, ok := payload["error"].(map[string]any) + require.True(t, ok, "error object: %s", rec.Body.String()) + require.Equal(t, ImageGenerationPermissionMessage(), errObj["message"]) + if wantGoogleStatus != "" { + require.Equal(t, wantGoogleStatus, errObj["status"]) + } else { + require.Equal(t, "invalid_request_error", errObj["type"]) + } +} + +func TestGeminiForwardNative_ImageGenerationDisabledGroupRejectsBeforeUpstream(t *testing.T) { + gin.SetMode(gin.TestMode) + textBody := []byte(`{"contents":[{"role":"user","parts":[{"text":"draw a cat"}]}]}`) + imageModalityBody := []byte(`{"contents":[{"role":"user","parts":[{"text":"draw a cat"}]}],"generationConfig":{"responseModalities":["TEXT","IMAGE"]}}`) + + cases := []struct { + name string + model string + mapping map[string]any + body []byte + }{ + {name: "image model", model: "gemini-3-pro-image", body: textBody}, + {name: "account mapping alias to image model", model: "my-draw", mapping: map[string]any{"my-draw": "gemini-3.1-flash-image"}, body: textBody}, + {name: "text model asking for image modality", model: "gemini-3.7-flash", body: imageModalityBody}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + svc, httpStub := newGeminiVertexAPIKeyTestService() + c, rec := newGeminiNativeTestContext(t) + withGeminiImageGateAPIKey(c, imageDisabledGroup()) + account := geminiVertexAPIKeyTestAccount("") + if tc.mapping != nil { + account.Credentials["model_mapping"] = tc.mapping + } + + result, err := svc.ForwardNative(context.Background(), c, account, tc.model, "generateContent", false, tc.body) + require.Error(t, err) + require.Nil(t, result) + require.Zero(t, httpStub.calls) + requireGeminiImagePermissionError(t, rec, "INVALID_ARGUMENT") + }) + } +} + +func TestGeminiForwardNative_ImageGenerationGateAllowsPermittedRequests(t *testing.T) { + gin.SetMode(gin.TestMode) + body := []byte(`{"contents":[{"role":"user","parts":[{"text":"draw a cat"}]}]}`) + + cases := []struct { + name string + group *Group + model string + action string + }{ + {name: "group allows image generation", group: &Group{ID: 34, Platform: PlatformGemini, AllowImageGeneration: true}, model: "gemini-3-pro-image", action: "generateContent"}, + {name: "ungrouped key", group: nil, model: "gemini-3-pro-image", action: "generateContent"}, + {name: "text model in disabled group", group: imageDisabledGroup(), model: "gemini-3.7-flash", action: "generateContent"}, + {name: "countTokens on image model", group: imageDisabledGroup(), model: "gemini-3-pro-image", action: "countTokens"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + svc, httpStub := newGeminiVertexAPIKeyTestService() + c, rec := newGeminiNativeTestContext(t) + withGeminiImageGateAPIKey(c, tc.group) + + _, _ = svc.ForwardNative(context.Background(), c, geminiVertexAPIKeyTestAccount(""), tc.model, tc.action, false, body) + require.Equal(t, 1, httpStub.calls) + require.NotEqual(t, http.StatusBadRequest, rec.Code) + }) + } +} + +func TestGeminiCompatForward_ImageGenerationDisabledGroupRejectsBeforeUpstream(t *testing.T) { + gin.SetMode(gin.TestMode) + svc, httpStub := newGeminiVertexAPIKeyTestService() + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + withGeminiImageGateAPIKey(c, imageDisabledGroup()) + body := []byte(`{"model":"gemini-3-pro-image","max_tokens":16,"messages":[{"role":"user","content":"draw a cat"}]}`) + + result, err := svc.Forward(context.Background(), c, geminiVertexAPIKeyTestAccount(""), body) + require.Error(t, err) + require.Nil(t, result) + require.Zero(t, httpStub.calls) + requireGeminiImagePermissionError(t, rec, "") +} + +func TestGeminiForwardAsChatCompletions_ImageGenerationDisabledGroupRejectsBeforeUpstream(t *testing.T) { + gin.SetMode(gin.TestMode) + svc, httpStub := newGeminiVertexAPIKeyTestService() + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"gemini-3.1-flash-image","messages":[{"role":"user","content":"draw a cat"}]}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + withGeminiImageGateAPIKey(c, imageDisabledGroup()) + + result, err := svc.ForwardAsChatCompletions(context.Background(), c, geminiVertexAPIKeyTestAccount(""), body) + require.Error(t, err) + require.Nil(t, result) + require.Zero(t, httpStub.calls) + requireGeminiImagePermissionError(t, rec, "") +} + +func newAntigravityImageGateAccount() *Account { + account := newAntigravityCompatAccount(AccountTypeOAuth) + account.Credentials["model_mapping"] = map[string]any{ + "gemini-3-pro-image": "gemini-3-pro-image", + "my-draw": "gemini-3.1-flash-image", + } + return account +} + +func TestAntigravityForwards_ImageGenerationGate(t *testing.T) { + gin.SetMode(gin.TestMode) + geminiBody := []byte(`{"contents":[{"role":"user","parts":[{"text":"draw a cat"}]}]}`) + claudeBody := []byte(`{"model":"my-draw","max_tokens":16,"stream":true,"messages":[{"role":"user","content":"draw a cat"}]}`) + chatBody := []byte(`{"model":"gemini-3-pro-image","stream":true,"messages":[{"role":"user","content":"draw a cat"}]}`) + + forwards := []struct { + name string + path string + body []byte + wantGoogleStatus string + forward func(*AntigravityGatewayService, *gin.Context, *Account) (*ForwardResult, error) + }{ + { + name: "ForwardGemini", + path: "/v1beta/models/gemini-3-pro-image:streamGenerateContent", + body: geminiBody, + wantGoogleStatus: "INVALID_ARGUMENT", + forward: func(svc *AntigravityGatewayService, c *gin.Context, account *Account) (*ForwardResult, error) { + return svc.ForwardGemini(context.Background(), c, account, "gemini-3-pro-image", "streamGenerateContent", true, geminiBody, false) + }, + }, + { + name: "Forward", + path: "/v1/messages", + body: claudeBody, + forward: func(svc *AntigravityGatewayService, c *gin.Context, account *Account) (*ForwardResult, error) { + return svc.Forward(context.Background(), c, account, claudeBody, false) + }, + }, + { + name: "ForwardAsChatCompletions", + path: "/v1/chat/completions", + body: chatBody, + forward: func(svc *AntigravityGatewayService, c *gin.Context, account *Account) (*ForwardResult, error) { + return svc.ForwardAsChatCompletions(context.Background(), c, account, chatBody, nil) + }, + }, + } + for _, fw := range forwards { + t.Run(fw.name+"/disabled group rejects", func(t *testing.T) { + upstream := &queuedHTTPUpstreamStub{} + svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream) + c, rec := newAntigravityCompatContext(http.MethodPost, fw.path, fw.body) + withGeminiImageGateAPIKey(c, &Group{ID: 20, Platform: PlatformAntigravity, AllowImageGeneration: false}) + + result, err := fw.forward(svc, c, newAntigravityImageGateAccount()) + require.Error(t, err) + require.Nil(t, result) + require.Zero(t, upstream.callCount) + requireGeminiImagePermissionError(t, rec, fw.wantGoogleStatus) + }) + t.Run(fw.name+"/enabled group reaches upstream", func(t *testing.T) { + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{antigravityCompatSuccessResponse()}} + svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream) + c, rec := newAntigravityCompatContext(http.MethodPost, fw.path, fw.body) + withGeminiImageGateAPIKey(c, &Group{ID: 21, Platform: PlatformAntigravity, AllowImageGeneration: true}) + + _, _ = fw.forward(svc, c, newAntigravityImageGateAccount()) + require.Equal(t, 1, upstream.callCount) + require.NotEqual(t, http.StatusBadRequest, rec.Code) + }) + } +} diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index 48b095fb36..497bff0223 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -555,6 +555,9 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex if err != nil { return nil, s.writeClaudeError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) } + if geminiImageGenerationDenied(c, geminiReq, originalModel, mappedModel) { + return nil, s.writeClaudeError(c, http.StatusBadRequest, "invalid_request_error", ImageGenerationPermissionMessage()) + } geminiReq = ensureGeminiFunctionCallThoughtSignatures(geminiReq) includeThoughts := req.Stream && claudeRequestEnablesThinking(body) geminiReq = applyGeminiCompatThinkingConfig(geminiReq, body, mappedModel, includeThoughts) @@ -1111,6 +1114,9 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. if account.Type == AccountTypeAPIKey || account.Type == AccountTypeServiceAccount { mappedModel = account.GetMappedModel(originalModel) } + if action != "countTokens" && geminiImageGenerationDenied(c, body, originalModel, mappedModel) { + return nil, s.writeGoogleError(c, http.StatusBadRequest, ImageGenerationPermissionMessage()) + } proxyURL := "" if account.ProxyID != nil && account.Proxy != nil { diff --git a/backend/migrations/246_enable_gemini_image_generation_groups.sql b/backend/migrations/246_enable_gemini_image_generation_groups.sql new file mode 100644 index 0000000000..ae37f206fc --- /dev/null +++ b/backend/migrations/246_enable_gemini_image_generation_groups.sql @@ -0,0 +1,6 @@ +-- gemini / antigravity 分组的生图开关同时约束 Gemini 系入口,存量分组统一置为开启。 +-- composite 分组的同一开关还约束 OpenAI 生图,不在本迁移范围内。 +UPDATE groups +SET allow_image_generation = true +WHERE platform IN ('gemini', 'antigravity') + AND allow_image_generation = false; diff --git a/backend/migrations/gemini_image_generation_groups_migration_test.go b/backend/migrations/gemini_image_generation_groups_migration_test.go new file mode 100644 index 0000000000..81630a151b --- /dev/null +++ b/backend/migrations/gemini_image_generation_groups_migration_test.go @@ -0,0 +1,24 @@ +package migrations + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestEnableGeminiImageGenerationGroupsMigration(t *testing.T) { + content, err := FS.ReadFile("246_enable_gemini_image_generation_groups.sql") + require.NoError(t, err) + + var statements []string + for _, line := range strings.Split(string(content), "\n") { + if !strings.HasPrefix(strings.TrimSpace(line), "--") { + statements = append(statements, line) + } + } + sql := strings.Join(strings.Fields(strings.Join(statements, " ")), " ") + require.Equal(t, + "UPDATE groups SET allow_image_generation = true WHERE platform IN ('gemini', 'antigravity') AND allow_image_generation = false;", + sql) +} diff --git a/frontend/src/views/admin/GroupsView.vue b/frontend/src/views/admin/GroupsView.vue index 3fb2c95cd5..8572f7b0bf 100644 --- a/frontend/src/views/admin/GroupsView.vue +++ b/frontend/src/views/admin/GroupsView.vue @@ -4364,6 +4364,7 @@ import { type ReasoningEffortMappingRow, } from "./groupsReasoningEffort"; import { + defaultAllowImageGenerationForPlatform, getDefaultImagePreviewPrice, getDefaultVideoPreviewPrice, getImagePricePlaceholder, @@ -6726,6 +6727,7 @@ watch( createForm.require_oauth_only = false; createForm.require_privacy_set = false; } + createForm.allow_image_generation = defaultAllowImageGenerationForPlatform(newVal); resetDisabledBatchImagePricing(createForm); resetModelAllowlistState(createModelAllowlistState); loadModelAllowlistCandidates("create", 0, newVal); diff --git a/frontend/src/views/admin/__tests__/groupsImagePricing.spec.ts b/frontend/src/views/admin/__tests__/groupsImagePricing.spec.ts index 1a37b05778..57a3f7d7ee 100644 --- a/frontend/src/views/admin/__tests__/groupsImagePricing.spec.ts +++ b/frontend/src/views/admin/__tests__/groupsImagePricing.spec.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { + defaultAllowImageGenerationForPlatform, getDefaultImagePreviewPrice, getDefaultVideoPreviewPrice, getImagePricePlaceholder, @@ -27,6 +28,14 @@ describe("groups image pricing platform support", () => { expect(supportsImagePricingPlatform("anthropic")).toBe(false); }); + it("defaults image generation on for Grok and Gemini-family groups only", () => { + expect(defaultAllowImageGenerationForPlatform("grok")).toBe(true); + expect(defaultAllowImageGenerationForPlatform("gemini")).toBe(true); + expect(defaultAllowImageGenerationForPlatform("antigravity")).toBe(true); + expect(defaultAllowImageGenerationForPlatform("composite")).toBe(false); + expect(defaultAllowImageGenerationForPlatform("openai")).toBe(false); + }); + it("includes Composite groups in image pricing controls", () => { expect(supportsImagePricingPlatform("composite")).toBe(true); expect(imagePricingPlatforms.has("composite")).toBe(true); diff --git a/frontend/src/views/admin/groupsImagePricing.ts b/frontend/src/views/admin/groupsImagePricing.ts index 95152e3efd..e4f3de5e12 100644 --- a/frontend/src/views/admin/groupsImagePricing.ts +++ b/frontend/src/views/admin/groupsImagePricing.ts @@ -9,6 +9,12 @@ export const imagePricingPlatforms = new Set([ export const supportsImagePricingPlatform = (platform: string): boolean => imagePricingPlatforms.has(platform); +// 与后端 DefaultAllowImageGenerationForPlatform 一致:这些平台新建分组默认允许生图。 +const imageGenerationDefaultPlatforms = new Set(["antigravity", "gemini", "grok"]); + +export const defaultAllowImageGenerationForPlatform = (platform: string): boolean => + imageGenerationDefaultPlatforms.has(platform); + export const supportsVideoPricingPlatform = (platform: string): boolean => platform === "grok"; From 4355236e00230de65226ad6ba710cffd1a512473 Mon Sep 17 00:00:00 2001 From: feeeei Date: Tue, 20 Oct 2026 01:25:19 +0800 Subject: [PATCH 014/297] =?UTF-8?q?fix(gateway):=20=E5=85=BC=E5=AE=B9?= =?UTF-8?q?=E6=B5=81=E4=B8=8A=E6=B8=B8=E6=9C=AA=E6=AD=A3=E5=B8=B8=E7=BB=93?= =?UTF-8?q?=E6=9D=9F=E6=97=B6=E6=8A=A5=E9=94=99=E5=B9=B6=E5=AF=B9=E9=BD=90?= =?UTF-8?q?=E5=8E=9F=E7=94=9F=E6=94=B6=E5=B0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 客户端在线时,Anthropic 账号的 chat/responses 兼容流在上游未发出结束事件 (message_stop、带 stop_reason 的 message_delta 或 [DONE])就中断,不再补发 finish_reason / [DONE] / response.completed 报成功: - 读间隔超时、读错误、message_start 之后直接 EOF:service 写出协议内终止 事件(CC 为 error 帧,Responses 为沿用流内 id 与 sequence_number 的 response.failed),返回错误并带上已观测到的 usage;读间隔超时调用 HandleStreamTimeout。 - 流内 event: error:立即结束读取,与 /v1/messages 共用 sseStreamErrorEventFailover 转为 UpstreamFailoverError,未输出前换号重试, 客户端在线时不计费。 - 两个 handler 的错误分支对带结果的错误照常入账。 客户端断开后的读取:stream_data_interval_timeout 未启用时按 180s 启用读间隔 上限;请求 ctx 取消也视为断开。复用 anthropicNativeStreamInterval。行泵在 计时器到期且已有缓冲行时优先交付数据,下游写入慢不再被判为上游空闲。 --- .../gateway_compat_stream_usage_test.go | 229 ++++++ .../gateway_handler_chat_completions.go | 75 +- .../handler/gateway_handler_responses.go | 75 +- backend/internal/service/gateway_forward.go | 104 +-- .../gateway_forward_as_chat_completions.go | 93 +-- .../service/gateway_forward_as_responses.go | 49 +- ...y_forward_compat_client_disconnect_test.go | 671 +++++++++++++++++- .../service/gateway_forward_compat_stream.go | 291 ++++++++ .../openai_gateway_anthropic_native_pump.go | 66 +- ...enai_gateway_anthropic_native_pump_test.go | 81 +++ ...teway_chat_completions_anthropic_native.go | 4 +- ...enai_gateway_responses_anthropic_native.go | 4 +- 12 files changed, 1498 insertions(+), 244 deletions(-) create mode 100644 backend/internal/handler/gateway_compat_stream_usage_test.go create mode 100644 backend/internal/service/gateway_forward_compat_stream.go diff --git a/backend/internal/handler/gateway_compat_stream_usage_test.go b/backend/internal/handler/gateway_compat_stream_usage_test.go new file mode 100644 index 0000000000..84f2e587d4 --- /dev/null +++ b/backend/internal/handler/gateway_compat_stream_usage_test.go @@ -0,0 +1,229 @@ +//go:build unit + +package handler + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type compatStreamUsageUpstream struct { + service.HTTPUpstream + response *http.Response + calls int +} + +func (u *compatStreamUsageUpstream) DoWithTLS(*http.Request, string, int64, int, *tlsfingerprint.Profile) (*http.Response, error) { + u.calls++ + return u.response, nil +} + +type compatStreamUsageBillingRepo struct { + service.UsageBillingRepository + mu sync.Mutex + commands []*service.UsageBillingCommand +} + +func (r *compatStreamUsageBillingRepo) Apply(ctx context.Context, cmd *service.UsageBillingCommand) (*service.UsageBillingApplyResult, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.commands = append(r.commands, cmd) + return &service.UsageBillingApplyResult{Applied: true}, nil +} + +const compatStreamUsagePartialStream = "event: message_start\n" + + `data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4.5","usage":{"input_tokens":12,"output_tokens":1}}}` + "\n\n" + + "event: content_block_start\n" + + `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}` + "\n\n" + + "event: content_block_delta\n" + + `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"partial"}}` + "\n\n" + +const compatStreamUsageCompletion = "event: content_block_stop\n" + + `data: {"type":"content_block_stop","index":0}` + "\n\n" + + "event: message_delta\n" + + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":7}}` + "\n\n" + + "event: message_stop\n" + + `data: {"type":"message_stop"}` + "\n\n" + +type compatStreamUsageRun struct { + rec *httptest.ResponseRecorder + upstream *compatStreamUsageUpstream + usageRepo *openAIWSUsageHandlerUsageLogRepoStub + billingRepo *compatStreamUsageBillingRepo +} + +// runCompatStreamUsageHandler 经 GatewayHandler 转发一次流式请求;上游写完 upstreamStream 后, +// closeUpstream 为 false 时保持连接不再发送数据。 +func runCompatStreamUsageHandler(t *testing.T, endpoint, upstreamStream string, closeUpstream bool) compatStreamUsageRun { + t.Helper() + cfg := &config.Config{Gateway: config.GatewayConfig{StreamDataIntervalTimeout: 1}} + groupID := int64(9300) + group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive, RateMultiplier: 1} + account := &service.Account{ + ID: 9301, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, + Credentials: map[string]any{"api_key": "test-key"}, + AccountGroups: []service.AccountGroup{{AccountID: 9301, GroupID: groupID}}, + } + snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{account}}, nil, nil, nil, nil) + run := compatStreamUsageRun{ + rec: httptest.NewRecorder(), + usageRepo: &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 2)}, + billingRepo: &compatStreamUsageBillingRepo{}, + } + billingCache := service.NewBillingCacheService(newHandlerInflightCache(100), nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCache.Stop) + + pr, pw := io.Pipe() + t.Cleanup(func() { _ = pr.Close(); _ = pw.Close() }) + go func() { + _, _ = io.WriteString(pw, upstreamStream) + if closeUpstream { + _ = pw.Close() + } + }() + run.upstream = &compatStreamUsageUpstream{response: &http.Response{ + StatusCode: http.StatusOK, Body: pr, + Header: http.Header{"X-Request-Id": []string{"compat-stream-usage"}}, + }} + gw := service.NewGatewayService( + nil, &fakeGroupRepo{group: group}, run.usageRepo, run.billingRepo, nil, nil, nil, nil, cfg, + snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, run.upstream, + &service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + ) + h := &GatewayHandler{ + gatewayService: gw, billingCacheService: billingCache, cfg: cfg, maxAccountSwitches: 1, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0), + } + + body := `{"model":"claude-sonnet-4.5","stream":true,"input":"hello"}` + if endpoint == "chat/completions" { + body = `{"model":"claude-sonnet-4.5","stream":true,"messages":[{"role":"user","content":"hello"}]}` + } + c, _ := gin.CreateTestContext(run.rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/"+endpoint, bytes.NewBufferString(body)) + c.Request.Header.Set("Content-Type", "application/json") + apiKey := &service.APIKey{ID: 9302, UserID: 9303, GroupID: &groupID, Group: group, User: &service.User{ID: 9303, Balance: 100}} + c.Set(string(middleware.ContextKeyAPIKey), apiKey) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9303}) + + if endpoint == "chat/completions" { + h.ChatCompletions(c) + } else { + h.Responses(c) + } + return run +} + +// compatStreamUsageMarkers 返回成功收尾与终止错误的标记。 +func compatStreamUsageMarkers(endpoint string) (success, failure string) { + if endpoint == "responses" { + return "event: response.completed", "event: response.failed" + } + return "[DONE]", `data: {"error":` +} + +func TestGatewayCompatibilityHandlers_StreamUsageRecordedOnceWithTerminalEvent(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, endpoint := range []string{"chat/completions", "responses"} { + for _, tc := range []struct { + name string + completion string + wantOutput int + }{ + {name: "complete", completion: compatStreamUsageCompletion, wantOutput: 7}, + {name: "idle_before_message_stop", wantOutput: 1}, + } { + t.Run(endpoint+"/"+tc.name, func(t *testing.T) { + successMarker, failureMarker := compatStreamUsageMarkers(endpoint) + wantMarker, denyMarker := successMarker, failureMarker + if tc.completion == "" { + wantMarker, denyMarker = failureMarker, successMarker + } + + run := runCompatStreamUsageHandler(t, endpoint, compatStreamUsagePartialStream+tc.completion, tc.completion != "") + + require.Equal(t, 1, run.upstream.calls) + out := run.rec.Body.String() + require.Contains(t, out, "partial") + require.Contains(t, out, wantMarker) + require.NotContains(t, out, denyMarker) + require.Equal(t, 1, strings.Count(out, wantMarker), "exactly one terminal event") + require.NotContains(t, out, `data: {"type":"error"`, "the handler must not append a fallback frame") + if tc.completion == "" { + require.Contains(t, out, "stream_timeout") + } + + run.billingRepo.mu.Lock() + defer run.billingRepo.mu.Unlock() + require.Len(t, run.billingRepo.commands, 1, "usage must be settled exactly once") + require.Equal(t, 12, run.billingRepo.commands[0].InputTokens) + require.Equal(t, tc.wantOutput, run.billingRepo.commands[0].OutputTokens) + require.Len(t, run.usageRepo.created, 1) + }) + } + } +} + +func TestGatewayCompatibilityHandlers_IdleBeforeAnyEventWritesStreamError(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, endpoint := range []string{"chat/completions", "responses"} { + t.Run(endpoint, func(t *testing.T) { + successMarker, failureMarker := compatStreamUsageMarkers(endpoint) + + run := runCompatStreamUsageHandler(t, endpoint, "", false) + + require.Equal(t, 1, run.upstream.calls) + require.Equal(t, http.StatusOK, run.rec.Code) + require.Equal(t, "text/event-stream", run.rec.Header().Get("Content-Type")) + out := run.rec.Body.String() + require.Equal(t, 1, strings.Count(out, failureMarker), "exactly one terminal event") + require.NotContains(t, out, `data: {"type":"error"`, "the handler must not append a fallback frame") + require.Contains(t, out, "stream_timeout") + require.NotContains(t, out, successMarker) + + run.billingRepo.mu.Lock() + defer run.billingRepo.mu.Unlock() + require.Empty(t, run.billingRepo.commands, "no usage was observed") + require.Empty(t, run.usageRepo.created) + }) + } +} + +func TestGatewayCompatibilityHandlers_UpstreamErrorEventAfterOutputIsNotBilled(t *testing.T) { + gin.SetMode(gin.TestMode) + upstreamError := "event: error\n" + `data: {"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}` + "\n\n" + for _, endpoint := range []string{"chat/completions", "responses"} { + t.Run(endpoint, func(t *testing.T) { + successMarker, failureMarker := compatStreamUsageMarkers(endpoint) + + run := runCompatStreamUsageHandler(t, endpoint, compatStreamUsagePartialStream+upstreamError, true) + + require.Equal(t, 1, run.upstream.calls) + out := run.rec.Body.String() + require.Contains(t, out, "partial") + require.Equal(t, 1, strings.Count(out, failureMarker), "exactly one terminal event") + require.NotContains(t, out, `data: {"type":"error"`, "the handler must not append a fallback frame") + require.Contains(t, out, "Overloaded") + require.NotContains(t, out, successMarker) + + run.billingRepo.mu.Lock() + defer run.billingRepo.mu.Unlock() + require.Empty(t, run.billingRepo.commands, "an upstream error event is not billed while the client is online") + require.Empty(t, run.usageRepo.created) + }) + } +} diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 561ed1bca0..ec0a43d88b 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -317,6 +317,44 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { accountReleaseFunc() } + // 提交 usage 记录。成功路径与"流中断但 Forward 已观测到 usage 的部分结果" + // 错误路径共用;failover 错误恒定 result=nil,不会重复计费。 + submitForwardUsage := func(result *service.ForwardResult) { + userAgent := c.GetHeader("User-Agent") + clientIP := ip.GetClientIP(c) + requestPayloadHash := service.HashUsageRequestPayload(body) + inboundEndpoint := GetInboundEndpoint(c) + upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform) + + quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + sessionID := service.ExtractClientSessionID(c) + stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context())) + h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { + if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ + Result: result, + QuotaPlatform: quotaPlatform, + APIKey: apiKey, + User: apiKey.User, + Account: account, + Subscription: subscription, + PricingAt: pricingAt, + InboundEndpoint: inboundEndpoint, + UpstreamEndpoint: upstreamEndpoint, + UserAgent: userAgent, + IPAddress: clientIP, + RequestPayloadHash: requestPayloadHash, + APIKeyService: h.apiKeyService, + SessionID: sessionID, + ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), + }); err != nil { + reqLog.Error("gateway.cc.record_usage_failed", + zap.Int64("account_id", account.ID), + zap.Error(err), + ) + } + }) + } + if err != nil { var failoverErr *service.UpstreamFailoverError if errors.As(err, &failoverErr) { @@ -347,43 +385,14 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated), zap.Error(err), ) + if result != nil { + submitForwardUsage(result) + } return } // 6. Record usage - userAgent := c.GetHeader("User-Agent") - clientIP := ip.GetClientIP(c) - requestPayloadHash := service.HashUsageRequestPayload(body) - inboundEndpoint := GetInboundEndpoint(c) - upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform) - - quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) - sessionID := service.ExtractClientSessionID(c) - stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context())) - h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { - if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ - Result: result, - QuotaPlatform: quotaPlatform, - APIKey: apiKey, - User: apiKey.User, - Account: account, - Subscription: subscription, - PricingAt: pricingAt, - InboundEndpoint: inboundEndpoint, - UpstreamEndpoint: upstreamEndpoint, - UserAgent: userAgent, - IPAddress: clientIP, - RequestPayloadHash: requestPayloadHash, - APIKeyService: h.apiKeyService, - SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), - }); err != nil { - reqLog.Error("gateway.cc.record_usage_failed", - zap.Int64("account_id", account.ID), - zap.Error(err), - ) - } - }) + submitForwardUsage(result) return } } diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 5ef6bace91..3d143c8ca2 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -299,6 +299,44 @@ func (h *GatewayHandler) Responses(c *gin.Context) { accountReleaseFunc() } + // 提交 usage 记录。成功路径与"流中断但 Forward 已观测到 usage 的部分结果" + // 错误路径共用;failover 错误恒定 result=nil,不会重复计费。 + submitForwardUsage := func(result *service.ForwardResult) { + userAgent := c.GetHeader("User-Agent") + clientIP := ip.GetClientIP(c) + requestPayloadHash := service.HashUsageRequestPayload(body) + inboundEndpoint := GetInboundEndpoint(c) + upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform) + + quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + sessionID := service.ExtractClientSessionID(c) + stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context())) + h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { + if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ + Result: result, + QuotaPlatform: quotaPlatform, + APIKey: apiKey, + User: apiKey.User, + Account: account, + Subscription: subscription, + PricingAt: pricingAt, + InboundEndpoint: inboundEndpoint, + UpstreamEndpoint: upstreamEndpoint, + UserAgent: userAgent, + IPAddress: clientIP, + RequestPayloadHash: requestPayloadHash, + APIKeyService: h.apiKeyService, + SessionID: sessionID, + ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), + }); err != nil { + reqLog.Error("gateway.responses.record_usage_failed", + zap.Int64("account_id", account.ID), + zap.Error(err), + ) + } + }) + } + if err != nil { var failoverErr *service.UpstreamFailoverError if errors.As(err, &failoverErr) { @@ -330,43 +368,14 @@ func (h *GatewayHandler) Responses(c *gin.Context) { zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated), zap.Error(err), ) + if result != nil { + submitForwardUsage(result) + } return } // 6. Record usage - userAgent := c.GetHeader("User-Agent") - clientIP := ip.GetClientIP(c) - requestPayloadHash := service.HashUsageRequestPayload(body) - inboundEndpoint := GetInboundEndpoint(c) - upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform) - - quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) - sessionID := service.ExtractClientSessionID(c) - stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context())) - h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { - if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ - Result: result, - QuotaPlatform: quotaPlatform, - APIKey: apiKey, - User: apiKey.User, - Account: account, - Subscription: subscription, - PricingAt: pricingAt, - InboundEndpoint: inboundEndpoint, - UpstreamEndpoint: upstreamEndpoint, - UserAgent: userAgent, - IPAddress: clientIP, - RequestPayloadHash: requestPayloadHash, - APIKeyService: h.apiKeyService, - SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), - }); err != nil { - reqLog.Error("gateway.responses.record_usage_failed", - zap.Int64("account_id", account.ID), - zap.Error(err), - ) - } - }) + submitForwardUsage(result) return } } diff --git a/backend/internal/service/gateway_forward.go b/backend/internal/service/gateway_forward.go index 388f2495a9..b0d59656ad 100644 --- a/backend/internal/service/gateway_forward.go +++ b/backend/internal/service/gateway_forward.go @@ -823,55 +823,7 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *A if err != nil { var sseErr *sseStreamErrorEventError if errors.As(err, &sseErr) { - // 上游 HTTP 200 + SSE 流体内出现 event:error 帧。 - body := []byte(sseErr.RawData) - semanticStatus := http.StatusForbidden - if c.Writer.Size() == writerSizeBeforeStream && gjson.GetBytes(body, "error.type").String() == "overloaded_error" { - semanticStatus = 529 - syntheticResp := &http.Response{ - StatusCode: semanticStatus, - Header: resp.Header.Clone(), - Body: io.NopCloser(bytes.NewReader(body)), - } - s.handleFailoverSideEffects(ctx, syntheticResp, account, reqModel) - } - - upstreamMsg := sanitizeUpstreamErrorMessage( - strings.TrimSpace(extractUpstreamErrorMessage(body)), - ) - - upstreamDetail := "" - if s.cfg != nil && s.cfg.Gateway.LogUpstreamErrorBody { - maxBytes := s.cfg.Gateway.LogUpstreamErrorBodyMaxBytes - if maxBytes <= 0 { - maxBytes = 2048 - } - upstreamDetail = truncateString(sseErr.RawData, maxBytes) - } - - appendOpsUpstreamError(c, OpsUpstreamErrorEvent{ - ProxyID: opsUpstreamProxyID(account), - ProxyName: opsUpstreamProxyName(account), - Platform: account.Platform, - AccountID: account.ID, - AccountName: account.Name, - UpstreamStatusCode: semanticStatus, - UpstreamRequestID: resp.Header.Get("x-request-id"), - Kind: "stream_error", - Message: upstreamMsg, - Detail: upstreamDetail, - }) - - logger.LegacyPrintf("service.gateway", - "[Forward] SSE error event in stream: Account=%d(%s) RequestID=%s Body=%s", - account.ID, account.Name, resp.Header.Get("x-request-id"), - truncateString(sseErr.RawData, 1000), - ) - - return nil, &UpstreamFailoverError{ - StatusCode: semanticStatus, - ResponseBody: body, - } + return nil, s.sseStreamErrorEventFailover(ctx, c, account, resp, sseErr.RawData, reqModel, c.Writer.Size() != writerSizeBeforeStream) } // 流中断(缺失 terminal 事件、读错误、数据间隔超时等)时保留已观测到的 // usage 与错误一起返回,handler 在错误处理完成后照常提交 usage 记录。 @@ -1064,3 +1016,57 @@ func (s *GatewayService) isStickyAccountUpstreamRestricted(ctx context.Context, } return s.isUpstreamModelRestrictedByChannel(ctx, *groupID, account, requestedModel) } + +// sseStreamErrorEventFailover 把上游 HTTP 200 + SSE 流体内的 event:error 帧转为 +// UpstreamFailoverError:尚未向客户端写出内容且错误类型为 overloaded_error 时按 529 +// 处理并触发账号侧副作用,其余按 403;同时登记 stream_error 运维记录。 +func (s *GatewayService) sseStreamErrorEventFailover(ctx context.Context, c *gin.Context, account *Account, resp *http.Response, rawData, model string, outputStarted bool) *UpstreamFailoverError { + body := []byte(rawData) + semanticStatus := http.StatusForbidden + if !outputStarted && gjson.GetBytes(body, "error.type").String() == "overloaded_error" { + semanticStatus = 529 + syntheticResp := &http.Response{ + StatusCode: semanticStatus, + Header: resp.Header.Clone(), + Body: io.NopCloser(bytes.NewReader(body)), + } + s.handleFailoverSideEffects(ctx, syntheticResp, account, model) + } + + upstreamMsg := sanitizeUpstreamErrorMessage( + strings.TrimSpace(extractUpstreamErrorMessage(body)), + ) + + upstreamDetail := "" + if s.cfg != nil && s.cfg.Gateway.LogUpstreamErrorBody { + maxBytes := s.cfg.Gateway.LogUpstreamErrorBodyMaxBytes + if maxBytes <= 0 { + maxBytes = 2048 + } + upstreamDetail = truncateString(rawData, maxBytes) + } + + appendOpsUpstreamError(c, OpsUpstreamErrorEvent{ + ProxyID: opsUpstreamProxyID(account), + ProxyName: opsUpstreamProxyName(account), + Platform: account.Platform, + AccountID: account.ID, + AccountName: account.Name, + UpstreamStatusCode: semanticStatus, + UpstreamRequestID: resp.Header.Get("x-request-id"), + Kind: "stream_error", + Message: upstreamMsg, + Detail: upstreamDetail, + }) + + logger.LegacyPrintf("service.gateway", + "[Forward] SSE error event in stream: Account=%d(%s) RequestID=%s Body=%s", + account.ID, account.Name, resp.Header.Get("x-request-id"), + truncateString(rawData, 1000), + ) + + return &UpstreamFailoverError{ + StatusCode: semanticStatus, + ResponseBody: body, + } +} diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index bb96b28a6b..24a281d612 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -187,7 +187,15 @@ func (s *GatewayService) ForwardAsChatCompletions( var result *ForwardResult var handleErr error if clientStream { + writerSizeBeforeStream := c.Writer.Size() result, handleErr = s.handleCCStreamingFromAnthropic(resp, c, originalModel, mappedModel, reasoningEffort, startTime) + var sseErr *sseStreamErrorEventError + switch { + case errors.As(handleErr, &sseErr): + return nil, s.sseStreamErrorEventFailover(ctx, c, account, resp, sseErr.RawData, mappedModel, c.Writer.Size() != writerSizeBeforeStream) + case errors.Is(handleErr, errAnthropicNativeStreamIdle) && s.rateLimitService != nil: + s.rateLimitService.HandleStreamTimeout(ctx, account, originalModel) + } } else { result, handleErr = s.handleCCBufferedFromAnthropic(resp, c, originalModel, mappedModel, reasoningEffort, startTime) } @@ -381,21 +389,10 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( var usage ClaudeUsage var firstTokenMs *int firstChunk := true - // 客户端断开后停止向下游写入,继续读完上游以合并 message_delta 的最终 usage。 - clientDisconnected := false + writerSizeBeforeStream := c.Writer.Size() - scanner := bufio.NewScanner(resp.Body) - maxLineSize := defaultMaxLineSize - if s.cfg != nil && s.cfg.Gateway.MaxLineSize > 0 { - maxLineSize = s.cfg.Gateway.MaxLineSize - } - scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) - streamInterval := s.anthropicCompatStreamInterval() - pump := newAnthropicNativeLinePump(scanner, streamInterval) - defer pump.stop() - nextLine := func() (string, bool) { - return nextAnthropicCompatLine(pump, resp.Body, streamInterval, "forward_as_cc", requestID, clientDisconnected) - } + stream := newAnthropicCompatStream(s.cfg, c, resp, "forward_as_cc", requestID) + defer stream.stop() resultWithUsage := func() *ForwardResult { return &ForwardResult{ @@ -408,17 +405,10 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( Stream: true, Duration: time.Since(startTime), FirstTokenMs: firstTokenMs, - ClientDisconnect: clientDisconnected, + ClientDisconnect: stream.clientDisconnected, } } - markClientDisconnected := func() { - clientDisconnected = true - logger.L().Info("forward_as_cc stream: client disconnected, continuing to drain upstream for billing", - zap.String("request_id", requestID), - ) - } - writeChunk := func(chunk apicompat.ChatCompletionsChunk) bool { sse, err := apicompat.ChatChunkToSSE(chunk) if err != nil { @@ -438,11 +428,11 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( return } if event.Type == "ping" { - if clientDisconnected { + if stream.clientDisconnected { return } if _, err := fmt.Fprint(c.Writer, ": ping\n\n"); err != nil { - markClientDisconnected() + stream.markClientDisconnected() return } c.Writer.Flush() @@ -462,7 +452,7 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( if event.Type == "message_start" && event.Message != nil { mergeAnthropicUsage(&usage, event.Message.Usage) } - if clientDisconnected { + if stream.clientDisconnected { return } @@ -477,7 +467,7 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( ccChunks := apicompat.ResponsesEventToChatChunks(&resEvt, ccState) for _, chunk := range ccChunks { if disconnected := writeChunk(chunk); disconnected { - markClientDisconnected() + stream.markClientDisconnected() return } } @@ -486,7 +476,7 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( } for { - line, ok := nextLine() + line, ok := stream.nextLine() if !ok { break } @@ -495,7 +485,7 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( continue } - dataLine, ok := nextLine() + dataLine, ok := stream.nextLine() if !ok { break } @@ -513,10 +503,19 @@ func (s *GatewayService) handleCCStreamingFromAnthropic( // The intermediate Responses converter synthesizes usage even when absent. ccState.IncludeUsage = ccState.IncludeUsage || anthropicChatStreamHasUsage(&event, payload) + stream.observe(&event, payload) + if stream.upstreamErrType != "" { + break + } processAnthropicEvent(&event) } - if clientDisconnected { + if failure := stream.failure(); failure != nil { + return finishAnthropicCompatStreamFailure(c, writerSizeBeforeStream, failure, resultWithUsage(), func() { + writeAnthropicCompatCCStreamFailure(c, failure) + }) + } + if stream.clientDisconnected { return resultWithUsage(), nil } @@ -552,42 +551,6 @@ func writeGatewayCCError(c *gin.Context, statusCode int, errType, message string }) } -// anthropicCompatStreamInterval 返回 Anthropic 上游协议转换流的逐行读间隔上限, -// gateway.stream_data_interval_timeout <= 0 时不限。 -func (s *GatewayService) anthropicCompatStreamInterval() time.Duration { - if s.cfg != nil && s.cfg.Gateway.StreamDataIntervalTimeout > 0 { - return time.Duration(s.cfg.Gateway.StreamDataIntervalTimeout) * time.Second - } - return 0 -} - -// nextAnthropicCompatLine 从行泵取下一行;ok=false 表示上游流已结束(EOF、读错误 -// 或读间隔超时),调用方按已累计的 usage 收尾。读间隔超时时关闭 body,解除泵 -// goroutine 阻塞中的读并释放上游连接。 -func nextAnthropicCompatLine(pump *anthropicNativeLinePump, body io.Closer, interval time.Duration, logPrefix, requestID string, clientDisconnected bool) (string, bool) { - line, err := pump.next() - if err == nil { - return line, true - } - switch { - case errors.Is(err, errAnthropicNativeStreamIdle): - _ = body.Close() - logger.L().Warn(logPrefix+" stream: data interval timeout", - zap.String("request_id", requestID), - zap.Duration("interval", interval), - zap.Bool("client_disconnected", clientDisconnected), - ) - case errors.Is(err, io.EOF), errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded): - // 正常收流或取消:不记日志。 - default: - logger.L().Warn(logPrefix+" stream: read error", - zap.Error(err), - zap.String("request_id", requestID), - ) - } - return "", false -} - // anthropicChatStreamHasUsage distinguishes an explicit zero-valued usage object // from omitted/null usage before the Anthropic→Responses conversion loses that distinction. func anthropicChatStreamHasUsage(event *apicompat.AnthropicStreamEvent, payload string) bool { diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index fa2d601a05..f7f4897d5a 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -198,7 +198,15 @@ func (s *GatewayService) ForwardAsResponses( var result *ForwardResult var handleErr error if clientStream { + writerSizeBeforeStream := c.Writer.Size() result, handleErr = s.handleResponsesStreamingResponse(resp, c, originalModel, mappedModel, reasoningEffort, startTime, clientToolMapping) + var sseErr *sseStreamErrorEventError + switch { + case errors.As(handleErr, &sseErr): + return nil, s.sseStreamErrorEventFailover(ctx, c, account, resp, sseErr.RawData, mappedModel, c.Writer.Size() != writerSizeBeforeStream) + case errors.Is(handleErr, errAnthropicNativeStreamIdle) && s.rateLimitService != nil: + s.rateLimitService.HandleStreamTimeout(ctx, account, originalModel) + } } else { result, handleErr = s.handleResponsesBufferedStreamingResponse(resp, c, originalModel, mappedModel, reasoningEffort, startTime, clientToolMapping) } @@ -545,21 +553,10 @@ func (s *GatewayService) handleResponsesStreamingResponse( var usage ClaudeUsage var firstTokenMs *int firstChunk := true - // 客户端断开后停止向下游写入,继续读完上游以合并 message_delta 的最终 usage。 - clientDisconnected := false + writerSizeBeforeStream := c.Writer.Size() - scanner := bufio.NewScanner(resp.Body) - maxLineSize := defaultMaxLineSize - if s.cfg != nil && s.cfg.Gateway.MaxLineSize > 0 { - maxLineSize = s.cfg.Gateway.MaxLineSize - } - scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) - streamInterval := s.anthropicCompatStreamInterval() - pump := newAnthropicNativeLinePump(scanner, streamInterval) - defer pump.stop() - nextLine := func() (string, bool) { - return nextAnthropicCompatLine(pump, resp.Body, streamInterval, "forward_as_responses", requestID, clientDisconnected) - } + stream := newAnthropicCompatStream(s.cfg, c, resp, "forward_as_responses", requestID) + defer stream.stop() resultWithUsage := func() *ForwardResult { return &ForwardResult{ @@ -572,7 +569,7 @@ func (s *GatewayService) handleResponsesStreamingResponse( Stream: true, Duration: time.Since(startTime), FirstTokenMs: firstTokenMs, - ClientDisconnect: clientDisconnected, + ClientDisconnect: stream.clientDisconnected, } } @@ -592,7 +589,7 @@ func (s *GatewayService) handleResponsesStreamingResponse( if event.Type == "message_start" && event.Message != nil { mergeAnthropicUsage(&usage, event.Message.Usage) } - if clientDisconnected { + if stream.clientDisconnected { return } @@ -625,10 +622,7 @@ func (s *GatewayService) handleResponsesStreamingResponse( for _, restored := range payloads { eventType := gjson.GetBytes(restored, "type").String() if _, err := fmt.Fprintf(c.Writer, "event: %s\ndata: %s\n\n", eventType, restored); err != nil { - clientDisconnected = true - logger.L().Info("forward_as_responses stream: client disconnected, continuing to drain upstream for billing", - zap.String("request_id", requestID), - ) + stream.markClientDisconnected() return } } @@ -639,7 +633,12 @@ func (s *GatewayService) handleResponsesStreamingResponse( } finalizeStream := func() (*ForwardResult, error) { - if clientDisconnected { + if failure := stream.failure(); failure != nil { + return finishAnthropicCompatStreamFailure(c, writerSizeBeforeStream, failure, resultWithUsage(), func() { + writeAnthropicCompatResponsesStreamFailure(c, state, clientToolRestorer, failure) + }) + } + if stream.clientDisconnected { return resultWithUsage(), nil } if finalEvents := apicompat.FinalizeAnthropicResponsesStream(state); len(finalEvents) > 0 { @@ -658,7 +657,7 @@ func (s *GatewayService) handleResponsesStreamingResponse( // Read Anthropic SSE events for { - line, ok := nextLine() + line, ok := stream.nextLine() if !ok { break } @@ -668,7 +667,7 @@ func (s *GatewayService) handleResponsesStreamingResponse( } // Read data line - dataLine, ok := nextLine() + dataLine, ok := stream.nextLine() if !ok { break } @@ -687,6 +686,10 @@ func (s *GatewayService) handleResponsesStreamingResponse( continue } + stream.observe(&event, payload) + if stream.upstreamErrType != "" { + break + } processEvent(&event) } diff --git a/backend/internal/service/gateway_forward_compat_client_disconnect_test.go b/backend/internal/service/gateway_forward_compat_client_disconnect_test.go index cfa55a0f0a..d41e42a4ad 100644 --- a/backend/internal/service/gateway_forward_compat_client_disconnect_test.go +++ b/backend/internal/service/gateway_forward_compat_client_disconnect_test.go @@ -3,11 +3,14 @@ package service import ( + "bufio" + "context" "errors" "fmt" "io" "net/http" "net/http/httptest" + "strconv" "strings" "testing" "time" @@ -16,6 +19,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" ) // disconnectOnMarkerResponseWriter 在首次写入包含 marker 的数据时返回错误,模拟客户端中途断开。 @@ -97,8 +101,10 @@ func newCompatStreamIdleTestService(intervalSec int) *GatewayService { return &GatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{StreamDataIntervalTimeout: intervalSec}}} } -func TestAnthropicCompatStreaming_IdleUpstreamEndsWithinInterval(t *testing.T) { - handlers := map[string]func(*GatewayService, *http.Response, *gin.Context) (*ForwardResult, error){ +type compatStreamHandler func(*GatewayService, *http.Response, *gin.Context) (*ForwardResult, error) + +func compatStreamHandlers() map[string]compatStreamHandler { + return map[string]compatStreamHandler{ "chat_completions": func(svc *GatewayService, resp *http.Response, c *gin.Context) (*ForwardResult, error) { return svc.handleCCStreamingFromAnthropic(resp, c, "claude-sonnet-4-6", "claude-sonnet-4-6", nil, time.Now()) }, @@ -106,8 +112,54 @@ func TestAnthropicCompatStreaming_IdleUpstreamEndsWithinInterval(t *testing.T) { return svc.handleResponsesStreamingResponse(resp, c, "claude-sonnet-4-6", "claude-sonnet-4-6", nil, time.Now(), apicompat.ResponsesClientToolMapping{}) }, } - stream := strings.TrimSuffix(anthropicStreamWithMidStreamText(), "event: message_stop\ndata: {\"type\":\"message_stop\"}\n") - for name, handle := range handlers { +} + +// compatStreamTerminalMarkers 是两条兼容流按成功收尾时写出的完成标记。 +var compatStreamTerminalMarkers = map[string]string{ + "chat_completions": "[DONE]", + "responses": "response.completed", +} + +// compatStreamFailureMarkers 是两条兼容流写出终止错误时的标记。 +var compatStreamFailureMarkers = map[string]string{ + "chat_completions": `data: {"error":`, + "responses": "event: response.failed", +} + +// anthropicStreamWithoutMessageStop 以带 stop_reason 的 message_delta 结束,不含 message_stop。 +func anthropicStreamWithoutMessageStop() string { + return strings.TrimSuffix(anthropicStreamWithMidStreamText(), "event: message_stop\ndata: {\"type\":\"message_stop\"}\n") +} + +// anthropicStreamTruncatedBeforeMessageDelta 在 message_delta 之前中断,usage 只有 message_start 的部分。 +func anthropicStreamTruncatedBeforeMessageDelta() string { + full := anthropicStreamWithMidStreamText() + return full[:strings.Index(full, "event: message_delta")] +} + +type compatStreamOutcome struct { + result *ForwardResult + err error +} + +func runCompatStreamWithDeadline(t *testing.T, handle compatStreamHandler, svc *GatewayService, resp *http.Response, c *gin.Context) compatStreamOutcome { + t.Helper() + done := make(chan compatStreamOutcome, 1) + go func() { + result, err := handle(svc, resp, c) + done <- compatStreamOutcome{result: result, err: err} + }() + select { + case got := <-done: + return got + case <-time.After(5 * time.Second): + t.Fatal("stream did not end after upstream idle interval") + return compatStreamOutcome{} + } +} + +func TestAnthropicCompatStreaming_IdleUpstreamEndsWithinInterval(t *testing.T) { + for name, handle := range compatStreamHandlers() { for _, disconnect := range []bool{false, true} { t.Run(fmt.Sprintf("%s/client_disconnected=%t", name, disconnect), func(t *testing.T) { gin.SetMode(gin.TestMode) @@ -117,28 +169,25 @@ func TestAnthropicCompatStreaming_IdleUpstreamEndsWithinInterval(t *testing.T) { } writer := &disconnectOnMarkerResponseWriter{ResponseRecorder: httptest.NewRecorder(), marker: marker} c, _ := gin.CreateTestContext(writer) - resp, pw := stallingAnthropicUpstream(t, stream) + resp, pw := stallingAnthropicUpstream(t, anthropicStreamTruncatedBeforeMessageDelta()) - type outcome struct { - result *ForwardResult - err error - } - done := make(chan outcome, 1) - go func() { - result, err := handle(newCompatStreamIdleTestService(1), resp, c) - done <- outcome{result: result, err: err} - }() - var got outcome - select { - case got = <-done: - case <-time.After(5 * time.Second): - t.Fatal("stream did not end after upstream idle interval") - } + got := runCompatStreamWithDeadline(t, handle, newCompatStreamIdleTestService(1), resp, c) - require.NoError(t, got.err) + if disconnect { + require.NoError(t, got.err) + } else { + require.ErrorIs(t, got.err, errAnthropicNativeStreamIdle) + body := writer.Body.String() + require.NotContains(t, body, compatStreamTerminalMarkers[name], "a stream cut by idle timeout must not be reported as completed") + require.Contains(t, body, compatStreamFailureMarkers[name]) + require.Contains(t, body, "stream_timeout") + require.True(t, IsResponseCommitted(c)) + } + require.NotNil(t, got.result) require.Equal(t, disconnect, got.result.ClientDisconnect) require.Equal(t, disconnect, writer.failed) - require.Equal(t, 42, got.result.Usage.OutputTokens) + require.Equal(t, 20, got.result.Usage.InputTokens) + require.Equal(t, 1, got.result.Usage.OutputTokens) require.Zero(t, writer.writesAfterError) _, werr := io.WriteString(pw, "event: ping\n") require.Error(t, werr, "upstream body must be closed after idle timeout") @@ -147,6 +196,584 @@ func TestAnthropicCompatStreaming_IdleUpstreamEndsWithinInterval(t *testing.T) { } } +func TestAnthropicCompatStreaming_IdleAfterTerminalEventCompletes(t *testing.T) { + for name, handle := range compatStreamHandlers() { + for streamName, stream := range map[string]string{ + "message_stop": anthropicStreamWithMidStreamText(), + "stop_reason": anthropicStreamWithoutMessageStop(), + } { + t.Run(name+"/"+streamName, func(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + resp, _ := stallingAnthropicUpstream(t, stream) + + got := runCompatStreamWithDeadline(t, handle, newCompatStreamIdleTestService(1), resp, c) + + require.NoError(t, got.err) + require.NotNil(t, got.result) + require.Equal(t, 42, got.result.Usage.OutputTokens) + require.Contains(t, rec.Body.String(), compatStreamTerminalMarkers[name]) + require.NotContains(t, rec.Body.String(), compatStreamFailureMarkers[name]) + }) + } + } +} + +// errAfterReader 读完 data 后返回 err,模拟上游连接中途断开。 +type errAfterReader struct { + data *strings.Reader + err error +} + +func (r *errAfterReader) Read(p []byte) (int, error) { + if r.data.Len() > 0 { + return r.data.Read(p) + } + return 0, r.err +} + +func TestAnthropicCompatStreaming_ReadErrorBeforeTerminalEventFails(t *testing.T) { + messageStartOnly := strings.Join([]string{ + `event: message_start`, + `data: {"type":"message_start","message":{"id":"msg_disc","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4-6","usage":{"input_tokens":20,"output_tokens":1}}}`, + ``, + }, "\n") + "\n" + for name, handle := range compatStreamHandlers() { + for _, tc := range []struct { + name string + stream string + wantErr bool + wantResult bool + }{ + {name: "after_text", stream: anthropicStreamTruncatedBeforeMessageDelta(), wantErr: true, wantResult: true}, + {name: "after_message_start", stream: messageStartOnly, wantErr: true, wantResult: true}, + {name: "before_any_event", stream: "", wantErr: true}, + {name: "after_stop_reason", stream: anthropicStreamWithoutMessageStop(), wantResult: true}, + {name: "after_message_stop_without_stop_reason", stream: strings.Replace(anthropicStreamWithMidStreamText(), `"delta":{"stop_reason":"end_turn"}`, `"delta":{}`, 1), wantResult: true}, + } { + t.Run(name+"/"+tc.name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := io.NopCloser(&errAfterReader{data: strings.NewReader(tc.stream), err: io.ErrUnexpectedEOF}) + + result, err := handle(&GatewayService{}, &http.Response{Header: http.Header{}, Body: body}, c) + + if tc.wantErr { + require.ErrorIs(t, err, io.ErrUnexpectedEOF) + require.NotErrorIs(t, err, errAnthropicNativeStreamIdle) + require.NotContains(t, rec.Body.String(), compatStreamTerminalMarkers[name]) + require.Contains(t, rec.Body.String(), compatStreamFailureMarkers[name]) + require.Contains(t, rec.Body.String(), "stream_read_error") + } else { + require.NoError(t, err) + require.Contains(t, rec.Body.String(), compatStreamTerminalMarkers[name]) + } + if !tc.wantResult { + require.Nil(t, result) + return + } + require.NotNil(t, result) + require.False(t, result.ClientDisconnect) + require.Equal(t, 20, result.Usage.InputTokens) + }) + } + } +} + +// compatResponsesSSEEvents 解析 Responses SSE 输出中各 data 帧的 type 与 sequence_number。 +func compatResponsesSSEEvents(t *testing.T, body string) []gjson.Result { + t.Helper() + var events []gjson.Result + for _, line := range strings.Split(body, "\n") { + if payload, ok := strings.CutPrefix(line, "data: "); ok { + require.True(t, gjson.Valid(payload), payload) + events = append(events, gjson.Parse(payload)) + } + } + return events +} + +func TestAnthropicCompatStreaming_EOFWithoutTerminalEventFails(t *testing.T) { + truncatedToolUse := strings.Join([]string{ + `event: message_start`, + `data: {"type":"message_start","message":{"id":"msg_disc","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4-6","usage":{"input_tokens":20,"output_tokens":1}}}`, + ``, + `event: content_block_start`, + `data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_1","name":"write_file","input":{}}}`, + ``, + `event: content_block_delta`, + `data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"path\":\"/tmp/a\",\"content\":\"hal"}}`, + ``, + }, "\n") + "\n" + for name, handle := range compatStreamHandlers() { + for _, tc := range []struct { + name string + stream string + wantErrText string + wantType string + }{ + {name: "truncated", stream: anthropicStreamTruncatedBeforeMessageDelta(), wantErrText: "missing terminal event", wantType: "stream_incomplete"}, + {name: "truncated_tool_use", stream: truncatedToolUse, wantErrText: "missing terminal event", wantType: "stream_incomplete"}, + } { + t.Run(name+"/"+tc.name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + + result, err := handle(&GatewayService{}, &http.Response{Header: http.Header{}, Body: io.NopCloser(strings.NewReader(tc.stream))}, c) + + require.ErrorContains(t, err, tc.wantErrText) + require.NotNil(t, result) + require.Equal(t, 20, result.Usage.InputTokens) + require.True(t, IsResponseCommitted(c)) + body := rec.Body.String() + require.NotContains(t, body, compatStreamTerminalMarkers[name]) + require.NotContains(t, body, `"finish_reason":"`) + require.Equal(t, 1, strings.Count(body, compatStreamFailureMarkers[name])) + if name != "responses" { + require.Contains(t, body, tc.wantType) + return + } + events := compatResponsesSSEEvents(t, body) + require.GreaterOrEqual(t, len(events), 2) + failed := events[len(events)-1] + require.Equal(t, "response.failed", failed.Get("type").String()) + require.Equal(t, "msg_disc", failed.Get("response.id").String()) + require.Equal(t, "failed", failed.Get("response.status").String()) + require.Equal(t, tc.wantType, failed.Get("response.error.code").String()) + require.Equal(t, events[len(events)-2].Get("sequence_number").Int()+1, failed.Get("sequence_number").Int()) + }) + } + } +} + +func TestAnthropicCompatStreaming_EOFBeforeMessageStartKeepsExistingEnding(t *testing.T) { + for name, handle := range compatStreamHandlers() { + t.Run(name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + + result, err := handle(&GatewayService{}, &http.Response{Header: http.Header{}, Body: io.NopCloser(strings.NewReader("event: ping\ndata: {\"type\":\"ping\"}\n\n"))}, c) + + require.NoError(t, err) + require.NotNil(t, result) + require.NotContains(t, rec.Body.String(), compatStreamFailureMarkers[name]) + }) + } +} + +func TestAnthropicCompatStreaming_DoneLineCountsAsTerminalEvent(t *testing.T) { + for name, handle := range compatStreamHandlers() { + t.Run(name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + stream := anthropicStreamTruncatedBeforeMessageDelta() + "data: [DONE]\n\n" + + result, err := handle(&GatewayService{}, &http.Response{Header: http.Header{}, Body: io.NopCloser(strings.NewReader(stream))}, c) + + require.NoError(t, err) + require.NotNil(t, result) + require.NotContains(t, rec.Body.String(), compatStreamFailureMarkers[name]) + }) + } +} + +func anthropicStreamWithInBandError(messageBeforeError, after string) string { + return strings.Join([]string{ + `event: message_start`, + `data: {"type":"message_start","message":{"id":"msg_disc","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4-6","usage":{"input_tokens":20,"output_tokens":1}}}`, + ``, + `event: content_block_start`, + `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + ``, + `event: content_block_delta`, + `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"second"}}`, + ``, + `event: error`, + `data: {"type":"error","error":{"type":"overloaded_error","message":` + strconv.Quote(messageBeforeError) + `}}`, + ``, + }, "\n") + "\n" + after +} + +func TestAnthropicCompatStreaming_UpstreamErrorEventEndsStreamWithoutWaiting(t *testing.T) { + for name, handle := range compatStreamHandlers() { + for _, disconnect := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/client_disconnected=%t", name, disconnect), func(t *testing.T) { + gin.SetMode(gin.TestMode) + marker := "\x00never-written" + if disconnect { + marker = "second" + } + writer := &disconnectOnMarkerResponseWriter{ResponseRecorder: httptest.NewRecorder(), marker: marker} + c, _ := gin.CreateTestContext(writer) + resp, pw := stallingAnthropicUpstream(t, anthropicStreamWithInBandError("Overloaded", "")) + + got := runCompatStreamWithDeadline(t, handle, newCompatStreamIdleTestService(0), resp, c) + + if disconnect { + require.NoError(t, got.err) + require.NotNil(t, got.result) + require.True(t, got.result.ClientDisconnect) + require.Equal(t, 20, got.result.Usage.InputTokens) + require.Zero(t, writer.writesAfterError) + } else { + var sseErr *sseStreamErrorEventError + require.ErrorAs(t, got.err, &sseErr) + require.Nil(t, got.result, "an upstream error event is not billed while the client is online") + require.Equal(t, 1, strings.Count(writer.Body.String(), compatStreamFailureMarkers[name])) + require.Contains(t, writer.Body.String(), "Overloaded") + } + _, werr := io.WriteString(pw, "event: ping\n") + require.Error(t, werr, "upstream body must be closed after an upstream error event") + }) + } + } +} + +func TestAnthropicCompatStreaming_UpstreamErrorEventStopsReadingBufferedEvents(t *testing.T) { + after := strings.Join([]string{ + `event: content_block_delta`, + `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"LEAKED"}}`, + ``, + `event: message_delta`, + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":9}}`, + ``, + `event: message_stop`, + `data: {"type":"message_stop"}`, + ``, + }, "\n") + "\n" + for name, handle := range compatStreamHandlers() { + t.Run(name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + + result, err := handle(&GatewayService{}, &http.Response{Header: http.Header{}, Body: io.NopCloser(strings.NewReader(anthropicStreamWithInBandError("Overloaded", after)))}, c) + + var sseErr *sseStreamErrorEventError + require.ErrorAs(t, err, &sseErr) + require.Nil(t, result) + body := rec.Body.String() + require.NotContains(t, body, "LEAKED") + require.NotContains(t, body, compatStreamTerminalMarkers[name]) + require.Equal(t, 1, strings.Count(body, compatStreamFailureMarkers[name])) + }) + } +} + +func TestAnthropicCompatStreaming_UpstreamErrorEventMessageIsSanitized(t *testing.T) { + for name, handle := range compatStreamHandlers() { + t.Run(name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + stream := anthropicStreamWithInBandError("upstream https://example.test/v1?key=SECRET failed", "") + + _, err := handle(&GatewayService{}, &http.Response{Header: http.Header{}, Body: io.NopCloser(strings.NewReader(stream))}, c) + + require.Error(t, err) + require.Contains(t, rec.Body.String(), "key=***") + require.NotContains(t, rec.Body.String(), "SECRET") + }) + } +} + +func TestAnthropicCompatStreaming_UpstreamErrorEventBeforeOutputWritesNothing(t *testing.T) { + stream := "event: error\ndata: {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}\n\n" + for name, handle := range compatStreamHandlers() { + t.Run(name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + + result, err := handle(&GatewayService{}, &http.Response{Header: http.Header{}, Body: io.NopCloser(strings.NewReader(stream))}, c) + + var sseErr *sseStreamErrorEventError + require.ErrorAs(t, err, &sseErr) + require.Nil(t, result) + require.Zero(t, rec.Body.Len(), "the handler fails over to another account") + require.False(t, IsResponseCommitted(c)) + }) + } +} + +func TestForwardAsCompatStreaming_UpstreamErrorEventFailsOver(t *testing.T) { + beforeOutput := "event: error\ndata: {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}\n\n" + for _, endpoint := range []string{"chat_completions", "responses"} { + for _, tc := range []struct { + name string + stream string + wantStatus int + }{ + {name: "before_output", stream: beforeOutput, wantStatus: 529}, + {name: "after_output", stream: anthropicStreamWithInBandError("Overloaded", ""), wantStatus: http.StatusForbidden}, + } { + t.Run(endpoint+"/"+tc.name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := `{"model":"claude-sonnet-4-6","messages":[{"role":"user","content":"hi"}],"stream":true}` + path := "/v1/chat/completions" + if endpoint == "responses" { + body = `{"model":"claude-sonnet-4-6","input":"hi","stream":true}` + path = "/v1/responses" + } + c.Request = httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(tc.stream))} + svc := &GatewayService{ + cfg: rawChatCompletionsTestConfig(), + httpUpstream: &anthropicHTTPUpstreamRecorder{resp: resp}, + rateLimitService: &RateLimitService{accountRepo: &errorPolicyRepoStub{}, cfg: &config.Config{}}, + } + account := &Account{ID: 1, Platform: PlatformAnthropic, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "sk-test"}} + + var result *ForwardResult + var err error + if endpoint == "responses" { + result, err = svc.ForwardAsResponses(context.Background(), c, account, []byte(body), nil) + } else { + result, err = svc.ForwardAsChatCompletions(context.Background(), c, account, []byte(body), nil) + } + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, tc.wantStatus, failoverErr.StatusCode) + require.Nil(t, result) + }) + } + } +} + +func TestAnthropicCompatStreaming_LineTooLongFails(t *testing.T) { + for name, handle := range compatStreamHandlers() { + t.Run(name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + svc := &GatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 128 * 1024}}} + stream := anthropicStreamTruncatedBeforeMessageDelta() + "event: content_block_delta\ndata: " + strings.Repeat("x", 256*1024) + "\n\n" + + result, err := handle(svc, &http.Response{Header: http.Header{}, Body: io.NopCloser(strings.NewReader(stream))}, c) + + require.ErrorIs(t, err, bufio.ErrTooLong) + require.NotNil(t, result) + require.Contains(t, rec.Body.String(), compatStreamFailureMarkers[name]) + require.Contains(t, rec.Body.String(), "response_too_large") + }) + } +} + +func TestHandleResponsesStreamingResponse_FailureSequenceFollowsRestoredEvents(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + stream := strings.Join([]string{ + `event: message_start`, + `data: {"type":"message_start","message":{"id":"msg_tool","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4-6","usage":{"input_tokens":20,"output_tokens":1}}}`, + ``, + `event: content_block_start`, + `data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_1","name":"apply_patch","input":{}}}`, + ``, + `event: content_block_delta`, + `data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"input\":"}}`, + ``, + `event: content_block_delta`, + `data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"\"*** Begin"}}`, + ``, + `event: content_block_delta`, + `data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":" Patch"}}`, + ``, + }, "\n") + "\n" + mapping := apicompat.ResponsesClientToolMapping{CustomTools: map[string]bool{"apply_patch": true}} + + _, err := (&GatewayService{}).handleResponsesStreamingResponse( + &http.Response{Header: http.Header{}, Body: io.NopCloser(strings.NewReader(stream))}, + c, "claude-sonnet-4-6", "claude-sonnet-4-6", nil, time.Now(), mapping, + ) + + require.ErrorContains(t, err, "missing terminal event") + events := compatResponsesSSEEvents(t, rec.Body.String()) + require.NotEmpty(t, events) + require.Equal(t, "response.failed", events[len(events)-1].Get("type").String()) + for i, event := range events { + require.Equal(t, int64(i), event.Get("sequence_number").Int(), "sequence_number must be contiguous: %s", event.Raw) + } +} + +func TestAnthropicCompatStream_ClientGoneAtStreamEndMarksDisconnected(t *testing.T) { + gin.SetMode(gin.TestMode) + // 泵 goroutine 结束与请求 ctx 取消同时就绪时 select 随机选择,多轮重复以覆盖两种选择。 + for round := 0; round < 64; round++ { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + c.Request = httptest.NewRequest(http.MethodPost, "/", nil).WithContext(ctx) + stream := newAnthropicCompatStream(nil, c, &http.Response{Header: http.Header{}, Body: io.NopCloser(strings.NewReader(""))}, "test", "req") + time.Sleep(time.Millisecond) + + _, ok := stream.nextLine() + + require.False(t, ok) + require.True(t, stream.clientDisconnected, "round %d", round) + require.Nil(t, stream.failure()) + stream.stop() + } +} + +func TestAnthropicCompatStreaming_RequestContextCanceledDrainsWithoutWriting(t *testing.T) { + for name, handle := range compatStreamHandlers() { + for _, delayed := range []bool{true, false} { + t.Run(fmt.Sprintf("%s/upstream_delayed=%t", name, delayed), func(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + c.Request = httptest.NewRequest(http.MethodPost, "/", nil).WithContext(ctx) + var body io.ReadCloser = io.NopCloser(strings.NewReader(anthropicStreamWithMidStreamText())) + if delayed { + pr, pw := io.Pipe() + t.Cleanup(func() { _ = pr.Close() }) + go func() { + time.Sleep(20 * time.Millisecond) + _, _ = io.WriteString(pw, anthropicStreamWithMidStreamText()) + _ = pw.Close() + }() + body = pr + } + + got := runCompatStreamWithDeadline(t, handle, newCompatStreamIdleTestService(0), &http.Response{Header: http.Header{}, Body: body}, c) + + require.NoError(t, got.err) + require.NotNil(t, got.result) + require.True(t, got.result.ClientDisconnect) + require.Equal(t, 20, got.result.Usage.InputTokens) + require.Equal(t, 42, got.result.Usage.OutputTokens) + require.NotContains(t, rec.Body.String(), compatStreamTerminalMarkers[name]) + }) + } + } +} + +func TestAnthropicCompatStream_ClientDisconnectBoundsDrainWhenIntervalDisabled(t *testing.T) { + for _, tc := range []struct { + name string + intervalSec int + wantInterval time.Duration + }{ + {name: "interval_disabled", intervalSec: 0, wantInterval: anthropicCompatDisconnectDrainInterval}, + {name: "interval_configured", intervalSec: 30, wantInterval: 30 * time.Second}, + } { + t.Run(tc.name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + pr, pw := io.Pipe() + t.Cleanup(func() { _ = pw.Close(); _ = pr.Close() }) + cfg := &config.Config{Gateway: config.GatewayConfig{StreamDataIntervalTimeout: tc.intervalSec}} + stream := newAnthropicCompatStream(cfg, c, &http.Response{Header: http.Header{}, Body: pr}, "test", "req") + defer stream.stop() + require.Equal(t, tc.intervalSec > 0, stream.pump.timer != nil) + + stream.markClientDisconnected() + + require.True(t, stream.clientDisconnected) + require.NotNil(t, stream.pump.timer) + require.Equal(t, tc.wantInterval, stream.pump.interval) + }) + } +} + +func TestAnthropicCompatStreaming_DisconnectDrainEndsWhenIntervalDisabled(t *testing.T) { + original := anthropicCompatDisconnectDrainInterval + anthropicCompatDisconnectDrainInterval = 200 * time.Millisecond + t.Cleanup(func() { anthropicCompatDisconnectDrainInterval = original }) + + for name, handle := range compatStreamHandlers() { + t.Run(name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + writer := &disconnectOnMarkerResponseWriter{ResponseRecorder: httptest.NewRecorder(), marker: "second"} + c, _ := gin.CreateTestContext(writer) + resp, pw := stallingAnthropicUpstream(t, anthropicStreamTruncatedBeforeMessageDelta()) + + got := runCompatStreamWithDeadline(t, handle, newCompatStreamIdleTestService(0), resp, c) + + require.NoError(t, got.err) + require.NotNil(t, got.result) + require.True(t, got.result.ClientDisconnect) + require.Equal(t, 20, got.result.Usage.InputTokens) + require.Zero(t, writer.writesAfterError) + _, werr := io.WriteString(pw, "event: ping\n") + require.Error(t, werr, "upstream body must be closed after the disconnect drain bound") + }) + } +} + +func TestForwardAsCompatStreaming_IdleTimeoutTriggersStreamTimeoutHandling(t *testing.T) { + for _, endpoint := range []string{"chat_completions", "responses"} { + for _, tc := range []struct { + name string + stream string + marker string + wantErr bool + wantOutput int + wantPenalty int + }{ + {name: "client_online", stream: anthropicStreamTruncatedBeforeMessageDelta(), marker: "\x00never-written", wantErr: true, wantOutput: 1, wantPenalty: 1}, + {name: "client_disconnected", stream: anthropicStreamTruncatedBeforeMessageDelta(), marker: "second", wantOutput: 1}, + {name: "after_message_stop", stream: anthropicStreamWithMidStreamText(), marker: "\x00never-written", wantOutput: 42}, + {name: "after_stop_reason", stream: anthropicStreamWithoutMessageStop(), marker: "\x00never-written", wantOutput: 42}, + } { + t.Run(endpoint+"/"+tc.name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + writer := &disconnectOnMarkerResponseWriter{ResponseRecorder: httptest.NewRecorder(), marker: tc.marker} + c, _ := gin.CreateTestContext(writer) + body := `{"model":"claude-sonnet-4-6","messages":[{"role":"user","content":"hi"}],"stream":true}` + path := "/v1/chat/completions" + if endpoint == "responses" { + body = `{"model":"claude-sonnet-4-6","input":"hi","stream":true}` + path = "/v1/responses" + } + c.Request = httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + resp, _ := stallingAnthropicUpstream(t, tc.stream) + resp.StatusCode = http.StatusOK + repo := &errorPolicyRepoStub{} + settings := NewSettingService(&settingRepoStub{values: map[string]string{ + SettingKeyStreamTimeoutSettings: `{"enabled":true,"action":"temp_unsched","temp_unsched_minutes":1,"threshold_count":1,"threshold_window_minutes":1}`, + }}, nil) + cfg := rawChatCompletionsTestConfig() + cfg.Gateway.StreamDataIntervalTimeout = 1 + svc := &GatewayService{ + cfg: cfg, + httpUpstream: &anthropicHTTPUpstreamRecorder{resp: resp}, + rateLimitService: &RateLimitService{accountRepo: repo, settingService: settings}, + } + account := &Account{ID: 1, Platform: PlatformAnthropic, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "sk-test"}} + + var result *ForwardResult + var err error + if endpoint == "responses" { + result, err = svc.ForwardAsResponses(context.Background(), c, account, []byte(body), nil) + } else { + result, err = svc.ForwardAsChatCompletions(context.Background(), c, account, []byte(body), nil) + } + + if tc.wantErr { + require.ErrorIs(t, err, errAnthropicNativeStreamIdle) + } else { + require.NoError(t, err) + } + require.NotNil(t, result) + require.Equal(t, tc.wantOutput, result.Usage.OutputTokens) + require.Equal(t, tc.wantPenalty, repo.tempCalls) + }) + } + } +} + func TestHandleCCStreamingFromAnthropic_ClientDisconnectDrainsUpstreamUsage(t *testing.T) { gin.SetMode(gin.TestMode) writer := &disconnectOnMarkerResponseWriter{ResponseRecorder: httptest.NewRecorder(), marker: "second"} diff --git a/backend/internal/service/gateway_forward_compat_stream.go b/backend/internal/service/gateway_forward_compat_stream.go new file mode 100644 index 0000000000..7be3e85c35 --- /dev/null +++ b/backend/internal/service/gateway_forward_compat_stream.go @@ -0,0 +1,291 @@ +package service + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/tidwall/gjson" + "go.uber.org/zap" +) + +// anthropicCompatDisconnectDrainInterval 是 gateway.stream_data_interval_timeout +// 未启用时,客户端断开后继续读取上游的读间隔上限,与该配置项的默认值一致。 +var anthropicCompatDisconnectDrainInterval = 180 * time.Second + +// anthropicCompatStream 是 Anthropic 上游经 chat/responses 兼容入口流式转发时的 +// 上游读取状态。上游请求 ctx 与客户端解绑,客户端断开后调用方停止向下游写入、 +// 继续读取上游以合并最终 usage。逐行读间隔受 gateway.stream_data_interval_timeout +// 限制;该配置未启用时,客户端断开后以 anthropicCompatDisconnectDrainInterval 限制。 +type anthropicCompatStream struct { + pump *anthropicNativeLinePump + body io.Closer + maxLineSize int + logPrefix string + requestID string + // clientGone 是请求 ctx 的 Done,客户端断开后为 nil。 + clientGone <-chan struct{} + + clientDisconnected bool + sawMessageStart bool + // sawTerminal 表示上游已发出 message_stop、带 stop_reason 的 message_delta 或 [DONE]。 + sawTerminal bool + // upstreamErr* 记录上游流内的 error 事件;收到后调用方结束读取。 + upstreamErrType string + upstreamErrMessage string + upstreamErrPayload string + // readErr 是上游流结束的原因(io.EOF、读错误或 errAnthropicNativeStreamIdle)。 + readErr error +} + +// anthropicCompatStreamFailure 描述客户端在线时上游流未正常结束的原因: +// err 返回给调用方,errType / message 写入下游的终止错误事件。 +type anthropicCompatStreamFailure struct { + err error + errType string + message string +} + +// newAnthropicCompatStream 启动上游行泵;调用方 defer stop()。 +func newAnthropicCompatStream(cfg *config.Config, c *gin.Context, resp *http.Response, logPrefix, requestID string) *anthropicCompatStream { + scanner := bufio.NewScanner(resp.Body) + maxLineSize := defaultMaxLineSize + if cfg != nil && cfg.Gateway.MaxLineSize > 0 { + maxLineSize = cfg.Gateway.MaxLineSize + } + scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) + stream := &anthropicCompatStream{ + pump: newAnthropicNativeLinePump(scanner, anthropicNativeStreamInterval(cfg)), + body: resp.Body, + maxLineSize: maxLineSize, + logPrefix: logPrefix, + requestID: requestID, + } + if c.Request != nil { + stream.clientGone = c.Request.Context().Done() + } + return stream +} + +func (st *anthropicCompatStream) stop() { + st.pump.stop() +} + +// markClientDisconnected 标记客户端已断开,此后调用方不再向下游写入;读间隔上限 +// 未启用时以 anthropicCompatDisconnectDrainInterval 启用。 +func (st *anthropicCompatStream) markClientDisconnected() { + if st.clientDisconnected { + return + } + st.clientDisconnected = true + st.clientGone = nil + st.pump.enableInterval(anthropicCompatDisconnectDrainInterval) + logger.L().Info(st.logPrefix+" stream: client disconnected, continuing to drain upstream for billing", + zap.String("request_id", st.requestID), + ) +} + +// nextLine 返回上游下一行;ok=false 表示上游流已结束,原因记入 readErr。 +// 读间隔超时时关闭 body,解除泵 goroutine 阻塞中的读并释放上游连接。 +// 上游流结束时请求 ctx 已取消的,按客户端已断开收尾。 +func (st *anthropicCompatStream) nextLine() (string, bool) { + for { + line, err := st.pump.nextOrClientGone(st.clientGone) + if err == nil { + if payload, ok := extractOpenAISSEDataLine(line); ok && strings.TrimSpace(payload) == "[DONE]" { + st.sawTerminal = true + } + return line, true + } + if errors.Is(err, errAnthropicNativeClientGone) { + st.markClientDisconnected() + continue + } + if st.clientGone != nil { + select { + case <-st.clientGone: + st.clientDisconnected = true + st.clientGone = nil + default: + } + } + st.readErr = err + switch { + case errors.Is(err, errAnthropicNativeStreamIdle): + _ = st.body.Close() + logger.L().Warn(st.logPrefix+" stream: data interval timeout", + zap.String("request_id", st.requestID), + zap.Duration("interval", st.pump.interval), + zap.Bool("client_disconnected", st.clientDisconnected), + ) + case errors.Is(err, io.EOF), errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded): + // 正常收流或取消:不记日志。 + default: + logger.L().Warn(st.logPrefix+" stream: read error", + zap.Error(err), + zap.String("request_id", st.requestID), + ) + } + return "", false + } +} + +// observe 记录决定收尾方式的上游事件。收到上游 error 事件时关闭上游 body, +// 调用方不再处理该事件并结束读取。 +func (st *anthropicCompatStream) observe(event *apicompat.AnthropicStreamEvent, payload string) { + switch event.Type { + case "message_start": + st.sawMessageStart = true + case "message_stop": + st.sawTerminal = true + case "message_delta": + if event.Delta != nil && event.Delta.StopReason != "" { + st.sawTerminal = true + } + case "error": + st.upstreamErrPayload = payload + st.upstreamErrType = firstNonEmpty(gjson.Get(payload, "error.type").String(), "upstream_error") + st.upstreamErrMessage = firstNonEmpty(sanitizeUpstreamErrorMessage(gjson.Get(payload, "error.message").String()), "upstream stream error") + _ = st.body.Close() + logger.L().Warn(st.logPrefix+" stream: upstream error event", + zap.String("request_id", st.requestID), + zap.String("error_type", st.upstreamErrType), + zap.String("error_message", st.upstreamErrMessage), + zap.Bool("client_disconnected", st.clientDisconnected), + ) + } +} + +// failure 返回客户端在线、上游未发出结束事件即中断时的失败原因:上游流内 +// error 事件、读间隔超时、读错误,或 message_start 之后正常关闭。此时调用方不补发 +// 完成事件,而是写出协议内的终止错误。上游已发出结束事件、客户端已断开,或上游 +// 未发出 message_start 即正常关闭时返回 nil,调用方按已累计的 usage 正常收尾。 +// 读间隔超时时 err 为 errAnthropicNativeStreamIdle。 +func (st *anthropicCompatStream) failure() *anthropicCompatStreamFailure { + if st.clientDisconnected || st.sawTerminal { + return nil + } + switch { + case st.upstreamErrType != "": + return &anthropicCompatStreamFailure{ + err: &sseStreamErrorEventError{RawData: st.upstreamErrPayload}, + errType: st.upstreamErrType, + message: st.upstreamErrMessage, + } + case errors.Is(st.readErr, errAnthropicNativeStreamIdle): + return &anthropicCompatStreamFailure{ + err: errAnthropicNativeStreamIdle, + errType: "stream_timeout", + message: fmt.Sprintf("upstream stream idle for %s", st.pump.interval), + } + case errors.Is(st.readErr, bufio.ErrTooLong): + return &anthropicCompatStreamFailure{ + err: fmt.Errorf("stream usage incomplete: %w", st.readErr), + errType: "response_too_large", + message: fmt.Sprintf("upstream SSE line exceeded %d bytes", st.maxLineSize), + } + case st.readErr != nil && !errors.Is(st.readErr, io.EOF): + return &anthropicCompatStreamFailure{ + err: fmt.Errorf("stream usage incomplete: %w", st.readErr), + errType: "stream_read_error", + message: "upstream stream disconnected: " + sanitizeStreamError(st.readErr), + } + case st.sawMessageStart: + return &anthropicCompatStreamFailure{ + err: errors.New("stream usage incomplete: missing terminal event"), + errType: "stream_incomplete", + message: "upstream stream ended without a terminal event", + } + default: + return nil + } +} + +// finishAnthropicCompatStreamFailure 按失败原因收尾,返回交给调用方的结果与错误。 +// 上游流内 error 事件与 /v1/messages 一致:不计费,返回 sseStreamErrorEventError +// 由调用方转为 UpstreamFailoverError;尚未向客户端写出内容时不写终止错误,由 +// handler 换号重试。其余失败写出终止错误,并带上已观测到的 usage;未观测到任何 +// usage 时结果为 nil。 +func finishAnthropicCompatStreamFailure(c *gin.Context, writerSizeBeforeStream int, failure *anthropicCompatStreamFailure, result *ForwardResult, writeFailure func()) (*ForwardResult, error) { + var sseErr *sseStreamErrorEventError + if errors.As(failure.err, &sseErr) { + if c.Writer.Size() != writerSizeBeforeStream { + writeFailure() + } + return nil, failure.err + } + writeFailure() + if !result.Usage.hasObservedTokens() { + return nil, failure.err + } + return result, failure.err +} + +// writeAnthropicCompatCCStreamFailure 向 Chat Completions 流写出终止错误帧, +// 并标记响应已提交,handler 不再追加兜底错误。 +func writeAnthropicCompatCCStreamFailure(c *gin.Context, failure *anthropicCompatStreamFailure) { + payload, _ := json.Marshal(map[string]any{ + "error": map[string]string{ + "type": failure.errType, + "message": failure.message, + }, + }) + commitAnthropicCompatStreamFailure(c, failure, "data: "+string(payload)+"\n\n") +} + +// writeAnthropicCompatResponsesStreamFailure 向 Responses 流写出 response.failed +// 终止事件,沿用流内的 response id;sequence_number 经 restorer 与已写出的事件 +// 保持连续。写出后标记响应已提交。 +func writeAnthropicCompatResponsesStreamFailure(c *gin.Context, state *apicompat.AnthropicEventToResponsesState, restorer *apicompat.ResponsesClientToolStreamRestorer, failure *anthropicCompatStreamFailure) { + responseID := state.ResponseID + if responseID == "" { + responseID = "resp_" + strings.ReplaceAll(uuid.NewString(), "-", "") + } + evt := apicompat.ResponsesStreamEvent{ + Type: "response.failed", + SequenceNumber: state.SequenceNumber, + Response: &apicompat.ResponsesResponse{ + ID: responseID, + Object: "response", + CreatedAt: state.Created, + Model: state.Model, + Status: "failed", + Output: []apicompat.ResponsesOutput{}, + Error: &apicompat.ResponsesError{Code: failure.errType, Message: failure.message}, + }, + } + state.SequenceNumber++ + payload, err := json.Marshal(evt) + if err != nil { + return + } + payloads, _, err := restorer.RestoreEvent(payload) + if err != nil { + return + } + var frames strings.Builder + for _, restored := range payloads { + fmt.Fprintf(&frames, "event: %s\ndata: %s\n\n", gjson.GetBytes(restored, "type").String(), restored) + } + commitAnthropicCompatStreamFailure(c, failure, frames.String()) +} + +func commitAnthropicCompatStreamFailure(c *gin.Context, failure *anthropicCompatStreamFailure, frame string) { + MarkOpsStreamError(c, failure.errType, failure.message, http.StatusBadGateway) + MarkResponseCommitted(c) + if _, err := io.WriteString(c.Writer, frame); err != nil { + return + } + c.Writer.Flush() +} diff --git a/backend/internal/service/openai_gateway_anthropic_native_pump.go b/backend/internal/service/openai_gateway_anthropic_native_pump.go index 8a19677705..3b679bc4e8 100644 --- a/backend/internal/service/openai_gateway_anthropic_native_pump.go +++ b/backend/internal/service/openai_gateway_anthropic_native_pump.go @@ -1,8 +1,10 @@ package service -// 国产供应商 Anthropic 协议转换路径的上游 SSE 行泵。 +// Anthropic 协议转换路径的上游 SSE 行泵,用于 OpenAI 侧国产供应商的 +// CC×anthropic / Responses×anthropic 转换链,以及 Anthropic 账号的 +// chat/responses 兼容入口(anthropicCompatStream)。 // -// 这两条转换链(CC×anthropic / Responses×anthropic)的上游 ctx 是 +// 这些转换链的上游 ctx 是 // WithoutCancel(detachStreamUpstreamContext)、http.Client 无整体 Timeout, // 客户端断开后的排水阶段若上游挂住 SSE(不发数据也不断连), // scanner.Scan() 将永久阻塞:goroutine 钉死、resp.Body 不归还、连接池位 @@ -18,11 +20,17 @@ import ( "errors" "io" "time" + + "github.com/Wei-Shaw/sub2api/internal/config" ) // errAnthropicNativeStreamIdle 表示上游流读间隔超时(见上方文件注释)。 var errAnthropicNativeStreamIdle = errors.New("stream data interval timeout") +// errAnthropicNativeClientGone 表示等待上游数据期间客户端已离开;泵状态不变, +// 调用方可继续读取。 +var errAnthropicNativeClientGone = errors.New("client gone") + // anthropicNativeLineEvent 是行泵交付的单次读取结果:line 为一行 SSE 文本, // err 为 scanner 读错误(流自然结束时 next 返回 io.EOF,不经过本字段)。 type anthropicNativeLineEvent struct { @@ -31,7 +39,7 @@ type anthropicNativeLineEvent struct { } // anthropicNativeLinePump 以独立 goroutine 泵送 scanner 的行,并对逐行到达 -// 间隔施加 interval 上限(<=0 表示禁用,保持无界读的旧行为)。 +// 间隔施加 interval 上限(<=0 表示禁用,可经 enableInterval 启用)。 type anthropicNativeLinePump struct { events chan anthropicNativeLineEvent done chan struct{} @@ -69,25 +77,53 @@ func newAnthropicNativeLinePump(scanner *bufio.Scanner, interval time.Duration) } // next 阻塞返回下一行。返回 io.EOF 表示上游正常收流;errAnthropicNativeStreamIdle -// 表示 interval 内无任何数据到达(计时从收到上一行时起算,事件处理耗时不算入, -// 与 readOpenAICompatBufferedTerminal 的 resetTimeout 语义一致)。 +// 表示自交付上一行起已过 interval 且没有可交付的行;计时器到期时若已有缓冲的行, +// 优先交付该行,调用方处理事件期间上游送达的数据不会被判为上游空闲。 func (p *anthropicNativeLinePump) next() (string, error) { + return p.nextOrClientGone(nil) +} + +// nextOrClientGone 与 next 相同,另在等待期间 clientGone 关闭时返回 +// errAnthropicNativeClientGone。clientGone 为 nil 时不监听。 +func (p *anthropicNativeLinePump) nextOrClientGone(clientGone <-chan struct{}) (string, error) { var timeoutCh <-chan time.Time if p.timer != nil { timeoutCh = p.timer.C } select { case ev, ok := <-p.events: - if !ok { - return "", io.EOF - } - p.resetTimer() - return ev.line, ev.err + return p.deliver(ev, ok) case <-timeoutCh: - return "", errAnthropicNativeStreamIdle + select { + case ev, ok := <-p.events: + return p.deliver(ev, ok) + default: + return "", errAnthropicNativeStreamIdle + } + case <-clientGone: + return "", errAnthropicNativeClientGone } } +// deliver 交付一次读取结果;ok=false 表示泵 goroutine 已结束。 +func (p *anthropicNativeLinePump) deliver(ev anthropicNativeLineEvent, ok bool) (string, error) { + if !ok { + return "", io.EOF + } + p.resetTimer() + return ev.line, ev.err +} + +// enableInterval 在读间隔上限未启用时以 interval 启用,计时从调用时起算; +// 已启用时不变。只能在调用 next 的 goroutine 中调用。 +func (p *anthropicNativeLinePump) enableInterval(interval time.Duration) { + if p.timer != nil || interval <= 0 { + return + } + p.interval = interval + p.timer = time.NewTimer(interval) +} + // resetTimer 在收到一行后重启间隔计时器。 func (p *anthropicNativeLinePump) resetTimer() { if p.timer == nil { @@ -116,11 +152,11 @@ func (p *anthropicNativeLinePump) stop() { } } -// anthropicNativeStreamInterval 返回本组转换路径适用的读间隔上限; +// anthropicNativeStreamInterval 返回 Anthropic 上游协议转换路径适用的读间隔上限; // gateway.stream_data_interval_timeout <= 0 时视为禁用。 -func (s *OpenAIGatewayService) anthropicNativeStreamInterval() time.Duration { - if s.cfg != nil && s.cfg.Gateway.StreamDataIntervalTimeout > 0 { - return time.Duration(s.cfg.Gateway.StreamDataIntervalTimeout) * time.Second +func anthropicNativeStreamInterval(cfg *config.Config) time.Duration { + if cfg != nil && cfg.Gateway.StreamDataIntervalTimeout > 0 { + return time.Duration(cfg.Gateway.StreamDataIntervalTimeout) * time.Second } return 0 } diff --git a/backend/internal/service/openai_gateway_anthropic_native_pump_test.go b/backend/internal/service/openai_gateway_anthropic_native_pump_test.go index e5b9d0dd84..328f5c99b6 100644 --- a/backend/internal/service/openai_gateway_anthropic_native_pump_test.go +++ b/backend/internal/service/openai_gateway_anthropic_native_pump_test.go @@ -130,6 +130,87 @@ func TestAnthropicNativeLinePump_DataResetsTimer(t *testing.T) { } } +func TestAnthropicNativeLinePump_SlowConsumerGetsBufferedLineInsteadOfIdle(t *testing.T) { + // 计时器与缓冲行同时就绪时 select 随机选择,多轮重复以覆盖两种选择。 + for round := 0; round < 64; round++ { + pump := &anthropicNativeLinePump{ + events: make(chan anthropicNativeLineEvent, 1), + done: make(chan struct{}), + timer: time.NewTimer(0), + interval: time.Hour, + } + pump.events <- anthropicNativeLineEvent{line: "data: {}"} + time.Sleep(time.Millisecond) + + line, err := pump.next() + pump.stop() + if err != nil || line != "data: {}" { + t.Fatalf("round %d: expected buffered line, got %q err=%v", round, line, err) + } + } +} + +func TestAnthropicNativeLinePump_ClientGoneKeepsPumpReadable(t *testing.T) { + pr, pw := io.Pipe() + scanner := bufio.NewScanner(pr) + pump := newAnthropicNativeLinePump(scanner, 0) + defer pump.stop() + defer func() { _ = pr.Close() }() + + clientGone := make(chan struct{}) + close(clientGone) + if _, err := pump.nextOrClientGone(clientGone); err != errAnthropicNativeClientGone { + t.Fatalf("expected client gone, got %v", err) + } + + go func() { + _, _ = pw.Write([]byte("event: ping\n")) + _ = pw.Close() + }() + line, err := pump.nextOrClientGone(nil) + if err != nil || line != "event: ping" { + t.Fatalf("expected the pending line after client gone, got %q err=%v", line, err) + } + if _, err := pump.next(); err != io.EOF { + t.Fatalf("expected EOF, got %v", err) + } +} + +func TestAnthropicNativeLinePump_EnableIntervalBoundsDisabledPump(t *testing.T) { + pr, _ := io.Pipe() + scanner := bufio.NewScanner(pr) + defer func() { _ = pr.Close() }() + + pump := newAnthropicNativeLinePump(scanner, 0) + defer pump.stop() + pump.enableInterval(50 * time.Millisecond) + + start := time.Now() + if _, err := pump.next(); err != errAnthropicNativeStreamIdle { + t.Fatalf("expected interval timeout after enableInterval, got %v", err) + } + if elapsed := time.Since(start); elapsed > 5*time.Second { + t.Fatalf("timeout not respected: %v", elapsed) + } +} + +func TestAnthropicNativeLinePump_EnableIntervalKeepsConfiguredInterval(t *testing.T) { + pr, _ := io.Pipe() + scanner := bufio.NewScanner(pr) + defer func() { _ = pr.Close() }() + + pump := newAnthropicNativeLinePump(scanner, 50*time.Millisecond) + defer pump.stop() + pump.enableInterval(time.Hour) + + if pump.interval != 50*time.Millisecond { + t.Fatalf("configured interval must not change, got %v", pump.interval) + } + if _, err := pump.next(); err != errAnthropicNativeStreamIdle { + t.Fatalf("expected interval timeout, got %v", err) + } +} + func TestCCStreamingFromNativeAnthropic_HangTimesOut(t *testing.T) { gin.SetMode(gin.TestMode) svc := newNativeAnthropicHangTestService(1) diff --git a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go index f76a457370..f6333661f5 100644 --- a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go +++ b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go @@ -169,7 +169,7 @@ func (s *OpenAIGatewayService) handleCCBufferedFromNativeAnthropic( var usage ClaudeUsage // 读间隔上限:上游挂住 SSE 时中止组装(缓冲路径尚未提交响应头,可回 502)。 - streamInterval := s.anthropicNativeStreamInterval() + streamInterval := anthropicNativeStreamInterval(s.cfg) pump := newAnthropicNativeLinePump(scanner, streamInterval) defer pump.stop() @@ -356,7 +356,7 @@ func (s *OpenAIGatewayService) handleCCStreamingFromNativeAnthropic( // 读间隔上限:上游挂住 SSE(不发数据也不断连)时结束排水。上游 ctx 为 // WithoutCancel 且 http.Client 无整体 Timeout,无此界限则客户端断开后 // scanner.Scan() 永久阻塞(见 anthropic native pump 文件注释)。 - streamInterval := s.anthropicNativeStreamInterval() + streamInterval := anthropicNativeStreamInterval(s.cfg) pump := newAnthropicNativeLinePump(scanner, streamInterval) defer pump.stop() diff --git a/backend/internal/service/openai_gateway_responses_anthropic_native.go b/backend/internal/service/openai_gateway_responses_anthropic_native.go index 09278d2914..ec4fada790 100644 --- a/backend/internal/service/openai_gateway_responses_anthropic_native.go +++ b/backend/internal/service/openai_gateway_responses_anthropic_native.go @@ -171,7 +171,7 @@ func (s *OpenAIGatewayService) handleResponsesBufferedFromNativeAnthropic( var usage ClaudeUsage // 读间隔上限:上游挂住 SSE 时中止组装(缓冲路径尚未提交响应头,可回 502)。 - streamInterval := s.anthropicNativeStreamInterval() + streamInterval := anthropicNativeStreamInterval(s.cfg) pump := newAnthropicNativeLinePump(scanner, streamInterval) defer pump.stop() @@ -367,7 +367,7 @@ func (s *OpenAIGatewayService) handleResponsesStreamingFromNativeAnthropic( // 读间隔上限:上游挂住 SSE(不发数据也不断连)时结束转换循环。上游 ctx 为 // WithoutCancel 且 http.Client 无整体 Timeout,无此界限则 scanner.Scan() // 永久阻塞(见 anthropic native pump 文件注释)。 - streamInterval := s.anthropicNativeStreamInterval() + streamInterval := anthropicNativeStreamInterval(s.cfg) pump := newAnthropicNativeLinePump(scanner, streamInterval) defer pump.stop() From 89654873ff4b8d586e333a1dd21d194aa82facf0 Mon Sep 17 00:00:00 2001 From: feeeei Date: Tue, 20 Oct 2026 20:33:13 +0800 Subject: [PATCH 015/297] =?UTF-8?q?perf(account):=20=E6=A8=A1=E5=9E=8B?= =?UTF-8?q?=E6=98=A0=E5=B0=84=E7=AD=BE=E5=90=8D=E6=94=B9=E4=B8=BA=E4=B8=8E?= =?UTF-8?q?=E9=81=8D=E5=8E=86=E9=A1=BA=E5=BA=8F=E6=97=A0=E5=85=B3=E3=80=81?= =?UTF-8?q?=E9=9B=B6=E5=88=86=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GetModelMapping 命中缓存前要计算 model_mapping 的签名:收集全部 key、 排序、再逐个写入 fnv64a。签名只存放在 Account 的未导出字段里,不持久化、 不序列化、不跨进程比较,排序的唯一作用是消除 Go map 的随机遍历顺序。 改为逐条目计算 FNV-1a(key、分隔字节、value 或非字符串标记)并经 fmix64 收尾后求和:内容相同签名相同,单条改值、改键、两个 key 互换 value 都能检出, 且不分配内存。30 条映射单次计算约 2.3µs/1 次分配降到约 0.8µs/0 次分配; 选号时每个候选账号每次调用 3 次。 --- backend/internal/service/account.go | 59 ++++++++---- .../account_model_mapping_signature_test.go | 96 +++++++++++++++++++ 2 files changed, 139 insertions(+), 16 deletions(-) create mode 100644 backend/internal/service/account_model_mapping_signature_test.go diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 06b94b754e..ae2b250122 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -4,7 +4,6 @@ package service import ( "encoding/json" "errors" - "hash/fnv" "log/slog" "net/url" "reflect" @@ -717,28 +716,56 @@ func mapPtr(m map[string]any) uintptr { return reflect.ValueOf(m).Pointer() } +const ( + modelMappingSignatureFNVOffset = 14695981039346656037 + modelMappingSignatureFNVPrime = 1099511628211 +) + +// modelMappingSignature 计算原始映射内容的进程内校验值,与 map 遍历顺序无关且不分配内存。 +// 每个条目把 key、分隔字节 0 与 value(string 写其字节,其它类型写标记字节 1) +// 放进同一个 FNV-1a 哈希并经 fmix64 收尾,再对所有条目求和; +// key 与 value 同在一个条目哈希里,交换两个 key 的 value 会改变结果。 func modelMappingSignature(rawMapping map[string]any) uint64 { if len(rawMapping) == 0 { return 0 } - keys := make([]string, 0, len(rawMapping)) - for k := range rawMapping { - keys = append(keys, k) - } - sort.Strings(keys) - - h := fnv.New64a() - for _, k := range keys { - _, _ = h.Write([]byte(k)) - _, _ = h.Write([]byte{0}) - if v, ok := rawMapping[k].(string); ok { - _, _ = h.Write([]byte(v)) + var sum uint64 + for k, v := range rawMapping { + h := uint64(modelMappingSignatureFNVOffset) + h = fnv1aString(h, k) + h = fnv1aByte(h, 0) + if s, ok := v.(string); ok { + h = fnv1aString(h, s) } else { - _, _ = h.Write([]byte{1}) + h = fnv1aByte(h, 1) } - _, _ = h.Write([]byte{0xff}) + sum += fmix64(h) } - return h.Sum64() + return sum +} + +func fnv1aString(h uint64, s string) uint64 { + for i := 0; i < len(s); i++ { + h ^= uint64(s[i]) + h *= modelMappingSignatureFNVPrime + } + return h +} + +func fnv1aByte(h uint64, b byte) uint64 { + h ^= uint64(b) + h *= modelMappingSignatureFNVPrime + return h +} + +// fmix64 是 MurmurHash3 的 64 位收尾函数,使条目哈希各位充分混合后再求和。 +func fmix64(h uint64) uint64 { + h ^= h >> 33 + h *= 0xff51afd7ed558ccd + h ^= h >> 33 + h *= 0xc4ceb9fe1a85ec53 + h ^= h >> 33 + return h } // antigravityDefaultPassthroughModels 是 Antigravity 显式 model_mapping 运行时补齐的默认透传条目: diff --git a/backend/internal/service/account_model_mapping_signature_test.go b/backend/internal/service/account_model_mapping_signature_test.go new file mode 100644 index 0000000000..a83c05dc81 --- /dev/null +++ b/backend/internal/service/account_model_mapping_signature_test.go @@ -0,0 +1,96 @@ +//go:build unit + +package service + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestModelMappingSignature_IndependentOfInsertionOrder(t *testing.T) { + const size = 64 + forward := make(map[string]any, size) + backward := make(map[string]any, size) + for i := 0; i < size; i++ { + forward[fmt.Sprintf("model-%02d", i)] = fmt.Sprintf("upstream-%02d", i) + } + for i := size - 1; i >= 0; i-- { + backward[fmt.Sprintf("model-%02d", i)] = fmt.Sprintf("upstream-%02d", i) + } + forward["non-string"] = 42 + backward["non-string"] = 42 + + want := modelMappingSignature(forward) + require.NotZero(t, want) + for i := 0; i < 20; i++ { + require.Equal(t, want, modelMappingSignature(forward)) + require.Equal(t, want, modelMappingSignature(backward)) + } +} + +func TestModelMappingSignature_DetectsContentChanges(t *testing.T) { + base := map[string]any{ + "claude-sonnet": "sonnet-a", + "claude-opus": "opus-a", + "gpt-5": "gpt-5-upstream", + } + baseSig := modelMappingSignature(base) + + cases := map[string]map[string]any{ + "value changed": { + "claude-sonnet": "sonnet-b", + "claude-opus": "opus-a", + "gpt-5": "gpt-5-upstream", + }, + "key renamed": { + "claude-sonnet-x": "sonnet-a", + "claude-opus": "opus-a", + "gpt-5": "gpt-5-upstream", + }, + "values swapped between keys": { + "claude-sonnet": "opus-a", + "claude-opus": "sonnet-a", + "gpt-5": "gpt-5-upstream", + }, + "string value replaced by non-string": { + "claude-sonnet": 1, + "claude-opus": "opus-a", + "gpt-5": "gpt-5-upstream", + }, + "entry removed": { + "claude-sonnet": "sonnet-a", + "claude-opus": "opus-a", + }, + } + for name, changed := range cases { + require.NotEqual(t, baseSig, modelMappingSignature(changed), name) + } + + // 非 string 的 value 统一按类型标记参与签名,具体取值不影响结果。 + require.Equal(t, + modelMappingSignature(map[string]any{"m": 1}), + modelMappingSignature(map[string]any{"m": true}), + ) +} + +func TestModelMappingSignature_EmptyIsZero(t *testing.T) { + require.Zero(t, modelMappingSignature(nil)) + require.Zero(t, modelMappingSignature(map[string]any{})) +} + +func TestModelMappingSignature_DoesNotAllocate(t *testing.T) { + mapping := map[string]any{ + "claude-sonnet": "sonnet-a", + "claude-opus": "opus-a", + "gpt-5": "gpt-5-upstream", + "non-string": 3.14, + } + var sink uint64 + allocs := testing.AllocsPerRun(1000, func() { + sink += modelMappingSignature(mapping) + }) + require.Zero(t, allocs) + require.NotZero(t, sink) +} From 38b72d734e0aa92ce7547a5ea8618abb7290cf98 Mon Sep 17 00:00:00 2001 From: feeeei Date: Tue, 20 Oct 2026 20:33:13 +0800 Subject: [PATCH 016/297] =?UTF-8?q?fix(ratelimit):=20=E6=A8=A1=E5=9E=8B?= =?UTF-8?q?=E9=99=90=E6=B5=81=E5=BF=AB=E7=85=A7=E5=86=99=E5=85=A5=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E5=86=99=E6=97=B6=E5=A4=8D=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit setAccountModelRateLimitSnapshot 原地写 account.Extra 以及其中的 model_rate_limits map。选号阶段的 Anthropic Fable 阈值过滤 (filterAccountsBySchedulingThreshold → ApplyAccountSchedulingThreshold) 会对候选账号调用它;候选账号的 Extra 一旦与其它请求共享,原地写就会造成 并发 map 读写并污染共享对象。 改为复制旧的 limits 与 Extra 顶层、写入新条目后替换 account.Extra, 不修改任何已有 map,本请求后续读取到的结果不变。其余调用方 (ratelimit_cline、cline_usage、openai_images_balance)都通过同一个 *Account 读取结果,不依赖原地修改可见。 --- backend/internal/service/model_rate_limit.go | 21 +- .../model_rate_limit_snapshot_cow_test.go | 207 ++++++++++++++++++ 2 files changed, 220 insertions(+), 8 deletions(-) create mode 100644 backend/internal/service/model_rate_limit_snapshot_cow_test.go diff --git a/backend/internal/service/model_rate_limit.go b/backend/internal/service/model_rate_limit.go index a75fa62094..46e3419e03 100644 --- a/backend/internal/service/model_rate_limit.go +++ b/backend/internal/service/model_rate_limit.go @@ -2,6 +2,7 @@ package service import ( "context" + "maps" "strings" "time" @@ -209,18 +210,13 @@ func (a *Account) modelRateLimitReason(scope string) string { return reason } +// setAccountModelRateLimitSnapshot 把模型级限流写进本账号对象的 Extra 快照。 +// 写时复制:Extra 与其中的 model_rate_limits 可能与调度快照母本及其它副本共享, +// 这里只读取旧 map,写入新复制的 map 后替换 account.Extra,不修改任何已有 map。 func setAccountModelRateLimitSnapshot(account *Account, scope string, resetAt time.Time, reason string, now time.Time) { if account == nil || strings.TrimSpace(scope) == "" { return } - if account.Extra == nil { - account.Extra = make(map[string]any) - } - limits, ok := account.Extra[modelRateLimitsKey].(map[string]any) - if !ok { - limits = make(map[string]any) - account.Extra[modelRateLimitsKey] = limits - } payload := map[string]any{ "rate_limited_at": now.UTC().Format(time.RFC3339), "rate_limit_reset_at": resetAt.UTC().Format(time.RFC3339), @@ -228,5 +224,14 @@ func setAccountModelRateLimitSnapshot(account *Account, scope string, resetAt ti if reason = strings.TrimSpace(reason); reason != "" { payload["reason"] = reason } + + oldLimits, _ := account.Extra[modelRateLimitsKey].(map[string]any) + limits := make(map[string]any, len(oldLimits)+1) + maps.Copy(limits, oldLimits) limits[scope] = payload + + extra := make(map[string]any, len(account.Extra)+1) + maps.Copy(extra, account.Extra) + extra[modelRateLimitsKey] = limits + account.Extra = extra } diff --git a/backend/internal/service/model_rate_limit_snapshot_cow_test.go b/backend/internal/service/model_rate_limit_snapshot_cow_test.go new file mode 100644 index 0000000000..97e35c296e --- /dev/null +++ b/backend/internal/service/model_rate_limit_snapshot_cow_test.go @@ -0,0 +1,207 @@ +//go:build unit + +package service + +import ( + "context" + "fmt" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +func TestSetAccountModelRateLimitSnapshot_CopyOnWrite(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC().Truncate(time.Second) + existingLimit := map[string]any{ + "rate_limited_at": now.Format(time.RFC3339), + "rate_limit_reset_at": now.Add(time.Hour).Format(time.RFC3339), + } + limits := map[string]any{"claude-opus-5": existingLimit} + extra := map[string]any{ + modelRateLimitsKey: limits, + "session_window_utilization": 0.5, + } + account := &Account{ID: 1, Platform: PlatformAnthropic, Extra: extra} + before := *account + + setAccountModelRateLimitSnapshot(account, anthropicFableRateLimitKey, now.Add(2*time.Hour), " threshold ", now) + + // 调用前的 Extra 与嵌套 limits 原样保留。 + require.Len(t, extra, 2) + require.Equal(t, 0.5, extra["session_window_utilization"]) + require.Len(t, limits, 1) + require.Equal(t, existingLimit, limits["claude-opus-5"]) + require.NotContains(t, limits, anthropicFableRateLimitKey) + require.False(t, before.isModelRateLimitedWithContext(ctx, "claude-fable-5")) + + // 新 Extra 同时带有旧条目与新限流,本请求后续读取结果与原地写入一致。 + require.Equal(t, 0.5, account.Extra["session_window_utilization"]) + newLimits, ok := account.Extra[modelRateLimitsKey].(map[string]any) + require.True(t, ok) + require.Len(t, newLimits, 2) + require.Equal(t, existingLimit, newLimits["claude-opus-5"]) + require.Equal(t, map[string]any{ + "rate_limited_at": now.Format(time.RFC3339), + "rate_limit_reset_at": now.Add(2 * time.Hour).Format(time.RFC3339), + "reason": "threshold", + }, newLimits[anthropicFableRateLimitKey]) + require.Equal(t, "threshold", account.modelRateLimitReason(anthropicFableRateLimitKey)) + require.True(t, account.isModelRateLimitedWithContext(ctx, "claude-fable-5")) + require.True(t, account.isModelRateLimitedWithContext(ctx, "claude-opus-5")) + require.False(t, account.isModelRateLimitedWithContext(ctx, "claude-sonnet-5")) +} + +func TestSetAccountModelRateLimitSnapshot_InitializesMissingOrInvalidLimits(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC() + + empty := &Account{Platform: PlatformAnthropic} + setAccountModelRateLimitSnapshot(empty, "claude-opus-5", now.Add(time.Hour), "", now) + require.True(t, empty.isModelRateLimitedWithContext(ctx, "claude-opus-5")) + require.Empty(t, empty.modelRateLimitReason("claude-opus-5")) + + invalidExtra := map[string]any{modelRateLimitsKey: "corrupted", "keep": true} + invalid := &Account{Platform: PlatformAnthropic, Extra: invalidExtra} + setAccountModelRateLimitSnapshot(invalid, "claude-opus-5", now.Add(time.Hour), "r", now) + require.True(t, invalid.isModelRateLimitedWithContext(ctx, "claude-opus-5")) + require.Equal(t, true, invalid.Extra["keep"]) + require.Equal(t, "corrupted", invalidExtra[modelRateLimitsKey]) + + unchanged := &Account{Platform: PlatformAnthropic, Extra: map[string]any{"k": 1}} + setAccountModelRateLimitSnapshot(unchanged, " ", now.Add(time.Hour), "r", now) + require.Equal(t, map[string]any{"k": 1}, unchanged.Extra) +} + +// 同一母本的浅拷贝并发写各自的限流快照:-race 下不得出现竞争,母本与其它副本都看不到这些写入。 +func TestSetAccountModelRateLimitSnapshot_ConcurrentCopiesOfSharedMaster(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC() + master := &Account{ + ID: 7, + Platform: PlatformAnthropic, + Extra: map[string]any{ + modelRateLimitsKey: map[string]any{ + "claude-opus-5": map[string]any{"rate_limit_reset_at": now.Add(time.Hour).Format(time.RFC3339)}, + }, + "session_window_utilization": 0.2, + }, + } + + const workers = 16 + var wg sync.WaitGroup + for worker := 0; worker < workers; worker++ { + wg.Add(1) + go func(worker int) { + defer wg.Done() + own := fmt.Sprintf("model-%d", worker) + other := fmt.Sprintf("model-%d", (worker+1)%workers) + for i := 0; i < 50; i++ { + replica := *master + setAccountModelRateLimitSnapshot(&replica, own, now.Add(time.Hour), "r", now) + if !replica.isModelRateLimitedWithContext(ctx, own) { + t.Errorf("worker %d: own limit missing", worker) + return + } + if !replica.isModelRateLimitedWithContext(ctx, "claude-opus-5") { + t.Errorf("worker %d: inherited limit missing", worker) + return + } + if replica.isModelRateLimitedWithContext(ctx, other) { + t.Errorf("worker %d: saw another replica's limit", worker) + return + } + probe := *master + if probe.isModelRateLimitedWithContext(ctx, own) { + t.Errorf("worker %d: master was mutated", worker) + return + } + } + }(worker) + } + wg.Wait() + + limits, ok := master.Extra[modelRateLimitsKey].(map[string]any) + require.True(t, ok) + require.Len(t, limits, 1) + require.Len(t, master.Extra, 2) +} + +type sharedSnapshotFableRepoStub struct { + AccountRepository + modelCalls atomic.Int64 +} + +func (r *sharedSnapshotFableRepoStub) SetModelRateLimit(_ context.Context, _ int64, _ string, _ time.Time, _ ...string) error { + r.modelCalls.Add(1) + return nil +} + +// Fable 阈值在选号阶段写入候选对象:同一母本的其它副本(包括并发读取的副本)与母本本身都不得出现该限流。 +func TestApplyAccountSchedulingThreshold_FableLimitStaysOnOwnSnapshotCopy(t *testing.T) { + accountSchedulingThresholdsSF.Forget(SettingKeyAccountSchedulingThresholds) + accountSchedulingThresholdsCache.Store(&cachedAccountSchedulingThresholds{}) + t.Cleanup(func() { + accountSchedulingThresholdsSF.Forget(SettingKeyAccountSchedulingThresholds) + accountSchedulingThresholdsCache.Store(&cachedAccountSchedulingThresholds{}) + }) + + settingsRepo := newMockSettingRepo() + settingsRepo.data[SettingKeyAccountSchedulingThresholds] = `{"anthropic":100}` + repo := &sharedSnapshotFableRepoStub{} + limiter := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + limiter.SetSettingService(NewSettingService(settingsRepo, &config.Config{})) + + now := time.Now().UTC() + master := &Account{ + ID: 1006, + Platform: PlatformAnthropic, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{"account_scheduling_threshold": 60}, + Extra: map[string]any{ + "passive_usage_7d_utilization": 0.40, + "passive_usage_7d_reset": float64(now.Add(3 * 24 * time.Hour).Unix()), + "passive_usage_7d_oi_utilization": 0.61, + "passive_usage_7d_oi_reset": float64(now.Add(4 * 24 * time.Hour).Unix()), + }, + } + + const pairs = 8 + var wg sync.WaitGroup + for i := 0; i < pairs; i++ { + wg.Add(2) + go func() { + defer wg.Done() + candidate := *master + if limiter.ApplyAccountSchedulingThreshold(context.Background(), &candidate) { + t.Error("the Fable-only window must not pause the whole account") + } + if candidate.IsSchedulableForModel("claude-fable-5") { + t.Error("the candidate that crossed the threshold must stop scheduling Fable") + } + if !candidate.IsSchedulableForModel("claude-opus-5") { + t.Error("non-Fable models must stay schedulable") + } + }() + go func() { + defer wg.Done() + for j := 0; j < 20; j++ { + reader := *master + if !reader.IsSchedulableForModel("claude-fable-5") { + t.Error("a sibling copy must not see the Fable limit") + return + } + } + }() + } + wg.Wait() + + require.Equal(t, int64(pairs), repo.modelCalls.Load()) + require.NotContains(t, master.Extra, modelRateLimitsKey) + require.True(t, master.IsSchedulableForModel("claude-fable-5")) +} From d5dbb5c36be3e2b76e7f0197e6ef7f3f214df6fc Mon Sep 17 00:00:00 2001 From: feeeei Date: Tue, 20 Oct 2026 17:23:26 +0800 Subject: [PATCH 017/297] =?UTF-8?q?perf(gateway):=20=E5=8D=95=20antigravit?= =?UTF-8?q?y=20=E8=B4=A6=E5=8F=B7=E5=88=86=E7=BB=84=E5=88=A4=E5=AE=9A?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=E6=8C=89=E9=9C=80=E6=B1=82=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 三个入口(Gemini 原生、/v1/messages 的 Gemini 分支与 Claude 路径) 每个请求都会查询分组的 antigravity:forced 快照桶。纯 Gemini/Anthropic 分组的该桶恒为空,空快照按未命中处理,于是每个请求都回源 PG 并重新 发布快照,而判定结果只被 antigravity 账号的 503 原地重试与模型限流 预检查读取。 入口改为挂载延迟判定:antigravity 账号首次需要时才查询快照,同一请求 内只查一次;显式设置的 SingleAccountRetry 标记仍优先。其他平台的请求 不再触发该查询。 --- backend/internal/handler/gateway_handler.go | 18 +- ...eway_handler_warmup_intercept_unit_test.go | 6 +- .../handler/gemini_client_cancel_test.go | 16 +- .../internal/handler/gemini_v1beta_handler.go | 9 +- .../single_account_retry_probe_unit_test.go | 120 +++++++++++ .../service/antigravity_gateway_retry.go | 8 +- .../internal/service/gateway_scheduling.go | 20 +- backend/internal/service/request_metadata.go | 33 +++ .../single_account_retry_probe_test.go | 191 ++++++++++++++++++ 9 files changed, 388 insertions(+), 33 deletions(-) create mode 100644 backend/internal/handler/single_account_retry_probe_unit_test.go create mode 100644 backend/internal/service/single_account_retry_probe_test.go diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index e990e3dd0a..c332e38ea0 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -339,12 +339,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) { if platform == service.PlatformGemini { fs := NewFailoverState(h.maxAccountSwitchesGemini, hasBoundSession) - // 单账号分组提前设置 SingleAccountRetry 标记,让 Service 层首次 503 就不设模型限流标记。 - // 避免单账号分组收到 503 (MODEL_CAPACITY_EXHAUSTED) 时设 29s 限流,导致后续请求连续快速失败。 - if h.gatewayService.IsSingleAntigravityAccountGroup(c.Request.Context(), apiKey.GroupID) { - ctx := service.WithSingleAccountRetry(c.Request.Context(), true, h.metadataBridgeEnabled()) - c.Request = c.Request.WithContext(ctx) - } + // 单账号分组首次 503 就不设模型限流标记,避免设 29s 限流导致后续请求连续快速失败; + // 是否单账号分组在 antigravity 账号遇到 503 或模型限流预检查时才判定。 + c.Request = c.Request.WithContext(h.gatewayService.WithSingleAntigravityAccountGroupProbe(c.Request.Context(), apiKey.GroupID)) for { selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), apiKey.GroupID, sessionKey, reqModel, fs.FailedAccountIDs, "", int64(0)) // Gemini 不使用会话限制 @@ -639,12 +636,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) { } fallbackUsed := false - // 单账号分组提前设置 SingleAccountRetry 标记,让 Service 层首次 503 就不设模型限流标记。 - // 避免单账号分组收到 503 (MODEL_CAPACITY_EXHAUSTED) 时设 29s 限流,导致后续请求连续快速失败。 - if h.gatewayService.IsSingleAntigravityAccountGroup(c.Request.Context(), currentAPIKey.GroupID) { - ctx := service.WithSingleAccountRetry(c.Request.Context(), true, h.metadataBridgeEnabled()) - c.Request = c.Request.WithContext(ctx) - } + // 单账号分组首次 503 就不设模型限流标记,避免设 29s 限流导致后续请求连续快速失败; + // 是否单账号分组在 antigravity 账号遇到 503 或模型限流预检查时才判定。 + c.Request = c.Request.WithContext(h.gatewayService.WithSingleAntigravityAccountGroupProbe(c.Request.Context(), currentAPIKey.GroupID)) // 会话槽失败释放:failover 链上每个选中的 Anthropic OAuth 账号都注册过同一会话 // (checkAndRegisterSession)。若请求最终失败(转发失败/客户端中断/换号耗尽), diff --git a/backend/internal/handler/gateway_handler_warmup_intercept_unit_test.go b/backend/internal/handler/gateway_handler_warmup_intercept_unit_test.go index aad6fcaad1..a4e37119f2 100644 --- a/backend/internal/handler/gateway_handler_warmup_intercept_unit_test.go +++ b/backend/internal/handler/gateway_handler_warmup_intercept_unit_test.go @@ -158,8 +158,12 @@ func (f *fakeConcurrencyCache) CleanupStaleProcessSlots(context.Context, string) func newTestGatewayHandler(t *testing.T, group *service.Group, accounts []*service.Account) (*GatewayHandler, func()) { t.Helper() + return newTestGatewayHandlerWithSchedulerCache(t, group, &fakeSchedulerCache{accounts: accounts}) +} + +func newTestGatewayHandlerWithSchedulerCache(t *testing.T, group *service.Group, schedulerCache service.SchedulerCache) (*GatewayHandler, func()) { + t.Helper() - schedulerCache := &fakeSchedulerCache{accounts: accounts} schedulerSnapshot := service.NewSchedulerSnapshotService(schedulerCache, nil, nil, nil, nil) gwSvc := service.NewGatewayService( diff --git a/backend/internal/handler/gemini_client_cancel_test.go b/backend/internal/handler/gemini_client_cancel_test.go index aad811f025..6fda17db5a 100644 --- a/backend/internal/handler/gemini_client_cancel_test.go +++ b/backend/internal/handler/gemini_client_cancel_test.go @@ -34,11 +34,12 @@ func (u *clientCancelUpstream) Do(req *http.Request, _ string, _ int64, _ int) ( } type geminiClientCancelFixture struct { - handler *GatewayHandler - group *service.Group - apiKey *service.APIKey - upstream *clientCancelUpstream - ctx context.Context + handler *GatewayHandler + group *service.Group + apiKey *service.APIKey + upstream *clientCancelUpstream + schedulerCache *bucketRecordingSchedulerCache + ctx context.Context } func newGeminiClientCancelFixture(t *testing.T) *geminiClientCancelFixture { @@ -57,7 +58,8 @@ func newGeminiClientCancelFixture(t *testing.T) *geminiClientCancelFixture { Priority: 1, AccountGroups: []service.AccountGroup{{AccountID: accountID, GroupID: groupID}}, } - h, cleanup := newTestGatewayHandler(t, group, []*service.Account{account}) + schedulerCache := &bucketRecordingSchedulerCache{fakeSchedulerCache: &fakeSchedulerCache{accounts: []*service.Account{account}}} + h, cleanup := newTestGatewayHandlerWithSchedulerCache(t, group, schedulerCache) t.Cleanup(cleanup) ctx, cancel := context.WithCancel(context.Background()) @@ -69,7 +71,7 @@ func newGeminiClientCancelFixture(t *testing.T) *geminiClientCancelFixture { ID: 9202, UserID: 9203, GroupID: &groupID, Group: group, Status: service.StatusActive, User: &service.User{ID: 9203, Concurrency: 10, Balance: 100}, } - return &geminiClientCancelFixture{handler: h, group: group, apiKey: apiKey, upstream: upstream, ctx: ctx} + return &geminiClientCancelFixture{handler: h, group: group, apiKey: apiKey, upstream: upstream, schedulerCache: schedulerCache, ctx: ctx} } // serve 经 ops 错误日志中间件执行请求,返回响应与 ops 队列中的条目数。 diff --git a/backend/internal/handler/gemini_v1beta_handler.go b/backend/internal/handler/gemini_v1beta_handler.go index 95c550302e..ee2ee55583 100644 --- a/backend/internal/handler/gemini_v1beta_handler.go +++ b/backend/internal/handler/gemini_v1beta_handler.go @@ -546,12 +546,9 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { } fs := NewFailoverState(maxAccountSwitches, hasBoundSession) - // 单账号分组提前设置 SingleAccountRetry 标记,让 Service 层首次 503 就不设模型限流标记。 - // 避免单账号分组收到 503 (MODEL_CAPACITY_EXHAUSTED) 时设 29s 限流,导致后续请求连续快速失败。 - if h.gatewayService.IsSingleAntigravityAccountGroup(c.Request.Context(), apiKey.GroupID) { - ctx := service.WithSingleAccountRetry(c.Request.Context(), true, h.metadataBridgeEnabled()) - c.Request = c.Request.WithContext(ctx) - } + // 单账号分组首次 503 就不设模型限流标记,避免设 29s 限流导致后续请求连续快速失败; + // 是否单账号分组在 antigravity 账号遇到 503 或模型限流预检查时才判定。 + c.Request = c.Request.WithContext(h.gatewayService.WithSingleAntigravityAccountGroupProbe(c.Request.Context(), apiKey.GroupID)) for { excludedAccountIDs := fs.FailedAccountIDs diff --git a/backend/internal/handler/single_account_retry_probe_unit_test.go b/backend/internal/handler/single_account_retry_probe_unit_test.go new file mode 100644 index 0000000000..8b73067e25 --- /dev/null +++ b/backend/internal/handler/single_account_retry_probe_unit_test.go @@ -0,0 +1,120 @@ +//go:build unit + +package handler + +import ( + "bytes" + "context" + "net/http/httptest" + "sync" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// bucketRecordingSchedulerCache 记录读取过的快照桶平台。 +type bucketRecordingSchedulerCache struct { + *fakeSchedulerCache + mu sync.Mutex + platforms []string +} + +func (c *bucketRecordingSchedulerCache) GetSnapshot(ctx context.Context, bucket service.SchedulerBucket) ([]*service.Account, bool, error) { + c.mu.Lock() + c.platforms = append(c.platforms, bucket.Platform) + c.mu.Unlock() + return c.fakeSchedulerCache.GetSnapshot(ctx, bucket) +} + +func (c *bucketRecordingSchedulerCache) readPlatforms() []string { + c.mu.Lock() + defer c.mu.Unlock() + return append([]string(nil), c.platforms...) +} + +// 非 antigravity 账号的请求不读取单 antigravity 账号分组判定,选号之外不查询 antigravity 快照桶。 +func TestGeminiGroupRequestsDoNotReadAntigravityBucket(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + route string + path string + body string + call func(h *GatewayHandler) func(*gin.Context) + }{ + { + name: "gemini native", + route: "/v1beta/models/*modelAction", + path: "/v1beta/models/gemini-2.5-flash:generateContent", + body: `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`, + call: func(h *GatewayHandler) func(*gin.Context) { return h.GeminiV1BetaModels }, + }, + { + name: "messages on gemini group", + route: "/v1/messages", + path: "/v1/messages", + body: `{"model":"gemini-2.5-flash","max_tokens":16,"messages":[{"role":"user","content":"hi"}]}`, + call: func(h *GatewayHandler) func(*gin.Context) { return h.Messages }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f := newGeminiClientCancelFixture(t) + + f.serve(t, tt.route, tt.path, tt.body, tt.call(f.handler)) + + require.Equal(t, int32(1), f.upstream.calls.Load(), "请求应完成选号并到达上游") + platforms := f.schedulerCache.readPlatforms() + require.NotEmpty(t, platforms) + require.NotContains(t, platforms, service.PlatformAntigravity) + }) + } +} + +func TestMessagesAnthropicGroupDoesNotReadAntigravityBucket(t *testing.T) { + gin.SetMode(gin.TestMode) + groupID := int64(9400) + accountID := int64(9401) + group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive} + account := &service.Account{ + ID: accountID, + Platform: service.PlatformAnthropic, + Type: service.AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "test-key", "intercept_warmup_requests": true}, + Status: service.StatusActive, + Schedulable: true, + Concurrency: 1, + Priority: 1, + AccountGroups: []service.AccountGroup{{AccountID: accountID, GroupID: groupID}}, + } + schedulerCache := &bucketRecordingSchedulerCache{fakeSchedulerCache: &fakeSchedulerCache{accounts: []*service.Account{account}}} + h, cleanup := newTestGatewayHandlerWithSchedulerCache(t, group, schedulerCache) + t.Cleanup(cleanup) + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := `{"model":"claude-sonnet-4-5","max_tokens":256,"messages":[{"role":"user","content":[{"type":"text","text":"Warmup"}]}]}` + req := httptest.NewRequest("POST", "/v1/messages", bytes.NewBufferString(body)) + req.Header.Set("Content-Type", "application/json") + c.Request = req.WithContext(context.WithValue(req.Context(), ctxkey.Group, group)) + apiKey := &service.APIKey{ + ID: 9402, UserID: 9403, GroupID: &groupID, Group: group, Status: service.StatusActive, + User: &service.User{ID: 9403, Concurrency: 10, Balance: 100}, + } + c.Set(string(middleware.ContextKeyAPIKey), apiKey) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.UserID, Concurrency: 10}) + + h.Messages(c) + + require.Equal(t, 200, rec.Code) + selected, ok := c.Get(opsAccountIDKey) + require.True(t, ok) + require.Equal(t, accountID, selected) + platforms := schedulerCache.readPlatforms() + require.NotEmpty(t, platforms) + require.NotContains(t, platforms, service.PlatformAntigravity) +} diff --git a/backend/internal/service/antigravity_gateway_retry.go b/backend/internal/service/antigravity_gateway_retry.go index ee7a983481..9a317c1a06 100644 --- a/backend/internal/service/antigravity_gateway_retry.go +++ b/backend/internal/service/antigravity_gateway_retry.go @@ -850,10 +850,12 @@ func sleepAntigravityBackoffWithContext(ctx context.Context, attempt int) bool { } } -// isSingleAccountRetry 检查 context 中是否设置了单账号退避重试标记 +// isSingleAccountRetry 检查是否处于单账号退避重试模式:显式标记优先,否则使用请求挂载的延迟判定。 func isSingleAccountRetry(ctx context.Context) bool { - v, _ := SingleAccountRetryFromContext(ctx) - return v + if v, ok := SingleAccountRetryFromContext(ctx); ok { + return v + } + return singleAccountRetryProbeResult(ctx) } // setModelRateLimitByModelName 使用官方模型 ID 设置模型级限流 diff --git a/backend/internal/service/gateway_scheduling.go b/backend/internal/service/gateway_scheduling.go index 059d7e2b2c..c2c9f419c6 100644 --- a/backend/internal/service/gateway_scheduling.go +++ b/backend/internal/service/gateway_scheduling.go @@ -1122,10 +1122,22 @@ func (s *GatewayService) listSchedulableAccounts(ctx context.Context, groupID *i return accounts, useMixed, nil } -// IsSingleAntigravityAccountGroup 检查指定分组是否只有一个 antigravity 平台的可调度账号。 -// 用于 Handler 层在首次请求时提前设置 SingleAccountRetry context, -// 避免单账号分组收到 503 时错误地设置模型限流标记导致后续请求连续快速失败。 -func (s *GatewayService) IsSingleAntigravityAccountGroup(ctx context.Context, groupID *int64) bool { +// WithSingleAntigravityAccountGroupProbe 为请求挂载「分组是否只有一个 antigravity 可调度账号」的延迟判定。 +// 只有 antigravity 账号遇到 503 或模型限流预检查时才会查询;其他平台的请求不读取该判定。 +func (s *GatewayService) WithSingleAntigravityAccountGroupProbe(ctx context.Context, groupID *int64) context.Context { + var probeGroupID *int64 + if groupID != nil { + id := *groupID + probeGroupID = &id + } + return WithSingleAccountRetryProbe(ctx, func(probeCtx context.Context) bool { + return s.isSingleAntigravityAccountGroup(probeCtx, probeGroupID) + }) +} + +// isSingleAntigravityAccountGroup 检查指定分组是否只有一个 antigravity 平台的可调度账号。 +// 单账号分组收到 503 时原地重试而不设置模型限流,避免后续请求连续快速失败。 +func (s *GatewayService) isSingleAntigravityAccountGroup(ctx context.Context, groupID *int64) bool { accounts, _, err := s.listSchedulableAccounts(ctx, groupID, PlatformAntigravity, true) if err != nil { return false diff --git a/backend/internal/service/request_metadata.go b/backend/internal/service/request_metadata.go index 5c81bbf122..4a521c20f6 100644 --- a/backend/internal/service/request_metadata.go +++ b/backend/internal/service/request_metadata.go @@ -2,6 +2,7 @@ package service import ( "context" + "sync" "sync/atomic" "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" @@ -11,6 +12,15 @@ type requestMetadataContextKey struct{} var requestMetadataKey = requestMetadataContextKey{} +type singleAccountRetryProbeContextKey struct{} + +// singleAccountRetryProbe 在首次需要时判定是否进入单账号退避重试模式,同一请求内至多判定一次。 +type singleAccountRetryProbe struct { + once sync.Once + check func(ctx context.Context) bool + result bool +} + type RequestMetadata struct { IsMaxTokensOneHaikuRequest *bool ThinkingEnabled *bool @@ -107,6 +117,29 @@ func WithSingleAccountRetry(ctx context.Context, value bool, bridgeOldKeys bool) }) } +// WithSingleAccountRetryProbe 挂载单账号退避重试的延迟判定;显式设置的 SingleAccountRetry 标记优先于它。 +func WithSingleAccountRetryProbe(ctx context.Context, check func(ctx context.Context) bool) context.Context { + if ctx == nil || check == nil { + return ctx + } + return context.WithValue(ctx, singleAccountRetryProbeContextKey{}, &singleAccountRetryProbe{check: check}) +} + +func singleAccountRetryProbeResult(ctx context.Context) bool { + if ctx == nil { + return false + } + probe, _ := ctx.Value(singleAccountRetryProbeContextKey{}).(*singleAccountRetryProbe) + if probe == nil { + return false + } + // 判定结果在整个请求内复用,不能因调用时 ctx 已取消而被记成 false。 + probe.once.Do(func() { + probe.result = probe.check(context.WithoutCancel(ctx)) + }) + return probe.result +} + func WithAccountSwitchCount(ctx context.Context, value int, bridgeOldKeys bool) context.Context { return updateRequestMetadata(ctx, bridgeOldKeys, func(md *RequestMetadata) { v := value diff --git a/backend/internal/service/single_account_retry_probe_test.go b/backend/internal/service/single_account_retry_probe_test.go new file mode 100644 index 0000000000..660762b908 --- /dev/null +++ b/backend/internal/service/single_account_retry_probe_test.go @@ -0,0 +1,191 @@ +//go:build unit + +package service + +import ( + "context" + "net/http" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/stretchr/testify/require" +) + +func TestIsSingleAccountRetry_ProbeEvaluatedLazilyOnce(t *testing.T) { + calls := 0 + ctx := WithSingleAccountRetryProbe(context.Background(), func(context.Context) bool { + calls++ + return true + }) + require.Zero(t, calls, "挂载时不应判定") + + require.True(t, isSingleAccountRetry(ctx)) + require.True(t, isSingleAccountRetry(ctx)) + require.Equal(t, 1, calls, "同一请求内只判定一次") +} + +func TestIsSingleAccountRetry_ProbeFalse(t *testing.T) { + ctx := WithSingleAccountRetryProbe(context.Background(), func(context.Context) bool { return false }) + require.False(t, isSingleAccountRetry(ctx)) +} + +func TestIsSingleAccountRetry_ExplicitFlagOverridesProbe(t *testing.T) { + calls := 0 + probe := func(context.Context) bool { + calls++ + return false + } + + ctx := WithSingleAccountRetryProbe(context.Background(), probe) + ctx = WithSingleAccountRetry(ctx, true, false) + require.True(t, isSingleAccountRetry(ctx)) + + legacy := context.WithValue(WithSingleAccountRetryProbe(context.Background(), probe), ctxkey.SingleAccountRetry, true) + require.True(t, isSingleAccountRetry(legacy)) + + explicitFalse := WithSingleAccountRetry(WithSingleAccountRetryProbe(context.Background(), func(context.Context) bool { + calls++ + return true + }), false, false) + require.False(t, isSingleAccountRetry(explicitFalse)) + + require.Zero(t, calls, "显式标记存在时不应触发判定") +} + +func TestIsSingleAccountRetry_ProbeIgnoresCanceledContext(t *testing.T) { + ctx, cancel := context.WithCancel(WithSingleAccountRetryProbe(context.Background(), func(probeCtx context.Context) bool { + return probeCtx.Err() == nil + })) + cancel() + require.True(t, isSingleAccountRetry(ctx)) +} + +func TestIsSingleAccountRetry_ProbeSurvivesMetadataUpdates(t *testing.T) { + ctx := WithSingleAccountRetryProbe(context.Background(), func(context.Context) bool { return true }) + ctx = WithAccountSwitchCount(ctx, 1, false) + ctx = WithThinkingEnabled(ctx, true, false) + require.True(t, isSingleAccountRetry(ctx)) +} + +// groupRecordingAccountRepo 记录单平台分组查询的分组与平台。 +type groupRecordingAccountRepo struct { + *mockAccountRepoForPlatform + groupIDs []int64 + platforms []string +} + +func (r *groupRecordingAccountRepo) ListSchedulableByGroupIDAndPlatform(ctx context.Context, groupID int64, platform string) ([]Account, error) { + r.groupIDs = append(r.groupIDs, groupID) + r.platforms = append(r.platforms, platform) + return r.mockAccountRepoForPlatform.ListSchedulableByGroupIDAndPlatform(ctx, groupID, platform) +} + +func newSingleAntigravityProbeTestService(accounts ...Account) (*GatewayService, *groupRecordingAccountRepo) { + repo := &groupRecordingAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{accounts: accounts}} + return &GatewayService{accountRepo: repo}, repo +} + +func probeTestAccount(id int64, platform string) Account { + return Account{ID: id, Platform: platform, Status: StatusActive, Schedulable: true} +} + +func TestWithSingleAntigravityAccountGroupProbe_QueriesOnlyWhenRead(t *testing.T) { + svc, repo := newSingleAntigravityProbeTestService(probeTestAccount(1, PlatformAntigravity)) + groupID := int64(42) + + ctx := svc.WithSingleAntigravityAccountGroupProbe(context.Background(), &groupID) + require.Empty(t, repo.groupIDs, "挂载时不应查询账号") + + require.True(t, isSingleAccountRetry(ctx)) + require.True(t, isSingleAccountRetry(ctx)) + require.Equal(t, []int64{42}, repo.groupIDs) + require.Equal(t, []string{PlatformAntigravity}, repo.platforms) +} + +func TestWithSingleAntigravityAccountGroupProbe_UsesGroupAtMountTime(t *testing.T) { + svc, repo := newSingleAntigravityProbeTestService(probeTestAccount(1, PlatformAntigravity)) + groupID := int64(42) + + ctx := svc.WithSingleAntigravityAccountGroupProbe(context.Background(), &groupID) + groupID = 99 + + require.True(t, isSingleAccountRetry(ctx)) + require.Equal(t, []int64{42}, repo.groupIDs) +} + +func TestWithSingleAntigravityAccountGroupProbe_CountsOnlyAntigravityAccounts(t *testing.T) { + groupID := int64(42) + tests := []struct { + name string + accounts []Account + want bool + }{ + {name: "no antigravity accounts", accounts: []Account{probeTestAccount(1, PlatformGemini)}, want: false}, + {name: "single antigravity account", accounts: []Account{probeTestAccount(1, PlatformAntigravity), probeTestAccount(2, PlatformGemini)}, want: true}, + {name: "two antigravity accounts", accounts: []Account{probeTestAccount(1, PlatformAntigravity), probeTestAccount(2, PlatformAntigravity)}, want: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + svc, _ := newSingleAntigravityProbeTestService(tt.accounts...) + ctx := svc.WithSingleAntigravityAccountGroupProbe(context.Background(), &groupID) + require.Equal(t, tt.want, isSingleAccountRetry(ctx)) + }) + } +} + +func runRateLimitedPreCheckWithProbe(t *testing.T, single bool) (*antigravityRetryLoopResult, *recordingOKUpstream, error) { + t.Helper() + upstream := &recordingOKUpstream{} + account := &Account{ + ID: 30, + Type: AccountTypeOAuth, + Platform: PlatformAntigravity, + Schedulable: true, + Status: StatusActive, + Concurrency: 1, + Extra: map[string]any{ + modelRateLimitsKey: map[string]any{ + "claude-sonnet-4-5": map[string]any{ + "rate_limit_reset_at": time.Now().Add(30 * time.Second).Format(time.RFC3339), + }, + }, + }, + } + ctx := WithSingleAccountRetryProbe(context.Background(), func(context.Context) bool { return single }) + svc := &AntigravityGatewayService{} + result, err := svc.antigravityRetryLoop(antigravityRetryLoopParams{ + ctx: ctx, + prefix: "[test]", + account: account, + accessToken: "token", + action: "generateContent", + body: []byte(`{"input":"test"}`), + httpUpstream: upstream, + requestedModel: "claude-sonnet-4-5", + handleError: func(ctx context.Context, prefix string, account *Account, statusCode int, headers http.Header, body []byte, requestedModel string, groupID int64, sessionHash string, isStickySession bool) *handleModelRateLimitResult { + return nil + }, + }) + return result, upstream, err +} + +func TestAntigravityRetryLoop_PreCheck_ProbeSingleAccount_SkipsRateLimit(t *testing.T) { + result, upstream, err := runRateLimitedPreCheckWithProbe(t, true) + + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, result.resp) + require.Equal(t, http.StatusOK, result.resp.StatusCode) + require.Equal(t, 1, upstream.calls) +} + +func TestAntigravityRetryLoop_PreCheck_ProbeMultiAccount_SwitchesOnRateLimit(t *testing.T) { + result, upstream, err := runRateLimitedPreCheckWithProbe(t, false) + + require.Nil(t, result) + var switchErr *AntigravityAccountSwitchError + require.ErrorAs(t, err, &switchErr) + require.Equal(t, "claude-sonnet-4-5", switchErr.RateLimitedModel) + require.Zero(t, upstream.calls) +} From 53002f677c3d8e182ba11858e00b301079107f6e Mon Sep 17 00:00:00 2001 From: feeeei Date: Tue, 20 Oct 2026 20:33:13 +0800 Subject: [PATCH 018/297] =?UTF-8?q?perf(scheduler):=20=E8=B0=83=E5=BA=A6?= =?UTF-8?q?=E5=BF=AB=E7=85=A7=E8=A7=A3=E7=A0=81=E7=BB=93=E6=9E=9C=E5=B8=B8?= =?UTF-8?q?=E9=A9=BB=E8=BF=9B=E7=A8=8B=E5=86=85=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GetSnapshot 每次选号都 ZRANGE 全组账号 ID、分块 MGET 全组 sched:meta 并逐条 JSON 解码,Redis 出口、CPU 与 GC 都随分组号数线性增长。 - 每个 bucket 的解码结果常驻进程内存。每次读取用一次 MGET 取 ready、 active、全局修订号与 bucket 平台修订号(mixed 另加 antigravity),全部与 条目一致且条目未超过 10 秒才复用,否则重新加载。last_used 仍每次读取, 套用在本次调用独占的副本上,LRU 语义不变。 - 修订号是随机串:精简记录改写后写入所涉平台的修订号,与最后一批写入同一 pipeline 发出;删除记录、账号平台变化(SET ... GET 取回旧值比对)、 写入出错时写入全局修订号,出错路径在后台合并写入。 - 母本发布前预解析模型映射;副本在指针、长度与运行时版本都匹配时直接复用, 不计算签名。 - 未命中、空快照、记录缺失、解码失败、Redis 出错的返回与原实现一致;选中后 的整账号读取仍每次重新解码,转发路径对账号的原地修改不触及常驻对象。 真实 Redis 端到端(SelectAccountWithLoadAwareness,本机): 100 号:3.83ms → 0.73ms,Redis 出口 251KB → 7.0KB,分配 2.03MB → 0.23MB 1000 号:27.8ms → 1.92ms,Redis 出口 2.47MB → 25KB,分配 20.2MB → 1.97MB 每次都未命中:100 号 3.83ms → 3.10ms,1000 号 27.6ms → 21.9ms 常驻内存约为每号 7KB × 活跃 bucket 数;闲置超过 100 秒的条目在写入新 条目时清除。 --- .../internal/repository/scheduler_cache.go | 378 ++++++- ...scheduler_cache_snapshot_memo_unit_test.go | 980 ++++++++++++++++++ backend/internal/service/account.go | 21 + .../service/account_shared_snapshot_test.go | 82 ++ .../model_rate_limit_snapshot_cow_test.go | 2 + backend/internal/service/scheduler_cache.go | 2 + 6 files changed, 1422 insertions(+), 43 deletions(-) create mode 100644 backend/internal/repository/scheduler_cache_snapshot_memo_unit_test.go create mode 100644 backend/internal/service/account_shared_snapshot_test.go diff --git a/backend/internal/repository/scheduler_cache.go b/backend/internal/repository/scheduler_cache.go index 827a750577..2aa73c61ea 100644 --- a/backend/internal/repository/scheduler_cache.go +++ b/backend/internal/repository/scheduler_cache.go @@ -5,13 +5,18 @@ import ( "crypto/rand" "encoding/hex" "encoding/json" + "errors" "fmt" "log/slog" + "slices" "strconv" + "sync" + "sync/atomic" "time" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/redis/go-redis/v9" + "github.com/tidwall/gjson" ) const ( @@ -27,6 +32,12 @@ const ( schedulerRetiredPrefix = "sched:retired:" schedulerSnapshotPrefix = "sched:" schedulerLockPrefix = "sched:lock:" + // 账号精简记录(sched:meta:)的修订号:全局修订号与按平台划分的修订号(前缀后接平台名)。 + // 改写精简记录后写入所涉平台的修订号;删除记录、改写平台为空或平台发生变化的记录、写入出错时写入全局修订号。 + // 取值都是新的随机串,读侧只比较是否相等,键丢失后重建也不会与旧取值相同; + // Redis 回滚恢复出缓存记录过的旧取值时,由最长复用时长兜底。 + schedulerAccountMetaRevisionKey = "sched:meta:rev" + schedulerAccountMetaPlatformRevisionPrefix = "sched:meta:rev:" defaultSchedulerSnapshotMGetChunkSize = 128 defaultSchedulerSnapshotWriteChunkSize = 256 @@ -35,6 +46,16 @@ const ( // snapshotGraceTTLSeconds 旧快照过期的宽限期(秒)。 // 替代立即 DEL,让正在读取旧版本的 reader 有足够时间完成 ZRANGE。 snapshotGraceTTLSeconds = 60 + + // schedulerSnapshotCacheMaxAge 是进程内快照缓存条目的最长复用时长, + // 限定了未推进修订号的精简记录改写在本进程的最长可见延迟,与 outbox_lag_rebuild_seconds 默认 10 秒的陈旧容忍度相同。 + schedulerSnapshotCacheMaxAge = 10 * time.Second + // schedulerSnapshotCacheEvictAge:写入条目时,加载时间早于该时长的其它条目一并清除, + // 已退休分组的条目不会长期驻留。 + schedulerSnapshotCacheEvictAge = 10 * schedulerSnapshotCacheMaxAge + + schedulerAccountMetaRevisionBytes = 16 + schedulerAccountMetaRevisionWriteTimeout = 3 * time.Second ) const ( @@ -223,6 +244,28 @@ type schedulerCache struct { rdb *redis.Client mgetChunkSize int writeChunkSize int + + // now 是进程内快照缓存判定条目年龄的时钟。 + now func() time.Time + + snapshotMu sync.RWMutex + snapshotEntries map[string]*schedulerSnapshotEntry + + // globalRevisionPending 与 globalRevisionWriting 合并写入出错后的后台全局修订号写入,见 scheduleGlobalAccountMetaRevision。 + globalRevisionPending atomic.Bool + globalRevisionWriting atomic.Bool +} + +// schedulerSnapshotEntry 是一个 bucket 的已解码快照。 +// revisions 依次是全局修订号与该 bucket 成员可能涉及的各平台修订号(见 schedulerSnapshotTagKeys)。 +// accounts 是按快照顺序排列的母本,发布后只读,指针不外泄; +// 每次读取都按值复制出本次请求独占的副本再套用 last_used。 +type schedulerSnapshotEntry struct { + active string + revisions []string + loadedAt time.Time + accounts []*service.Account + lastUsedKeys []string } func NewSchedulerCache(rdb *redis.Client) service.SchedulerCache { @@ -237,42 +280,67 @@ func newSchedulerCacheWithChunkSizes(rdb *redis.Client, mgetChunkSize, writeChun writeChunkSize = defaultSchedulerSnapshotWriteChunkSize } return &schedulerCache{ - rdb: rdb, - mgetChunkSize: mgetChunkSize, - writeChunkSize: writeChunkSize, + rdb: rdb, + mgetChunkSize: mgetChunkSize, + writeChunkSize: writeChunkSize, + now: time.Now, + snapshotEntries: make(map[string]*schedulerSnapshotEntry), } } +// GetSnapshot 读取 bucket 的激活快照。解码后的精简记录按 bucket 常驻进程内存, +// 只有 ready、active 版本、全局修订号与该 bucket 所涉平台的修订号都与 Redis 一致且未超过最长复用时长时才复用; +// 否则重新从 Redis 加载。last_used 每次都从 Redis 读取。 +// 返回的账号对象由本次调用独占,可以修改其顶层字段;map、切片底层数组与指针指向的值与其它调用共享,不得原地修改。 func (c *schedulerCache) GetSnapshot(ctx context.Context, bucket service.SchedulerBucket) ([]*service.Account, bool, error) { - readyKey := schedulerBucketKey(schedulerReadyPrefix, bucket) - readyVal, err := c.rdb.Get(ctx, readyKey).Result() - if err == redis.Nil { - return nil, false, nil - } + bucketKey := bucket.String() + tagKeys := schedulerSnapshotTagKeys(bucket) + tags, err := c.rdb.MGet(ctx, tagKeys...).Result() if err != nil { return nil, false, err } - if readyVal != "1" { - return nil, false, nil - } - - activeKey := schedulerBucketKey(schedulerActivePrefix, bucket) - activeVal, err := c.rdb.Get(ctx, activeKey).Result() - if err == redis.Nil { - return nil, false, nil + if len(tags) != len(tagKeys) { + return nil, false, fmt.Errorf("unexpected scheduler snapshot tag count: got %d, want %d", len(tags), len(tagKeys)) } + readyVal, err := schedulerCacheOptionalString(tags[0]) if err != nil { return nil, false, err } + activeVal, err := schedulerCacheOptionalString(tags[1]) + if err != nil { + return nil, false, err + } + // 修订号缺失(nil)按空字符串比较:它是一个独立取值,不会与任何写入过的随机修订号相等。 + revisions := make([]string, 0, len(tags)-2) + for _, tag := range tags[2:] { + revision, err := schedulerCacheOptionalString(tag) + if err != nil { + return nil, false, err + } + revisions = append(revisions, revision) + } + if readyVal != "1" || activeVal == "" { + c.dropSnapshotEntry(bucketKey) + return nil, false, nil + } - snapshotKey := schedulerSnapshotKey(bucket, activeVal) - ids, err := c.rdb.ZRange(ctx, snapshotKey, 0, -1).Result() + now := c.now() + if entry := c.lookupSnapshotEntry(bucketKey); entry != nil && entry.matches(activeVal, revisions, now) { + accounts, err := c.snapshotAccountsFromEntry(ctx, entry) + if err != nil { + return nil, false, err + } + return accounts, true, nil + } + + ids, err := c.rdb.ZRange(ctx, schedulerSnapshotKey(bucket, activeVal), 0, -1).Result() if err != nil { return nil, false, err } if len(ids) == 0 { // 空快照视为缓存未命中,触发数据库回退查询 // 这解决了新分组创建后立即绑定账号时的竞态条件问题 + c.dropSnapshotEntry(bucketKey) return nil, false, nil } @@ -286,29 +354,143 @@ func (c *schedulerCache) GetSnapshot(ctx context.Context, bucket service.Schedul if err != nil { return nil, false, err } - lastUsedValues, err := c.mgetChunked(ctx, lastUsedKeys) - if err != nil { - return nil, false, err - } - accounts := make([]*service.Account, 0, len(values)) - for i, val := range values { + masters := make([]*service.Account, 0, len(values)) + for _, val := range values { if val == nil { + c.dropSnapshotEntry(bucketKey) return nil, false, nil } account, err := decodeCachedAccount(val) if err != nil { return nil, false, err } - if err := applySchedulerLastUsed(account, lastUsedValues[i]); err != nil { - return nil, false, err - } - accounts = append(accounts, account) + masters = append(masters, account) + } + // 母本发布进缓存前由本 goroutine 完成预处理,发布后只读。 + for _, master := range masters { + master.PrepareSharedSnapshot() } + // 条目记录的是加载前读到的 (active, 修订号) 与当时的时钟:精简记录读取晚于这组取值, + // 之后若再有改写,修订号或 active 必然不同,或在最长复用时长后过期。 + entry := &schedulerSnapshotEntry{ + active: activeVal, + revisions: revisions, + loadedAt: now, + accounts: masters, + lastUsedKeys: lastUsedKeys, + } + c.storeSnapshotEntry(bucketKey, entry) + + accounts, err := c.snapshotAccountsFromEntry(ctx, entry) + if err != nil { + return nil, false, err + } return accounts, true, nil } +func (e *schedulerSnapshotEntry) matches(active string, revisions []string, now time.Time) bool { + if e.active != active || !slices.Equal(e.revisions, revisions) { + return false + } + age := now.Sub(e.loadedAt) + return age >= 0 && age < schedulerSnapshotCacheMaxAge +} + +// snapshotAccountsFromEntry 读取最新 last_used,并为本次调用一次性分配一组母本副本。 +func (c *schedulerCache) snapshotAccountsFromEntry(ctx context.Context, entry *schedulerSnapshotEntry) ([]*service.Account, error) { + lastUsedValues, err := c.mgetChunked(ctx, entry.lastUsedKeys) + if err != nil { + return nil, err + } + if len(lastUsedValues) != len(entry.accounts) { + return nil, fmt.Errorf("unexpected scheduler last_used value count: got %d, want %d", len(lastUsedValues), len(entry.accounts)) + } + slab := make([]service.Account, len(entry.accounts)) + accounts := make([]*service.Account, len(entry.accounts)) + for i, master := range entry.accounts { + slab[i] = *master + account := &slab[i] + if err := applySchedulerLastUsed(account, lastUsedValues[i]); err != nil { + return nil, err + } + accounts[i] = account + } + return accounts, nil +} + +func (c *schedulerCache) lookupSnapshotEntry(bucketKey string) *schedulerSnapshotEntry { + c.snapshotMu.RLock() + defer c.snapshotMu.RUnlock() + return c.snapshotEntries[bucketKey] +} + +// storeSnapshotEntry 写入条目,并清除加载时间早于 schedulerSnapshotCacheEvictAge 的其它条目。 +// 已有条目的加载时间晚于新条目时保留已有条目:它基于更晚读到的 (active, 修订号)。 +func (c *schedulerCache) storeSnapshotEntry(bucketKey string, entry *schedulerSnapshotEntry) { + c.snapshotMu.Lock() + defer c.snapshotMu.Unlock() + if current := c.snapshotEntries[bucketKey]; current == nil || !current.loadedAt.After(entry.loadedAt) { + c.snapshotEntries[bucketKey] = entry + } + for key, other := range c.snapshotEntries { + if key != bucketKey && entry.loadedAt.Sub(other.loadedAt) > schedulerSnapshotCacheEvictAge { + delete(c.snapshotEntries, key) + } + } +} + +func (c *schedulerCache) dropSnapshotEntry(bucketKey string) { + c.snapshotMu.RLock() + _, ok := c.snapshotEntries[bucketKey] + c.snapshotMu.RUnlock() + if !ok { + return + } + c.snapshotMu.Lock() + delete(c.snapshotEntries, bucketKey) + c.snapshotMu.Unlock() +} + +// schedulerSnapshotTagKeys 返回 GetSnapshot 一次读取的键:ready、active、全局修订号、bucket 平台的修订号, +// mixed 模式再加 antigravity 平台的修订号。按平台判定失效依赖 bucket 成员只取自 bucket 平台 +// (mixed 模式另含开启混合调度的 antigravity 账号);账号平台发生变化时,写入方另行写入全局修订号。 +func schedulerSnapshotTagKeys(bucket service.SchedulerBucket) []string { + keys := make([]string, 0, 5) + keys = append(keys, + schedulerBucketKey(schedulerReadyPrefix, bucket), + schedulerBucketKey(schedulerActivePrefix, bucket), + schedulerAccountMetaRevisionKey, + schedulerAccountMetaRevisionKeyForPlatform(bucket.Platform), + ) + if bucket.Mode == service.SchedulerModeMixed && bucket.Platform != service.PlatformAntigravity { + keys = append(keys, schedulerAccountMetaRevisionKeyForPlatform(service.PlatformAntigravity)) + } + return keys +} + +// schedulerAccountMetaRevisionKeyForPlatform 返回平台修订号的键;平台为空时返回全局修订号的键。 +func schedulerAccountMetaRevisionKeyForPlatform(platform string) string { + if platform == "" { + return schedulerAccountMetaRevisionKey + } + return schedulerAccountMetaPlatformRevisionPrefix + platform +} + +func schedulerCacheOptionalString(value any) (string, error) { + switch typed := value.(type) { + case nil: + return "", nil + case string: + return typed, nil + case []byte: + return string(typed), nil + default: + return "", fmt.Errorf("unexpected scheduler cache value type: %T", value) + } +} + func (c *schedulerCache) CaptureBucketWriteToken(ctx context.Context, bucket service.SchedulerBucket) (service.SchedulerBucketWriteToken, error) { result, err := captureBucketWriteTokenScript.Run(ctx, c.rdb, []string{ schedulerBucketKey(schedulerEpochPrefix, bucket), @@ -604,7 +786,13 @@ func (c *schedulerCache) DeleteAccount(ctx context.Context, accountID int64) err return nil } id := strconv.FormatInt(accountID, 10) - return c.rdb.Del(ctx, schedulerAccountKey(id), schedulerAccountMetaKey(id), schedulerLastUsedKey(id)).Err() + // 删除精简记录与推进全局修订号在同一个 MULTI 中原子执行:读到删除结果的读者也读到新修订号, + // 进程内快照缓存不会给出已删除的账号。 + pipe := c.rdb.TxPipeline() + pipe.Del(ctx, schedulerAccountKey(id), schedulerAccountMetaKey(id), schedulerLastUsedKey(id)) + pipe.Set(ctx, schedulerAccountMetaRevisionKey, newSchedulerAccountMetaRevision(), 0) + _, err := pipe.Exec(ctx) + return err } func (c *schedulerCache) UpdateLastUsed(ctx context.Context, updates map[int64]time.Time) error { @@ -614,6 +802,7 @@ func (c *schedulerCache) UpdateLastUsed(ctx context.Context, updates map[int64]t pipe := c.rdb.Pipeline() queued := 0 + metaDeleted := false keys := make([]string, 0, schedulerLastUsedUpdateChunkSize*2) args := make([]any, 0, schedulerLastUsedUpdateChunkSize) queueBatch := func() { @@ -638,6 +827,7 @@ func (c *schedulerCache) UpdateLastUsed(ctx context.Context, updates map[int64]t idText := strconv.FormatInt(id, 10) pipe.Del(ctx, schedulerAccountKey(idText), schedulerAccountMetaKey(idText), schedulerLastUsedKey(idText)) queued++ + metaDeleted = true continue } idText := strconv.FormatInt(id, 10) @@ -651,6 +841,10 @@ func (c *schedulerCache) UpdateLastUsed(ctx context.Context, updates map[int64]t if queued == 0 { return nil } + if metaDeleted { + // 被删账号的平台未知,全局修订号排在同一 pipeline 的 DEL 之后。 + pipe.Set(ctx, schedulerAccountMetaRevisionKey, newSchedulerAccountMetaRevision(), 0) + } _, err := pipe.Exec(ctx) return err } @@ -776,21 +970,53 @@ func decodeCachedAccount(val any) (*service.Account, error) { return &account, nil } +// writeAccountIDs 分块写入整账号与精简记录,返回成功编码并写入的有序账号 ID。 +// 每块在追加下一个账号前才执行,最后一块总是非空;所涉平台的修订号追加在最后一块末尾, +// 与最后一批精简记录同一次往返发出,且排在全部精简记录写入之后。 +// 精简记录用 SET ... GET 写入并取回旧值:旧值的平台与新平台不同时,旧平台 bucket 中可能仍缓存着该账号, +// 全部写入完成后另行写入全局修订号。该检测尽力而为(客户端在 pipeline 内部重试时取回的可能已是本次写入的值), +// 漏检由进程内快照缓存的最长复用时长兜底。 +// 任一块执行出错时,此前已执行的块与出错的块都可能已有精简记录生效,返回时启动后台写入全局修订号。 func (c *schedulerCache) writeAccountIDs(ctx context.Context, accounts []service.Account) ([]int64, error) { if len(accounts) == 0 { return nil, nil } + type metaWrite struct { + platform string + previous *redis.StatusCmd + } pipe := c.rdb.Pipeline() accountIDs := make([]int64, 0, len(accounts)) + platforms := make([]string, 0, 1) + writes := make([]metaWrite, 0, min(len(accounts), c.writeChunkSize)) pending := 0 - flush := func() error { - if pending == 0 { - return nil + execFailed := false + platformChanged := false + defer func() { + if execFailed { + c.scheduleGlobalAccountMetaRevision(ctx) } - if _, err := pipe.Exec(ctx); err != nil { + }() + exec := func() error { + cmds, err := pipe.Exec(ctx) + if err != nil && !errors.Is(err, redis.Nil) { + execFailed = true return err } + // SET ... GET 在键原本不存在时返回 redis.Nil,不算失败;其余命令的错误逐条检查。 + for _, cmd := range cmds { + if cmdErr := cmd.Err(); cmdErr != nil && !errors.Is(cmdErr, redis.Nil) { + execFailed = true + return cmdErr + } + } + for _, write := range writes { + if schedulerMetaPlatformChanged(write.previous, write.platform) { + platformChanged = true + } + } + writes = writes[:0] pipe = c.rdb.Pipeline() pending = 0 return nil @@ -805,27 +1031,93 @@ func (c *schedulerCache) writeAccountIDs(ctx context.Context, accounts []service ) continue } - - id := strconv.FormatInt(account.ID, 10) - pipe.Set(ctx, schedulerAccountKey(id), fullPayload, 0) - pipe.Set(ctx, schedulerAccountMetaKey(id), metaPayload, 0) - // Keep the hot LastUsedAt side key untouched: a lagging snapshot rebuild - // must not overwrite a newer scheduler update. - accountIDs = append(accountIDs, account.ID) - pending++ if pending >= c.writeChunkSize { - if err := flush(); err != nil { + if err := exec(); err != nil { return nil, err } } + + id := strconv.FormatInt(account.ID, 10) + pipe.Set(ctx, schedulerAccountKey(id), fullPayload, 0) + writes = append(writes, metaWrite{ + platform: account.Platform, + previous: pipe.SetArgs(ctx, schedulerAccountMetaKey(id), metaPayload, redis.SetArgs{Get: true}), + }) + // Keep the hot LastUsedAt side key untouched: a lagging snapshot rebuild + // must not overwrite a newer scheduler update. + accountIDs = append(accountIDs, account.ID) + if !slices.Contains(platforms, account.Platform) { + platforms = append(platforms, account.Platform) + } + pending++ } - if err := flush(); err != nil { + if pending == 0 { + return accountIDs, nil + } + for _, platform := range platforms { + pipe.Set(ctx, schedulerAccountMetaRevisionKeyForPlatform(platform), newSchedulerAccountMetaRevision(), 0) + } + if err := exec(); err != nil { return nil, err } + if platformChanged { + c.advanceGlobalAccountMetaRevision(ctx) + } return accountIDs, nil } +// schedulerMetaPlatformChanged 判断 SET ... GET 取回的旧精简记录是否属于另一个平台; +// 旧值不是合法 JSON 或缺少字符串类型的顶层 Platform 时按已变化处理。 +func schedulerMetaPlatformChanged(previous *redis.StatusCmd, platform string) bool { + raw, err := previous.Result() + if err != nil { + return false + } + if !gjson.Valid(raw) { + return true + } + old := gjson.Get(raw, "Platform") + return old.Type != gjson.String || old.Str != platform +} + +// scheduleGlobalAccountMetaRevision 在后台写入全局修订号,不阻塞调用方。 +// 同一时刻至多一个后台写入:写入前先清除待写标记,写完后标记再次被置位就再写一轮, +// 因此每次调用之后都至少还有一次完整的写入发生在它之后。 +func (c *schedulerCache) scheduleGlobalAccountMetaRevision(ctx context.Context) { + c.globalRevisionPending.Store(true) + if !c.globalRevisionWriting.CompareAndSwap(false, true) { + return + } + go func() { + for { + c.globalRevisionPending.Store(false) + c.advanceGlobalAccountMetaRevision(ctx) + c.globalRevisionWriting.Store(false) + if !c.globalRevisionPending.Load() || !c.globalRevisionWriting.CompareAndSwap(false, true) { + return + } + } + }() +} + +// advanceGlobalAccountMetaRevision 单独写入新的全局修订号,使所有 bucket 的进程内快照失效。 +// 不受调用方取消影响;失败只记录日志,由进程内快照缓存的最长复用时长兜底。 +func (c *schedulerCache) advanceGlobalAccountMetaRevision(ctx context.Context) { + writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), schedulerAccountMetaRevisionWriteTimeout) + defer cancel() + if err := c.rdb.Set(writeCtx, schedulerAccountMetaRevisionKey, newSchedulerAccountMetaRevision(), 0).Err(); err != nil { + slog.Warn("scheduler cache failed to advance account metadata revision", "error", err) + } +} + +func newSchedulerAccountMetaRevision() string { + raw := make([]byte, schedulerAccountMetaRevisionBytes) + // crypto/rand.Read 读取失败时直接终止进程,不会返回错误。 + _, _ = rand.Read(raw) + return hex.EncodeToString(raw) +} + func marshalSchedulerCacheAccount(account service.Account) ([]byte, []byte, error) { fullPayload, err := json.Marshal(account) if err != nil { diff --git a/backend/internal/repository/scheduler_cache_snapshot_memo_unit_test.go b/backend/internal/repository/scheduler_cache_snapshot_memo_unit_test.go new file mode 100644 index 0000000000..9b3d92ea26 --- /dev/null +++ b/backend/internal/repository/scheduler_cache_snapshot_memo_unit_test.go @@ -0,0 +1,980 @@ +//go:build unit + +package repository + +import ( + "context" + "errors" + "fmt" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/alicebob/miniredis/v2" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" +) + +// schedulerCacheCommandRecorder 记录发往 Redis 的命令(名称 + 首个参数)与每次 pipeline 执行的命令批次, +// 并可让第 N 次 pipeline 执行失败。新连接的握手命令不计入。 +type schedulerCacheCommandRecorder struct { + mu sync.Mutex + commands []string + batches [][]string + pipelines int + failPipelineAt int +} + +func (r *schedulerCacheCommandRecorder) DialHook(next redis.DialHook) redis.DialHook { return next } + +func (r *schedulerCacheCommandRecorder) ProcessHook(next redis.ProcessHook) redis.ProcessHook { + return func(ctx context.Context, cmd redis.Cmder) error { + if !isSchedulerCacheHandshakeCommand(cmd) { + r.record(cmd) + } + return next(ctx, cmd) + } +} + +func (r *schedulerCacheCommandRecorder) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook { + return func(ctx context.Context, cmds []redis.Cmder) error { + handshake := len(cmds) > 0 + for _, cmd := range cmds { + handshake = handshake && isSchedulerCacheHandshakeCommand(cmd) + } + if handshake { + return next(ctx, cmds) + } + r.mu.Lock() + r.pipelines++ + fail := r.failPipelineAt > 0 && r.pipelines == r.failPipelineAt + r.mu.Unlock() + batch := make([]string, 0, len(cmds)) + for _, cmd := range cmds { + batch = append(batch, r.record(cmd)) + } + r.mu.Lock() + r.batches = append(r.batches, batch) + r.mu.Unlock() + if fail { + err := errors.New("injected pipeline failure") + for _, cmd := range cmds { + cmd.SetErr(err) + } + return err + } + return next(ctx, cmds) + } +} + +func isSchedulerCacheHandshakeCommand(cmd redis.Cmder) bool { + switch strings.ToLower(cmd.Name()) { + case "hello", "auth", "client", "select": + return true + default: + return false + } +} + +func (r *schedulerCacheCommandRecorder) record(cmd redis.Cmder) string { + entry := strings.ToLower(cmd.Name()) + if args := cmd.Args(); len(args) > 1 { + entry += " " + fmt.Sprint(args[1]) + } + r.mu.Lock() + r.commands = append(r.commands, entry) + r.mu.Unlock() + return entry +} + +func (r *schedulerCacheCommandRecorder) reset() { + r.mu.Lock() + r.commands = nil + r.batches = nil + r.pipelines = 0 + r.mu.Unlock() +} + +func (r *schedulerCacheCommandRecorder) pipelineBatches() [][]string { + r.mu.Lock() + defer r.mu.Unlock() + return append([][]string(nil), r.batches...) +} + +func (r *schedulerCacheCommandRecorder) setFailPipelineAt(n int) { + r.mu.Lock() + r.failPipelineAt = n + r.mu.Unlock() +} + +func (r *schedulerCacheCommandRecorder) recorded() []string { + r.mu.Lock() + defer r.mu.Unlock() + return append([]string(nil), r.commands...) +} + +func (r *schedulerCacheCommandRecorder) countPrefix(prefix string) int { + count := 0 + for _, command := range r.recorded() { + if strings.HasPrefix(command, prefix) { + count++ + } + } + return count +} + +func newSchedulerCacheMemoUnit(t *testing.T, writeChunkSize int) (*schedulerCache, *miniredis.Miniredis, *schedulerCacheCommandRecorder) { + t.Helper() + mr := miniredis.RunT(t) + rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()}) + t.Cleanup(func() { _ = rdb.Close() }) + recorder := &schedulerCacheCommandRecorder{} + rdb.AddHook(recorder) + cache, ok := newSchedulerCacheWithChunkSizes(rdb, defaultSchedulerSnapshotMGetChunkSize, writeChunkSize).(*schedulerCache) + require.True(t, ok) + return cache, mr, recorder +} + +func memoTestBucket(groupID int64) service.SchedulerBucket { + return service.SchedulerBucket{GroupID: groupID, Platform: service.PlatformAnthropic, Mode: service.SchedulerModeSingle} +} + +func memoTestAccount(id int64, name string) service.Account { + return memoTestAccountOn(service.PlatformAnthropic, id, name) +} + +func memoTestAccountOn(platform string, id int64, name string) service.Account { + return service.Account{ + ID: id, + Name: name, + Platform: platform, + Type: service.AccountTypeOAuth, + Status: service.StatusActive, + Schedulable: true, + Concurrency: 2, + Credentials: map[string]any{ + "model_mapping": map[string]any{"claude-sonnet": "sonnet-" + name}, + "access_token": "dropped-by-projection", + }, + Extra: map[string]any{"session_window_utilization": 0.25}, + } +} + +func memoPublish(t *testing.T, cache *schedulerCache, bucket service.SchedulerBucket, accounts ...service.Account) { + t.Helper() + ctx := context.Background() + token, err := cache.CaptureBucketWriteToken(ctx, bucket) + require.NoError(t, err) + require.NoError(t, cache.SetSnapshot(ctx, bucket, token, accounts)) +} + +func memoRead(t *testing.T, cache *schedulerCache, bucket service.SchedulerBucket) []*service.Account { + t.Helper() + accounts, hit, err := cache.GetSnapshot(context.Background(), bucket) + require.NoError(t, err) + require.True(t, hit) + return accounts +} + +func memoRequireMiss(t *testing.T, cache *schedulerCache, bucket service.SchedulerBucket) { + t.Helper() + accounts, hit, err := cache.GetSnapshot(context.Background(), bucket) + require.NoError(t, err) + require.False(t, hit) + require.Nil(t, accounts) +} + +func memoIDs(accounts []*service.Account) []int64 { + ids := make([]int64, 0, len(accounts)) + for _, account := range accounts { + ids = append(ids, account.ID) + } + return ids +} + +func memoRevision(t *testing.T, cache *schedulerCache, key string) string { + t.Helper() + revision, err := cache.rdb.Get(context.Background(), key).Result() + if errors.Is(err, redis.Nil) { + return "" + } + require.NoError(t, err) + return revision +} + +// memoRevisionValue 读取修订号,不做断言,供 require.Eventually 的条件函数使用。 +func memoRevisionValue(cache *schedulerCache, key string) string { + revision, _ := cache.rdb.Get(context.Background(), key).Result() + return revision +} + +var memoAnthropicRevisionKey = schedulerAccountMetaRevisionKeyForPlatform(service.PlatformAnthropic) + +func memoEntryCount(cache *schedulerCache) int { + cache.snapshotMu.RLock() + defer cache.snapshotMu.RUnlock() + return len(cache.snapshotEntries) +} + +func TestSchedulerCacheSnapshotMemoSecondReadOnlyFetchesTagsAndLastUsed(t *testing.T) { + cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(101) + memoPublish(t, cache, bucket, memoTestAccount(1, "a"), memoTestAccount(2, "b"), memoTestAccount(3, "c")) + + recorder.reset() + first := memoRead(t, cache, bucket) + require.Equal(t, 1, recorder.countPrefix("zrange ")) + require.Equal(t, 1, recorder.countPrefix("mget "+schedulerAccountMetaPrefix)) + + recorder.reset() + second := memoRead(t, cache, bucket) + require.Equal(t, []string{ + "mget " + schedulerBucketKey(schedulerReadyPrefix, bucket), + "mget " + schedulerLastUsedKey("1"), + }, recorder.recorded()) + + require.Equal(t, []int64{1, 2, 3}, memoIDs(second)) + require.Equal(t, first, second) + for i := range first { + require.NotSame(t, first[i], second[i]) + } + require.Equal(t, "sonnet-b", second[1].GetMappedModel("claude-sonnet")) + require.NotContains(t, second[1].Credentials, "access_token") +} + +func TestSchedulerCacheSnapshotMemoLastUsedIsFreshAndCopiesAreIndependent(t *testing.T) { + ctx := context.Background() + cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(102) + embedded := time.Now().UTC().Truncate(time.Millisecond).Add(-time.Hour) + account := memoTestAccount(11, "a") + account.LastUsedAt = &embedded + memoPublish(t, cache, bucket, account) + + first := memoRead(t, cache, bucket) + require.Equal(t, embedded, *first[0].LastUsedAt) + + latest := embedded.Add(42 * time.Second) + require.NoError(t, cache.UpdateLastUsed(ctx, map[int64]time.Time{account.ID: latest})) + recorder.reset() + second := memoRead(t, cache, bucket) + require.Zero(t, recorder.countPrefix("zrange "), "last_used updates must not invalidate the decoded snapshot") + require.Equal(t, latest, *second[0].LastUsedAt) + require.Equal(t, embedded, *first[0].LastUsedAt, "an earlier result must not observe later reads") + + // 修改返回对象的顶层字段只影响本次结果。 + second[0].Schedulable = false + second[0].Name = "mutated" + second[0].LastUsedAt = nil + second[0].Credentials = map[string]any{"model_mapping": map[string]any{"claude-sonnet": "replaced"}} + require.Equal(t, "replaced", second[0].GetMappedModel("claude-sonnet")) + + // 删除 last_used 侧键(不改精简记录):若母本曾被套用 last_used,这里会读到 latest。 + require.NoError(t, cache.rdb.Del(ctx, schedulerLastUsedKey("11")).Err()) + recorder.reset() + third := memoRead(t, cache, bucket) + require.Zero(t, recorder.countPrefix("zrange ")) + require.Equal(t, embedded, *third[0].LastUsedAt) + require.True(t, third[0].Schedulable) + require.Equal(t, "a", third[0].Name) + require.Equal(t, "sonnet-a", third[0].GetMappedModel("claude-sonnet")) +} + +func TestSchedulerCacheSnapshotMemoSetAccountIsVisibleImmediately(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(103) + account := memoTestAccount(21, "a") + memoPublish(t, cache, bucket, account, memoTestAccount(22, "b")) + require.True(t, memoRead(t, cache, bucket)[0].Schedulable) + + globalBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey) + platformBefore := memoRevision(t, cache, memoAnthropicRevisionKey) + account.Schedulable = false + account.Extra = map[string]any{"session_window_utilization": 0.9} + require.NoError(t, cache.SetAccount(ctx, &account)) + require.NotEqual(t, platformBefore, memoRevision(t, cache, memoAnthropicRevisionKey)) + require.Equal(t, globalBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) + + got := memoRead(t, cache, bucket) + require.Equal(t, []int64{21, 22}, memoIDs(got)) + require.False(t, got[0].Schedulable) + require.Equal(t, 0.9, got[0].Extra["session_window_utilization"]) + require.True(t, got[1].Schedulable) +} + +func TestSchedulerCacheSnapshotMemoDeleteAccountMisses(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(104) + memoPublish(t, cache, bucket, memoTestAccount(31, "a"), memoTestAccount(32, "b")) + memoRead(t, cache, bucket) + + revisionBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey) + require.NoError(t, cache.DeleteAccount(ctx, 32)) + require.NotEqual(t, revisionBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) + memoRequireMiss(t, cache, bucket) + require.Zero(t, memoEntryCount(cache)) +} + +func TestSchedulerCacheSnapshotMemoCrossBucketMetadataRewrite(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucketA := memoTestBucket(105) + bucketB := memoTestBucket(106) + shared := memoTestAccount(41, "shared") + memoPublish(t, cache, bucketA, shared) + memoPublish(t, cache, bucketB, shared, memoTestAccount(42, "b-only")) + require.Equal(t, "shared", memoRead(t, cache, bucketB)[0].Name) + activeB := cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucketB)).Val() + + shared.Name = "shared-renamed" + shared.Priority = 9 + memoPublish(t, cache, bucketA, shared) + + require.Equal(t, activeB, cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucketB)).Val()) + got := memoRead(t, cache, bucketB) + require.Equal(t, []int64{41, 42}, memoIDs(got)) + require.Equal(t, "shared-renamed", got[0].Name) + require.Equal(t, 9, got[0].Priority) +} + +func TestSchedulerCacheSnapshotMemoUnencodableLastUsedDeletionMisses(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(107) + memoPublish(t, cache, bucket, memoTestAccount(51, "a"), memoTestAccount(52, "b")) + memoRead(t, cache, bucket) + + revisionBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey) + invalid := time.Date(10000, time.January, 1, 0, 0, 0, 0, time.UTC) + require.NoError(t, cache.UpdateLastUsed(ctx, map[int64]time.Time{52: invalid})) + require.NotEqual(t, revisionBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) + memoRequireMiss(t, cache, bucket) + + // 正常的 last_used 写入不推进任何修订号。 + globalAfterDelete := memoRevision(t, cache, schedulerAccountMetaRevisionKey) + platformAfterDelete := memoRevision(t, cache, memoAnthropicRevisionKey) + require.NoError(t, cache.UpdateLastUsed(ctx, map[int64]time.Time{51: time.Now()})) + require.Equal(t, globalAfterDelete, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) + require.Equal(t, platformAfterDelete, memoRevision(t, cache, memoAnthropicRevisionKey)) +} + +func TestSchedulerCacheSnapshotMemoMembershipChangeByAccountIDs(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(108) + token, err := cache.CaptureBucketWriteToken(ctx, bucket) + require.NoError(t, err) + ids, err := cache.SetSnapshotAndReturnAccountIDs(ctx, bucket, token, []service.Account{memoTestAccount(61, "a"), memoTestAccount(62, "b")}) + require.NoError(t, err) + require.Equal(t, []int64{61, 62}, ids) + require.Equal(t, []int64{61, 62}, memoIDs(memoRead(t, cache, bucket))) + + globalBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey) + platformBefore := memoRevision(t, cache, memoAnthropicRevisionKey) + activeBefore := cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucket)).Val() + token, err = cache.CaptureBucketWriteToken(ctx, bucket) + require.NoError(t, err) + require.NoError(t, cache.SetSnapshotByAccountIDs(ctx, bucket, token, []int64{62})) + + require.Equal(t, globalBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey), "membership-only publishing does not touch metadata") + require.Equal(t, platformBefore, memoRevision(t, cache, memoAnthropicRevisionKey), "membership-only publishing does not touch metadata") + require.NotEqual(t, activeBefore, cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucket)).Val()) + require.Equal(t, []int64{62}, memoIDs(memoRead(t, cache, bucket))) +} + +func TestSchedulerCacheSnapshotMemoRetireReopenAndRepublish(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(109) + memoPublish(t, cache, bucket, memoTestAccount(71, "before")) + memoRead(t, cache, bucket) + + require.NoError(t, cache.RetireBucket(ctx, bucket)) + memoRequireMiss(t, cache, bucket) + require.Zero(t, memoEntryCount(cache)) + + token, err := cache.ReopenBucket(ctx, bucket) + require.NoError(t, err) + memoRequireMiss(t, cache, bucket) + + require.NoError(t, cache.SetSnapshot(ctx, bucket, token, []service.Account{memoTestAccount(72, "after")})) + got := memoRead(t, cache, bucket) + require.Equal(t, []int64{72}, memoIDs(got)) + require.Equal(t, "after", got[0].Name) +} + +func TestSchedulerCacheSnapshotMemoEmptyAndNilMetadataAreNotCached(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + + t.Run("empty zset", func(t *testing.T) { + bucket := memoTestBucket(110) + _, err := cache.writeAccountIDs(ctx, []service.Account{memoTestAccount(81, "a")}) + require.NoError(t, err) + memoPublish(t, cache, bucket) + memoRequireMiss(t, cache, bucket) + + active := cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucket)).Val() + require.NotEmpty(t, active) + require.NoError(t, cache.rdb.ZAdd(ctx, schedulerSnapshotKey(bucket, active), redis.Z{Score: 0, Member: "81"}).Err()) + require.Equal(t, []int64{81}, memoIDs(memoRead(t, cache, bucket))) + }) + + t.Run("nil metadata", func(t *testing.T) { + bucket := memoTestBucket(111) + memoPublish(t, cache, bucket, memoTestAccount(91, "a"), memoTestAccount(92, "b")) + metaKey := schedulerAccountMetaKey("92") + payload, err := cache.rdb.Get(ctx, metaKey).Bytes() + require.NoError(t, err) + require.NoError(t, cache.rdb.Del(ctx, metaKey).Err()) + memoRequireMiss(t, cache, bucket) + + require.NoError(t, cache.rdb.Set(ctx, metaKey, payload, 0).Err()) + require.Equal(t, []int64{91, 92}, memoIDs(memoRead(t, cache, bucket))) + }) +} + +func TestSchedulerCacheSnapshotMemoDecodeFailureIsNotCached(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(112) + memoPublish(t, cache, bucket, memoTestAccount(101, "a")) + metaKey := schedulerAccountMetaKey("101") + payload, err := cache.rdb.Get(ctx, metaKey).Bytes() + require.NoError(t, err) + require.NoError(t, cache.rdb.Set(ctx, metaKey, "{not-json", 0).Err()) + + accounts, hit, err := cache.GetSnapshot(ctx, bucket) + require.Error(t, err) + require.False(t, hit) + require.Nil(t, accounts) + require.Zero(t, memoEntryCount(cache)) + + require.NoError(t, cache.rdb.Set(ctx, metaKey, payload, 0).Err()) + require.Equal(t, "a", memoRead(t, cache, bucket)[0].Name) +} + +func TestSchedulerCacheSnapshotMemoRedisErrorIsReturned(t *testing.T) { + cache, mr, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(113) + memoPublish(t, cache, bucket, memoTestAccount(111, "a")) + memoRead(t, cache, bucket) + + mr.SetError("injected failure") + accounts, hit, err := cache.GetSnapshot(context.Background(), bucket) + require.Error(t, err) + require.False(t, hit) + require.Nil(t, accounts) + + mr.SetError("") + require.Equal(t, []int64{111}, memoIDs(memoRead(t, cache, bucket))) +} + +func TestSchedulerCacheSnapshotMemoConcurrentReadersAndWriters(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(114) + accounts := []service.Account{memoTestAccount(121, "a"), memoTestAccount(122, "b"), memoTestAccount(123, "c")} + memoPublish(t, cache, bucket, accounts...) + + var wg sync.WaitGroup + for reader := 0; reader < 8; reader++ { + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < 40; i++ { + got, hit, err := cache.GetSnapshot(ctx, bucket) + if err != nil || !hit { + t.Errorf("GetSnapshot: hit=%v err=%v", hit, err) + return + } + for _, account := range got { + if account.GetModelMapping()["claude-sonnet"] == "" { + t.Errorf("account %d lost its model mapping", account.ID) + return + } + _ = account.IsSchedulableForModel("claude-sonnet") + _ = account.GetHeaderOverrides() + account.Schedulable = !account.Schedulable + account.LastUsedAt = nil + } + } + }() + } + for writer := 0; writer < 2; writer++ { + wg.Add(1) + go func(writer int) { + defer wg.Done() + for i := 0; i < 20; i++ { + account := memoTestAccount(int64(121+writer), fmt.Sprintf("w%d-%d", writer, i)) + account.Extra = map[string]any{"session_window_utilization": float64(i) / 100} + if err := cache.SetAccount(ctx, &account); err != nil { + t.Errorf("SetAccount: %v", err) + return + } + if err := cache.UpdateLastUsed(ctx, map[int64]time.Time{account.ID: time.Now()}); err != nil { + t.Errorf("UpdateLastUsed: %v", err) + return + } + } + }(writer) + } + wg.Wait() + + got := memoRead(t, cache, bucket) + require.Equal(t, "w0-19", got[0].Name) + require.Equal(t, "w1-19", got[1].Name) + require.Equal(t, "c", got[2].Name) +} + +func TestSchedulerCacheSnapshotMemoWriteAccountIDsAdvancesRevision(t *testing.T) { + ctx := context.Background() + geminiRevisionKey := schedulerAccountMetaRevisionKeyForPlatform(service.PlatformGemini) + + t.Run("revisions share the last chunk", func(t *testing.T) { + cache, _, recorder := newSchedulerCacheMemoUnit(t, 2) + accounts := []service.Account{ + memoTestAccount(131, "a"), + memoTestAccountOn(service.PlatformGemini, 132, "b"), + memoTestAccount(133, "c"), + } + recorder.reset() + ids, err := cache.writeAccountIDs(ctx, accounts) + require.NoError(t, err) + require.Equal(t, []int64{131, 132, 133}, ids) + + batches := recorder.pipelineBatches() + require.Len(t, batches, 2, "one execution per chunk") + require.Equal(t, []string{ + "set " + schedulerAccountKey("133"), + "set " + schedulerAccountMetaKey("133"), + "set " + memoAnthropicRevisionKey, + "set " + geminiRevisionKey, + }, batches[1]) + require.NotContains(t, strings.Join(batches[0], "\n"), schedulerAccountMetaRevisionKey) + require.Equal(t, 2, recorder.countPrefix("set "+schedulerAccountMetaRevisionKey), "no revision write outside the last chunk") + require.Empty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) + first := memoRevision(t, cache, memoAnthropicRevisionKey) + require.Len(t, first, schedulerAccountMetaRevisionBytes*2) + require.Len(t, memoRevision(t, cache, geminiRevisionKey), schedulerAccountMetaRevisionBytes*2) + + _, err = cache.writeAccountIDs(ctx, accounts[:1]) + require.NoError(t, err) + require.NotEqual(t, first, memoRevision(t, cache, memoAnthropicRevisionKey)) + }) + + t.Run("account count is a multiple of the chunk size", func(t *testing.T) { + cache, _, recorder := newSchedulerCacheMemoUnit(t, 2) + accounts := []service.Account{ + memoTestAccount(141, "a"), memoTestAccount(142, "b"), + memoTestAccount(143, "c"), memoTestAccount(144, "d"), + } + recorder.reset() + _, err := cache.writeAccountIDs(ctx, accounts) + require.NoError(t, err) + + batches := recorder.pipelineBatches() + require.Len(t, batches, 2, "no extra execution for the revision") + require.Equal(t, []string{ + "set " + schedulerAccountKey("143"), + "set " + schedulerAccountMetaKey("143"), + "set " + schedulerAccountKey("144"), + "set " + schedulerAccountMetaKey("144"), + "set " + memoAnthropicRevisionKey, + }, batches[1]) + require.Len(t, recorder.recorded(), 9, "every command travels inside the two pipelines") + }) + + t.Run("failure in a later chunk advances the global revision", func(t *testing.T) { + cache, _, recorder := newSchedulerCacheMemoUnit(t, 1) + accounts := []service.Account{memoTestAccount(151, "a"), memoTestAccount(152, "b"), memoTestAccount(153, "c")} + bucket := memoTestBucket(115) + memoPublish(t, cache, bucket, accounts...) + memoRead(t, cache, bucket) + globalBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey) + platformBefore := memoRevision(t, cache, memoAnthropicRevisionKey) + + renamed := []service.Account{memoTestAccount(151, "a2"), memoTestAccount(152, "b2"), memoTestAccount(153, "c2")} + recorder.reset() + recorder.setFailPipelineAt(2) + _, err := cache.writeAccountIDs(ctx, renamed) + require.Error(t, err) + recorder.setFailPipelineAt(0) + require.Eventually(t, func() bool { + return memoRevisionValue(cache, schedulerAccountMetaRevisionKey) != globalBefore + }, 2*time.Second, 5*time.Millisecond, "the global revision is advanced in the background") + require.Equal(t, platformBefore, memoRevision(t, cache, memoAnthropicRevisionKey)) + + recorder.reset() + got := memoRead(t, cache, bucket) + require.Equal(t, 1, recorder.countPrefix("zrange "), "the cached snapshot must be reloaded") + require.Equal(t, []string{"a2", "b", "c"}, []string{got[0].Name, got[1].Name, got[2].Name}) + }) + + t.Run("failure in the last chunk advances the global revision", func(t *testing.T) { + cache, _, recorder := newSchedulerCacheMemoUnit(t, 2) + recorder.reset() + recorder.setFailPipelineAt(1) + _, err := cache.writeAccountIDs(ctx, []service.Account{memoTestAccount(161, "a")}) + require.Error(t, err) + recorder.setFailPipelineAt(0) + require.Eventually(t, func() bool { + return memoRevisionValue(cache, schedulerAccountMetaRevisionKey) != "" + }, 2*time.Second, 5*time.Millisecond, "the global revision is advanced in the background") + require.Empty(t, memoRevision(t, cache, memoAnthropicRevisionKey)) + }) + + t.Run("nothing encodable", func(t *testing.T) { + cache, _, recorder := newSchedulerCacheMemoUnit(t, 1) + invalid := time.Date(10000, time.January, 1, 0, 0, 0, 0, time.UTC) + recorder.reset() + ids, err := cache.writeAccountIDs(ctx, []service.Account{{ID: 171, Platform: service.PlatformAnthropic, ExpiresAt: &invalid}}) + require.NoError(t, err) + require.Empty(t, ids) + require.Empty(t, recorder.recorded()) + require.Empty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) + require.Empty(t, memoRevision(t, cache, memoAnthropicRevisionKey)) + }) + + t.Run("empty platform uses the global revision", func(t *testing.T) { + cache, _, _ := newSchedulerCacheMemoUnit(t, 2) + _, err := cache.writeAccountIDs(ctx, []service.Account{{ID: 181, Name: "no-platform"}}) + require.NoError(t, err) + require.NotEmpty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) + }) +} + +// memoReadExpectHit 读取一次并报告是否重新加载(发出过 ZRANGE)。 +func memoReadExpectHit(t *testing.T, cache *schedulerCache, recorder *schedulerCacheCommandRecorder, bucket service.SchedulerBucket) ([]*service.Account, bool) { + t.Helper() + recorder.reset() + accounts := memoRead(t, cache, bucket) + return accounts, recorder.countPrefix("zrange ") > 0 +} + +func TestSchedulerCacheSnapshotMemoPlatformRevisionScopesInvalidation(t *testing.T) { + ctx := context.Background() + cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + geminiSingle := service.SchedulerBucket{GroupID: 201, Platform: service.PlatformGemini, Mode: service.SchedulerModeSingle} + gemini := memoTestAccountOn(service.PlatformGemini, 211, "gemini") + memoPublish(t, cache, geminiSingle, gemini) + _, reloaded := memoReadExpectHit(t, cache, recorder, geminiSingle) + require.True(t, reloaded) + + anthropic := memoTestAccount(212, "anthropic") + require.NoError(t, cache.SetAccount(ctx, &anthropic)) + recorder.reset() + memoRead(t, cache, geminiSingle) + require.Equal(t, []string{ + "mget " + schedulerBucketKey(schedulerReadyPrefix, geminiSingle), + "mget " + schedulerLastUsedKey("211"), + }, recorder.recorded(), "an Anthropic account write must not invalidate a Gemini bucket") + + gemini.Name = "gemini-renamed" + require.NoError(t, cache.SetAccount(ctx, &gemini)) + got, reloaded := memoReadExpectHit(t, cache, recorder, geminiSingle) + require.True(t, reloaded) + require.Equal(t, "gemini-renamed", got[0].Name) +} + +func TestSchedulerCacheSnapshotMemoPlatformChangeInvalidatesOldPlatformBuckets(t *testing.T) { + ctx := context.Background() + cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + geminiSingle := service.SchedulerBucket{GroupID: 202, Platform: service.PlatformGemini, Mode: service.SchedulerModeSingle} + moved := memoTestAccountOn(service.PlatformGemini, 221, "moved") + memoPublish(t, cache, geminiSingle, moved) + globalBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey) + + moved.Name = "same-platform" + require.NoError(t, cache.SetAccount(ctx, &moved)) + require.Equal(t, globalBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey), "a same-platform rewrite only advances its platform revision") + memoRead(t, cache, geminiSingle) + + moved.Platform = service.PlatformAnthropic + moved.Name = "now-anthropic" + require.NoError(t, cache.SetAccount(ctx, &moved)) + require.NotEqual(t, globalBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey), "a platform change advances the global revision") + + got, reloaded := memoReadExpectHit(t, cache, recorder, geminiSingle) + require.True(t, reloaded, "the old platform bucket must drop the cached account") + require.Equal(t, service.PlatformAnthropic, got[0].Platform) + require.Equal(t, "now-anthropic", got[0].Name) +} + +func TestSchedulerCacheSnapshotMemoNewAccountOnlyAdvancesPlatformRevision(t *testing.T) { + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + fresh := memoTestAccountOn(service.PlatformGemini, 231, "fresh") + require.NoError(t, cache.SetAccount(context.Background(), &fresh)) + require.Empty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) + require.NotEmpty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKeyForPlatform(service.PlatformGemini))) +} + +func TestSchedulerCacheSnapshotMemoAntigravityRevisionInvalidatesMixedBuckets(t *testing.T) { + ctx := context.Background() + cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + antigravity := memoTestAccountOn(service.PlatformAntigravity, 221, "ag") + antigravity.Extra = map[string]any{"mixed_scheduling": true} + gemini := memoTestAccountOn(service.PlatformGemini, 222, "gemini") + anthropic := memoTestAccount(223, "anthropic") + + geminiMixed := service.SchedulerBucket{GroupID: 202, Platform: service.PlatformGemini, Mode: service.SchedulerModeMixed} + anthropicMixed := service.SchedulerBucket{GroupID: 202, Platform: service.PlatformAnthropic, Mode: service.SchedulerModeMixed} + geminiSingle := service.SchedulerBucket{GroupID: 202, Platform: service.PlatformGemini, Mode: service.SchedulerModeSingle} + geminiForced := service.SchedulerBucket{GroupID: 202, Platform: service.PlatformGemini, Mode: service.SchedulerModeForced} + memoPublish(t, cache, geminiMixed, gemini, antigravity) + memoPublish(t, cache, anthropicMixed, anthropic, antigravity) + memoPublish(t, cache, geminiSingle, gemini) + memoPublish(t, cache, geminiForced, gemini) + for _, bucket := range []service.SchedulerBucket{geminiMixed, anthropicMixed, geminiSingle, geminiForced} { + memoRead(t, cache, bucket) + } + + antigravity.Name = "ag-renamed" + require.NoError(t, cache.SetAccount(ctx, &antigravity)) + + got, reloaded := memoReadExpectHit(t, cache, recorder, geminiMixed) + require.True(t, reloaded) + require.Equal(t, "ag-renamed", got[1].Name) + got, reloaded = memoReadExpectHit(t, cache, recorder, anthropicMixed) + require.True(t, reloaded) + require.Equal(t, "ag-renamed", got[1].Name) + _, reloaded = memoReadExpectHit(t, cache, recorder, geminiSingle) + require.False(t, reloaded, "single buckets never contain Antigravity accounts") + _, reloaded = memoReadExpectHit(t, cache, recorder, geminiForced) + require.False(t, reloaded, "forced buckets never contain Antigravity accounts") +} + +func TestSchedulerCacheSnapshotMemoGlobalRevisionInvalidatesEveryPlatform(t *testing.T) { + ctx := context.Background() + buckets := []service.SchedulerBucket{ + {GroupID: 203, Platform: service.PlatformGemini, Mode: service.SchedulerModeSingle}, + {GroupID: 203, Platform: service.PlatformAnthropic, Mode: service.SchedulerModeSingle}, + {GroupID: 203, Platform: service.PlatformOpenAI, Mode: service.SchedulerModeSingle}, + } + setup := func(t *testing.T) (*schedulerCache, *schedulerCacheCommandRecorder) { + cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + for i, bucket := range buckets { + memoPublish(t, cache, bucket, memoTestAccountOn(bucket.Platform, int64(231+i), bucket.Platform)) + memoRead(t, cache, bucket) + } + // 不属于任何上述 bucket 的账号。 + unrelated := memoTestAccountOn(service.PlatformGrok, 239, "grok") + require.NoError(t, cache.SetAccount(ctx, &unrelated)) + for _, bucket := range buckets { + _, reloaded := memoReadExpectHit(t, cache, recorder, bucket) + require.False(t, reloaded) + } + return cache, recorder + } + + t.Run("DeleteAccount", func(t *testing.T) { + cache, recorder := setup(t) + require.NoError(t, cache.DeleteAccount(ctx, 239)) + for _, bucket := range buckets { + _, reloaded := memoReadExpectHit(t, cache, recorder, bucket) + require.True(t, reloaded, bucket.String()) + } + }) + + t.Run("UpdateLastUsed unencodable deletion", func(t *testing.T) { + cache, recorder := setup(t) + invalid := time.Date(10000, time.January, 1, 0, 0, 0, 0, time.UTC) + require.NoError(t, cache.UpdateLastUsed(ctx, map[int64]time.Time{239: invalid})) + for _, bucket := range buckets { + _, reloaded := memoReadExpectHit(t, cache, recorder, bucket) + require.True(t, reloaded, bucket.String()) + } + }) +} + +func TestSchedulerCacheSnapshotMemoFlushAllAndRepublishSameVersion(t *testing.T) { + ctx := context.Background() + cache, mr, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(116) + memoPublish(t, cache, bucket, memoTestAccount(141, "before")) + require.Equal(t, "before", memoRead(t, cache, bucket)[0].Name) + activeBefore := cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucket)).Val() + + mr.FlushAll() + memoPublish(t, cache, bucket, memoTestAccount(141, "after")) + require.Equal(t, activeBefore, cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucket)).Val()) + require.Equal(t, "after", memoRead(t, cache, bucket)[0].Name) +} + +type memoTestClock struct { + mu sync.Mutex + now time.Time +} + +func (c *memoTestClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.now +} + +func (c *memoTestClock) Advance(d time.Duration) { + c.mu.Lock() + c.now = c.now.Add(d) + c.mu.Unlock() +} + +func TestSchedulerCacheSnapshotMemoMaxAgeBoundsUnversionedWrites(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + clock := &memoTestClock{now: time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)} + cache.now = clock.Now + bucket := memoTestBucket(117) + memoPublish(t, cache, bucket, memoTestAccount(151, "old")) + require.Equal(t, "old", memoRead(t, cache, bucket)[0].Name) + + // 模拟不推进修订号的旧实例:直接改写精简记录。 + _, metaPayload, err := marshalSchedulerCacheAccount(memoTestAccount(151, "new")) + require.NoError(t, err) + globalBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey) + platformBefore := memoRevision(t, cache, memoAnthropicRevisionKey) + require.NoError(t, cache.rdb.Set(ctx, schedulerAccountMetaKey("151"), metaPayload, 0).Err()) + require.Equal(t, globalBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) + require.Equal(t, platformBefore, memoRevision(t, cache, memoAnthropicRevisionKey)) + + clock.Advance(schedulerSnapshotCacheMaxAge - time.Millisecond) + require.Equal(t, "old", memoRead(t, cache, bucket)[0].Name) + + clock.Advance(time.Millisecond) + require.Equal(t, "new", memoRead(t, cache, bucket)[0].Name) +} + +func TestSchedulerCacheSnapshotMemoEvictsLongIdleEntries(t *testing.T) { + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + clock := &memoTestClock{now: time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC)} + cache.now = clock.Now + idle := memoTestBucket(118) + recent := memoTestBucket(119) + active := memoTestBucket(120) + memoPublish(t, cache, idle, memoTestAccount(161, "idle")) + memoPublish(t, cache, recent, memoTestAccount(162, "recent")) + memoPublish(t, cache, active, memoTestAccount(163, "active")) + + memoRead(t, cache, idle) + clock.Advance(schedulerSnapshotCacheEvictAge / 2) + memoRead(t, cache, recent) + clock.Advance(schedulerSnapshotCacheEvictAge/2 + time.Second) + memoRead(t, cache, active) + + cache.snapshotMu.RLock() + defer cache.snapshotMu.RUnlock() + require.NotContains(t, cache.snapshotEntries, idle.String()) + require.Contains(t, cache.snapshotEntries, recent.String()) + require.Contains(t, cache.snapshotEntries, active.String()) +} + +func TestSchedulerCacheSnapshotMemoKeepsNewerEntryOnLateStore(t *testing.T) { + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + base := time.Date(2026, 10, 20, 8, 0, 0, 0, time.UTC) + newer := &schedulerSnapshotEntry{active: "2", revisions: []string{"r2"}, loadedAt: base.Add(time.Second)} + older := &schedulerSnapshotEntry{active: "1", revisions: []string{"r1"}, loadedAt: base} + cache.storeSnapshotEntry("b", newer) + cache.storeSnapshotEntry("b", older) + require.Same(t, newer, cache.lookupSnapshotEntry("b")) +} + +// 母本在发布前预解析了模型映射:副本命中时不计算签名。此处故意原地改写共享的原始映射, +// 只用来观察副本走的是免签名路径(生产代码不会原地修改该 map)。 +func TestSchedulerCacheSnapshotMemoPreparesSharedModelMapping(t *testing.T) { + cache, _, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + bucket := memoTestBucket(121) + memoPublish(t, cache, bucket, memoTestAccount(171, "a")) + memoRead(t, cache, bucket) + + hit := memoRead(t, cache, bucket)[0] + require.Equal(t, "sonnet-a", hit.GetMappedModel("claude-sonnet")) + + replaced := memoRead(t, cache, bucket)[0] + replaced.Credentials = map[string]any{"model_mapping": map[string]any{"claude-sonnet": "sonnet-replaced"}} + require.Equal(t, "sonnet-replaced", replaced.GetMappedModel("claude-sonnet")) + + probe := memoRead(t, cache, bucket)[0] + rawMapping, ok := probe.Credentials["model_mapping"].(map[string]any) + require.True(t, ok) + rawMapping["claude-sonnet"] = "sonnet-mutated-in-place" + require.Equal(t, "sonnet-a", probe.GetMappedModel("claude-sonnet")) +} + +func TestSchedulerCacheSnapshotMemoRevisionValuesAreUnique(t *testing.T) { + seen := make(map[string]struct{}, 64) + for i := 0; i < 64; i++ { + revision := newSchedulerAccountMetaRevision() + require.Len(t, revision, schedulerAccountMetaRevisionBytes*2) + _, err := strconv.ParseUint(revision[:8], 16, 32) + require.NoError(t, err) + _, dup := seen[revision] + require.False(t, dup) + seen[revision] = struct{}{} + } +} + +func TestSchedulerCacheSnapshotMemoPlatformChangeInEarlierChunk(t *testing.T) { + ctx := context.Background() + cache, _, _ := newSchedulerCacheMemoUnit(t, 1) + require.NoError(t, cache.SetAccount(ctx, ptrAccount(memoTestAccountOn(service.PlatformGemini, 241, "moved")))) + require.NoError(t, cache.SetAccount(ctx, ptrAccount(memoTestAccount(242, "stays")))) + globalBefore := memoRevision(t, cache, schedulerAccountMetaRevisionKey) + + _, err := cache.writeAccountIDs(ctx, []service.Account{ + memoTestAccount(241, "moved"), + memoTestAccount(242, "stays"), + }) + require.NoError(t, err) + require.NotEqual(t, globalBefore, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) +} + +func TestSchedulerCacheSnapshotMemoUnparsableOldMetadataAdvancesGlobalRevision(t *testing.T) { + ctx := context.Background() + cache, mr, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + require.NoError(t, mr.Set(schedulerAccountMetaKey("251"), "not-json")) + + require.NoError(t, cache.SetAccount(ctx, ptrAccount(memoTestAccount(251, "replaced")))) + require.NotEmpty(t, memoRevision(t, cache, schedulerAccountMetaRevisionKey)) +} + +func TestSchedulerCacheSnapshotMemoNilBeforeRealPipelineError(t *testing.T) { + ctx := context.Background() + cache, mr, _ := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + mr.HSet(schedulerAccountMetaKey("262"), "field", "value") + + _, err := cache.writeAccountIDs(ctx, []service.Account{ + memoTestAccount(261, "fresh"), + memoTestAccount(262, "wrong-type"), + }) + require.Error(t, err, "a WRONGTYPE reply after a nil SET ... GET reply must fail the write") + require.Eventually(t, func() bool { + return memoRevisionValue(cache, schedulerAccountMetaRevisionKey) != "" + }, 2*time.Second, 5*time.Millisecond, "the global revision is advanced in the background") +} + +func TestSchedulerCacheSnapshotMemoCoalescesBackgroundGlobalRevisionWrites(t *testing.T) { + cache, _, recorder := newSchedulerCacheMemoUnit(t, defaultSchedulerSnapshotWriteChunkSize) + recorder.reset() + for range 50 { + cache.scheduleGlobalAccountMetaRevision(context.Background()) + } + require.Eventually(t, func() bool { + return !cache.globalRevisionWriting.Load() && memoRevisionValue(cache, schedulerAccountMetaRevisionKey) != "" + }, 2*time.Second, 5*time.Millisecond) + writes := 0 + for _, command := range recorder.recorded() { + if command == "set "+schedulerAccountMetaRevisionKey { + writes++ + } + } + require.GreaterOrEqual(t, writes, 1) + require.LessOrEqual(t, writes, 3, "concurrent schedules collapse into at most a couple of background writes") +} + +func ptrAccount(account service.Account) *service.Account { + return &account +} diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 06b94b754e..27a9bbccc8 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -76,6 +76,9 @@ type Account struct { modelMappingCacheRawLen int modelMappingCacheRawSig uint64 modelMappingCacheRuntimeVersion uint64 + // modelMappingCacheShared 为 true 时缓存来自只读共享母本(见 PrepareSharedSnapshot), + // 指针、长度与运行时版本匹配即直接复用预解析结果,不计算签名。 + modelMappingCacheShared bool // header_overrides 热路径缓存(非持久化字段,同 model_mapping 缓存先例) headerOverrideCache map[string]string @@ -635,6 +638,9 @@ func (a *Account) GetModelMapping() map[string]string { a.modelMappingCacheRawPtr == rawPtr && a.modelMappingCacheRawLen == rawLen && a.modelMappingCacheRuntimeVersion == runtimeVersion { + if a.modelMappingCacheShared { + return a.modelMappingCache + } rawSig = modelMappingSignature(rawMapping) rawSigReady = true if a.modelMappingCacheRawSig == rawSig { @@ -654,9 +660,24 @@ func (a *Account) GetModelMapping() map[string]string { a.modelMappingCacheRawLen = rawLen a.modelMappingCacheRawSig = rawSig a.modelMappingCacheRuntimeVersion = runtimeVersion + a.modelMappingCacheShared = false return mapping } +// PrepareSharedSnapshot 预解析模型映射,并把账号标记为只读共享母本。 +// 母本按值复制出的副本与母本共用 Credentials 及其中 model_mapping 的同一 map: +// 这些内层 map 在运行期不被原地修改,母本留在缓存期间持有这些 map,其地址不会被复用, +// 因此副本在指针、长度与运行时版本都匹配时直接复用预解析结果,不计算签名; +// 副本替换 Credentials 等导致任一项不匹配时回到普通的重建路径。 +// 只能由构造该账号的 goroutine 在其发布给其它 goroutine 之前调用,发布后母本不得再被修改。 +func (a *Account) PrepareSharedSnapshot() { + if a == nil { + return + } + a.GetModelMapping() + a.modelMappingCacheShared = true +} + func (a *Account) resolveModelMapping(rawMapping map[string]any) map[string]string { if a.Credentials == nil { // Antigravity 平台使用默认映射 diff --git a/backend/internal/service/account_shared_snapshot_test.go b/backend/internal/service/account_shared_snapshot_test.go new file mode 100644 index 0000000000..2d3421193d --- /dev/null +++ b/backend/internal/service/account_shared_snapshot_test.go @@ -0,0 +1,82 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// 共享母本的副本命中预解析缓存时不计算签名:此处故意原地改写共享的原始映射, +// 只用来观察副本走的是免签名路径(生产代码不会原地修改该 map)。 +func TestAccountPrepareSharedSnapshot_CopiesReusePreparedMappingWithoutSignature(t *testing.T) { + rawMapping := map[string]any{"claude-sonnet": "sonnet-a"} + master := &Account{ + Platform: PlatformAnthropic, + Credentials: map[string]any{"model_mapping": rawMapping}, + } + master.PrepareSharedSnapshot() + + replica := *master + require.Equal(t, map[string]string{"claude-sonnet": "sonnet-a"}, replica.GetModelMapping()) + + rawMapping["claude-sonnet"] = "sonnet-b" + require.Equal(t, "sonnet-a", replica.GetModelMapping()["claude-sonnet"], + "the shared fast path must not recompute the signature") + require.Equal(t, "sonnet-a", replica.GetMappedModel("claude-sonnet")) + + // 未标记为共享的账号仍按签名检出原地改写。 + plainRaw := map[string]any{"claude-sonnet": "sonnet-a"} + plain := &Account{ + Platform: PlatformAnthropic, + Credentials: map[string]any{"model_mapping": plainRaw}, + } + require.Equal(t, "sonnet-a", plain.GetModelMapping()["claude-sonnet"]) + plainRaw["claude-sonnet"] = "sonnet-b" + require.Equal(t, "sonnet-b", plain.GetModelMapping()["claude-sonnet"]) +} + +func TestAccountPrepareSharedSnapshot_ReplacedCredentialsFallBackToSignaturePath(t *testing.T) { + master := &Account{ + Platform: PlatformAnthropic, + Credentials: map[string]any{"model_mapping": map[string]any{"claude-sonnet": "sonnet-a"}}, + } + master.PrepareSharedSnapshot() + + replica := *master + replacedRaw := map[string]any{"claude-sonnet": "sonnet-b"} + replica.Credentials = map[string]any{"model_mapping": replacedRaw} + require.Equal(t, "sonnet-b", replica.GetModelMapping()["claude-sonnet"]) + + // 重建后副本回到普通路径:同一 map 的原地改写由签名检出。 + replacedRaw["claude-sonnet"] = "sonnet-c" + require.Equal(t, "sonnet-c", replica.GetModelMapping()["claude-sonnet"]) + + // 母本不受副本重建影响。 + require.Equal(t, "sonnet-a", master.GetModelMapping()["claude-sonnet"]) +} + +func TestAccountPrepareSharedSnapshot_MappingLengthChangeRebuilds(t *testing.T) { + rawMapping := map[string]any{"claude-sonnet": "sonnet-a"} + master := &Account{ + Platform: PlatformAnthropic, + Credentials: map[string]any{"model_mapping": rawMapping}, + } + master.PrepareSharedSnapshot() + + replica := *master + rawMapping["claude-opus"] = "opus-a" + require.Equal(t, "opus-a", replica.GetModelMapping()["claude-opus"]) +} + +func TestAccountPrepareSharedSnapshot_NilAccountAndNoMapping(t *testing.T) { + var nilAccount *Account + require.NotPanics(t, nilAccount.PrepareSharedSnapshot) + + master := &Account{Platform: PlatformAnthropic} + master.PrepareSharedSnapshot() + replica := *master + require.Nil(t, replica.GetModelMapping()) + require.Equal(t, "claude-sonnet", replica.GetMappedModel("claude-sonnet")) +} diff --git a/backend/internal/service/model_rate_limit_snapshot_cow_test.go b/backend/internal/service/model_rate_limit_snapshot_cow_test.go index 97e35c296e..a73fcff5fe 100644 --- a/backend/internal/service/model_rate_limit_snapshot_cow_test.go +++ b/backend/internal/service/model_rate_limit_snapshot_cow_test.go @@ -91,6 +91,7 @@ func TestSetAccountModelRateLimitSnapshot_ConcurrentCopiesOfSharedMaster(t *test "session_window_utilization": 0.2, }, } + master.PrepareSharedSnapshot() const workers = 16 var wg sync.WaitGroup @@ -170,6 +171,7 @@ func TestApplyAccountSchedulingThreshold_FableLimitStaysOnOwnSnapshotCopy(t *tes "passive_usage_7d_oi_reset": float64(now.Add(4 * 24 * time.Hour).Unix()), }, } + master.PrepareSharedSnapshot() const pairs = 8 var wg sync.WaitGroup diff --git a/backend/internal/service/scheduler_cache.go b/backend/internal/service/scheduler_cache.go index d507d6ce2a..5e5dbed164 100644 --- a/backend/internal/service/scheduler_cache.go +++ b/backend/internal/service/scheduler_cache.go @@ -76,6 +76,8 @@ func ParseSchedulerBucket(raw string) (SchedulerBucket, bool) { // SchedulerCache 负责调度快照与账号快照的缓存读写。 type SchedulerCache interface { // GetSnapshot 读取快照并返回命中与否(ready + active + 数据完整)。 + // 返回的账号对象由本次调用独占,可以修改其顶层字段;map、切片底层数组与指针指向的值 + // 与其它调用共享,不得原地修改。 GetSnapshot(ctx context.Context, bucket SchedulerBucket) ([]*Account, bool, error) // CaptureBucketWriteToken captures the current open epoch without changing // retirement state. A tombstoned bucket returns ErrSchedulerBucketRetired. From e0fa4b94f9b962949da039c09e63968358324e26 Mon Sep 17 00:00:00 2001 From: wucm667 Date: Wed, 21 Oct 2026 02:34:30 +0800 Subject: [PATCH 019/297] fix(ratelimit): avoid penalizing Cloudflare 1010 blocks --- backend/internal/service/ratelimit_service.go | 78 +++++++++++++++---- .../ratelimit_service_403_html_test.go | 65 +++++++++++++++- 2 files changed, 128 insertions(+), 15 deletions(-) diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go index 7aa64632c4..2f2f705640 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -1003,10 +1003,19 @@ func buildForbiddenErrorMessage(prefix string, upstreamMsg string, responseBody return prefix + fallback } -// handle403 处理 403 Forbidden 错误 -// Antigravity 平台区分 validation/violation/generic 三种类型,均 SetError 永久禁用; -// 其他平台保持原有 SetError 行为。 +// handle403 处理 403 Forbidden 错误。Cloudflare 1010 是请求/边缘级拦截, +// 不应将其视为账号级故障;其他真实 403 继续按平台策略处理。 func (s *RateLimitService) handle403(ctx context.Context, account *Account, upstreamMsg string, responseBody []byte) (shouldDisable bool) { + if isCloudflareBotBlockResponse(responseBody) { + slog.Warn( + "403_cloudflare_bot_block_skips_account_penalty", + "account_id", account.ID, + "platform", account.Platform, + "upstream_message", upstreamMsg, + ) + return false + } + if account.Platform == PlatformAntigravity { return s.handleAntigravity403(ctx, account, upstreamMsg, responseBody) } @@ -1064,16 +1073,6 @@ func (s *RateLimitService) handleOpenAI403(ctx context.Context, account *Account ) return false } - if isCloudflareBotBlockResponse(responseBody) { - slog.Warn( - "openai_403_cloudflare_bot_block_skips_account_penalty", - "account_id", account.ID, - "platform", account.Platform, - "upstream_message", upstreamMsg, - ) - return false - } - msg := buildForbiddenErrorMessage( "Access forbidden (403):", upstreamMsg, @@ -1123,9 +1122,62 @@ func (s *RateLimitService) handleOpenAI403(ctx context.Context, account *Account // request/edge-level failure and must not consume the account 403 strike budget. func isCloudflareBotBlockResponse(body []byte) bool { normalized := strings.ToLower(strings.TrimSpace(string(body))) + var payload any + if json.Unmarshal(body, &payload) == nil { + return containsCloudflareBotBlockCode(payload) + } return strings.Contains(normalized, "error code: 1010") } +func containsCloudflareBotBlockCode(value any) bool { + switch node := value.(type) { + case map[string]any: + cloudflareError := false + for key, child := range node { + if strings.EqualFold(key, "cloudflare_error") { + if is, ok := child.(bool); ok && is { + cloudflareError = true + } + } + } + for key, child := range node { + if strings.EqualFold(key, "error_name") { + if name, ok := child.(string); ok && strings.EqualFold(strings.TrimSpace(name), "browser_signature_banned") { + return true + } + } + if cloudflareError && (strings.EqualFold(key, "code") || strings.EqualFold(key, "error_code")) { + if isCloudflareBotBlockCode(child) { + return true + } + } + if containsCloudflareBotBlockCode(child) { + return true + } + } + case []any: + for _, child := range node { + if containsCloudflareBotBlockCode(child) { + return true + } + } + } + return false +} + +func isCloudflareBotBlockCode(value any) bool { + switch code := value.(type) { + case float64: + return code == 1010 + case json.Number: + return code == "1010" + case string: + return strings.TrimSpace(code) == "1010" + default: + return false + } +} + // handleAntigravity403 处理 Antigravity 平台的 403 错误 // validation(需要验证)→ 永久 SetError(需人工去 Google 验证后恢复) // violation(违规封号)→ 永久 SetError(需人工处理) diff --git a/backend/internal/service/ratelimit_service_403_html_test.go b/backend/internal/service/ratelimit_service_403_html_test.go index 8768b41fea..8048dd3cab 100644 --- a/backend/internal/service/ratelimit_service_403_html_test.go +++ b/backend/internal/service/ratelimit_service_403_html_test.go @@ -104,8 +104,8 @@ func TestHandleUpstreamError_OpenAIHTML403RepeatedNeverEscalates(t *testing.T) { h.requireNoAccountPenalty(t) } -func TestHandleUpstreamError_OpenAICloudflare1010DoesNotPenalizeAccount(t *testing.T) { - for _, platform := range []string{PlatformOpenAI, PlatformOpenCodeGo} { +func TestHandleUpstreamError_Cloudflare1010DoesNotPenalizeAccount(t *testing.T) { + for _, platform := range []string{PlatformOpenAI, PlatformOpenCodeGo, PlatformAnthropic, PlatformGemini, PlatformAntigravity} { t.Run(platform, func(t *testing.T) { repo := &rateLimitAccountRepoStub{} counter := &countingOpenAI403CounterCache{ @@ -130,6 +130,67 @@ func TestHandleUpstreamError_OpenAICloudflare1010DoesNotPenalizeAccount(t *testi } } +func TestHandleUpstreamError_Cloudflare1010JSONDoesNotPenalizeAccount(t *testing.T) { + for _, body := range []string{ + `{"cloudflare_error":true,"error_code":1010,"error_name":"browser_signature_banned","detail":"blocked"}`, + `{"error_name":"browser_signature_banned","detail":"blocked by Cloudflare"}`, + } { + t.Run(body, func(t *testing.T) { + repo := &rateLimitAccountRepoStub{} + counter := &countingOpenAI403CounterCache{ + openAI403CounterCacheStub: openAI403CounterCacheStub{counts: []int64{openAI403DisableThreshold}}, + } + svc := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + svc.SetOpenAI403CounterCache(counter) + account := &Account{ID: 602, Platform: PlatformAnthropic, Type: AccountTypeAPIKey} + + require.False(t, svc.HandleUpstreamError( + context.Background(), account, http.StatusForbidden, http.Header{}, []byte(body), + )) + require.Equal(t, 0, counter.increments) + require.Equal(t, 0, repo.setErrorCalls) + require.Equal(t, 0, repo.tempCalls) + }) + } +} + +func TestIsCloudflareBotBlockResponseOnlyMatches1010(t *testing.T) { + cases := []struct { + name string + body string + want bool + }{ + {"plain text", "error code: 1010", true}, + {"root numeric JSON code", `{"cloudflare_error":true,"code":1010}`, true}, + {"nested string JSON code", `{"errors":[{"cloudflare_error":true,"code":"1010"}]}`, true}, + {"cloudflare error code", `{"cloudflare_error":true,"error_code":1010}`, true}, + {"browser signature name", `{"error_name":"browser_signature_banned"}`, true}, + {"different JSON code", `{"code":403,"message":"forbidden"}`, false}, + {"unrelated code 1010", `{"error":{"code":1010,"message":"account banned"}}`, false}, + {"message mentions 1010", `{"message":"error code: 1010"}`, false}, + {"malformed JSON", `{"code":1010`, false}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.want, isCloudflareBotBlockResponse([]byte(tc.body))) + }) + } +} + +func TestHandleUpstreamError_AnthropicGenuine403StillPenalizes(t *testing.T) { + repo := &rateLimitAccountRepoStub{} + svc := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + account := &Account{ID: 603, Platform: PlatformAnthropic, Type: AccountTypeAPIKey} + + require.True(t, svc.HandleUpstreamError( + context.Background(), account, http.StatusForbidden, http.Header{}, + []byte(`{"error":{"type":"permission_error","message":"invalid API key"}}`), + )) + require.Equal(t, 1, repo.setErrorCalls) + require.Contains(t, repo.lastErrorMsg, "invalid API key") +} + // 对照不变式:真正的结构化 JSON 403 是账号级证据,处罚链路必须原样保留。 // 缺了这组断言,上面的跳过逻辑一旦写宽就会把真实的封号 403 也放过去。 func TestHandleUpstreamError_OpenAIStructured403StillPenalizes(t *testing.T) { From cacc80b8620e11e9655ab307471f71eb9ee31a0e Mon Sep 17 00:00:00 2001 From: wucm667 Date: Wed, 21 Oct 2026 15:27:29 +0800 Subject: [PATCH 020/297] fix(security): clear dependency security scan failures --- .github/workflows/security-scan.yml | 2 +- backend/go.mod | 2 +- frontend/package.json | 3 ++- frontend/pnpm-lock.yaml | 9 +++++---- 4 files changed, 9 insertions(+), 7 deletions(-) diff --git a/.github/workflows/security-scan.yml b/.github/workflows/security-scan.yml index 8caec3ff42..88da184e5d 100644 --- a/.github/workflows/security-scan.yml +++ b/.github/workflows/security-scan.yml @@ -23,7 +23,7 @@ jobs: cache-dependency-path: backend/go.sum - name: Verify Go version run: | - go version | grep -q 'go1.27.2' + go version | grep -q 'go1.27.3' - name: Run govulncheck working-directory: backend run: | diff --git a/backend/go.mod b/backend/go.mod index 2e68ebc9ac..50865afb0c 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -1,6 +1,6 @@ module github.com/Wei-Shaw/sub2api -go 1.27.2 +go 1.27.3 require ( entgo.io/ent v0.14.5 diff --git a/frontend/package.json b/frontend/package.json index e714a702f8..177259daa3 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -66,7 +66,8 @@ "form-data@<4.0.6": ">=4.0.6", "postcss@<8.5.18": ">=8.5.18", "dompurify@<3.4.14": ">=3.4.14", - "source-map-js@<1.2.2": ">=1.2.2" + "source-map-js@<1.2.2": ">=1.2.2", + "follow-redirects@<1.16.1": ">=1.16.1" } } } diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml index 1e36493ef0..5f02f3f2a8 100644 --- a/frontend/pnpm-lock.yaml +++ b/frontend/pnpm-lock.yaml @@ -10,6 +10,7 @@ overrides: postcss@<8.5.18: '>=8.5.18' dompurify@<3.4.14: '>=3.4.14' source-map-js@<1.2.2: '>=1.2.2' + follow-redirects@<1.16.1: '>=1.16.1' importers: @@ -2560,8 +2561,8 @@ packages: flatted@3.3.3: resolution: {integrity: sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==} - follow-redirects@1.16.0: - resolution: {integrity: sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==} + follow-redirects@1.16.1: + resolution: {integrity: sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==} engines: {node: '>=4.0'} peerDependencies: debug: '*' @@ -6552,7 +6553,7 @@ snapshots: axios@1.20.0: dependencies: - follow-redirects: 1.16.0 + follow-redirects: 1.16.1 form-data: 4.0.6 https-proxy-agent: 5.0.1 proxy-from-env: 2.1.0 @@ -7294,7 +7295,7 @@ snapshots: flatted@3.3.3: {} - follow-redirects@1.16.0: {} + follow-redirects@1.16.1: {} for-in@1.0.2: {} From 4c940c3cb7069d23cd304fc378f29ffae1ceb80f Mon Sep 17 00:00:00 2001 From: wucm667 Date: Wed, 21 Oct 2026 15:35:03 +0800 Subject: [PATCH 021/297] fix(ci): synchronize Go patch version checks --- .github/workflows/backend-ci.yml | 4 ++-- .github/workflows/release.yml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/backend-ci.yml b/.github/workflows/backend-ci.yml index 7367f680cf..c9a140f886 100644 --- a/.github/workflows/backend-ci.yml +++ b/.github/workflows/backend-ci.yml @@ -35,7 +35,7 @@ jobs: cache-dependency-path: backend/go.sum - name: Verify Go version run: | - go version | grep -q 'go1.27.2' + go version | grep -q 'go1.27.3' - name: Unit tests working-directory: backend run: make test-unit @@ -75,7 +75,7 @@ jobs: cache-dependency-path: backend/go.sum - name: Verify Go version run: | - go version | grep -q 'go1.27.2' + go version | grep -q 'go1.27.3' - name: golangci-lint uses: golangci/golangci-lint-action@v9 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e70f1680e0..9cef765b62 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -137,7 +137,7 @@ jobs: check-latest: false cache: false - name: Verify Go version - run: go version | grep -q 'go1.27.2' + run: go version | grep -q 'go1.27.3' - name: Restore target-specific Go cache id: go-cache uses: actions/cache/restore@v6 From 67dca9687eddcd4a21d44b354c2afe2d921942a6 Mon Sep 17 00:00:00 2001 From: feeeei Date: Wed, 21 Oct 2026 15:36:36 +0800 Subject: [PATCH 022/297] =?UTF-8?q?perf(billing):=20=E8=B4=A6=E5=8F=B7?= =?UTF-8?q?=E9=85=8D=E9=A2=9D=E7=B4=AF=E5=8A=A0=E6=8C=89=E5=B7=B2=E8=AE=BE?= =?UTF-8?q?=E7=BD=AE=E7=9A=84=E5=91=A8=E6=9C=9F=E7=BB=B4=E5=BA=A6=E9=80=89?= =?UTF-8?q?=E6=8B=A9=E8=AF=AD=E5=8F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 计费事务中账号配额累加位于余额(或订阅用量)扣减之后、提交之前,与同一用户 共享的余额行锁处在同一持有区间。累加语句约 9.4KB,无论账号设置了哪些上限, 都要解析、规划并求值总额度、日、周三个维度的全部分支;lib/pq 每次执行都重新 规划,同一用户的并发计费在这段上串行。 - 预先拼好 4 条语句:只累加总额度、加日维度、加周维度、日周都累加(与原语句 去空白后逐字相同)。按账号设置的日/周上限选择,只设总额度的账号使用约 1KB 的语句。 - 选择依据来自构造计费命令时的账号配置:UsageBillingCommand 新增 AccountQuotaHasDailyLimit / AccountQuotaHasWeeklyLimit,不参与幂等指纹。 省略维度的语句在 WHERE 中要求 extra 为对象、被省略维度未设上限(键不存在、 JSON null 或不大于 0 的数字);库中配置不符时命中 0 行,再执行日周都累加的 语句,结果与原语句一致。条件只用 ->、jsonb_typeof 与 jsonb 比较,对任何行 求值都不报错。 - 事务内语句顺序、加锁顺序、越线入队 scheduler_outbox 与返回的额度状态不变。 集成测试对 15 种 extra 配置 × 4 种选择组合,与原语句比对 extra、updated_at、 返回值与报错码,并断言各语句是否命中。 单条语句耗时(PostgreSQL 18,BEGIN/ROLLBACK 内,扣除空事务): 只设总额度 0.77ms → 0.24ms 设日上限 0.79ms → 0.50ms 设周上限 0.79ms → 0.57ms 日周都设 不变 压测(PostgreSQL 18、NVMe、lib/pq;1 个用户经 41 个只设总额度的账号计费, 同时运行 usage_logs 批量写入;TPS): 并发 32:488 → 1209 并发 64:424 → 874 并发 128:357 → 575 --- .../internal/repository/usage_billing_repo.go | 179 +++++++++++++----- .../usage_billing_repo_integration_test.go | 136 +++++++++++++ .../usage_billing_repo_unit_test.go | 102 +++++++++- .../internal/service/gateway_usage_billing.go | 2 + ...ateway_usage_billing_account_quota_test.go | 92 +++++++++ backend/internal/service/usage_billing.go | 5 + 6 files changed, 464 insertions(+), 52 deletions(-) create mode 100644 backend/internal/service/gateway_usage_billing_account_quota_test.go diff --git a/backend/internal/repository/usage_billing_repo.go b/backend/internal/repository/usage_billing_repo.go index 01f5f857f5..6b509215b3 100644 --- a/backend/internal/repository/usage_billing_repo.go +++ b/backend/internal/repository/usage_billing_repo.go @@ -204,7 +204,7 @@ func (r *usageBillingRepository) applyUsageBillingEffects(ctx context.Context, t // 账号已不存在时跳过其配额计数,其余结算项不受影响。 if cmd.AccountQuotaCost > 0 && service.AccountTypeSupportsQuota(cmd.AccountType) { - quotaState, err := incrementUsageBillingAccountQuota(ctx, tx, cmd.AccountID, cmd.AccountQuotaCost) + quotaState, err := incrementUsageBillingAccountQuota(ctx, tx, cmd.AccountID, cmd.AccountQuotaCost, cmd.AccountQuotaHasDailyLimit, cmd.AccountQuotaHasWeeklyLimit) if err != nil && !errors.Is(err, service.ErrAccountNotFound) { return err } @@ -466,83 +466,130 @@ func incrementUsageBillingAPIKeyRateLimit(ctx context.Context, tx *sql.Tx, apiKe return nil } -func incrementUsageBillingAccountQuota(ctx context.Context, tx *sql.Tx, accountID int64, amount float64) (*service.AccountQuotaState, error) { - rows, err := tx.QueryContext(ctx, - `UPDATE accounts SET extra = ( - COALESCE(extra, '{}'::jsonb) - || jsonb_build_object('quota_used', COALESCE((extra->>'quota_used')::numeric, 0) + $1) +// accountQuotaTotalIncrementExpr 累加总额度已用量。 +const accountQuotaTotalIncrementExpr = `COALESCE(extra, '{}'::jsonb) + || jsonb_build_object('quota_used', COALESCE((extra->>'quota_used')::numeric, 0) + $1)` + +// accountQuotaDailyIncrementExpr 在库中设置了日上限时累加日用量,周期过期时从本次金额重新计数。 +const accountQuotaDailyIncrementExpr = ` || CASE WHEN COALESCE((extra->>'quota_daily_limit')::numeric, 0) > 0 THEN jsonb_build_object( 'quota_daily_used', - CASE WHEN `+dailyExpiredExpr+` + CASE WHEN ` + dailyExpiredExpr + ` THEN $1 ELSE COALESCE((extra->>'quota_daily_used')::numeric, 0) + $1 END, 'quota_daily_start', - CASE WHEN `+dailyExpiredExpr+` - THEN `+nowUTC+` - ELSE COALESCE(extra->>'quota_daily_start', `+nowUTC+`) END + CASE WHEN ` + dailyExpiredExpr + ` + THEN ` + nowUTC + ` + ELSE COALESCE(extra->>'quota_daily_start', ` + nowUTC + `) END ) - || CASE WHEN `+dailyExpiredExpr+` AND `+nextDailyResetAtExpr+` IS NOT NULL - THEN jsonb_build_object('quota_daily_reset_at', `+nextDailyResetAtExpr+`) + || CASE WHEN ` + dailyExpiredExpr + ` AND ` + nextDailyResetAtExpr + ` IS NOT NULL + THEN jsonb_build_object('quota_daily_reset_at', ` + nextDailyResetAtExpr + `) ELSE '{}'::jsonb END - ELSE '{}'::jsonb END + ELSE '{}'::jsonb END` + +// accountQuotaWeeklyIncrementExpr 在库中设置了周上限时累加周用量,周期过期时从本次金额重新计数。 +const accountQuotaWeeklyIncrementExpr = ` || CASE WHEN COALESCE((extra->>'quota_weekly_limit')::numeric, 0) > 0 THEN jsonb_build_object( 'quota_weekly_used', - CASE WHEN `+weeklyExpiredExpr+` + CASE WHEN ` + weeklyExpiredExpr + ` THEN $1 ELSE COALESCE((extra->>'quota_weekly_used')::numeric, 0) + $1 END, 'quota_weekly_start', - CASE WHEN `+weeklyExpiredExpr+` - THEN `+nowUTC+` - ELSE COALESCE(extra->>'quota_weekly_start', `+nowUTC+`) END + CASE WHEN ` + weeklyExpiredExpr + ` + THEN ` + nowUTC + ` + ELSE COALESCE(extra->>'quota_weekly_start', ` + nowUTC + `) END ) - || CASE WHEN `+weeklyExpiredExpr+` AND `+nextWeeklyResetAtExpr+` IS NOT NULL - THEN jsonb_build_object('quota_weekly_reset_at', `+nextWeeklyResetAtExpr+`) + || CASE WHEN ` + weeklyExpiredExpr + ` AND ` + nextWeeklyResetAtExpr + ` IS NOT NULL + THEN jsonb_build_object('quota_weekly_reset_at', ` + nextWeeklyResetAtExpr + `) ELSE '{}'::jsonb END - ELSE '{}'::jsonb END - ), updated_at = NOW() - WHERE id = $2 AND deleted_at IS NULL + ELSE '{}'::jsonb END` + +// accountQuotaExtraIsObjectCond 要求 extra 为 JSON 对象:省略某个维度的语句只在对象上与完整语句等价。 +// +// accountQuotaDailyLimitUnsetCond / accountQuotaWeeklyLimitUnsetCond 在库中未设置日/周上限时为真: +// 键不存在、值为 JSON null 或不大于 0 的数字。其他取值一律为假,交给包含该维度的语句处理。 +// 三个条件都只使用 ->、jsonb_typeof 与 jsonb 比较,对任何行求值都不会报错。 +const ( + accountQuotaExtraIsObjectCond = `jsonb_typeof(extra) = 'object'` + accountQuotaDailyLimitUnsetCond = `(extra->'quota_daily_limit' IS NULL + OR jsonb_typeof(extra->'quota_daily_limit') = 'null' + OR (jsonb_typeof(extra->'quota_daily_limit') = 'number' AND extra->'quota_daily_limit' <= '0'::jsonb))` + accountQuotaWeeklyLimitUnsetCond = `(extra->'quota_weekly_limit' IS NULL + OR jsonb_typeof(extra->'quota_weekly_limit') = 'null' + OR (jsonb_typeof(extra->'quota_weekly_limit') = 'number' AND extra->'quota_weekly_limit' <= '0'::jsonb))` +) + +const accountQuotaIncrementReturning = ` RETURNING COALESCE((extra->>'quota_used')::numeric, 0), COALESCE((extra->>'quota_limit')::numeric, 0), COALESCE((extra->>'quota_daily_used')::numeric, 0), COALESCE((extra->>'quota_daily_limit')::numeric, 0), COALESCE((extra->>'quota_weekly_used')::numeric, 0), - COALESCE((extra->>'quota_weekly_limit')::numeric, 0)`, - amount, accountID) + COALESCE((extra->>'quota_weekly_limit')::numeric, 0)` + +// accountQuotaIncrementSQLs 按 accountQuotaIncrementSQLIndex 存放账号配额累加语句。省略日或周维度的语句 +// 在 WHERE 中附加 accountQuotaExtraIsObjectCond 与被省略维度的未设置条件,条件不成立时命中 0 行; +// 同时包含日、周维度的语句不附加这些条件,对任何账号配置都给出完整的累加结果。 +var accountQuotaIncrementSQLs = buildAccountQuotaIncrementSQLs() + +func accountQuotaIncrementSQLIndex(daily, weekly bool) int { + index := 0 + if daily { + index |= 1 + } + if weekly { + index |= 2 + } + return index +} + +func buildAccountQuotaIncrementSQLs() [4]string { + var sqls [4]string + for _, daily := range []bool{false, true} { + for _, weekly := range []bool{false, true} { + set := accountQuotaTotalIncrementExpr + where := "id = $2 AND deleted_at IS NULL" + if !daily || !weekly { + where += "\n\t\t\tAND " + accountQuotaExtraIsObjectCond + } + if daily { + set += accountQuotaDailyIncrementExpr + } else { + where += "\n\t\t\tAND " + accountQuotaDailyLimitUnsetCond + } + if weekly { + set += accountQuotaWeeklyIncrementExpr + } else { + where += "\n\t\t\tAND " + accountQuotaWeeklyLimitUnsetCond + } + sqls[accountQuotaIncrementSQLIndex(daily, weekly)] = "UPDATE accounts SET extra = (\n\t\t\t" + set + + "\n\t\t), updated_at = NOW()\n\t\tWHERE " + where + accountQuotaIncrementReturning + } + } + return sqls +} + +// incrementUsageBillingAccountQuota 累加账号配额并返回累加后的状态。hasDaily/hasWeekly 是调用方所见的 +// 账号日/周上限设置,只决定先执行哪条语句;该语句的附加条件不成立而命中 0 行时,再执行同时包含日、周维度的语句。 +func incrementUsageBillingAccountQuota(ctx context.Context, tx *sql.Tx, accountID int64, amount float64, hasDaily, hasWeekly bool) (*service.AccountQuotaState, error) { + index := accountQuotaIncrementSQLIndex(hasDaily, hasWeekly) + fullIndex := accountQuotaIncrementSQLIndex(true, true) + state, err := execAccountQuotaIncrement(ctx, tx, accountQuotaIncrementSQLs[index], accountID, amount) if err != nil { return nil, err } - - var state service.AccountQuotaState - if rows.Next() { - if err := rows.Scan( - &state.TotalUsed, &state.TotalLimit, - &state.DailyUsed, &state.DailyLimit, - &state.WeeklyUsed, &state.WeeklyLimit, - ); err != nil { - _ = rows.Close() + if state == nil && index != fullIndex { + state, err = execAccountQuotaIncrement(ctx, tx, accountQuotaIncrementSQLs[fullIndex], accountID, amount) + if err != nil { return nil, err } - } else { - if err := rows.Err(); err != nil { - _ = rows.Close() - return nil, err - } - _ = rows.Close() + } + if state == nil { return nil, service.ErrAccountNotFound } - if err := rows.Err(); err != nil { - _ = rows.Close() - return nil, err - } - // 必须在执行下一条 SQL 前显式关闭 rows:pq 驱动在同一连接上 - // 不允许前一条查询的结果集未耗尽时启动新查询,否则会返回 - // "unexpected Parse response" 错误。 - if err := rows.Close(); err != nil { - return nil, err - } // 任意维度额度在本次递增中从"未超"跨越到"已超"时,必须刷新调度快照, // 否则 Redis 中缓存的 Account 仍显示旧的 used 值,后续请求会继续选中本账号, // 最终观察到 daily_used / weekly_used 大幅超过配置的 limit。 @@ -557,5 +604,37 @@ func incrementUsageBillingAccountQuota(ctx context.Context, tx *sql.Tx, accountI return nil, err } } - return &state, nil + return state, nil +} + +// execAccountQuotaIncrement 执行一条账号配额累加语句,未命中任何行时返回 nil 状态。 +func execAccountQuotaIncrement(ctx context.Context, tx *sql.Tx, query string, accountID int64, amount float64) (*service.AccountQuotaState, error) { + rows, err := tx.QueryContext(ctx, query, amount, accountID) + if err != nil { + return nil, err + } + + var state *service.AccountQuotaState + if rows.Next() { + state = &service.AccountQuotaState{} + if err := rows.Scan( + &state.TotalUsed, &state.TotalLimit, + &state.DailyUsed, &state.DailyLimit, + &state.WeeklyUsed, &state.WeeklyLimit, + ); err != nil { + _ = rows.Close() + return nil, err + } + } + if err := rows.Err(); err != nil { + _ = rows.Close() + return nil, err + } + // 必须在执行下一条 SQL 前显式关闭 rows:pq 驱动在同一连接上 + // 不允许前一条查询的结果集未耗尽时启动新查询,否则会返回 + // "unexpected Parse response" 错误。 + if err := rows.Close(); err != nil { + return nil, err + } + return state, nil } diff --git a/backend/internal/repository/usage_billing_repo_integration_test.go b/backend/internal/repository/usage_billing_repo_integration_test.go index c7f2e6c528..07971d08d9 100644 --- a/backend/internal/repository/usage_billing_repo_integration_test.go +++ b/backend/internal/repository/usage_billing_repo_integration_test.go @@ -5,11 +5,13 @@ package repository import ( "context" "fmt" + "maps" "strings" "testing" "time" "github.com/google/uuid" + "github.com/lib/pq" "github.com/stretchr/testify/require" "github.com/Wei-Shaw/sub2api/internal/service" @@ -442,6 +444,140 @@ func TestUsageBillingRepositoryApply_EnqueuesSchedulerOutboxOnQuotaCrossing(t *t require.NoError(t, err) require.Equal(t, 1, outboxCountFor(t, accountID), "single-shot crossing weekly limit should enqueue once") }) + + t.Run("total_first_crossing_enqueues", func(t *testing.T) { + apiKeyID, accountID := newFixture(t, map[string]any{ + "quota_limit": 10.0, + }) + _, err := repo.Apply(ctx, &service.UsageBillingCommand{ + RequestID: uuid.NewString(), + APIKeyID: apiKeyID, + AccountID: accountID, + AccountType: service.AccountTypeAPIKey, + AccountQuotaCost: 4, + }) + require.NoError(t, err) + require.Equal(t, 0, outboxCountFor(t, accountID), "below limit should not enqueue") + + _, err = repo.Apply(ctx, &service.UsageBillingCommand{ + RequestID: uuid.NewString(), + APIKeyID: apiKeyID, + AccountID: accountID, + AccountType: service.AccountTypeAPIKey, + AccountQuotaCost: 8, + }) + require.NoError(t, err) + require.Equal(t, 1, outboxCountFor(t, accountID), "crossing total limit should enqueue once") + }) +} + +func TestIncrementUsageBillingAccountQuota_StatementVariantsMatchFullStatement(t *testing.T) { + ctx := context.Background() + client := testEntClient(t) + now := time.Now().UTC() + at := func(offset time.Duration) string { return now.Add(offset).Format(time.RFC3339) } + + // dailyUnset/weeklyUnset 为库中该维度视为未设置上限:省略该维度的语句在这些配置上命中,其余配置命中 0 行。 + configs := []struct { + name string + extra map[string]any + rawExtra string + dailyUnset bool + weeklyUnset bool + wantErr bool + }{ + {name: "no_limits", extra: map[string]any{}, dailyUnset: true, weeklyUnset: true}, + {name: "total_only", extra: map[string]any{"quota_limit": 100.0, "quota_used": 3.0}, dailyUnset: true, weeklyUnset: true}, + {name: "zero_and_negative_period_limits", extra: map[string]any{"quota_limit": 5.0, "quota_daily_limit": 0.0, "quota_weekly_limit": -1.0}, dailyUnset: true, weeklyUnset: true}, + {name: "null_period_limits", extra: map[string]any{"quota_daily_limit": nil, "quota_weekly_limit": nil}, dailyUnset: true, weeklyUnset: true}, + {name: "string_period_limits", extra: map[string]any{"quota_daily_limit": "10", "quota_weekly_limit": "0"}}, + {name: "daily_rolling_active", extra: map[string]any{"quota_daily_limit": 10.0, "quota_daily_used": 4.0, "quota_daily_start": at(-time.Hour)}, weeklyUnset: true}, + {name: "daily_rolling_expired", extra: map[string]any{"quota_daily_limit": 10.0, "quota_daily_used": 9.0, "quota_daily_start": at(-30 * time.Hour)}, weeklyUnset: true}, + {name: "daily_fixed_expired", extra: map[string]any{ + "quota_daily_limit": 10.0, "quota_daily_used": 7.0, "quota_daily_reset_mode": "fixed", + "quota_daily_reset_hour": 3, "quota_reset_timezone": "Asia/Shanghai", "quota_daily_reset_at": at(-2 * time.Hour), + }, weeklyUnset: true}, + {name: "weekly_rolling_active", extra: map[string]any{"quota_weekly_limit": 50.0, "quota_weekly_used": 20.0, "quota_weekly_start": at(-48 * time.Hour)}, dailyUnset: true}, + {name: "weekly_fixed_expired", extra: map[string]any{ + "quota_weekly_limit": 50.0, "quota_weekly_used": 49.0, "quota_weekly_reset_mode": "fixed", + "quota_weekly_reset_day": 1, "quota_weekly_reset_hour": 0, "quota_reset_timezone": "UTC", "quota_weekly_reset_at": at(-time.Hour), + }, dailyUnset: true}, + {name: "daily_and_weekly", extra: map[string]any{ + "quota_limit": 100.0, "quota_daily_limit": 10.0, "quota_weekly_limit": 50.0, + "quota_daily_used": 1.0, "quota_weekly_used": 2.0, "quota_daily_start": at(-time.Hour), "quota_weekly_start": at(-200 * time.Hour), + }}, + {name: "array_extra", rawExtra: `[]`}, + {name: "scalar_extra", rawExtra: `"value"`}, + {name: "non_numeric_daily_limit", extra: map[string]any{"quota_daily_limit": "abc"}, weeklyUnset: true, wantErr: true}, + {name: "boolean_weekly_limit", extra: map[string]any{"quota_weekly_limit": true}, dailyUnset: true, wantErr: true}, + } + + for _, cfg := range configs { + for _, hints := range [][2]bool{{false, false}, {true, false}, {false, true}, {true, true}} { + t.Run(fmt.Sprintf("%s/daily=%v/weekly=%v", cfg.name, hints[0], hints[1]), func(t *testing.T) { + variant := mustCreateAccount(t, client, &service.Account{ + Name: "usage-billing-quota-variant-" + uuid.NewString(), + Type: service.AccountTypeAPIKey, + Extra: maps.Clone(cfg.extra), + }) + reference := mustCreateAccount(t, client, &service.Account{ + Name: "usage-billing-quota-reference-" + uuid.NewString(), + Type: service.AccountTypeAPIKey, + Extra: maps.Clone(cfg.extra), + }) + if cfg.rawExtra != "" { + _, err := integrationDB.ExecContext(ctx, "UPDATE accounts SET extra = $1::jsonb WHERE id IN ($2, $3)", cfg.rawExtra, variant.ID, reference.ID) + require.NoError(t, err) + t.Cleanup(func() { + _, _ = integrationDB.ExecContext(ctx, "UPDATE accounts SET extra = '{}'::jsonb WHERE id IN ($1, $2)", variant.ID, reference.ID) + }) + } + + if cfg.wantErr { + sqlState := func(accountID int64, daily, weekly bool) pq.ErrorCode { + tx, err := integrationDB.BeginTx(ctx, nil) + require.NoError(t, err) + defer func() { _ = tx.Rollback() }() + _, err = incrementUsageBillingAccountQuota(ctx, tx, accountID, 2.5, daily, weekly) + var pqErr *pq.Error + require.ErrorAs(t, err, &pqErr) + return pqErr.Code + } + require.Equal(t, sqlState(reference.ID, true, true), sqlState(variant.ID, hints[0], hints[1])) + return + } + + tx, err := integrationDB.BeginTx(ctx, nil) + require.NoError(t, err) + defer func() { _ = tx.Rollback() }() + + isObject := cfg.rawExtra == "" + wantHit := (hints[0] && hints[1]) || (isObject && (hints[0] || cfg.dailyUnset) && (hints[1] || cfg.weeklyUnset)) + _, err = tx.ExecContext(ctx, "SAVEPOINT quota_variant_probe") + require.NoError(t, err) + probe, err := execAccountQuotaIncrement(ctx, tx, accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(hints[0], hints[1])], variant.ID, 2.5) + require.NoError(t, err) + require.Equal(t, wantHit, probe != nil, "variant statement hit") + _, err = tx.ExecContext(ctx, "ROLLBACK TO SAVEPOINT quota_variant_probe") + require.NoError(t, err) + + got, err := incrementUsageBillingAccountQuota(ctx, tx, variant.ID, 2.5, hints[0], hints[1]) + require.NoError(t, err) + want, err := incrementUsageBillingAccountQuota(ctx, tx, reference.ID, 2.5, true, true) + require.NoError(t, err) + require.Equal(t, *want, *got) + + var gotExtra, wantExtra string + var sameExtra, sameUpdatedAt bool + require.NoError(t, tx.QueryRowContext(ctx, + "SELECT v.extra::text, r.extra::text, v.extra = r.extra, v.updated_at = r.updated_at FROM accounts v, accounts r WHERE v.id = $1 AND r.id = $2", + variant.ID, reference.ID, + ).Scan(&gotExtra, &wantExtra, &sameExtra, &sameUpdatedAt)) + require.True(t, sameExtra, "variant extra %s != reference extra %s", gotExtra, wantExtra) + require.True(t, sameUpdatedAt) + }) + } + } } func TestDashboardAggregationRepositoryCleanupUsageBillingDedup_BatchDeletesOldRows(t *testing.T) { diff --git a/backend/internal/repository/usage_billing_repo_unit_test.go b/backend/internal/repository/usage_billing_repo_unit_test.go index a745eb8d73..73f29d2e4c 100644 --- a/backend/internal/repository/usage_billing_repo_unit_test.go +++ b/backend/internal/repository/usage_billing_repo_unit_test.go @@ -5,6 +5,7 @@ package repository import ( "context" "database/sql" + "strings" "testing" "github.com/DATA-DOG/go-sqlmock" @@ -22,7 +23,7 @@ const ( userExistsForBillingSQL = `(?s)SELECT 1\s+FROM users\s+WHERE id = \$1 AND deleted_at IS NULL` apiKeyQuotaIncrementSQL = `(?s)UPDATE api_keys\s+SET quota_used = quota_used \+ \$1,.*WHERE id = \$2 AND deleted_at IS NULL\s+RETURNING` apiKeyRateLimitIncrementSQL = `(?s)UPDATE api_keys SET\s+usage_5h = .*WHERE id = \$2 AND deleted_at IS NULL` - accountQuotaIncrementSQL = `(?s)UPDATE accounts SET extra = .*WHERE id = \$2 AND deleted_at IS NULL\s+RETURNING` + accountQuotaIncrementSQL = `(?s)UPDATE accounts SET extra = .*WHERE id = \$2 AND deleted_at IS NULL.*RETURNING` ) func TestDeductUsageBillingBalance_UsesSufficientBalanceGuard(t *testing.T) { @@ -152,7 +153,10 @@ func TestApplyUsageBillingEffects_DeletedAccountStillBillsBalance(t *testing.T) WillReturnRows(sqlmock.NewRows([]string{"balance"}).AddRow(90.0)) mock.ExpectQuery(accountQuotaIncrementSQL). WithArgs(4.0, int64(9)). - WillReturnRows(sqlmock.NewRows([]string{"quota_used", "quota_limit", "quota_daily_used", "quota_daily_limit", "quota_weekly_used", "quota_weekly_limit"})) + WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns)) + mock.ExpectQuery(accountQuotaIncrementSQL). + WithArgs(4.0, int64(9)). + WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns)) mock.ExpectCommit() result := &service.UsageBillingApplyResult{Applied: true} @@ -218,6 +222,100 @@ func TestDeductUsageBillingBalance_ReturnsUserNotFoundWhenNoUserUpdated(t *testi require.NoError(t, mock.ExpectationsWereMet()) } +var accountQuotaStateColumns = []string{"quota_used", "quota_limit", "quota_daily_used", "quota_daily_limit", "quota_weekly_used", "quota_weekly_limit"} + +func TestAccountQuotaIncrementSQLs_GuardOmittedDimensions(t *testing.T) { + for _, daily := range []bool{false, true} { + for _, weekly := range []bool{false, true} { + query := accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(daily, weekly)] + set, where, ok := strings.Cut(query, "WHERE ") + require.True(t, ok) + require.Equal(t, !daily || !weekly, strings.Contains(where, accountQuotaExtraIsObjectCond), "daily=%v weekly=%v", daily, weekly) + require.Equal(t, daily, strings.Contains(set, "'quota_daily_used'"), "daily=%v weekly=%v", daily, weekly) + require.Equal(t, weekly, strings.Contains(set, "'quota_weekly_used'"), "daily=%v weekly=%v", daily, weekly) + require.Equal(t, !daily, strings.Contains(where, accountQuotaDailyLimitUnsetCond), "daily=%v weekly=%v", daily, weekly) + require.Equal(t, !weekly, strings.Contains(where, accountQuotaWeeklyLimitUnsetCond), "daily=%v weekly=%v", daily, weekly) + } + } +} + +func TestIncrementUsageBillingAccountQuota_UsesStatementMatchingHints(t *testing.T) { + ctx := context.Background() + db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) + require.NoError(t, err) + defer func() { _ = db.Close() }() + + mock.ExpectBegin() + tx, err := db.BeginTx(ctx, nil) + require.NoError(t, err) + mock.ExpectQuery(accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(true, false)]). + WithArgs(2.5, int64(9)). + WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns).AddRow(12.5, 100.0, 2.5, 50.0, 0.0, 0.0)) + mock.ExpectCommit() + + state, err := incrementUsageBillingAccountQuota(ctx, tx, 9, 2.5, true, false) + require.NoError(t, err) + require.NotNil(t, state) + require.InDelta(t, 12.5, state.TotalUsed, 0.000001) + require.InDelta(t, 2.5, state.DailyUsed, 0.000001) + require.NoError(t, tx.Commit()) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestIncrementUsageBillingAccountQuota_FallsBackToFullStatementWhenGuardMisses(t *testing.T) { + ctx := context.Background() + db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) + require.NoError(t, err) + defer func() { _ = db.Close() }() + + mock.ExpectBegin() + tx, err := db.BeginTx(ctx, nil) + require.NoError(t, err) + mock.ExpectQuery(accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(false, false)]). + WithArgs(2.5, int64(9)). + WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns)) + mock.ExpectQuery(accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(true, true)]). + WithArgs(2.5, int64(9)). + WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns).AddRow(2.5, 0.0, 0.0, 0.0, 2.5, 20.0)) + mock.ExpectCommit() + + state, err := incrementUsageBillingAccountQuota(ctx, tx, 9, 2.5, false, false) + require.NoError(t, err) + require.NotNil(t, state) + require.InDelta(t, 2.5, state.WeeklyUsed, 0.000001) + require.InDelta(t, 20.0, state.WeeklyLimit, 0.000001) + require.NoError(t, tx.Commit()) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestIncrementUsageBillingAccountQuota_ReturnsNotFoundWhenFullStatementMisses(t *testing.T) { + for _, hints := range [][2]bool{{false, false}, {true, false}, {false, true}, {true, true}} { + ctx := context.Background() + db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) + require.NoError(t, err) + + mock.ExpectBegin() + tx, err := db.BeginTx(ctx, nil) + require.NoError(t, err) + mock.ExpectQuery(accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(hints[0], hints[1])]). + WithArgs(2.5, int64(9)). + WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns)) + if !(hints[0] && hints[1]) { + mock.ExpectQuery(accountQuotaIncrementSQLs[accountQuotaIncrementSQLIndex(true, true)]). + WithArgs(2.5, int64(9)). + WillReturnRows(sqlmock.NewRows(accountQuotaStateColumns)) + } + mock.ExpectRollback() + + state, err := incrementUsageBillingAccountQuota(ctx, tx, 9, 2.5, hints[0], hints[1]) + require.ErrorIs(t, err, service.ErrAccountNotFound, "hints=%v", hints) + require.Nil(t, state) + require.NoError(t, tx.Rollback()) + require.NoError(t, mock.ExpectationsWereMet(), "hints=%v", hints) + _ = db.Close() + } +} + func TestReserveUsageBillingBatchImageBalance_MovesAvailableToFrozen(t *testing.T) { ctx := context.Background() db, mock, err := sqlmock.New() diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index 426209b296..580ca81dc1 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -345,6 +345,8 @@ func buildUsageBillingCommand(requestID string, usageLog *UsageLog, p *postUsage } if p.shouldUpdateAccountQuota() { cmd.AccountQuotaCost = p.Cost.TotalCost * p.AccountRateMultiplier + cmd.AccountQuotaHasDailyLimit = p.Account.GetQuotaDailyLimit() > 0 + cmd.AccountQuotaHasWeeklyLimit = p.Account.GetQuotaWeeklyLimit() > 0 } cmd.Normalize() diff --git a/backend/internal/service/gateway_usage_billing_account_quota_test.go b/backend/internal/service/gateway_usage_billing_account_quota_test.go new file mode 100644 index 0000000000..8d45bcc54c --- /dev/null +++ b/backend/internal/service/gateway_usage_billing_account_quota_test.go @@ -0,0 +1,92 @@ +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestBuildUsageBillingCommand_AccountQuotaPeriodHints(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + accountType string + extra map[string]any + wantQuota bool + wantDaily bool + wantWeekly bool + }{ + {name: "no_limits", extra: map[string]any{}}, + {name: "total_only", extra: map[string]any{"quota_limit": 10.0}, wantQuota: true}, + {name: "daily_only", extra: map[string]any{"quota_daily_limit": 5.0}, wantQuota: true, wantDaily: true}, + {name: "weekly_only", extra: map[string]any{"quota_weekly_limit": 5.0}, wantQuota: true, wantWeekly: true}, + { + name: "all_dimensions", + extra: map[string]any{"quota_limit": 10.0, "quota_daily_limit": 5.0, "quota_weekly_limit": 7.0}, + wantQuota: true, wantDaily: true, wantWeekly: true, + }, + { + name: "non_positive_period_limits", + extra: map[string]any{"quota_limit": 10.0, "quota_daily_limit": 0.0, "quota_weekly_limit": -1.0}, + wantQuota: true, + }, + { + name: "service_account_total_only", + accountType: AccountTypeServiceAccount, + extra: map[string]any{"quota_limit": 10.0}, + wantQuota: true, + }, + { + name: "service_account_daily", + accountType: AccountTypeServiceAccount, + extra: map[string]any{"quota_limit": 10.0, "quota_daily_limit": 5.0}, + wantQuota: true, wantDaily: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + accountType := tt.accountType + if accountType == "" { + accountType = AccountTypeAPIKey + } + p := &postUsageBillingParams{ + Cost: &CostBreakdown{TotalCost: 1, ActualCost: 1}, + User: &User{ID: 1}, + APIKey: &APIKey{ID: 2}, + Account: &Account{ID: 3, Type: accountType, Extra: tt.extra}, + AccountRateMultiplier: 1, + } + + cmd := buildUsageBillingCommand("req-1", nil, p) + require.NotNil(t, cmd) + require.Equal(t, tt.wantQuota, cmd.AccountQuotaCost > 0) + require.Equal(t, tt.wantDaily, cmd.AccountQuotaHasDailyLimit) + require.Equal(t, tt.wantWeekly, cmd.AccountQuotaHasWeeklyLimit) + }) + } +} + +func TestUsageBillingCommandFingerprintIgnoresAccountQuotaPeriodHints(t *testing.T) { + t.Parallel() + + base := UsageBillingCommand{ + RequestID: "req-1", + UserID: 1, + APIKeyID: 2, + AccountID: 3, + AccountType: AccountTypeAPIKey, + BalanceCost: 1, + AccountQuotaCost: 1, + } + hinted := base + hinted.AccountQuotaHasDailyLimit = true + hinted.AccountQuotaHasWeeklyLimit = true + + base.Normalize() + hinted.Normalize() + require.NotEmpty(t, base.RequestFingerprint) + require.Equal(t, base.RequestFingerprint, hinted.RequestFingerprint) +} diff --git a/backend/internal/service/usage_billing.go b/backend/internal/service/usage_billing.go index e058ecb1b0..447260ecb4 100644 --- a/backend/internal/service/usage_billing.go +++ b/backend/internal/service/usage_billing.go @@ -42,6 +42,11 @@ type UsageBillingCommand struct { APIKeyQuotaCost float64 APIKeyRateLimitCost float64 AccountQuotaCost float64 + + // AccountQuotaHasDailyLimit / AccountQuotaHasWeeklyLimit 记录构造命令时账号是否设置了日/周上限, + // 只用于选择账号配额累加语句,不参与幂等指纹;实际累加哪些维度以数据库中的账号配置为准。 + AccountQuotaHasDailyLimit bool + AccountQuotaHasWeeklyLimit bool } func (c *UsageBillingCommand) Normalize() { From 7da09cab4e875463baa79fc150adde700c5438df Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 21 Oct 2026 20:19:37 +0800 Subject: [PATCH 023/297] chore: update sponsors --- README.md | 5 +++++ README_CN.md | 5 +++++ README_JA.md | 5 +++++ assets/partners/logos/chenju_ai.png | Bin 0 -> 115826 bytes 4 files changed, 15 insertions(+) create mode 100644 assets/partners/logos/chenju_ai.png diff --git a/README.md b/README.md index 985201c14b..11955a37b6 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,11 @@ Please read the following carefully before using this project: Modelflare: Full strength, stable, nothing watered down. Global SOTA models at a lower cost. Operated by US-based Havenbyte LLC, Modelflare supports GPT, Claude, Gemini, Grok, and other leading models through common compatible protocols, plus 40+ image and video models. Cache compensation is a highlight: selected OpenAI groups (price-first, stable, and premium) guarantee daily cache hit rates of 65%, 75%, or 85%, and if eligible requests fall short, Modelflare refunds the difference, visible on the usage dashboard after settlement. Special offers: a single top-up of US$20 unlocks the GPT discount group at a 0.015x price multiplier, and a single top-up of US$50 unlocks the Claude discount group at a 0.03x multiplier. Register via this exclusive link to get started. + +Chenju +Thanks to Chenju for sponsoring this project! This is probably the only ad slot in this section that doesn't ask you to sign up for anything. Good open-source projects deserve to be paid for, so Chenju is chipping in a gift and raising a glass to the author. Find Chenju on X to chat about API relays, upstream providers, or just shoot the breeze. + + ## Overview diff --git a/README_CN.md b/README_CN.md index 9d126cb144..9064b68eac 100644 --- a/README_CN.md +++ b/README_CN.md @@ -154,6 +154,11 @@ Modelflare:满血稳定不掺水,低成本享受全球 SOTA 模型。站点由美国 LLC 主体 Havenbyte LLC 运营,支持 GPT、Claude、Gemini、Grok 等主流模型和常用兼容协议,还支持 40 多种图片和视频模型。缓存补偿是一大亮点:部分 OpenAI 价格优先、稳定和高级分组提供每日 65%、75%、85% 的缓存命中率保障,符合条件的请求没达到目标的,平台补偿差额,结算后可在用量看板查看。特惠活动:单笔充值 US$20 即可解锁 0.015 倍价格倍率的 GPT 特惠分组,单笔充值 US$50 即可解锁 0.03 倍价格倍率的 Claude 特惠分组。通过专属链接注册即可参与 + +Chenju +感谢 陈局 赞助了本项目!这大概是本栏唯一一个不让你注册的广告位。好的开源项目值得被付费,陈局来随个份子,敬作者一杯。X 上找 陈局,聊中转、聊上游、吹吹水。 + + ## 项目概述 diff --git a/README_JA.md b/README_JA.md index bf5f13b930..367cce6373 100644 --- a/README_JA.md +++ b/README_JA.md @@ -153,6 +153,11 @@ Modelflare:フルスペック、安定、水増しなし。世界の SOTA モデルを、より低いコストで。米国拠点の Havenbyte LLC が運営する Modelflare は、一般的な互換プロトコルを通じて GPT、Claude、Gemini、Grok などの主要モデルに対応し、さらに 40 以上の画像・動画モデルも利用できます。注目はキャッシュ補償です。対象の OpenAI グループ(価格優先・安定・プレミアム)は、1 日のキャッシュヒット率をそれぞれ 65%、75%、85% で保証します。対象リクエストがこの水準に達しない場合、Modelflare が差額を返金し、精算後に利用状況ダッシュボードで確認できます。特別オファー:US$20 を 1 回チャージすると、価格倍率 0.015 倍の GPT 割引グループが解放されます。US$50 を 1 回チャージすると、価格倍率 0.03 倍の Claude 割引グループが解放されます。こちらの専用リンクから登録して始めましょう。 + +Chenju +陈局(Chenju)様、本プロジェクトへのご支援ありがとうございます!これはおそらく、この欄で唯一「登録しなくていい」広告枠です。良いオープンソースには対価が払われるべき——というわけで、陈局がご祝儀を包んで作者に一杯おごります。X で 陈局 を見つけて、中継サービスや上流の話、雑談でもどうぞ。 + + ## 概要 diff --git a/assets/partners/logos/chenju_ai.png b/assets/partners/logos/chenju_ai.png new file mode 100644 index 0000000000000000000000000000000000000000..2e4affee5d60580d2a89f20a3805c7253e8347ae GIT binary patch literal 115826 zcmd43bySpJ+cr!|Nh94QC<4+YouX3G-5t`+kVBUeg1`_eNJvS?NFz0bba%th1I#e* z_^#)ZsF&&sG;^JS?nfiXp^r?8>Up=mj`ASjjK*h-Cal*n=SpeS8jg= zX&jaG44+k|9iq($nGT#DI7|1tx)~`CSZ;?%BUzdr+k@mssTGtd zTpEq6H;kGYI~LvQ-ygWF-5MlgasU4DfBh_O5rK@HEGNc4e(l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0;_(mkyam%ubd}I2sv-5wtkodzr8Vq49j_I!dT_FeQQANFY0q-j-A*%6D z9{3T-zWx5c92WSuTfqLp2eoxVI7NiN#Qgsf9aRbl{NGMU{8NGa=f(Qusdo<3li&Kg z{|Wj(CJA^41J-}~+8cODosIweEQ+Tp Date: Wed, 21 Oct 2026 22:47:11 +0800 Subject: [PATCH 024/297] =?UTF-8?q?fix(build):=20=E5=AF=B9=E9=BD=90?= =?UTF-8?q?=E4=B8=8A=E6=B8=B8=20Go=201.27.3=20=E9=95=9C=E5=83=8F=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index aad052f4fd..0242d6f13e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,7 +8,7 @@ # ============================================================================= ARG NODE_IMAGE=node:24-alpine -ARG GOLANG_IMAGE=golang:1.27.2-alpine +ARG GOLANG_IMAGE=golang:1.27.3-alpine ARG ALPINE_IMAGE=alpine:3.21 ARG POSTGRES_IMAGE=postgres:18-alpine ARG GOPROXY=https://goproxy.cn,direct From de908ed6d29339fec04dcd9b39dab95b47a49575 Mon Sep 17 00:00:00 2001 From: coder-zhw <5379212+coder-zhw@users.noreply.github.com> Date: Thu, 22 Oct 2026 11:42:54 +0800 Subject: [PATCH 025/297] =?UTF-8?q?fix(ratelimit):=20=E5=9B=BD=E4=BA=A7=20?= =?UTF-8?q?Coding=20Plan=20=E7=9A=84=E9=A2=91=E7=8E=87=E5=9E=8B=20429=20?= =?UTF-8?q?=E6=94=B9=E7=94=A8=E7=A7=92=E7=BA=A7=E5=86=B7=E5=8D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 国产 Coding Plan 账号收到 429 时一律冷却到配额快照里最早的窗口重置点 (cooldownCNProviderToQuotaSnapshotReset)。但智谱对 Coding Plan 另有一层 请求频率限制,实测文案「您的账户已达到速率限制,请您控制请求频率」,此时 窗口额度往往只用了 10%~20%:一次并发突发就会把账号停调到 5h 窗口结束 (线上实测 1.5~4.8 小时),把「限频」误伤成「额度耗尽」。 改为按响应文案区分:命中频控文案、且快照显示窗口仍有可观余量(任一窗口 < 90%)时,不再走窗口冷却,交给默认 429 兜底 apply429FallbackRateLimit (管理端可配,默认 5s)。两条护栏: - 文案里同时出现额度类词(额度 / quota / usage limit / insufficient 等) 一律不降级; - 快照缺失、或任一窗口 >= 90% 一律不降级 —— 宁可多停调,也不要把真正的 额度耗尽当成限频反复重试。 窗口真正耗尽时行为完全不变;余额不足路径(临时停调)也不受影响。 --- .../ratelimit_cn_frequency_429_test.go | 139 ++++++++++++++++++ .../service/ratelimit_cn_providers.go | 101 ++++++++++++- 2 files changed, 239 insertions(+), 1 deletion(-) create mode 100644 backend/internal/service/ratelimit_cn_frequency_429_test.go diff --git a/backend/internal/service/ratelimit_cn_frequency_429_test.go b/backend/internal/service/ratelimit_cn_frequency_429_test.go new file mode 100644 index 0000000000..2343a0152c --- /dev/null +++ b/backend/internal/service/ratelimit_cn_frequency_429_test.go @@ -0,0 +1,139 @@ +//go:build unit + +package service + +import ( + "context" + "net/http" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +// 智谱 GLM Coding Plan 实测 429 文案:额度充裕时的「限频」。 +const zhipuFrequencyLimitedBody = `{"error":{"code":"1302","message":"您的账户已达到速率限制,请您控制请求频率"}}` + +// newZhipuCodingPlanAccount 构造一个智谱 Coding Plan 账号,Extra 带 5h/weekly +// 用量与重置快照(与 CNProviderQuotaService 写入的键一致)。 +func newZhipuCodingPlanAccount(h5Used, weeklyUsed float64, resetIn time.Duration) *Account { + extra := map[string]any{ + cnExtraKey(PlatformZhipu, cnExtraSuffix5hUsed): h5Used, + cnExtraKey(PlatformZhipu, cnExtraSuffixWeeklyUsed): weeklyUsed, + } + if resetIn > 0 { + extra[cnExtraKey(PlatformZhipu, cnExtraSuffix5hReset)] = time.Now().Add(resetIn).UTC().Format(time.RFC3339) + extra[cnExtraKey(PlatformZhipu, cnExtraSuffixWeeklyReset)] = time.Now().Add(4 * 24 * time.Hour).UTC().Format(time.RFC3339) + } + return &Account{ + ID: 701, + Platform: PlatformZhipu, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"account_mode": AccountModeCoding}, + Extra: extra, + } +} + +func runZhipu429(service *RateLimitService, account *Account, body string) bool { + return service.HandleUpstreamError( + context.Background(), + account, + http.StatusTooManyRequests, + http.Header{}, + []byte(body), + ) +} + +// 额度充裕 + 限频文案 → 走秒级 429 兜底,而不是冷却到 5h 窗口结束。 +func TestHandleUpstreamError_ZhipuFrequency429UsesShortCooldown(t *testing.T) { + repo := &rateLimitAccountRepoStub{} + service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + account := newZhipuCodingPlanAccount(12, 4, 4*time.Hour) + + runZhipu429(service, account, zhipuFrequencyLimitedBody) + + require.Equal(t, 0, repo.setErrorCalls, "a frequency 429 must never SetError") + require.Equal(t, 1, repo.rateLimitedCalls) + require.Equal(t, account.ID, repo.lastRateLimitedID) + require.WithinDuration(t, time.Now().Add(defaultRateLimit429CooldownSeconds*time.Second), + repo.lastRateLimitedAt, 30*time.Second, + "frequency 429 must cool down seconds, not to the 5h window reset") +} + +// 快照显示窗口已耗尽时,即使文案是限频,也仍然冷却到窗口重置点(护栏)。 +func TestHandleUpstreamError_ZhipuFrequency429WithExhaustedSnapshotKeepsWindowCooldown(t *testing.T) { + repo := &rateLimitAccountRepoStub{} + service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + account := newZhipuCodingPlanAccount(100, 40, 2*time.Hour) + + runZhipu429(service, account, zhipuFrequencyLimitedBody) + + require.Equal(t, 0, repo.setErrorCalls) + require.Equal(t, 1, repo.rateLimitedCalls) + require.True(t, repo.lastRateLimitedAt.After(time.Now().Add(time.Hour)), + "exhausted snapshot must keep cooling down to the window reset") +} + +// 额度类文案(即使同时出现"速率限制"字样)不降级,仍按窗口冷却。 +func TestHandleUpstreamError_ZhipuQuotaWorded429KeepsWindowCooldown(t *testing.T) { + repo := &rateLimitAccountRepoStub{} + service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + account := newZhipuCodingPlanAccount(12, 4, 2*time.Hour) + body := `{"error":{"message":"已达速率限制:本月额度已用尽,请升级套餐"}}` + + runZhipu429(service, account, body) + + require.Equal(t, 1, repo.rateLimitedCalls) + require.True(t, repo.lastRateLimitedAt.After(time.Now().Add(time.Hour)), + "quota wording must not be downgraded to the short 429 cooldown") +} + +// 余额不足文案仍走原有的临时停调路径,不受本次改动影响。 +func TestHandleUpstreamError_ZhipuInsufficientBalance429StillTempUnschedulable(t *testing.T) { + repo := &rateLimitAccountRepoStub{} + service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + account := newZhipuCodingPlanAccount(12, 4, 4*time.Hour) + + runZhipu429(service, account, `{"error":{"message":"余额不足,请充值"}}`) + + require.Equal(t, 0, repo.rateLimitedCalls) + require.Equal(t, 1, repo.tempCalls) + require.Contains(t, repo.lastTempReason, cnBalanceLowReasonPrefix) +} + +func TestCNProviderResponseIndicatesFrequencyLimit(t *testing.T) { + cases := []struct { + name string + body string + want bool + }{ + {"zhipu frequency wording", zhipuFrequencyLimitedBody, true}, + {"generic too many requests", `{"error":{"message":"Too many requests, please slow down"}}`, true}, + {"openai style rate limit", `{"error":{"code":"rate_limit_exceeded","message":"Rate limit exceeded"}}`, true}, + {"quota wording wins", `{"error":{"message":"已达到速率限制,但本月额度已用尽"}}`, false}, + {"usage limit wording wins", `{"error":{"message":"You've reached your weekly usage limit"}}`, false}, + {"insufficient balance wins", `{"error":{"message":"insufficient balance"}}`, false}, + {"unrelated error", `{"error":{"message":"model not found"}}`, false}, + {"empty body", ``, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.want, cnProviderResponseIndicatesFrequencyLimit([]byte(tc.body))) + }) + } +} + +func TestCNProviderQuotaSnapshotNearExhausted(t *testing.T) { + require.False(t, cnProviderQuotaSnapshotNearExhausted( + newZhipuCodingPlanAccount(12, 4, time.Hour), cnFrequencyLimitQuotaGuardPercent)) + require.True(t, cnProviderQuotaSnapshotNearExhausted( + newZhipuCodingPlanAccount(90, 4, time.Hour), cnFrequencyLimitQuotaGuardPercent)) + require.True(t, cnProviderQuotaSnapshotNearExhausted( + newZhipuCodingPlanAccount(12, 95, time.Hour), cnFrequencyLimitQuotaGuardPercent)) + + // 快照缺失:无法证明与额度无关 → 保守视为接近耗尽(沿用窗口冷却)。 + require.True(t, cnProviderQuotaSnapshotNearExhausted( + &Account{ID: 702, Platform: PlatformZhipu}, cnFrequencyLimitQuotaGuardPercent)) + require.True(t, cnProviderQuotaSnapshotNearExhausted(nil, cnFrequencyLimitQuotaGuardPercent)) +} diff --git a/backend/internal/service/ratelimit_cn_providers.go b/backend/internal/service/ratelimit_cn_providers.go index 226f7bdb0f..8ffa3e774d 100644 --- a/backend/internal/service/ratelimit_cn_providers.go +++ b/backend/internal/service/ratelimit_cn_providers.go @@ -121,6 +121,90 @@ func cnProviderResponseIndicatesInsufficientBalance(body []byte) bool { strings.Contains(s, "no enough balance") } +// cnFrequencyLimitQuotaGuardPercent 是「频率型 429」降级前必须通过的额度护栏: +// 快照里任一窗口用量达到该百分比,就不再按频控处理,仍冷却到窗口重置点。 +// 快照最多滞后一个额度探测周期(默认 10 分钟),因此真实耗尽在极端情况下可能 +// 被短暂降级成秒级冷却;5 秒后重试仍会拿到 429,下一轮探测刷新快照后自动纠正。 +const cnFrequencyLimitQuotaGuardPercent = 90 + +// cnFrequencyLimitMarkers 是「请求频率/速率限制」类 429 的文案特征(小写比较)。 +// 智谱实测文案:「您的账户已达到速率限制,请您控制请求频率」。 +var cnFrequencyLimitMarkers = []string{ + "速率限制", + "请求频率", + "访问频率", + "请求过于频繁", + "请求太频繁", + "too many requests", + "rate limit exceeded", + "rate_limit_exceeded", + "ratelimit exceeded", +} + +// cnQuotaExhaustionMarkers 是额度耗尽类文案;命中任一即认为 429 与额度有关, +// 绝不降级为短冷却(宁可多停调,也不要把真耗尽当成限频反复重试)。 +var cnQuotaExhaustionMarkers = []string{ + "额度", + "已用尽", + "用完", + "quota", + "usage limit", + "insufficient", + "balance", +} + +// cnProviderResponseIndicatesFrequencyLimit 通过响应体文案识别「请求频率/速率 +// 限制」类 429 —— 它与滚动窗口的额度消耗无关,重试即可能成功,不该按额度 +// 耗尽冷却到窗口结束。命中频控文案且不含任何额度类文案才算频控。 +func cnProviderResponseIndicatesFrequencyLimit(body []byte) bool { + if len(body) == 0 { + return false + } + s := strings.ToLower(string(body)) + matched := false + for _, marker := range cnFrequencyLimitMarkers { + if strings.Contains(s, marker) { + matched = true + break + } + } + if !matched { + return false + } + for _, marker := range cnQuotaExhaustionMarkers { + if strings.Contains(s, marker) { + return false + } + } + return true +} + +// cnProviderQuotaSnapshotNearExhausted 判断 Coding Plan 账号的滚动窗口用量快照 +// 是否已接近耗尽(任一窗口 >= percent)。快照完全缺失(额度探测还没跑过或 +// 解析失败)时返回 true:此时无法证明 429 与额度无关,保守沿用窗口冷却。 +func cnProviderQuotaSnapshotNearExhausted(account *Account, percent float64) bool { + if account == nil || len(account.Extra) == 0 { + return true + } + provider := account.Platform + suffixes := []string{cnExtraSuffix5hUsed, cnExtraSuffixWeeklyUsed} + if cnQuotaHasMonthlyWindow(provider) { + suffixes = append(suffixes, cnExtraSuffixMonthlyUsed) + } + seen := false + for _, suffix := range suffixes { + raw, ok := account.Extra[cnExtraKey(provider, suffix)] + if !ok { + continue + } + seen = true + if schedulingPercentValue(raw) >= percent { + return true + } + } + return !seen +} + // handleCNProviderInsufficientBalance 把余额不足标记为可恢复的临时停调: // 写入 balance_low 快照 + SetTempUnschedulable 一个余额检测周期, // 由周期任务在余额恢复后清除。返回前已通知调度阻塞。 @@ -288,7 +372,22 @@ func (s *RateLimitService) applyCNProviderReactive429( s.handleCNProviderInsufficientBalance(ctx, account, extractUpstreamErrorMessage(responseBody)) return true } - // 2) Coding Plan 窗口耗尽:冷却到快照中最早的窗口重置点(见 + // 2) 频率型 429("速率限制"/"请求频率"):与滚动窗口额度无关,交给默认 429 + // 兜底使用秒级冷却(管理端可配,默认 5s)。否则一次并发突发会把账号冷却到 + // 5h 窗口结束(实测 1.5~4.8 小时),把「限频」误伤成「额度耗尽」。 + // 护栏:快照显示窗口用量已接近耗尽时不降级,仍按窗口冷却(见 + // cnProviderQuotaSnapshotNearExhausted)。 + if account.IsCodingPlan() && + cnProviderResponseIndicatesFrequencyLimit(responseBody) && + !cnProviderQuotaSnapshotNearExhausted(account, cnFrequencyLimitQuotaGuardPercent) { + slog.Info("cn_coding_plan_frequency_429", + "account_id", account.ID, + "platform", account.Platform, + "handling", "short_429_cooldown", + ) + return false + } + // 3) Coding Plan 窗口耗尽:冷却到快照中最早的窗口重置点(见 // cnProviderQuotaSnapshotReset:429 多由 5h 窗口触发,取较早点避免过度停调)。 if account.IsCodingPlan() && s.cooldownCNProviderToQuotaSnapshotReset(ctx, account, "429", "cn_coding_plan_rate_limited") != nil { From 4197fa62021ca1fe7933fe3eb08ae119dc1fe91b Mon Sep 17 00:00:00 2001 From: feeeei Date: Thu, 22 Oct 2026 10:35:49 +0800 Subject: [PATCH 026/297] =?UTF-8?q?feat(gemini):=20=E5=90=8C=E8=B4=A6?= =?UTF-8?q?=E5=8F=B7=E9=87=8D=E8=AF=95=E6=AC=A1=E6=95=B0=E6=94=B9=E4=B8=BA?= =?UTF-8?q?=E5=8F=AF=E9=85=8D=E7=BD=AE=20gateway.max=5Fsame=5Faccount=5Fre?= =?UTF-8?q?tries=5Fgemini?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Gemini 三条转发路径(原生 v1beta、Claude 兼容、Chat 兼容)对 429/5xx 等可重试 上游错误的同号重试次数读取 gateway.max_same_account_retries_gemini(不含首次请求, 默认 4,范围 0–10),取代写死的每号 5 次请求。默认值下不涉及签名降级的请求仍是 每号最多 5 次。 Claude 兼容路径的签名错误两阶段降级重发不占用同号重试次数:每进入一个降级阶段 循环上限顺延一次,重试次数调小时第二阶段降级照常执行,循环不会带着已关闭的响应体 退出。默认配置下先降级再遇瞬时错误的请求单号最多 7 次请求。 --- backend/internal/config/config.go | 6 ++ backend/internal/config/config_test.go | 23 +++++ .../gemini_chat_completions_compat_service.go | 7 +- .../gemini_error_policy_single_check_test.go | 1 + .../service/gemini_messages_compat_service.go | 34 ++++--- .../gemini_same_account_retries_test.go | 92 +++++++++++++++++++ .../gemini_vertex_api_key_forward_test.go | 2 +- 7 files changed, 150 insertions(+), 15 deletions(-) create mode 100644 backend/internal/service/gemini_same_account_retries_test.go diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index 1f488c89af..3c6e562164 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -1109,6 +1109,8 @@ type GatewayConfig struct { MaxAccountSwitches int `mapstructure:"max_account_switches"` // Gemini 账户切换最大次数(Gemini 平台单独配置,因 API 限制更严格) MaxAccountSwitchesGemini int `mapstructure:"max_account_switches_gemini"` + // Gemini 同账号重试次数(429/5xx 等可重试错误在换号前对同一账号的重发次数,不含首次请求) + MaxSameAccountRetriesGemini int `mapstructure:"max_same_account_retries_gemini"` // Antigravity 429 fallback 限流时间(分钟),解析重置时间失败时使用 AntigravityFallbackCooldownMinutes int `mapstructure:"antigravity_fallback_cooldown_minutes"` @@ -2434,6 +2436,7 @@ func setDefaults() { viper.SetDefault("gateway.failover_on_400", false) viper.SetDefault("gateway.max_account_switches", 10) viper.SetDefault("gateway.max_account_switches_gemini", 3) + viper.SetDefault("gateway.max_same_account_retries_gemini", 4) viper.SetDefault("gateway.force_codex_cli", false) viper.SetDefault("gateway.disable_codex_identity_enforcement", false) viper.SetDefault("gateway.disable_codex_originator_normalization", false) @@ -3371,6 +3374,9 @@ func (c *Config) Validate() error { if c.Gateway.GrokResponseHeaderTimeout < 0 || c.Gateway.GrokResponseHeaderTimeout > 1800 { return fmt.Errorf("gateway.grok_response_header_timeout must be between 0-1800 seconds") } + if c.Gateway.MaxSameAccountRetriesGemini < 0 || c.Gateway.MaxSameAccountRetriesGemini > 10 { + return fmt.Errorf("gateway.max_same_account_retries_gemini must be between 0-10") + } if c.Gateway.OpenAIFirstOutputTimeoutSeconds < 0 || c.Gateway.OpenAIFirstOutputTimeoutSeconds > 600 || (c.Gateway.OpenAIFirstOutputTimeoutSeconds > 0 && c.Gateway.OpenAIFirstOutputTimeoutSeconds < 30) { return fmt.Errorf("gateway.openai_first_output_timeout_seconds must be 0 or between 30-600 seconds") diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go index 434b889955..adb48e5bb2 100644 --- a/backend/internal/config/config_test.go +++ b/backend/internal/config/config_test.go @@ -46,6 +46,19 @@ func TestLoadMinOutputTokensFromEnv(t *testing.T) { require.Equal(t, 16, cfg.Gateway.MinOutputTokens) } +func TestLoadGeminiSameAccountRetries(t *testing.T) { + resetViperWithJWTSecret(t) + cfg, err := Load() + require.NoError(t, err) + require.Equal(t, 4, cfg.Gateway.MaxSameAccountRetriesGemini) + + resetViperWithJWTSecret(t) + t.Setenv("GATEWAY_MAX_SAME_ACCOUNT_RETRIES_GEMINI", "0") + cfg, err = Load() + require.NoError(t, err) + require.Zero(t, cfg.Gateway.MaxSameAccountRetriesGemini) +} + func TestValidateMinOutputTokensMinimum(t *testing.T) { resetViperWithJWTSecret(t) cfg, err := Load() @@ -1887,6 +1900,16 @@ func TestValidateConfigErrors(t *testing.T) { mutate: func(c *Config) { c.Gateway.OpenAIResponseHeaderTimeout = -1 }, wantErr: "gateway.openai_response_header_timeout", }, + { + name: "gateway gemini same account retries negative", + mutate: func(c *Config) { c.Gateway.MaxSameAccountRetriesGemini = -1 }, + wantErr: "gateway.max_same_account_retries_gemini", + }, + { + name: "gateway gemini same account retries too large", + mutate: func(c *Config) { c.Gateway.MaxSameAccountRetriesGemini = 11 }, + wantErr: "gateway.max_same_account_retries_gemini", + }, { name: "gateway openai first output timeout below minimum", mutate: func(c *Config) { c.Gateway.OpenAIFirstOutputTimeoutSeconds = 29 }, diff --git a/backend/internal/service/gemini_chat_completions_compat_service.go b/backend/internal/service/gemini_chat_completions_compat_service.go index 02dcc073ff..e4924024f9 100644 --- a/backend/internal/service/gemini_chat_completions_compat_service.go +++ b/backend/internal/service/gemini_chat_completions_compat_service.go @@ -127,7 +127,8 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( var resp *http.Response // checkedPolicy 是循环内对当前 resp 的错误策略检查结果,未检查时为 nil。 var checkedPolicy *ErrorPolicyResult - for attempt := 1; attempt <= geminiMaxRetries; attempt++ { + maxAttempts := s.geminiMaxAttemptsPerAccount() + for attempt := 1; attempt <= maxAttempts; attempt++ { upstreamReq, idHeader, err := buildReq(ctx) if err != nil { if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { @@ -166,7 +167,7 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( if resp.StatusCode == http.StatusTooManyRequests { s.handleGeminiUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody) } - if attempt < geminiMaxRetries { + if attempt < maxAttempts { upstreamReqID := resp.Header.Get(requestIDHeader) if upstreamReqID == "" { upstreamReqID = resp.Header.Get("x-goog-request-id") @@ -184,7 +185,7 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( Kind: "retry", Message: upstreamMsg, }) - logger.LegacyPrintf("service.gemini_chat_completions", "Gemini account %d: upstream status %d, retry %d/%d", account.ID, resp.StatusCode, attempt, geminiMaxRetries) + logger.LegacyPrintf("service.gemini_chat_completions", "Gemini account %d: upstream status %d, retry %d/%d", account.ID, resp.StatusCode, attempt, maxAttempts) sleepGeminiBackoff(attempt) continue } diff --git a/backend/internal/service/gemini_error_policy_single_check_test.go b/backend/internal/service/gemini_error_policy_single_check_test.go index 0ba4344c53..3ab842a534 100644 --- a/backend/internal/service/gemini_error_policy_single_check_test.go +++ b/backend/internal/service/gemini_error_policy_single_check_test.go @@ -182,6 +182,7 @@ func TestGeminiForward_UncheckedFinalResponseIsCheckedAfterLoop(t *testing.T) { geminiSequenceUpstreamResponse{status: http.StatusServiceUnavailable, body: `{"error":{"code":503,"message":"backend busy","status":"UNAVAILABLE"}}`}, geminiSequenceUpstreamResponse{status: http.StatusBadRequest, body: `{"error":{"code":400,"message":"quota project misconfigured","status":"FAILED_PRECONDITION"}}`}, ) + svc.cfg.Gateway.MaxSameAccountRetriesGemini = 1 account := geminiAPIKeyAccountWithTempRule(map[string]any{ "error_code": float64(400), "keywords": []any{"misconfigured"}, diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index b4ca7607ad..386b17c473 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -35,9 +35,10 @@ import ( const geminiStickySessionTTL = time.Hour const ( - geminiMaxRetries = 5 - geminiRetryBaseDelay = 1 * time.Second - geminiRetryMaxDelay = 16 * time.Second + // 未注入配置时的同账号重试次数,与 gateway.max_same_account_retries_gemini 默认值一致 + geminiDefaultSameAccountRetries = 4 + geminiRetryBaseDelay = 1 * time.Second + geminiRetryMaxDelay = 16 * time.Second ) const ( @@ -717,7 +718,9 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex // checkedPolicy 是循环内对当前 resp 的错误策略检查结果,未检查时为 nil。 var checkedPolicy *ErrorPolicyResult signatureRetryStage := 0 - for attempt := 1; attempt <= geminiMaxRetries; attempt++ { + maxAttempts := s.geminiMaxAttemptsPerAccount() + // 签名降级重发不占用同号重试次数:每进入一个降级阶段,循环上限随之顺延一次。 + for attempt := 1; attempt <= maxAttempts+signatureRetryStage; attempt++ { checkedPolicy = nil upstreamReq, idHeader, err := buildReq(ctx) if err != nil { @@ -798,7 +801,6 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex logger.LegacyPrintf("service.gemini_messages_compat", "Gemini account %d: detected signature-related 400, retrying with downgraded Claude blocks (%s)", account.ID, stageName) // 降级只改写历史块,思考参数沿用客户端原始请求。 geminiReq = applyGeminiCompatThinkingConfig(retryGeminiReq, originalClaudeBody, mappedModel, includeThoughts) - // Consume one retry budget attempt and continue with the updated request payload. sleepGeminiBackoff(1) continue } @@ -837,7 +839,8 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex // Apply account-scoped 429 handling early so concurrent requests avoid a rate-limited account. s.handleGeminiUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody) } - if attempt < geminiMaxRetries { + retryAttempt := attempt - signatureRetryStage + if retryAttempt < maxAttempts { upstreamReqID := resp.Header.Get(requestIDHeader) if upstreamReqID == "" { upstreamReqID = resp.Header.Get("x-goog-request-id") @@ -865,8 +868,8 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex Detail: upstreamDetail, }) - logger.LegacyPrintf("service.gemini_messages_compat", "Gemini account %d: upstream status %d, retry %d/%d", account.ID, resp.StatusCode, attempt, geminiMaxRetries) - sleepGeminiBackoff(attempt) + logger.LegacyPrintf("service.gemini_messages_compat", "Gemini account %d: upstream status %d, retry %d/%d", account.ID, resp.StatusCode, retryAttempt, maxAttempts) + sleepGeminiBackoff(retryAttempt) continue } // Final attempt: surface the upstream error body (mapped below) instead of a generic retry error. @@ -1268,7 +1271,8 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. var resp *http.Response // checkedPolicy 是循环内对当前 resp 的错误策略检查结果,未检查时为 nil。 var checkedPolicy *ErrorPolicyResult - for attempt := 1; attempt <= geminiMaxRetries; attempt++ { + maxAttempts := s.geminiMaxAttemptsPerAccount() + for attempt := 1; attempt <= maxAttempts; attempt++ { checkedPolicy = nil upstreamReq, idHeader, err := buildReq(ctx) if err != nil { @@ -1339,7 +1343,7 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. if resp.StatusCode == 429 { s.handleGeminiUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody) } - if attempt < geminiMaxRetries { + if attempt < maxAttempts { upstreamReqID := resp.Header.Get(requestIDHeader) if upstreamReqID == "" { upstreamReqID = resp.Header.Get("x-goog-request-id") @@ -1367,7 +1371,7 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. Detail: upstreamDetail, }) - logger.LegacyPrintf("service.gemini_messages_compat", "Gemini account %d: upstream status %d, retry %d/%d", account.ID, resp.StatusCode, attempt, geminiMaxRetries) + logger.LegacyPrintf("service.gemini_messages_compat", "Gemini account %d: upstream status %d, retry %d/%d", account.ID, resp.StatusCode, attempt, maxAttempts) sleepGeminiBackoff(attempt) continue } @@ -1669,6 +1673,14 @@ func (s *GeminiMessagesCompatService) cachedContentPassthroughInLoop(ctx context return isGeminiCachedContentNotFound(resp.StatusCode, body), rebuilt } +// geminiMaxAttemptsPerAccount 返回可重试上游错误在单个账号上的最大请求次数(首次请求 + 同账号重试)。 +func (s *GeminiMessagesCompatService) geminiMaxAttemptsPerAccount() int { + if s == nil || s.cfg == nil { + return geminiDefaultSameAccountRetries + 1 + } + return s.cfg.Gateway.MaxSameAccountRetriesGemini + 1 +} + func (s *GeminiMessagesCompatService) shouldRetryGeminiUpstreamError(account *Account, statusCode int) bool { switch statusCode { case 429, 500, 502, 503, 504, 529: diff --git a/backend/internal/service/gemini_same_account_retries_test.go b/backend/internal/service/gemini_same_account_retries_test.go new file mode 100644 index 0000000000..56c63de789 --- /dev/null +++ b/backend/internal/service/gemini_same_account_retries_test.go @@ -0,0 +1,92 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +const ( + geminiRetryTest503Body = `{"error":{"code":503,"message":"The model is overloaded.","status":"UNAVAILABLE"}}` + geminiRetryTestSignatureBody = `{"error":{"code":400,"message":"Function call is missing a thought_signature in functionCall parts.","status":"INVALID_ARGUMENT"}}` + geminiRetryTestOKBody = `{"candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":1,"totalTokenCount":4}}` +) + +func geminiSameAccountRetryTestAccount() *Account { + return &Account{ + ID: 840, + Platform: PlatformGemini, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "test-key"}, + } +} + +func TestGeminiForward_SameAccountRetriesFollowConfig(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, retries := range []int{0, 1} { + for _, fw := range geminiSingleCheckForwarders { + t.Run(fmt.Sprintf("%s/retries=%d", fw.name, retries), func(t *testing.T) { + svc, upstream, _ := newGeminiSingleCheckService(geminiSequenceUpstreamResponse{status: http.StatusServiceUnavailable, body: geminiRetryTest503Body}) + svc.cfg.Gateway.MaxSameAccountRetriesGemini = retries + + err, _ := fw.forward(t, svc, geminiSameAccountRetryTestAccount()) + + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "同号重试耗尽应换号,got %T: %v", err, err) + require.Equal(t, http.StatusServiceUnavailable, failoverErr.StatusCode) + require.Equal(t, retries+1, upstream.calls) + }) + } + } +} + +func TestGeminiClaudeCompat_SignatureDowngradeDoesNotConsumeSameAccountRetries(t *testing.T) { + gin.SetMode(gin.TestMode) + forward := func(svc *GeminiMessagesCompatService) (*ForwardResult, error) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + body := []byte(`{"model":"gemini-2.5-flash","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + return svc.Forward(context.Background(), c, geminiSameAccountRetryTestAccount(), body) + } + + t.Run("both downgrade stages run without same-account retries", func(t *testing.T) { + svc, upstream, _ := newGeminiSingleCheckService( + geminiSequenceUpstreamResponse{status: http.StatusBadRequest, body: geminiRetryTestSignatureBody}, + geminiSequenceUpstreamResponse{status: http.StatusBadRequest, body: geminiRetryTestSignatureBody}, + geminiSequenceUpstreamResponse{status: http.StatusOK, body: geminiRetryTestOKBody}, + ) + svc.cfg.Gateway.MaxSameAccountRetriesGemini = 0 + + result, err := forward(svc) + + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, 3, upstream.calls) + }) + + t.Run("same-account retries are counted apart from downgrades", func(t *testing.T) { + svc, upstream, _ := newGeminiSingleCheckService( + geminiSequenceUpstreamResponse{status: http.StatusServiceUnavailable, body: geminiRetryTest503Body}, + geminiSequenceUpstreamResponse{status: http.StatusBadRequest, body: geminiRetryTestSignatureBody}, + geminiSequenceUpstreamResponse{status: http.StatusBadRequest, body: geminiRetryTestSignatureBody}, + geminiSequenceUpstreamResponse{status: http.StatusServiceUnavailable, body: geminiRetryTest503Body}, + ) + svc.cfg.Gateway.MaxSameAccountRetriesGemini = 1 + + _, err := forward(svc) + + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "同号重试耗尽应换号,got %T: %v", err, err) + require.Equal(t, http.StatusServiceUnavailable, failoverErr.StatusCode) + require.Equal(t, 4, upstream.calls) + }) +} diff --git a/backend/internal/service/gemini_vertex_api_key_forward_test.go b/backend/internal/service/gemini_vertex_api_key_forward_test.go index 5c1d5f1b20..1b57bbb1fc 100644 --- a/backend/internal/service/gemini_vertex_api_key_forward_test.go +++ b/backend/internal/service/gemini_vertex_api_key_forward_test.go @@ -144,7 +144,7 @@ func TestGeminiForwardNative_VertexSharedCapacity429RetriesSameAccountWithoutCoo repo := &geminiBoundCacheRateLimitRepo{} svc := &GeminiMessagesCompatService{ httpUpstream: upstream, - cfg: &config.Config{}, + cfg: &config.Config{Gateway: config.GatewayConfig{MaxSameAccountRetriesGemini: 1}}, accountRepo: repo, rateLimitService: NewRateLimitService(repo, nil, &config.Config{}, nil, nil), } From f9652804894eb150942af2b108bbce670594460c Mon Sep 17 00:00:00 2001 From: SipengXie2024 <184713193+SipengXie2024@users.noreply.github.com> Date: Thu, 22 Oct 2026 16:37:56 +0000 Subject: [PATCH 027/297] fix(pagination): keep page offsets from overflowing int A page such as 9223372036854775807 passed every pagination check, so (page-1)*pageSize wrapped around. With an even page size the offset became negative and PostgreSQL rejected the query with "OFFSET must not be negative"; paths that slice in memory (paginateSlice, balance history merge) panicked with a negative slice bound. Both surfaced as HTTP 500 on list endpoints such as /api/v1/admin/users, /api/v1/usage, /api/v1/keys and /api/v1/admin/payment/orders. - PaginationParams.Offset saturates Page at MaxInt/limit, so offset and offset+limit both stay within int. - ParsePagination clamps page the same way, which covers the repositories that compute (page-1)*pageSize themselves. - The prompt audit event list and the OpenAI token stats filter parse page on their own; they now reject an overflowing page with 400, like other invalid pagination input there. --- .../handler/admin/admin_helpers_test.go | 1 + .../handler/admin/ops_dashboard_handler.go | 4 +++ backend/internal/pkg/pagination/pagination.go | 12 ++++++-- .../pkg/pagination/pagination_test.go | 29 ++++++++++++++++++- backend/internal/pkg/response/response.go | 5 ++++ .../internal/pkg/response/response_test.go | 25 ++++++++++++++++ .../internal/securityaudit/prompt_handler.go | 5 ++++ .../securityaudit/prompt_handler_test.go | 1 + 8 files changed, 79 insertions(+), 3 deletions(-) diff --git a/backend/internal/handler/admin/admin_helpers_test.go b/backend/internal/handler/admin/admin_helpers_test.go index 980c26bab9..4177fa7954 100644 --- a/backend/internal/handler/admin/admin_helpers_test.go +++ b/backend/internal/handler/admin/admin_helpers_test.go @@ -136,6 +136,7 @@ func TestParseOpsOpenAITokenStatsFilter_InvalidParams(t *testing.T) { "/?page=0", "/?page_size=0", "/?page_size=101", + "/?page=9223372036854775807", } gin.SetMode(gin.TestMode) diff --git a/backend/internal/handler/admin/ops_dashboard_handler.go b/backend/internal/handler/admin/ops_dashboard_handler.go index ad16cfa08b..9f776e2cb7 100644 --- a/backend/internal/handler/admin/ops_dashboard_handler.go +++ b/backend/internal/handler/admin/ops_dashboard_handler.go @@ -2,6 +2,7 @@ package admin import ( "fmt" + "math" "net/http" "strconv" "strings" @@ -309,6 +310,9 @@ func parseOpsOpenAITokenStatsFilter(c *gin.Context) (*service.OpsOpenAITokenStat } filter.PageSize = pageSize } + if filter.Page > math.MaxInt/filter.PageSize { + return nil, fmt.Errorf("invalid page") + } return filter, nil } diff --git a/backend/internal/pkg/pagination/pagination.go b/backend/internal/pkg/pagination/pagination.go index 334ba809de..597afbcd5b 100644 --- a/backend/internal/pkg/pagination/pagination.go +++ b/backend/internal/pkg/pagination/pagination.go @@ -1,7 +1,10 @@ // Package pagination provides types and helpers for paginated responses. package pagination -import "strings" +import ( + "math" + "strings" +) const ( SortOrderAsc = "asc" @@ -38,7 +41,12 @@ func (p PaginationParams) Offset() int { if p.Page < 1 { p.Page = 1 } - return (p.Page - 1) * p.Limit() + limit := p.Limit() + // Saturate the page so both the offset and offset+limit stay within int. + if p.Page > math.MaxInt/limit { + p.Page = math.MaxInt / limit + } + return (p.Page - 1) * limit } // Limit 获取限制数 diff --git a/backend/internal/pkg/pagination/pagination_test.go b/backend/internal/pkg/pagination/pagination_test.go index 9704449e92..1b704a40ca 100644 --- a/backend/internal/pkg/pagination/pagination_test.go +++ b/backend/internal/pkg/pagination/pagination_test.go @@ -1,6 +1,9 @@ package pagination -import "testing" +import ( + "math" + "testing" +) func TestNormalizeSortOrder(t *testing.T) { t.Parallel() @@ -84,6 +87,11 @@ func TestPaginationParamsOffsetUsesNormalizedLimit(t *testing.T) { {name: "negative page size uses default", page: 2, pageSize: -1, want: 20}, {name: "normal values", page: 3, pageSize: 50, want: 100}, {name: "page size beyond max is clamped", page: 2, pageSize: 1500, want: 1000}, + {name: "max int page saturates", page: math.MaxInt, pageSize: 20, want: (math.MaxInt/20 - 1) * 20}, + {name: "max int page with odd page size saturates", page: math.MaxInt, pageSize: 21, want: (math.MaxInt/21 - 1) * 21}, + {name: "max int page with max page size saturates", page: math.MaxInt, pageSize: 1000, want: (math.MaxInt/1000 - 1) * 1000}, + {name: "page at saturation bound keeps", page: math.MaxInt / 20, pageSize: 20, want: (math.MaxInt/20 - 1) * 20}, + {name: "page just past saturation bound saturates", page: math.MaxInt/20 + 1, pageSize: 20, want: (math.MaxInt/20 - 1) * 20}, } for _, tt := range tests { @@ -96,3 +104,22 @@ func TestPaginationParamsOffsetUsesNormalizedLimit(t *testing.T) { }) } } + +func TestPaginationParamsOffsetDoesNotOverflow(t *testing.T) { + t.Parallel() + + pages := []int{math.MaxInt, math.MaxInt - 1, math.MaxInt / 2, 461168601842738791, math.MaxInt/1000 + 1} + pageSizes := []int{1, 2, 3, 20, 21, 999, 1000} + for _, page := range pages { + for _, pageSize := range pageSizes { + params := PaginationParams{Page: page, PageSize: pageSize} + offset, limit := params.Offset(), params.Limit() + if offset < 0 || offset > math.MaxInt-limit { + t.Fatalf("Offset() for Page=%d, PageSize=%d = %d, want 0 <= offset <= MaxInt-%d", page, pageSize, offset, limit) + } + if again := params.Offset(); again != offset { + t.Fatalf("Offset() for Page=%d, PageSize=%d is unstable: %d then %d", page, pageSize, offset, again) + } + } + } +} diff --git a/backend/internal/pkg/response/response.go b/backend/internal/pkg/response/response.go index b1d6c2d059..a7afc7348f 100644 --- a/backend/internal/pkg/response/response.go +++ b/backend/internal/pkg/response/response.go @@ -188,6 +188,11 @@ func ParsePagination(c *gin.Context) (page, pageSize int) { } } + // Clamp the page so (page-1)*pageSize computed by callers cannot overflow int. + if page > math.MaxInt/pageSize { + page = math.MaxInt / pageSize + } + return page, pageSize } diff --git a/backend/internal/pkg/response/response_test.go b/backend/internal/pkg/response/response_test.go index 0debce5fd6..0e69f5ffd2 100644 --- a/backend/internal/pkg/response/response_test.go +++ b/backend/internal/pkg/response/response_test.go @@ -5,6 +5,7 @@ package response import ( "encoding/json" "errors" + "math" "net/http" "net/http/httptest" "testing" @@ -691,6 +692,30 @@ func TestParsePagination(t *testing.T) { wantPage: 1, wantPageSize: 20, }, + { + name: "page为MaxInt_钳制到不溢出的上限", + query: "page=9223372036854775807", + wantPage: math.MaxInt / 20, + wantPageSize: 20, + }, + { + name: "page为MaxInt且page_size为1000_钳制到不溢出的上限", + query: "page=9223372036854775807&page_size=1000", + wantPage: math.MaxInt / 1000, + wantPageSize: 1000, + }, + { + name: "page恰好在上限_有效", + query: "page=461168601842738790", + wantPage: 461168601842738790, + wantPageSize: 20, + }, + { + name: "page刚超过上限_钳制", + query: "page=461168601842738791", + wantPage: math.MaxInt / 20, + wantPageSize: 20, + }, } for _, tt := range tests { diff --git a/backend/internal/securityaudit/prompt_handler.go b/backend/internal/securityaudit/prompt_handler.go index 342f3a5461..71d5d5ae71 100644 --- a/backend/internal/securityaudit/prompt_handler.go +++ b/backend/internal/securityaudit/prompt_handler.go @@ -3,6 +3,7 @@ package securityaudit import ( "context" "errors" + "math" "strconv" "strings" @@ -91,6 +92,10 @@ func (h *PromptAdminHandler) ListEvents(c *gin.Context) { response.ErrorFrom(c, err) return } + if page > math.MaxInt/pageSize { + response.ErrorFrom(c, infraerrors.BadRequest("prompt_audit_invalid_pagination", "分页参数无效")) + return + } filter, err := eventFilterFromQuery(c) if err != nil { response.ErrorFrom(c, err) diff --git a/backend/internal/securityaudit/prompt_handler_test.go b/backend/internal/securityaudit/prompt_handler_test.go index 0ec2ff5d8b..a8cf27447f 100644 --- a/backend/internal/securityaudit/prompt_handler_test.go +++ b/backend/internal/securityaudit/prompt_handler_test.go @@ -211,6 +211,7 @@ func TestPromptAdminRejectsInvalidEventIDsTimesAndPagination(t *testing.T) { {http.MethodGet, "/admin/prompt-audit/events?group_id=bad", nil, "prompt_audit_invalid_filter_id"}, {http.MethodGet, "/admin/prompt-audit/events?start_at=not-time", nil, "prompt_audit_invalid_time"}, {http.MethodGet, "/admin/prompt-audit/events?page=0", nil, "prompt_audit_invalid_pagination"}, + {http.MethodGet, "/admin/prompt-audit/events?page=9223372036854775807", nil, "prompt_audit_invalid_pagination"}, {http.MethodPost, "/admin/prompt-audit/events/batch-delete", map[string]any{"ids": []int64{1, -2}}, "prompt_audit_invalid_event_id"}, } { response := promptAdminRequest(t, router, tc.method, tc.path, tc.body) From c591412c42ab195dacdede9eb19f9cbfee221144 Mon Sep 17 00:00:00 2001 From: apple050620312 Date: Fri, 23 Oct 2026 01:51:48 +0800 Subject: [PATCH 028/297] =?UTF-8?q?fix(openai):=20=E5=90=88=E5=B9=B6=20Cod?= =?UTF-8?q?ex=20overload=20=E8=BA=AB=E4=BB=BD=E4=B8=8E=E7=A9=BA=E6=B5=81?= =?UTF-8?q?=E5=AE=89=E5=85=A8=E9=87=8D=E8=AF=95=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/pkg/openai/request.go | 40 +++++++- ...quest_codex_identity_normalization_test.go | 78 ++++++++++++++++ .../service/openai_capacity_shed_test.go | 92 +++++++++++++++++++ .../internal/service/openai_codex_identity.go | 17 ++-- .../service/openai_codex_identity_test.go | 4 +- .../openai_codex_version_sync_service_test.go | 14 ++- .../service/openai_gateway_passthrough.go | 19 +++- .../service/openai_gateway_service.go | 6 +- .../service/openai_gateway_upstream_errors.go | 62 +++++++++++++ .../service/openai_oauth_passthrough_test.go | 2 +- .../service/openai_setup_token_compat_test.go | 5 +- .../openai_ws_forwarder_success_test.go | 4 +- .../service/setting_gateway_runtime.go | 8 +- backend/internal/service/settings_view.go | 2 +- .../src/i18n/locales/en/admin/settings.ts | 4 +- .../src/i18n/locales/zh/admin/settings.ts | 4 +- 16 files changed, 323 insertions(+), 38 deletions(-) create mode 100644 backend/internal/pkg/openai/request_codex_identity_normalization_test.go diff --git a/backend/internal/pkg/openai/request.go b/backend/internal/pkg/openai/request.go index 8ddf8d188d..15d4bd14cb 100644 --- a/backend/internal/pkg/openai/request.go +++ b/backend/internal/pkg/openai/request.go @@ -49,7 +49,7 @@ const codexOfficialClientFamilyPrefix = "codex " // 或在 bump context/codex 时同步补入本集合。 var codexOfficialClientOriginators = map[string]bool{ "codex_cli_rs": true, // CLI 默认 DEFAULT_ORIGINATOR - "codex-tui": true, // 交互式 TUI(连字符,真实流量占比最高) + CodexTUIOriginator: true, // 交互式 TUI(连字符,真实流量占比最高) "codex_vscode": true, // VSCode/Cursor 扩展 "codex_vscode_copilot": true, // 扩展 GitHub Copilot 集成模式 "codex_app": true, // 历史保留 @@ -259,11 +259,43 @@ func canonicalizeCodexOriginator(name string) string { return name } -// CodexCLIOriginator 是 codex-rs 客户端的历史默认 originator,保留用于兼容识别。 +// CodexCLIOriginator 是 codex-rs 客户端的默认 originator。 const CodexCLIOriginator = "codex_cli_rs" -// CodexDefaultOriginator 是网关默认使用的 Codex TUI originator。 -const CodexDefaultOriginator = "codex-tui" +// CodexTUIOriginator 是交互式 Codex TUI 使用的 originator。 +const CodexTUIOriginator = "codex-tui" + +// CodexDefaultOriginator 是网关默认发送的 Codex originator。 +// 历史 TUI 身份曾触发上游的身份风控分层,因此默认使用 CLI 身份;TUI 仍保留在官方身份集合中, +// 供入站识别和兼容归一化。 +const CodexDefaultOriginator = CodexCLIOriginator + +// NormalizeCodexClientIdentityToCLI 将已配对的 TUI 身份归一为 CLI 身份。 +// sub2api 历史默认 UA 使用 codex-tui;上游仓库的 #5198 记录了该身份会收到 +// server_is_overloaded,而相同请求改用 codex_cli_rs 可以成功。归一化必须同时改写 +// originator 和 User-Agent 首段,避免触发 #3901 的身份配对校验。 +// +// 版本、操作系统、架构和终端指纹保持不变;尾部 `(name; version)` 客户端标识组 +// 属于 TUI 身份时移除,因为真实 CLI UA 不携带该组。 +func NormalizeCodexClientIdentityToCLI(originator, userAgent string) (string, string, bool) { + if !strings.EqualFold(strings.TrimSpace(originator), CodexTUIOriginator) { + return originator, userAgent, false + } + + ua := strings.TrimSpace(userAgent) + slash := strings.IndexByte(ua, '/') + if slash <= 0 { + return CodexCLIOriginator, ua, true + } + + rest := ua[slash:] + if trailer := codexUATrailerName(ua); trailer != "" && IsCodexOfficialClientOriginator(trailer) { + if open := strings.LastIndex(rest, "("); open > 0 { + rest = strings.TrimRight(rest[:open], " ") + } + } + return CodexCLIOriginator, CodexCLIOriginator + rest, true +} // CodexUserAgentVersion 提取 Codex UA 的完整版本段,即 `{client}/{version} (...` 中的 version。 // 与 ParseCodexEngineVersion 的区别:后者只取三段数字用于引擎版本比较(会丢掉 -alpha.4 diff --git a/backend/internal/pkg/openai/request_codex_identity_normalization_test.go b/backend/internal/pkg/openai/request_codex_identity_normalization_test.go new file mode 100644 index 0000000000..a2d0b357da --- /dev/null +++ b/backend/internal/pkg/openai/request_codex_identity_normalization_test.go @@ -0,0 +1,78 @@ +package openai + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestNormalizeCodexClientIdentityToCLI(t *testing.T) { + tests := []struct { + name string + originator string + userAgent string + wantOriginator string + wantUserAgent string + wantChanged bool + }{ + { + name: "TUI 完整身份", + originator: CodexTUIOriginator, + userAgent: "codex-tui/0.163.0 (Windows 11; x86_64) WindowsTerminal (codex-tui; 0.163.0)", + wantOriginator: CodexCLIOriginator, + wantUserAgent: "codex_cli_rs/0.163.0 (Windows 11; x86_64) WindowsTerminal", + wantChanged: true, + }, + { + name: "TUI 只有系统指纹", + originator: CodexTUIOriginator, + userAgent: "codex-tui/0.163.0 (Windows 11; x86_64) WindowsTerminal", + wantOriginator: CodexCLIOriginator, + wantUserAgent: "codex_cli_rs/0.163.0 (Windows 11; x86_64) WindowsTerminal", + wantChanged: true, + }, + { + name: "CLI 身份保持不变", + originator: CodexCLIOriginator, + userAgent: "codex_cli_rs/0.163.0 (Windows 11; x86_64) WindowsTerminal", + wantOriginator: CodexCLIOriginator, + wantUserAgent: "codex_cli_rs/0.163.0 (Windows 11; x86_64) WindowsTerminal", + wantChanged: false, + }, + { + name: "其他官方客户端保持不变", + originator: "codex_vscode", + userAgent: "codex_vscode/0.163.0 (Windows 11; x86_64) vscode (codex_vscode; 0.163.0)", + wantOriginator: "codex_vscode", + wantUserAgent: "codex_vscode/0.163.0 (Windows 11; x86_64) vscode (codex_vscode; 0.163.0)", + wantChanged: false, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + originator, userAgent, changed := NormalizeCodexClientIdentityToCLI(test.originator, test.userAgent) + require.Equal(t, test.wantOriginator, originator) + require.Equal(t, test.wantUserAgent, userAgent) + require.Equal(t, test.wantChanged, changed) + }) + } +} + +func TestNormalizeCodexClientIdentityToCLIIsPairedAndIdempotent(t *testing.T) { + originator, userAgent, changed := NormalizeCodexClientIdentityToCLI( + CodexTUIOriginator, + "codex-tui/0.163.0 (Windows 11; x86_64) WindowsTerminal (codex-tui; 0.163.0)", + ) + require.True(t, changed) + + pairedOriginator, pairedUserAgent, ok := PairCodexClientIdentity(userAgent) + require.True(t, ok) + require.Equal(t, originator, pairedOriginator) + require.Equal(t, userAgent, pairedUserAgent) + + againOriginator, againUserAgent, changedAgain := NormalizeCodexClientIdentityToCLI(originator, userAgent) + require.False(t, changedAgain) + require.Equal(t, originator, againOriginator) + require.Equal(t, userAgent, againUserAgent) +} diff --git a/backend/internal/service/openai_capacity_shed_test.go b/backend/internal/service/openai_capacity_shed_test.go index 086f7380e3..6737e42cbd 100644 --- a/backend/internal/service/openai_capacity_shed_test.go +++ b/backend/internal/service/openai_capacity_shed_test.go @@ -3,6 +3,7 @@ package service import ( "context" "errors" + "fmt" "io" "net/http" "net/http/httptest" @@ -14,6 +15,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/pkg/openai" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" ) // --- mock: 只记录临时不可调度写入,其余方法不应被调用 --- @@ -108,6 +110,33 @@ func TestOpenAIHTTPCapacityShedIsRequestScopedForOAuthAccounts(t *testing.T) { require.Zero(t, repo.tempUnschedCalls) } +func TestOpenAICapacityShedHonorsRetryAfter(t *testing.T) { + for _, test := range []struct { + name string + headers http.Header + body string + want time.Duration + }{ + {name: "http seconds", headers: http.Header{"Retry-After": []string{"6"}}, want: 6 * time.Second}, + {name: "http milliseconds", headers: http.Header{"Retry-After-Ms": []string{"6000"}}, want: 6 * time.Second}, + {name: "body seconds", body: `{"error":{"headers":{"retry-after":"7"},"message":"Our servers are currently overloaded. Please try again later."}}`, want: 7 * time.Second}, + {name: "body milliseconds", body: `{"response":{"error":{"headers":{"retry-after-ms":"7000"},"message":"Our servers are currently overloaded. Please try again later."}}}`, want: 7 * time.Second}, + {name: "bounded", headers: http.Header{"Retry-After": []string{"60"}}, want: openAIRequestScopedRetryMaxDelay}, + } { + t.Run(test.name, func(t *testing.T) { + failoverErr := newOpenAIUpstreamFailoverError( + http.StatusServiceUnavailable, + test.headers, + []byte(test.body), + "Our servers are currently overloaded. Please try again later.", + false, + ) + require.True(t, failoverErr.RequestScopedTransient) + require.Equal(t, test.want, failoverErr.SameAccountRetryDelay) + }) + } +} + // 上游降载的真实序列是「event: error → event: response.failed」。error 帧不算 // 客户端输出:若把它当首输出 flush,clientOutputStarted 被固化,随后的 failed // 事件就进不了 pre-output failover 分支,只能把致命错误原样转发给客户端。 @@ -218,6 +247,69 @@ func TestOpenAIStreamMetadataAndKeepaliveBeforeOverloadFailOver(t *testing.T) { } } +func TestOpenAIStreamEmptyContentBeforeFailureCanFailOver(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, payload := range []string{ + `{"type":"response.output_text.delta","delta":""}`, + `{"type":"response.reasoning_summary_text.delta","delta":""}`, + `{"type":"response.reasoning_text.delta","delta":""}`, + `{"type":"response.function_call_arguments.delta","delta":""}`, + `{"type":"response.custom_tool_call_input.delta","delta":""}`, + `{"type":"response.output_text.done","text":""}`, + `{"type":"response.reasoning_summary_text.done","text":""}`, + `{"type":"response.reasoning_text.done","text":""}`, + `{"type":"response.refusal.delta","delta":""}`, + `{"type":"response.refusal.done","refusal":""}`, + `{"type":"response.content_part.done","part":{"type":"output_text","text":""}}`, + `{"type":"response.reasoning_summary_part.done","part":{"type":"summary_text","text":""}}`, + } { + for _, passthrough := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/passthrough=%t", payload, passthrough), func(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}}} + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{}, + Body: io.NopCloser(strings.NewReader("data: " + payload + "\n\n" + + `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later."}}}` + "\n\n")), + } + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + var err error + if passthrough { + _, err = svc.handleStreamingResponsePassthrough(c.Request.Context(), resp, c, account, time.Now(), "model", "model") + } else { + _, err = svc.handleStreamingResponse(c.Request.Context(), resp, c, account, time.Now(), "model", "model") + } + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.True(t, failoverErr.RequestScopedTransient) + require.Empty(t, rec.Body.String()) + }) + } + } +} + +func TestOpenAIStreamReplayBoundaryPreservesContentAndToolCompletion(t *testing.T) { + for _, payload := range []string{ + `{"type":"response.output_text.delta","delta":" "}`, + `{"type":"response.function_call_arguments.delta","delta":"{}"}`, + `{"type":"response.custom_tool_call_input.delta","delta":"run"}`, + `{"type":"response.function_call_arguments.done","arguments":""}`, + `{"type":"response.custom_tool_call_input.done","input":""}`, + `{"type":"response.output_item.done","item":{"type":"function_call","arguments":""}}`, + `{"type":"response.output_item.done","item":{"type":"reasoning","encrypted_content":"ciphertext"}}`, + `{"type":"response.output_text.delta","delta":null}`, + `{"type":"response.output_text.delta"}`, + `{"type":"response.output_text.delta","delta":{}}`, + `{"type":"response.new_kind.delta","delta":""}`, + } { + eventType := gjson.Get(payload, "type").String() + require.True(t, openAIStreamDataStartsClientOutput(payload, eventType), payload) + } +} + func TestOpenAIStreamKeepaliveOnlyFailureDoesNotRecordFirstToken(t *testing.T) { gin.SetMode(gin.TestMode) for _, passthrough := range []bool{false, true} { diff --git a/backend/internal/service/openai_codex_identity.go b/backend/internal/service/openai_codex_identity.go index 09d1717c9a..fbbba4a857 100644 --- a/backend/internal/service/openai_codex_identity.go +++ b/backend/internal/service/openai_codex_identity.go @@ -32,7 +32,7 @@ func NormalizeCodexClientVersion(version string) string { return version } -// buildCodexCLIUserAgent 按版本号拼出规范 Codex TUI User-Agent。 +// buildCodexCLIUserAgent 按版本号拼出规范 Codex CLI User-Agent。 // UA 形态只在 codexCLIUserAgentSuffix 一处定义,避免多处拼装漂移。 func buildCodexCLIUserAgent(version string) string { if version = NormalizeCodexClientVersion(version); version == "" { @@ -43,7 +43,7 @@ func buildCodexCLIUserAgent(version string) string { // codexIdentityEnforcement 控制 enforceCodexIdentityHeaders 是否强制统一出站身份, // 由 gateway.disable_codex_identity_enforcement 在服务构造时取反发布。 -// 默认开启:上游在容量紧张时按客户端身份分优先级降载,被降载的请求会拿到 +// 默认开启:上游会按客户端身份进行风控分层,命中风险身份的请求会拿到 // HTTP 200 + 流内 server_is_overloaded,本次请求即失败;强制统一出口可确保没有 // 请求带着第三方或陈旧身份出站。关闭后退回「仅按最终 UA 配对 originator」的收口语义。 var codexIdentityEnforcement = func() *atomic.Bool { @@ -131,11 +131,11 @@ type codexOutboundIdentity struct { } // resolveCodexOutboundIdentity 由候选 User-Agent 推导自洽的出站身份。 -// candidateUA 为空时使用规范 User-Agent;推导不出官方身份时整体回退为规范 TUI 身份。 +// candidateUA 为空时使用规范 User-Agent;推导不出官方身份时整体回退为规范 CLI 身份。 // // 候选 UA(面板 / 账号级的管理员显式配置)只贡献客户端名与 OS / 架构 / 终端指纹, // 其自带的版本段一律用当前生效版本重建:一条填写于某个历史版本的 UA 否则会把出站身份 -// 永久钉死在陈旧版本上,绕过版本自动同步,落回上游优先降载的那一侧。 +// 永久钉死在陈旧版本上,绕过版本自动同步,落回上游身份风控更严格的一侧。 // 需要固定版本请填「Codex 客户端版本号」并关闭自动同步。 func resolveCodexOutboundIdentity(candidateUA string) codexOutboundIdentity { canonical := codexCanonicalUserAgent() @@ -149,9 +149,12 @@ func resolveCodexOutboundIdentity(candidateUA string) codexOutboundIdentity { originator, pairedUA, ok := openai.PairCodexClientIdentity(ua) if !ok { if originator, pairedUA, ok = openai.PairCodexClientIdentity(canonical); !ok { - originator, pairedUA = openai.CodexDefaultOriginator, codexCLIUserAgent + originator, pairedUA = openai.CodexCLIOriginator, codexCLIUserAgent } } + // 旧配置或账号级 UA 可能仍保存 codex-tui。该身份是 sub2api 默认出口曾经 + // 使用的风险指纹,必须与 UA 首段一起归一为 CLI,不能只替换 originator。 + originator, pairedUA, _ = openai.NormalizeCodexClientIdentityToCLI(originator, pairedUA) // 生效版本只有一个来源:规范身份(面板版本号 → 自动同步值 → 内置常量,见 // SettingService.GetOpenAICodexClientVersion)。UA 与 version 头由此同源派生。 version := codexClientVersionFromUA(canonical) @@ -206,8 +209,8 @@ func enforceCodexIdentityHeaders(h http.Header) { } // enforceCodexIdentityHeadersWithUA 强制统一 OAuth 出站身份:User-Agent / originator / version -// 一律改写为网关的规范身份,客户端自报身份不参与构造。上游在容量紧张时按客户端身份分优先级 -// 降载,被降载的请求会拿到 HTTP 200 + 流内 server_is_overloaded;统一出口可确保没有请求带着 +// 一律改写为网关的规范身份,客户端自报身份不参与构造。上游会按客户端身份进行风控分层, +// 命中风险身份的请求会拿到 HTTP 200 + 流内 server_is_overloaded;统一出口可确保没有请求带着 // 第三方或陈旧身份出站,也天然满足 originator 与 UA 首段配套的上游校验(issue #3901)。 // // overrideUA 是账号级自定义 User-Agent:管理员的显式配置仍然生效,但只贡献客户端名与 diff --git a/backend/internal/service/openai_codex_identity_test.go b/backend/internal/service/openai_codex_identity_test.go index 15768e5ea5..5580375e1c 100644 --- a/backend/internal/service/openai_codex_identity_test.go +++ b/backend/internal/service/openai_codex_identity_test.go @@ -174,8 +174,8 @@ func TestEnforceCodexIdentityHeadersWithAccountOverrideUA(t *testing.T) { enforceCodexIdentityHeadersWithUA(h, "codex-tui/0.125.0 (Mac OS X 14.0; arm64) iTerm") - require.Equal(t, "codex-tui", h.Get("originator")) - require.Equal(t, "codex-tui/0.200.1 (Mac OS X 14.0; arm64) iTerm", h.Get("user-agent")) + require.Equal(t, openai.CodexCLIOriginator, h.Get("originator")) + require.Equal(t, "codex_cli_rs/0.200.1 (Mac OS X 14.0; arm64) iTerm", h.Get("user-agent")) require.Equal(t, "0.200.1", h.Get("version")) }) } diff --git a/backend/internal/service/openai_codex_version_sync_service_test.go b/backend/internal/service/openai_codex_version_sync_service_test.go index b78cd8cc94..76dbfe84d3 100644 --- a/backend/internal/service/openai_codex_version_sync_service_test.go +++ b/backend/internal/service/openai_codex_version_sync_service_test.go @@ -7,6 +7,7 @@ import ( "testing" "time" + "github.com/Wei-Shaw/sub2api/internal/pkg/openai" "github.com/stretchr/testify/require" ) @@ -327,14 +328,14 @@ func TestGetOpenAICodexClientVersionFallsBackOnError(t *testing.T) { require.Equal(t, codexCLIVersion, svc.GetOpenAICodexClientVersion(context.Background())) } -// 规范 UA:面板未填完整 UA 时按当前生效版本号拼出标准 TUI 形态。 +// 规范 UA:面板未填完整 UA 时按当前生效版本号拼出标准 CLI 形态。 func TestGetOpenAICodexCanonicalUserAgentBuildsFromVersion(t *testing.T) { svc := NewSettingService(&codexVersionSettingRepoStub{values: map[string]string{ SettingKeyOpenAICodexClientVersionSynced: "0.200.1", }}, nil) require.Equal(t, - "codex-tui/0.200.1"+codexCLIUserAgentSuffix, + "codex_cli_rs/0.200.1"+codexCLIUserAgentSuffix, svc.GetOpenAICodexCanonicalUserAgent(context.Background()), ) } @@ -517,16 +518,19 @@ func TestGetOpenAICodexCanonicalUserAgentOutboundIdentity(t *testing.T) { SettingKeyOpenAICodexClientVersion: version.manual, SettingKeyOpenAICodexClientVersionSynced: version.synced, }}, nil) - wantUA := buildCodexCLIUserAgent(version.want) - wantOriginator := "codex-tui" + wantCanonicalUA := buildCodexCLIUserAgent(version.want) + wantUA := wantCanonicalUA + wantOriginator := openai.CodexDefaultOriginator if ua.client != "" { wantUA = ua.client + "/" + version.want + ua.suffix + wantCanonicalUA = wantUA wantOriginator = ua.client } + wantOriginator, wantUA, _ = openai.NormalizeCodexClientIdentityToCLI(wantOriginator, wantUA) SetCodexCanonicalUserAgentResolver(func() string { return svc.GetOpenAICodexCanonicalUserAgent(context.Background()) }) - require.Equal(t, wantUA, svc.GetOpenAICodexCanonicalUserAgent(context.Background())) + require.Equal(t, wantCanonicalUA, svc.GetOpenAICodexCanonicalUserAgent(context.Background())) identity := resolveCodexOutboundIdentity("") require.Equal(t, wantUA, identity.userAgent) require.Equal(t, wantOriginator, identity.originator) diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index e1da46f7ab..90039f0522 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -1151,7 +1151,7 @@ func openAIStreamAddedEventStartsClientOutput(payload []byte, eventType string) default: return true } - case "response.content_part.added": + case "response.content_part.added", "response.content_part.done": part := gjson.GetBytes(payload, "part") if !part.Exists() || !part.IsObject() { return true @@ -1164,7 +1164,7 @@ func openAIStreamAddedEventStartsClientOutput(payload []byte, eventType string) default: return true } - case "response.reasoning_summary_part.added": + case "response.reasoning_summary_part.added", "response.reasoning_summary_part.done": part := gjson.GetBytes(payload, "part") if !part.Exists() || !part.IsObject() || strings.TrimSpace(part.Get("type").String()) != "summary_text" { return true @@ -1180,6 +1180,7 @@ func openAIStreamDataStartsClientOutput(data, eventType string) bool { if trimmed == "" { return false } + field := "" switch strings.TrimSpace(eventType) { case "response.failed": return false @@ -1191,8 +1192,20 @@ func openAIStreamDataStartsClientOutput(data, eventType string) bool { // (content_policy / invalid_request 等)维持原样转发,保留上游错误细节。 payload := []byte(trimmed) return !openAIStreamFailedEventShouldFailover(payload, extractOpenAISSEErrorMessage(payload)) - case "response.output_item.added", "response.content_part.added", "response.reasoning_summary_part.added": + case "response.output_item.added", "response.content_part.added", "response.reasoning_summary_part.added", + "response.content_part.done", "response.reasoning_summary_part.done": return openAIStreamAddedEventStartsClientOutput([]byte(trimmed), eventType) + case "response.output_text.delta", "response.reasoning_summary_text.delta", "response.reasoning_text.delta", + "response.function_call_arguments.delta", "response.custom_tool_call_input.delta", "response.refusal.delta": + field = "delta" + case "response.output_text.done", "response.reasoning_summary_text.done", "response.reasoning_text.done": + field = "text" + case "response.refusal.done": + field = "refusal" + } + if field != "" && gjson.Valid(trimmed) { + value := gjson.Get(trimmed, field) + return value.Type != gjson.String || value.String() != "" } return !openAIStreamEventIsMetadata(eventType) } diff --git a/backend/internal/service/openai_gateway_service.go b/backend/internal/service/openai_gateway_service.go index 91f9b646a4..a29ff0d1c6 100644 --- a/backend/internal/service/openai_gateway_service.go +++ b/backend/internal/service/openai_gateway_service.go @@ -33,7 +33,7 @@ const ( openaiPlatformAPIURL = "https://api.openai.com/v1/responses" openaiPlatformAPIInputTokensURL = "https://api.openai.com/v1/responses/input_tokens" openaiStickySessionTTL = time.Hour // 粘性会话TTL - // 与真实 Codex TUI 的 User-Agent 结构对齐: + // 与真实 Codex CLI 的 User-Agent 结构对齐: // {originator}/{version} ({OS} {OS_version}; {arch}) {terminal} // 缺少 OS/架构/终端后缀的形态易被上游指纹识别为非官方客户端。 // 该后缀是 UA 形态的唯一定义处,buildCodexCLIUserAgent 按运行时版本号复用它。 @@ -57,8 +57,8 @@ const ( openAICompactSessionSeedKey = "openai_compact_session_seed" openAIUpstreamEndpointContextKey = "openai_actual_upstream_endpoint" // codexCLIVersion 是网关对上游声明的 Codex 客户端版本,同时供 codexCLIUserAgent - // 与 version 头使用。上游 /backend-api/codex 在容量紧张时按客户端身份分优先级降载, - // 陈旧版本会被优先丢弃(HTTP 200 + 流内 server_is_overloaded);非官方客户端配不出 + // 与 version 头使用。上游 /backend-api/codex 会按客户端身份进行风控分层, + // 陈旧版本可能被优先丢弃(HTTP 200 + 流内 server_is_overloaded);非官方客户端配不出 // 官方身份时整体回退到本常量,因此它必须跟随官方 CLI 的当前发布版本, // 落后多个版本会让这些请求稳定落在被优先丢弃的一侧。 codexCLIVersion = "0.146.0" diff --git a/backend/internal/service/openai_gateway_upstream_errors.go b/backend/internal/service/openai_gateway_upstream_errors.go index 2490043284..69d10bb238 100644 --- a/backend/internal/service/openai_gateway_upstream_errors.go +++ b/backend/internal/service/openai_gateway_upstream_errors.go @@ -7,7 +7,9 @@ import ( "fmt" "io" "net/http" + "strconv" "strings" + "time" "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" @@ -193,6 +195,63 @@ func isOpenAIRequestScopedCapacityShed(upstreamMsg string, upstreamBody []byte) (!gjson.ValidBytes(upstreamBody) && isOpenAICapacityShedMessage(string(upstreamBody))) } +const openAIRequestScopedRetryMaxDelay = 8 * time.Second + +func openAIRequestScopedRetryDelay(responseHeaders http.Header, responseBody []byte) time.Duration { + type retryAfterValue struct { + raw string + milliseconds bool + } + for _, value := range []retryAfterValue{ + {raw: responseHeaders.Get("Retry-After")}, + {raw: responseHeaders.Get("Retry-After-Ms"), milliseconds: true}, + {raw: gjson.GetBytes(responseBody, "error.headers.retry-after").String()}, + {raw: gjson.GetBytes(responseBody, "response.error.headers.retry-after").String()}, + {raw: gjson.GetBytes(responseBody, "error.headers.retry-after-ms").String(), milliseconds: true}, + {raw: gjson.GetBytes(responseBody, "response.error.headers.retry-after-ms").String(), milliseconds: true}, + } { + raw := strings.TrimSpace(value.raw) + if raw == "" { + continue + } + var delay time.Duration + var ok bool + if value.milliseconds { + delay, ok = parseOpenAIRequestScopedRetryDelayMilliseconds(raw) + } else { + delay, ok = parseOpenAIRequestScopedRetryDelay(raw) + } + if !ok || delay <= 0 { + continue + } + if delay > openAIRequestScopedRetryMaxDelay { + return openAIRequestScopedRetryMaxDelay + } + return delay + } + return 0 +} + +func parseOpenAIRequestScopedRetryDelay(raw string) (time.Duration, bool) { + if seconds, err := strconv.ParseFloat(raw, 64); err == nil && seconds > 0 { + return time.Duration(seconds * float64(time.Second)), true + } + if resetAt, err := http.ParseTime(raw); err == nil { + delay := time.Until(resetAt) + if delay > 0 { + return delay, true + } + } + return 0, false +} + +func parseOpenAIRequestScopedRetryDelayMilliseconds(raw string) (time.Duration, bool) { + if millis, err := strconv.ParseFloat(raw, 64); err == nil && millis > 0 { + return time.Duration(millis * float64(time.Millisecond)), true + } + return 0, false +} + func isOpenAIContextWindowError(upstreamMsg string, upstreamBody []byte) bool { match := func(text string) bool { lower := strings.ToLower(strings.TrimSpace(text)) @@ -336,6 +395,9 @@ func newOpenAIUpstreamFailoverError( RetryableOnSameAccount: retryableOnSameAccount || requestScopedCapacity, RequestScopedTransient: requestScopedCapacity, } + if requestScopedCapacity { + failoverErr.SameAccountRetryDelay = openAIRequestScopedRetryDelay(responseHeaders, responseBody) + } if isOpenAIRequestBodyTooLargeError(statusCode, upstreamMsg, responseBody) { failoverErr.RetryableOnSameAccount = false failoverErr.RequestScopedTransient = false diff --git a/backend/internal/service/openai_oauth_passthrough_test.go b/backend/internal/service/openai_oauth_passthrough_test.go index d871fcd901..c913bf0a94 100644 --- a/backend/internal/service/openai_oauth_passthrough_test.go +++ b/backend/internal/service/openai_oauth_passthrough_test.go @@ -1171,7 +1171,7 @@ func TestOpenAIGatewayService_OAuthLegacy_CompositeCodexUAUsesCodexOriginator(t _, err := svc.Forward(context.Background(), c, account, inputBody) require.NoError(t, err) require.NotNil(t, upstream.lastReq) - // 浏览器型复合 UA 被替换为默认 Codex TUI UA, + // 浏览器型复合 UA 被替换为默认 Codex CLI UA, // originator 随最终 UA 配套(issue #3901)。 require.Equal(t, DefaultOpenAICodexUserAgent, upstream.lastReq.Header.Get("User-Agent")) require.Equal(t, openai.CodexDefaultOriginator, upstream.lastReq.Header.Get("originator")) diff --git a/backend/internal/service/openai_setup_token_compat_test.go b/backend/internal/service/openai_setup_token_compat_test.go index 09dd2dae78..cf02f2803c 100644 --- a/backend/internal/service/openai_setup_token_compat_test.go +++ b/backend/internal/service/openai_setup_token_compat_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/openai" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" @@ -212,7 +213,7 @@ func TestOpenAISetupTokenMessagesUsesCodexBridgeAndTurnState(t *testing.T) { require.Equal(t, chatgptCodexURL, upstream.requests[0].URL.String()) require.Equal(t, "Bearer setup-token-value", upstream.requests[0].Header.Get("Authorization")) require.Equal(t, "chatgpt-setup", upstream.requests[0].Header.Get("chatgpt-account-id")) - requireOpenAIMessagesCodexIdentity(t, upstream.requests[0], codexCLIUserAgent, "codex-tui") + requireOpenAIMessagesCodexIdentity(t, upstream.requests[0], codexCLIUserAgent, openai.CodexCLIOriginator) require.Empty(t, upstream.requests[0].Header.Get("x-codex-turn-state")) secondBody := []byte(`{"model":"claude-sonnet-4-5","max_tokens":16,"messages":[{"role":"user","content":"next"}],"stream":false}`) @@ -229,7 +230,7 @@ func TestOpenAISetupTokenMessagesUsesCodexBridgeAndTurnState(t *testing.T) { require.Equal(t, "turn_state_setup", upstream.requests[1].Header.Get("x-codex-turn-state")) require.Equal(t, generateSessionUUID(isolateOpenAIUpstreamSessionID(0, account, "stable-cache-key")), upstream.requests[1].Header.Get("session_id")) require.Empty(t, upstream.requests[1].Header.Get("conversation_id")) - requireOpenAIMessagesCodexIdentity(t, upstream.requests[1], codexCLIUserAgent, "codex-tui") + requireOpenAIMessagesCodexIdentity(t, upstream.requests[1], codexCLIUserAgent, openai.CodexCLIOriginator) } func openAISetupTokenCompatAccount(id int64) *Account { diff --git a/backend/internal/service/openai_ws_forwarder_success_test.go b/backend/internal/service/openai_ws_forwarder_success_test.go index 0401f59f55..8f4c770877 100644 --- a/backend/internal/service/openai_ws_forwarder_success_test.go +++ b/backend/internal/service/openai_ws_forwarder_success_test.go @@ -1024,9 +1024,9 @@ func TestOpenAIGatewayService_Forward_WSv2_OAuthHonorsAccountUserAgent(t *testin result, err := svc.Forward(context.Background(), c, account, body) require.NoError(t, err) require.NotNil(t, result) - require.Equal(t, "codex-tui", captureDialer.lastHeaders.Get("originator")) + require.Equal(t, openai.CodexCLIOriginator, captureDialer.lastHeaders.Get("originator")) require.Equal(t, - "codex-tui/"+codexCLIVersion+" (Mac OS X 15.1.0; arm64) iTerm.app", + "codex_cli_rs/"+codexCLIVersion+" (Mac OS X 15.1.0; arm64) iTerm.app", captureDialer.lastHeaders.Get("user-agent"), ) require.Equal(t, codexCLIVersion, captureDialer.lastHeaders.Get("version")) diff --git a/backend/internal/service/setting_gateway_runtime.go b/backend/internal/service/setting_gateway_runtime.go index ec6d21d502..4e91284c91 100644 --- a/backend/internal/service/setting_gateway_runtime.go +++ b/backend/internal/service/setting_gateway_runtime.go @@ -98,7 +98,7 @@ const antigravityUserAgentVersionErrorTTL = 5 * time.Second const antigravityUserAgentVersionDBTimeout = 5 * time.Second // DefaultOpenAICodexUserAgent 是 OpenAI Codex 默认 User-Agent,用于规避浏览器 UA 的质询。 -// 默认采用 codex-tui 身份,版本段随 codexCLIVersion 一起更新。 +// 默认采用 codex_cli_rs 身份,避免历史 codex-tui 出口触发 sub2api 的身份风控指纹。 const DefaultOpenAICodexUserAgent = codexCLIUserAgent // cachedOpenAICodexUserAgent 缓存 OpenAI Codex UA(进程内缓存,60s TTL) @@ -339,7 +339,7 @@ func (s *SettingService) GetOpenAICodexUserAgent(ctx context.Context) string { // GetOpenAICodexClientVersion 返回出站声明的 Codex 客户端版本号。 // 优先级:管理员在面板覆写的版本 → 自动同步到的官方最新稳定版 → 内置常量。 -// 上游在容量紧张时按客户端身份分优先级降载,陈旧版本会被优先丢弃,故该值需保持跟随官方发布; +// 上游会按客户端身份进行风控分层,陈旧版本可能被优先丢弃,故该值需保持跟随官方发布; // 自动同步让运维不必为了跟版本而发新版本。 func (s *SettingService) GetOpenAICodexClientVersion(ctx context.Context) string { fallback := codexCLIVersion @@ -500,11 +500,11 @@ func (s *SettingService) InvalidateClaudeCodeClientVersionCache() { } // GetOpenAICodexCanonicalUserAgent 返回出站规范 Codex User-Agent。 -// 未填面板 UA 时按当前生效的客户端版本号拼出标准 Codex TUI UA。 +// 未填面板 UA 时按当前生效的客户端版本号拼出标准 Codex CLI UA。 // // 面板 UA 只贡献客户端名与 OS / 架构 / 终端指纹,版本段一律用生效版本重建:该输入框是 // 唯一能改 UA 后缀的地方,但它填写于某个历史版本,逐字沿用会把出站身份永久钉死在陈旧 -// 版本上并绕过自动同步——而陈旧身份正是上游优先降载的那一侧。 +// 版本上并绕过自动同步——而陈旧身份正是上游风控更严格的那一侧。 // 需要固定版本请填「Codex 客户端版本号」并关闭自动同步。 func (s *SettingService) GetOpenAICodexCanonicalUserAgent(ctx context.Context) string { if s == nil { diff --git a/backend/internal/service/settings_view.go b/backend/internal/service/settings_view.go index bf2e840baa..8535fb6b8b 100644 --- a/backend/internal/service/settings_view.go +++ b/backend/internal/service/settings_view.go @@ -247,7 +247,7 @@ type SystemSettings struct { EnableClientDatelineNormalization bool // 是否对 Anthropic OAuth/SetupToken 请求体做客户端 dateline 归一化(默认 true) RewriteMessageCacheControl bool // 是否改写 messages[*].content[*].cache_control(默认 false) AntigravityUserAgentVersion string // Antigravity 上游 User-Agent 版本号;空值使用配置/默认值 - OpenAICodexUserAgent string // OpenAI Codex 上游完整 User-Agent;空值由 Codex 客户端版本号拼出标准 TUI UA + OpenAICodexUserAgent string // OpenAI Codex 上游完整 User-Agent;空值由 Codex 客户端版本号拼出标准 CLI UA OpenAICodexClientVersion string // 出站声明的 Codex 客户端版本号(管理员覆写);空值跟随自动同步值 OpenAICodexClientVersionSynced string // 自动同步到的官方最新稳定版版本号(只读展示) OpenAICodexVersionAutoSyncEnabled bool // 是否启用 Codex 客户端版本号自动同步(默认 true) diff --git a/frontend/src/i18n/locales/en/admin/settings.ts b/frontend/src/i18n/locales/en/admin/settings.ts index a3075fc601..c056f3925b 100644 --- a/frontend/src/i18n/locales/en/admin/settings.ts +++ b/frontend/src/i18n/locales/en/admin/settings.ts @@ -548,8 +548,8 @@ export default { antigravityUserAgentVersionPlaceholder: '1.23.2', antigravityUserAgentVersionHint: 'Leave empty to use ANTIGRAVITY_USER_AGENT_VERSION or the built-in default 1.23.2; when set, the admin setting takes precedence.', openaiCodexUserAgent: 'OpenAI Codex UA', - openaiCodexUserAgentPlaceholder: 'codex-tui/0.146.1 (Ubuntu 22.4.0; x86_64) WindowsTerminal (codex-tui; 0.146.1)', - openaiCodexUserAgentHint: 'The full Codex User-Agent used for all outbound requests, for customizing the OS / arch / terminal fingerprint. Leave empty to build the standard codex-tui identity from the version below (recommended). If set, both the leading and trailing version declarations are synchronized to the version below, so the UA never stays pinned to the release entered here — under capacity pressure the upstream sheds load by client identity and drops stale or non-official identities first with server_is_overloaded.', + openaiCodexUserAgentPlaceholder: 'codex_cli_rs/0.146.1 (Ubuntu 22.4.0; x86_64) WindowsTerminal', + openaiCodexUserAgentHint: 'The full Codex User-Agent used for all outbound requests, for customizing the OS / arch / terminal fingerprint. Leave empty to build the standard codex_cli_rs identity from the version below (recommended). If set, both the leading and trailing version declarations are synchronized to the version below, so the UA never stays pinned to the release entered here — upstream identity and version risk controls may return server_is_overloaded for stale or non-official identities.', openaiCodexClientVersion: 'Codex client version', openaiCodexClientVersionPlaceholder: 'Leave empty to follow auto-sync', openaiCodexClientVersionHint: 'The Codex client version this gateway declares upstream, shared by the User-Agent and the version header. Leave empty to use the auto-synced latest stable release; setting a value pins it and stops following auto-sync.', diff --git a/frontend/src/i18n/locales/zh/admin/settings.ts b/frontend/src/i18n/locales/zh/admin/settings.ts index 14317bff89..27b282b88d 100644 --- a/frontend/src/i18n/locales/zh/admin/settings.ts +++ b/frontend/src/i18n/locales/zh/admin/settings.ts @@ -541,8 +541,8 @@ export default { antigravityUserAgentVersionPlaceholder: '1.23.2', antigravityUserAgentVersionHint: '留空时使用 ANTIGRAVITY_USER_AGENT_VERSION 或内置默认值 1.23.2;填写后后台设置优先。', openaiCodexUserAgent: 'OpenAI Codex UA', - openaiCodexUserAgentPlaceholder: 'codex-tui/0.146.1 (Ubuntu 22.4.0; x86_64) WindowsTerminal (codex-tui; 0.146.1)', - openaiCodexUserAgentHint: '出站统一使用的完整 Codex User-Agent,用于自定义 OS / 架构 / 终端指纹。留空则按下方版本号拼出标准 codex-tui 形态(推荐)。填写后首段和尾部的版本号仍会被下方版本号同步覆盖,避免这条 UA 停在填写时的旧版本——上游在容量紧张时按客户端身份分优先级降载,陈旧或非官方形态的身份会被优先丢弃并回 server_is_overloaded。', + openaiCodexUserAgentPlaceholder: 'codex_cli_rs/0.146.1 (Ubuntu 22.4.0; x86_64) WindowsTerminal', + openaiCodexUserAgentHint: '出站统一使用的完整 Codex User-Agent,用于自定义 OS / 架构 / 终端指纹。留空则按下方版本号拼出标准 codex_cli_rs 形态(推荐)。填写后首段和尾部的版本号仍会被下方版本号同步覆盖,避免这条 UA 停在填写时的旧版本——上游会根据客户端身份和版本进行风控分层,陈旧或非官方形态可能返回 server_is_overloaded。', openaiCodexClientVersion: 'Codex 客户端版本号', openaiCodexClientVersionPlaceholder: '留空则跟随自动同步', openaiCodexClientVersionHint: '网关对上游声明的 Codex 客户端版本号,User-Agent 与 version 头同源使用。留空表示使用自动同步到的官方最新稳定版;填写后固定为该版本,不再跟随同步。', From 8286268047cbbca4e7f5fbb63ff0890c1ea37cf5 Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 23 Oct 2026 14:07:16 +0800 Subject: [PATCH 029/297] fix(deps): bump dompurify to 3.4.17 for GHSA-cg2g-xh64-v4q7 / GHSA-mrv2-3pqr-j5jr DOMPurify <=3.4.16 is affected by two advisories published 2026-10-22: - GHSA-cg2g-xh64-v4q7 (critical): SAFE_FOR_TEMPLATES bypass via split template expressions in attached shadow root content on DOM output modes - GHSA-mrv2-3pqr-j5jr (high): IN_PLACE hook removing a parent/sibling leaves detached subtree event handlers armed Bump the direct dependency and the pnpm override floor to 3.4.17 so the mermaid-transitive copy dedupes to the same patched version. Lockfile-only regen via pnpm 9 (matches CI); no other package changes. --- frontend/package.json | 4 ++-- frontend/pnpm-lock.yaml | 16 ++++++++-------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/frontend/package.json b/frontend/package.json index 177259daa3..fa12747fa7 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -23,7 +23,7 @@ "@vueuse/core": "^10.7.0", "axios": "^1.20.0", "chart.js": "^4.4.1", - "dompurify": "^3.4.14", + "dompurify": "^3.4.17", "driver.js": "^1.4.0", "file-saver": "^2.0.5", "marked": "^17.0.1", @@ -65,7 +65,7 @@ "js-cookie": "3.0.7", "form-data@<4.0.6": ">=4.0.6", "postcss@<8.5.18": ">=8.5.18", - "dompurify@<3.4.14": ">=3.4.14", + "dompurify@<3.4.17": ">=3.4.17", "source-map-js@<1.2.2": ">=1.2.2", "follow-redirects@<1.16.1": ">=1.16.1" } diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml index 5f02f3f2a8..d2714896a9 100644 --- a/frontend/pnpm-lock.yaml +++ b/frontend/pnpm-lock.yaml @@ -8,7 +8,7 @@ overrides: js-cookie: 3.0.7 form-data@<4.0.6: '>=4.0.6' postcss@<8.5.18: '>=8.5.18' - dompurify@<3.4.14: '>=3.4.14' + dompurify@<3.4.17: '>=3.4.17' source-map-js@<1.2.2: '>=1.2.2' follow-redirects@<1.16.1: '>=1.16.1' @@ -38,8 +38,8 @@ importers: specifier: ^4.4.1 version: 4.5.1 dompurify: - specifier: ^3.4.14 - version: 3.4.14 + specifier: ^3.4.17 + version: 3.4.17 driver.js: specifier: ^1.4.0 version: 1.4.0 @@ -2327,8 +2327,8 @@ packages: resolution: {integrity: sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==} engines: {node: '>=6.0.0'} - dompurify@3.4.14: - resolution: {integrity: sha512-dVoH9z+MY+C9IilgGCk3YfFqjLi3fChm2OiKJMzh6axrJ5qwxqWaZamgmHrpv22CN/KdbZJuGEGgfQoL00LTdg==} + dompurify@3.4.17: + resolution: {integrity: sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==} driver.js@1.4.0: resolution: {integrity: sha512-Gm64jm6PmcU+si21sQhBrTAM1JvUrR0QhNmjkprNLxohOBzul9+pNHXgQaT9lW84gwg9GMLB3NZGuGolsz5uew==} @@ -6052,7 +6052,7 @@ snapshots: '@types/dompurify@3.2.0': dependencies: - dompurify: 3.4.14 + dompurify: 3.4.17 '@types/estree-jsx@1.0.5': dependencies: @@ -7001,7 +7001,7 @@ snapshots: dependencies: esutils: 2.0.3 - dompurify@3.4.14: + dompurify@3.4.17: optionalDependencies: '@types/trusted-types': 2.0.7 @@ -8102,7 +8102,7 @@ snapshots: d3-sankey: 0.12.3 dagre-d3-es: 7.0.14 dayjs: 1.11.20 - dompurify: 3.4.14 + dompurify: 3.4.17 katex: 0.16.45 khroma: 2.1.0 lodash-es: 4.18.1 From ac1b8f1271be0d674fa6f074403c1410f30a3a81 Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 23 Oct 2026 15:24:04 +0800 Subject: [PATCH 030/297] chore: update sponsors --- README.md | 5 +++++ README_CN.md | 5 +++++ README_JA.md | 5 +++++ assets/partners/logos/ooko.ai.png | Bin 0 -> 9566 bytes 4 files changed, 15 insertions(+) create mode 100644 assets/partners/logos/ooko.ai.png diff --git a/README.md b/README.md index 11955a37b6..38b70781cf 100644 --- a/README.md +++ b/README.md @@ -156,6 +156,11 @@ Please read the following carefully before using this project: Thanks to Chenju for sponsoring this project! This is probably the only ad slot in this section that doesn't ask you to sign up for anything. Good open-source projects deserve to be paid for, so Chenju is chipping in a gift and raising a glass to the author. Find Chenju on X to chat about API relays, upstream providers, or just shoot the breeze. + +ooko.ai +🔑 Buying AI accounts at top prices | Gemini · Claude · GPT | Main and alt accounts all welcome, any channel wanted | Pay-per-usage supported | Seeking first-hand resources from major providers, I'll bring the KEY.
WeChat: Liuyou-zawd | Telegram: AACC8888888 + + ## Overview diff --git a/README_CN.md b/README_CN.md index 9064b68eac..d34649c845 100644 --- a/README_CN.md +++ b/README_CN.md @@ -159,6 +159,11 @@ 感谢 陈局 赞助了本项目!这大概是本栏唯一一个不让你注册的广告位。好的开源项目值得被付费,陈局来随个份子,敬作者一杯。X 上找 陈局,聊中转、聊上游、吹吹水。 + +ooko.ai +🔑 高价收 AI 账号|Gemini · Claude · GPT|大小号通收,各种渠道都要|支持按量跑付|寻一手大厂资源,我上 KEY 。
微信:Liuyou-zawd|TG:AACC8888888 + + ## 项目概述 diff --git a/README_JA.md b/README_JA.md index 367cce6373..58c5f379f7 100644 --- a/README_JA.md +++ b/README_JA.md @@ -158,6 +158,11 @@ 陈局(Chenju)様、本プロジェクトへのご支援ありがとうございます!これはおそらく、この欄で唯一「登録しなくていい」広告枠です。良いオープンソースには対価が払われるべき——というわけで、陈局がご祝儀を包んで作者に一杯おごります。X で 陈局 を見つけて、中継サービスや上流の話、雑談でもどうぞ。 + +ooko.ai +🔑 AI アカウント高価買取|Gemini · Claude · GPT|メイン・サブアカウントすべて買取、チャネル問わず歓迎|従量制での支払いに対応|大手の一次リソースを求めています、KEY は私が用意します。
WeChat:Liuyou-zawd|Telegram:AACC8888888 + + ## 概要 diff --git a/assets/partners/logos/ooko.ai.png b/assets/partners/logos/ooko.ai.png new file mode 100644 index 0000000000000000000000000000000000000000..8884583403521912e778111f71ac6f497238bab1 GIT binary patch literal 9566 zcmbtacRbX8{68ZuyE>5wb(J#X>=im(oLn4EB+1O)TbUVAC+qBymB`+tOP8*QBiWgk zy|UNu{r&s*c>MnP-Q!_AJ`X-CD(*VAHU;$eb7Agn0uJNF?F8bk2AE0h*| z?{4Dv20u=_YU4a05ax6LebGP&8Qc(v00ebM&CoYvInyr?h8*5)ez%{xk|mW$Cjl4G zriWo}(;&sHy^u6&7U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1Yr ze@P-&W)v@Zgzs)(U@j*9spC`=T3JfA(8dIyPs+0q^^|F+3$+H?!Y=9r2 zHzj}=Z(H(S= z*+^-$y6@4+`pZ7%gT%=XV1Po(hJ~~a#Emg7dBmZPmchg5zQCb&9>^6m^TEx`kJR_P zzM^_eRZTw(Rt6x&1+SYhCgkNahFkNWDhe?Rw;&&#>lHJ* zpzpMvKj+%JiL z4DkeKX9ov$OibRJp5Rc(e3cf3XCZ!O z_ac!4Sg!3Yv{K)03%=Znf8s=Qw#+xSqu}%pp~Kpa6$DFR?eiXqPydf`q5m~obiyxN XHW>|3SFr;FQxFtV?@qb;qtO2WoZG(* literal 0 HcmV?d00001 From 9aa16c8c66326afdd2e1b070e3403ac36e8a7050 Mon Sep 17 00:00:00 2001 From: SipengXie2024 Date: Fri, 23 Oct 2026 15:24:24 +0800 Subject: [PATCH 031/297] fix(pagination): validate numeric ranges and reuse safe offsets Use strconv to reject pagination values outside the native int range, reuse PaginationParams.Offset for API key slices, and derive test bounds from math.MaxInt. Cover parsing, response metadata, strict handlers, and in-memory pagination at the arithmetic boundaries. --- .../handler/admin/admin_helpers_test.go | 28 +++++ .../pkg/pagination/pagination_test.go | 4 +- backend/internal/pkg/response/response.go | 17 ++- .../internal/pkg/response/response_test.go | 107 ++++++++++++++++-- .../internal/repository/pagination_test.go | 17 +++ .../securityaudit/prompt_handler_test.go | 14 +++ backend/internal/service/api_key_service.go | 6 +- backend/internal/service/pagination_test.go | 25 ++++ 8 files changed, 190 insertions(+), 28 deletions(-) create mode 100644 backend/internal/repository/pagination_test.go create mode 100644 backend/internal/service/pagination_test.go diff --git a/backend/internal/handler/admin/admin_helpers_test.go b/backend/internal/handler/admin/admin_helpers_test.go index 4177fa7954..9b6f7010be 100644 --- a/backend/internal/handler/admin/admin_helpers_test.go +++ b/backend/internal/handler/admin/admin_helpers_test.go @@ -2,6 +2,8 @@ package admin import ( "encoding/json" + "fmt" + "math" "net/http" "net/http/httptest" "net/netip" @@ -150,6 +152,32 @@ func TestParseOpsOpenAITokenStatsFilter_InvalidParams(t *testing.T) { } } +func TestParseOpsOpenAITokenStatsFilter_PaginationBoundaries(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, size := range []int{1, 20, 21, 100} { + bound := math.MaxInt / size + pages := []int{bound} + if bound < math.MaxInt { + pages = append(pages, bound+1) + } + for _, page := range pages { + query := fmt.Sprintf("/?page=%d&page_size=%d", page, size) + t.Run(query, func(t *testing.T) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodGet, query, nil) + filter, err := parseOpsOpenAITokenStatsFilter(c) + if page > bound { + require.ErrorContains(t, err, "invalid page") + return + } + require.NoError(t, err) + require.Equal(t, page, filter.Page) + require.Equal(t, size, filter.PageSize) + }) + } + } +} + func TestParseOpsTimeRange(t *testing.T) { gin.SetMode(gin.TestMode) w := httptest.NewRecorder() diff --git a/backend/internal/pkg/pagination/pagination_test.go b/backend/internal/pkg/pagination/pagination_test.go index 1b704a40ca..89b1613763 100644 --- a/backend/internal/pkg/pagination/pagination_test.go +++ b/backend/internal/pkg/pagination/pagination_test.go @@ -108,8 +108,8 @@ func TestPaginationParamsOffsetUsesNormalizedLimit(t *testing.T) { func TestPaginationParamsOffsetDoesNotOverflow(t *testing.T) { t.Parallel() - pages := []int{math.MaxInt, math.MaxInt - 1, math.MaxInt / 2, 461168601842738791, math.MaxInt/1000 + 1} - pageSizes := []int{1, 2, 3, 20, 21, 999, 1000} + pages := []int{math.MinInt, -1, 0, 1, math.MaxInt, math.MaxInt - 1, math.MaxInt / 2, math.MaxInt/20 + 1, math.MaxInt/1000 + 1} + pageSizes := []int{math.MinInt, -1, 0, 1, 2, 3, 20, 21, 999, 1000, 1001, math.MaxInt} for _, page := range pages { for _, pageSize := range pageSizes { params := PaginationParams{Page: page, PageSize: pageSize} diff --git a/backend/internal/pkg/response/response.go b/backend/internal/pkg/response/response.go index a7afc7348f..a91aebd9ea 100644 --- a/backend/internal/pkg/response/response.go +++ b/backend/internal/pkg/response/response.go @@ -5,6 +5,7 @@ import ( "log" "math" "net/http" + "strconv" infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" "github.com/Wei-Shaw/sub2api/internal/util/logredact" @@ -166,7 +167,8 @@ func PaginatedWithResult(c *gin.Context, items any, pagination *PaginationResult }) } -// ParsePagination 解析分页参数 +// ParsePagination 解析分页参数。无效或超出 int 范围的值使用默认值; +// 有效页码按 pageSize 限制上限,返回可安全计算 offset 和 offset+pageSize 的页码。 func ParsePagination(c *gin.Context) (page, pageSize int) { page = 1 pageSize = 20 @@ -188,7 +190,7 @@ func ParsePagination(c *gin.Context) (page, pageSize int) { } } - // Clamp the page so (page-1)*pageSize computed by callers cannot overflow int. + // Clamp the page so both offset and offset+pageSize stay within int. if page > math.MaxInt/pageSize { page = math.MaxInt / pageSize } @@ -197,12 +199,7 @@ func ParsePagination(c *gin.Context) (page, pageSize int) { } func parseInt(s string) (int, error) { - var result int - for _, c := range s { - if c < '0' || c > '9' { - return 0, nil - } - result = result*10 + int(c-'0') - } - return result, nil + // Parse unsigned decimal digits within the positive range of the native int. + value, err := strconv.ParseUint(s, 10, strconv.IntSize-1) + return int(value), err } diff --git a/backend/internal/pkg/response/response_test.go b/backend/internal/pkg/response/response_test.go index 0e69f5ffd2..202a9b4b5b 100644 --- a/backend/internal/pkg/response/response_test.go +++ b/backend/internal/pkg/response/response_test.go @@ -8,6 +8,8 @@ import ( "math" "net/http" "net/http/httptest" + "strconv" + "strings" "testing" errors2 "github.com/Wei-Shaw/sub2api/internal/pkg/errors" @@ -694,28 +696,58 @@ func TestParsePagination(t *testing.T) { }, { name: "page为MaxInt_钳制到不溢出的上限", - query: "page=9223372036854775807", + query: "page=" + strconv.Itoa(math.MaxInt), wantPage: math.MaxInt / 20, wantPageSize: 20, }, { name: "page为MaxInt且page_size为1000_钳制到不溢出的上限", - query: "page=9223372036854775807&page_size=1000", + query: "page=" + strconv.Itoa(math.MaxInt) + "&page_size=1000", wantPage: math.MaxInt / 1000, wantPageSize: 1000, }, { name: "page恰好在上限_有效", - query: "page=461168601842738790", - wantPage: 461168601842738790, + query: "page=" + strconv.Itoa(math.MaxInt/20), + wantPage: math.MaxInt / 20, wantPageSize: 20, }, { name: "page刚超过上限_钳制", - query: "page=461168601842738791", + query: "page=" + strconv.Itoa(math.MaxInt/20+1), wantPage: math.MaxInt / 20, wantPageSize: 20, }, + { + name: "page超过MaxInt_使用默认值", + query: "page=" + strconv.FormatUint(uint64(math.MaxInt)+1, 10), + wantPage: 1, + wantPageSize: 20, + }, + { + name: "page超过uint64范围_不能回绕为2", + query: "page=18446744073709551618", + wantPage: 1, + wantPageSize: 20, + }, + { + name: "page_size超过uint64范围_不能回绕为21", + query: "page_size=18446744073709551637&limit=50", + wantPage: 1, + wantPageSize: 20, + }, + { + name: "limit超过uint64范围_不能回绕为21", + query: "limit=18446744073709551637", + wantPage: 1, + wantPageSize: 20, + }, + { + name: "超长数字_使用默认值", + query: "page=" + strings.Repeat("9", 100), + wantPage: 1, + wantPageSize: 20, + }, } for _, tt := range tests { @@ -730,6 +762,38 @@ func TestParsePagination(t *testing.T) { } } +func TestParsePaginationBoundariesAndResponse(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, sizeParam := range []string{"page_size", "limit"} { + for _, size := range []int{1, 2, 3, 20, 21, 999, 1000} { + bound := math.MaxInt / size + pages := []int{bound - 1, bound, math.MaxInt} + if bound < math.MaxInt { + pages = append(pages, bound+1) + } + for _, requestedPage := range pages { + query := "page=" + strconv.Itoa(requestedPage) + "&" + sizeParam + "=" + strconv.Itoa(size) + t.Run(query, func(t *testing.T) { + w, c := newContextWithQuery(query) + page, pageSize := ParsePagination(c) + require.Equal(t, min(requestedPage, bound), page) + require.Equal(t, size, pageSize) + offset := (page - 1) * pageSize + require.GreaterOrEqual(t, offset, 0) + require.LessOrEqual(t, offset, math.MaxInt-pageSize) + + Paginated(c, []string{}, 0, page, pageSize) + require.Equal(t, http.StatusOK, w.Code) + _, data := parsePaginatedBody(t, w) + require.Equal(t, page, data.Page) + require.Equal(t, pageSize, data.PageSize) + require.Empty(t, data.Items) + }) + } + } + } +} + func Test_parseInt(t *testing.T) { tests := []struct { name string @@ -765,37 +829,58 @@ func Test_parseInt(t *testing.T) { name: "包含字母_返回0", input: "abc", wantVal: 0, - wantErr: false, + wantErr: true, }, { name: "数字开头接字母_返回0", input: "12a", wantVal: 0, - wantErr: false, + wantErr: true, }, { name: "包含负号_返回0", input: "-1", wantVal: 0, - wantErr: false, + wantErr: true, }, { name: "包含小数点_返回0", input: "1.5", wantVal: 0, - wantErr: false, + wantErr: true, }, { name: "包含空格_返回0", input: "1 2", wantVal: 0, - wantErr: false, + wantErr: true, }, { name: "空字符串", input: "", wantVal: 0, - wantErr: false, + wantErr: true, + }, + { + name: "前导零_有效", + input: "000123", + wantVal: 123, + }, + { + name: "正号_无效", + input: "+1", + wantErr: true, + }, + { + name: "MaxInt_有效", + input: strconv.Itoa(math.MaxInt), + wantVal: math.MaxInt, + }, + { + name: "超过MaxInt_返回范围错误", + input: strconv.FormatUint(uint64(math.MaxInt)+1, 10), + wantVal: math.MaxInt, + wantErr: true, }, } diff --git a/backend/internal/repository/pagination_test.go b/backend/internal/repository/pagination_test.go new file mode 100644 index 0000000000..5d11b5a379 --- /dev/null +++ b/backend/internal/repository/pagination_test.go @@ -0,0 +1,17 @@ +package repository + +import ( + "math" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/stretchr/testify/require" +) + +func TestPaginateSliceLargePage(t *testing.T) { + t.Parallel() + for _, size := range []int{0, 1, 2, 3, 20, 21, 1000, 1001} { + params := pagination.PaginationParams{Page: math.MaxInt, PageSize: size} + require.Empty(t, paginateSlice([]int{1}, params), "page_size=%d", size) + } +} diff --git a/backend/internal/securityaudit/prompt_handler_test.go b/backend/internal/securityaudit/prompt_handler_test.go index a8cf27447f..b5a6136c42 100644 --- a/backend/internal/securityaudit/prompt_handler_test.go +++ b/backend/internal/securityaudit/prompt_handler_test.go @@ -5,8 +5,10 @@ import ( "context" "encoding/json" "errors" + "math" "net/http" "net/http/httptest" + "strconv" "strings" "testing" @@ -220,6 +222,18 @@ func TestPromptAdminRejectsInvalidEventIDsTimesAndPagination(t *testing.T) { } } +func TestPromptAdminRejectsOverflowingPagination(t *testing.T) { + router := promptAdminRouter(nil) + for _, size := range []int{20, 21, 100} { + query := "/admin/prompt-audit/events?page=" + strconv.Itoa(math.MaxInt/size+1) + "&page_size=" + strconv.Itoa(size) + t.Run(query, func(t *testing.T) { + response := promptAdminRequest(t, router, http.MethodGet, query, nil) + require.Equal(t, http.StatusBadRequest, response.Code) + require.Contains(t, response.Body.String(), "prompt_audit_invalid_pagination") + }) + } +} + func validHandlerUpdateRequest(token string) UpdateConfigRequest { return UpdateConfigRequest{ ExpectedConfigVersion: 7, diff --git a/backend/internal/service/api_key_service.go b/backend/internal/service/api_key_service.go index e20a2697eb..ec9f2c46d9 100644 --- a/backend/internal/service/api_key_service.go +++ b/backend/internal/service/api_key_service.go @@ -653,11 +653,7 @@ func paginateAPIKeys(keys []APIKey, params pagination.PaginationParams) []APIKey return []APIKey{} } limit := params.Limit() - page := params.Page - if page < 1 { - page = 1 - } - offset := (page - 1) * limit + offset := params.Offset() if offset >= len(keys) { return []APIKey{} } diff --git a/backend/internal/service/pagination_test.go b/backend/internal/service/pagination_test.go new file mode 100644 index 0000000000..e195959e00 --- /dev/null +++ b/backend/internal/service/pagination_test.go @@ -0,0 +1,25 @@ +package service + +import ( + "math" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/stretchr/testify/require" +) + +func TestPaginateAPIKeysLargePage(t *testing.T) { + t.Parallel() + for _, size := range []int{0, 1, 2, 3, 20, 21, 1000, 1001} { + params := pagination.PaginationParams{Page: math.MaxInt, PageSize: size} + require.Empty(t, paginateAPIKeys([]APIKey{{ID: 1}}, params), "page_size=%d", size) + } +} + +func TestMergeBalanceHistoryCodesLargePage(t *testing.T) { + t.Parallel() + for _, size := range []int{0, 1, 2, 3, 20, 21, 1000, 1001} { + params := pagination.PaginationParams{Page: math.MaxInt, PageSize: size} + require.Empty(t, mergeBalanceHistoryCodes([]RedeemCode{{ID: 1}}, nil, params), "page_size=%d", size) + } +} From 5c185c5c5d4f5e409e2139806e0964ae944e03e8 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 23 Oct 2026 07:44:16 +0000 Subject: [PATCH 032/297] chore: sync VERSION to 0.2.18 [skip ci] --- backend/cmd/server/VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION index 0fcb3bba7e..51e8fdc95c 100644 --- a/backend/cmd/server/VERSION +++ b/backend/cmd/server/VERSION @@ -1 +1 @@ -0.2.17 +0.2.18 From 01a1a78db2c3ce88565d924c0804a40062472221 Mon Sep 17 00:00:00 2001 From: wucm667 Date: Fri, 23 Oct 2026 19:12:24 +0800 Subject: [PATCH 033/297] fix(antigravity): neutralize stale system identities on forwarding --- .../pkg/antigravity/attribution_test.go | 29 ++++- .../pkg/antigravity/request_transformer.go | 35 +++--- .../antigravity_gateway_compat_test.go | 104 ++++++++++++++++++ .../service/antigravity_gateway_service.go | 18 ++- 4 files changed, 160 insertions(+), 26 deletions(-) diff --git a/backend/internal/pkg/antigravity/attribution_test.go b/backend/internal/pkg/antigravity/attribution_test.go index 79cc3c7ab3..1eee227383 100644 --- a/backend/internal/pkg/antigravity/attribution_test.go +++ b/backend/internal/pkg/antigravity/attribution_test.go @@ -27,6 +27,22 @@ func TestTransformClaudeToGemini_AttributionSystemText(t *testing.T) { {"different field", "x-anthropic-billing-header-extra: keep", "x-anthropic-billing-header-extra: keep"}, {"quoted within instructions", "Explain this metadata: " + attribution, "Explain this metadata: " + attribution}, {"later line", "Example:\n" + attribution, "Example:\n" + attribution}, + {"Codex GPT 5", "You are Codex, based on GPT-5. Keep GPT-5 model ids.", "You are an AI agent. Keep GPT-5 model ids."}, + {"Codex GPT 5.6", "You are Codex, a coding agent based on GPT-5.6.\nKeep indentation.", "You are an AI agent.\nKeep indentation."}, + {"Codex GPT 6", "You are Codex, based on GPT-6.", "You are an AI agent."}, + {"Codex GPT 6 agent", "You are Codex, an agent based on GPT-6. Rest.", "You are an AI agent. Rest."}, + {"CLI comma", "You are GPT-5.6 running in the Codex CLI, a terminal-based coding assistant.", "You are an AI agent, a terminal-based coding assistant."}, + {"Codex model suffix", "You are Codex, based on GPT-5.6-Codex. Rest.", "You are an AI agent. Rest."}, + {"CLI GPT 5.6", "You are GPT-5.6 running in the Codex CLI. Rest.", "You are an AI agent. Rest."}, + {"CLI GPT 6", " \nYou are GPT-6 running in the Codex CLI\nRest.", "You are an AI agent.\nRest."}, + {"Claude CLI", "You are Claude Code, Anthropic's official CLI for Claude. Rest.", "You are an AI agent. Rest."}, + {"Claude SDK", "You are a Claude agent, built on Anthropic's Claude Agent SDK. Rest.", "You are an AI agent. Rest."}, + {"attribution before GPT", attribution + "\r\nYou are Codex, based on GPT-6. Rest.", "You are an AI agent. Rest."}, + {"quoted GPT", `"You are Codex, based on GPT-6."`, `"You are Codex, based on GPT-6."`}, + {"later GPT", "Example:\nYou are GPT-6 running in the Codex CLI.", "Example:\nYou are GPT-6 running in the Codex CLI."}, + {"vendor mentions", "Use OpenAI GPT-5.6 and Anthropic Claude; preserve gpt-6.", "Use OpenAI GPT-5.6 and Anthropic Claude; preserve gpt-6."}, + {"not identity", "You are Codex, do not claim to be based on GPT-6.", "You are Codex, do not claim to be based on GPT-6."}, + {"model token boundary", "You are Codex, based on GPT-6example.", "You are Codex, based on GPT-6example."}, } for _, tt := range tests { for _, arrayForm := range []bool{false, true} { @@ -39,12 +55,13 @@ func TestTransformClaudeToGemini_AttributionSystemText(t *testing.T) { t.Run(name, func(t *testing.T) { systemJSON, err := json.Marshal(system) require.NoError(t, err) - userJSON, err := json.Marshal(attribution) + userText := strings.TrimSpace(tt.text) + userJSON, err := json.Marshal(userText) require.NoError(t, err) input := &ClaudeRequest{ Model: "gemini-3.8-flash-high", System: systemJSON, Messages: []ClaudeMessage{{Role: "user", Content: userJSON}}, - Tools: []ClaudeTool{{Name: "example", Description: attribution, + Tools: []ClaudeTool{{Name: "example", Description: tt.text, InputSchema: map[string]any{"type": "object", "properties": map[string]any{"query": map[string]any{"type": "string"}}}}}, } before, err := json.Marshal(input) @@ -68,8 +85,8 @@ func TestTransformClaudeToGemini_AttributionSystemText(t *testing.T) { } require.Equal(t, want, texts) // The same literal text in user content and tool descriptions is not metadata. - require.Equal(t, attribution, got.Request.Contents[0].Parts[0].Text) - require.Equal(t, attribution, got.Request.Tools[0].FunctionDeclarations[0].Description) + require.Equal(t, userText, got.Request.Contents[0].Parts[0].Text) + require.Equal(t, tt.text, got.Request.Tools[0].FunctionDeclarations[0].Description) after, err := json.Marshal(input) require.NoError(t, err) require.JSONEq(t, string(before), string(after), "do not mutate the incoming request") @@ -124,7 +141,7 @@ func TestNeutralizeClaudeIdentity(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - require.Equal(t, tt.want, neutralizeClaudeIdentity(tt.text)) + require.Equal(t, tt.want, NeutralizeSystemIdentity(tt.text)) }) } } @@ -135,7 +152,7 @@ func TestAttributionAndIdentityTogether(t *testing.T) { attribution := "x-anthropic-billing-header: cc_version=2.1.278.0a9; cc_entrypoint=claude-vscode;" identity := "You are a Claude agent, built on Anthropic's Claude Agent SDK." require.Equal(t, "", stripClaudeAttribution(attribution)) - require.Equal(t, "You are an AI agent.", neutralizeClaudeIdentity(identity)) + require.Equal(t, "You are an AI agent.", NeutralizeSystemIdentity(identity)) } // End-to-end through the transformer: the attribution block and the identity diff --git a/backend/internal/pkg/antigravity/request_transformer.go b/backend/internal/pkg/antigravity/request_transformer.go index a13748926e..ea6717ccd9 100644 --- a/backend/internal/pkg/antigravity/request_transformer.go +++ b/backend/internal/pkg/antigravity/request_transformer.go @@ -294,27 +294,28 @@ func filterOpenCodePrompt(text string) string { return "" } -// stripClaudeAttribution removes the leading Claude Code attribution metadata line -// from Antigravity system text. This is prompt metadata, not an HTTP header; it -// can trigger RESOURCE_EXHAUSTED on the Google upstream. Keep this scoped to the -// Antigravity transformer: native Anthropic OAuth may require the attribution. -// claudeIdentityOpeners 是部分 Anthropic 客户端放在系统块开头的 Claude Agent SDK 身份语句。 -// 仅移除 x-anthropic-billing-header 行还不够:如果系统文本仍以这些语句开头, -// Google 上游仍会返回 429 RESOURCE_EXHAUSTED。 -// // The patterns are anchored at the start of a system block on purpose, so user -// instructions that merely mention Claude or Anthropic are left untouched. -var claudeIdentityOpeners = []*regexp.Regexp{ +// instructions that merely mention Claude, GPT or their vendors are left untouched. +var systemIdentityOpeners = []*regexp.Regexp{ regexp.MustCompile(`(?i)^[ \t\r\n]*You are a Claude agent, built on Anthropic'?s Claude Agent SDK\.?`), regexp.MustCompile(`(?i)^[ \t\r\n]*You are Claude Code, Anthropic'?s official CLI for Claude\.?`), + regexp.MustCompile(`(?i)^[ \t\r\n]*You are Codex,? (?:a coding agent |an agent )?based on GPT-[0-9]+(?:\.[0-9]+)*(?:-[a-z0-9]+)*\.?`), + regexp.MustCompile(`(?i)^[ \t\r\n]*You are GPT-[0-9]+(?:\.[0-9]+)*(?:-[a-z0-9]+)* running in the Codex CLI\.?`), } -// neutralizeClaudeIdentity rewrites a leading vendor identity sentence into a -// vendor-neutral one. It keeps the rest of the block, including any user -// instructions that follow. -func neutralizeClaudeIdentity(text string) string { - for _, re := range claudeIdentityOpeners { +// NeutralizeSystemIdentity removes leading client attribution and rewrites a +// leading vendor identity sentence, preserving the rest of the system block. +// Only Antigravity forwarding should use this; native Anthropic may require attribution. +func NeutralizeSystemIdentity(text string) string { + text = stripClaudeAttribution(text) + for _, re := range systemIdentityOpeners { if loc := re.FindStringIndex(text); loc != nil { + if strings.HasPrefix(text[loc[1]:], ",") { + return "You are an AI agent" + text[loc[1]:] + } + if loc[1] < len(text) && !strings.ContainsAny(text[loc[1]:loc[1]+1], " \t\r\n") { + continue + } return "You are an AI agent." + text[loc[1]:] } } @@ -349,7 +350,7 @@ func buildSystemInstruction(system json.RawMessage, modelName string, opts Trans // 尝试解析为字符串 var sysStr string if err := json.Unmarshal(system, &sysStr); err == nil { - sysStr = neutralizeClaudeIdentity(stripClaudeAttribution(sysStr)) + sysStr = NeutralizeSystemIdentity(sysStr) if strings.TrimSpace(sysStr) != "" { if strings.Contains(sysStr, "You are Antigravity") { userHasAntigravityIdentity = true @@ -365,7 +366,7 @@ func buildSystemInstruction(system json.RawMessage, modelName string, opts Trans var sysBlocks []SystemBlock if err := json.Unmarshal(system, &sysBlocks); err == nil { for _, block := range sysBlocks { - block.Text = neutralizeClaudeIdentity(stripClaudeAttribution(block.Text)) + block.Text = NeutralizeSystemIdentity(block.Text) if block.Type == "text" && strings.TrimSpace(block.Text) != "" { if strings.Contains(block.Text, "You are Antigravity") { userHasAntigravityIdentity = true diff --git a/backend/internal/service/antigravity_gateway_compat_test.go b/backend/internal/service/antigravity_gateway_compat_test.go index 825997e4f3..a1ea126ddd 100644 --- a/backend/internal/service/antigravity_gateway_compat_test.go +++ b/backend/internal/service/antigravity_gateway_compat_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "fmt" "io" "net/http" "net/http/httptest" @@ -131,6 +132,109 @@ func antigravityCompatSuccessResponse() *http.Response { } } +func TestAntigravitySystemIdentityAcrossProtocols(t *testing.T) { + gin.SetMode(gin.TestMode) + const task = "\nKeep GPT-5.6, gpt-6 and Claude model ids unchanged." + for _, identity := range []string{"You are Codex, based on GPT-5.6.", "You are Codex, an agent based on GPT-6.", "You are GPT-6 running in the Codex CLI.", "You are Claude Code, Anthropic's official CLI for Claude."} { + for _, model := range []string{"gemini-3.1-pro-high", "claude-sonnet-4-6"} { + for _, protocol := range []string{"responses", "chat", "messages"} { + for _, arraySystem := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/%s/%s/array=%t", identity, model, protocol, arraySystem), func(t *testing.T) { + text := "x-anthropic-billing-header: cc_version=example;\n" + identity + task + var system any = text + if arraySystem { + system = []map[string]any{{"type": "text", "text": text}} + } + request := map[string]any{"model": model, "max_tokens": 128} + switch protocol { + case "responses": + request["input"] = identity + request["instructions"] = text + if arraySystem { + delete(request, "instructions") + request["input"] = []map[string]any{ + {"type": "message", "role": "developer", "content": []map[string]string{{"type": "input_text", "text": text}}}, + {"type": "message", "role": "user", "content": identity}, + } + } + case "chat": + request["messages"] = []map[string]any{{"role": "system", "content": system}, {"role": "user", "content": identity}} + case "messages": + request["system"] = system + request["messages"] = []map[string]any{{"role": "user", "content": identity}} + } + body, err := json.Marshal(request) + require.NoError(t, err) + var forwarded []byte + upstream := &queuedHTTPUpstreamStub{ + responses: []*http.Response{antigravityCompatSuccessResponse()}, + onCall: func(req *http.Request, _ *queuedHTTPUpstreamStub) { + forwarded, err = io.ReadAll(req.Body) + require.NoError(t, err) + }, + } + svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream) + account := newAntigravityCompatAccount(AccountTypeOAuth) + c, _ := newAntigravityCompatContext(http.MethodPost, "/v1/"+protocol, body) + switch protocol { + case "responses": + _, err = svc.ForwardAsResponses(context.Background(), c, account, body, nil) + case "chat": + _, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, nil) + case "messages": + _, err = svc.Forward(context.Background(), c, account, body, false) + } + require.NoError(t, err) + systemText := gjson.GetBytes(forwarded, "request.systemInstruction.parts").Raw + require.Contains(t, systemText, "You are an AI agent.") + require.Contains(t, systemText, "Keep GPT-5.6, gpt-6 and Claude model ids unchanged.") + require.NotContains(t, systemText, identity) + require.NotContains(t, systemText, "x-anthropic-billing-header:") + require.Equal(t, identity, gjson.GetBytes(forwarded, "request.contents.0.parts.0.text").String()) + require.Equal(t, model, gjson.GetBytes(forwarded, "model").String()) + }) + } + } + } + } +} + +func TestInjectAntigravityGeminiSystemIdentity(t *testing.T) { + const identity = "You are Codex, based on GPT-6." + const mention = "Example: You are GPT-5.6 running in the Codex CLI." + for _, existingIdentity := range []bool{false, true} { + t.Run(fmt.Sprintf("existing identity=%t", existingIdentity), func(t *testing.T) { + parts := []map[string]any{ + {"text": "x-anthropic-billing-header: cc_version=example;"}, + {"text": identity, "custom": "preserved"}, + {"text": mention}, + {"text": `"You are Codex, based on GPT-6."`}, + } + if existingIdentity { + parts = append([]map[string]any{{"text": "You are Antigravity."}}, parts...) + } + body, err := json.Marshal(map[string]any{ + "systemInstruction": map[string]any{"parts": parts}, + "contents": []map[string]any{{"role": "user", "parts": []map[string]string{{"text": identity}}}}, + "tools": []map[string]any{{"functionDeclarations": []map[string]string{{"name": "example", "description": identity}}}}, + }) + require.NoError(t, err) + got, err := injectIdentityPatchToGeminiRequest(body) + require.NoError(t, err) + require.Equal(t, "You are an AI agent.", gjson.GetBytes(got, "systemInstruction.parts.2.text").String()) + require.Equal(t, "preserved", gjson.GetBytes(got, "systemInstruction.parts.2.custom").String()) + require.Equal(t, mention, gjson.GetBytes(got, "systemInstruction.parts.3.text").String()) + require.Equal(t, `"You are Codex, based on GPT-6."`, gjson.GetBytes(got, "systemInstruction.parts.4.text").String()) + for _, field := range []string{"contents", "tools"} { + require.JSONEq(t, gjson.GetBytes(body, field).Raw, gjson.GetBytes(got, field).Raw) + } + again, err := injectIdentityPatchToGeminiRequest(got) + require.NoError(t, err) + require.Equal(t, string(got), string(again)) + }) + } +} + func TestAntigravityCompatOAuthUsesNativeTokenAndRoute(t *testing.T) { gin.SetMode(gin.TestMode) diff --git a/backend/internal/service/antigravity_gateway_service.go b/backend/internal/service/antigravity_gateway_service.go index 66a0f02cdb..d2a4d81b1e 100644 --- a/backend/internal/service/antigravity_gateway_service.go +++ b/backend/internal/service/antigravity_gateway_service.go @@ -641,21 +641,33 @@ func injectIdentityPatchToGeminiRequest(body []byte) ([]byte, error) { return nil, fmt.Errorf("解析 Gemini 请求失败: %w", err) } + identityFound := false + systemChanged := false // 检查现有 systemInstruction 是否已包含身份提示词 if sysInst, ok := request["systemInstruction"].(map[string]any); ok { if parts, ok := sysInst["parts"].([]any); ok { for _, part := range parts { if partMap, ok := part.(map[string]any); ok { if text, ok := partMap["text"].(string); ok { - if strings.Contains(text, "You are Antigravity") { - // 已包含身份提示词,直接返回原始请求 - return body, nil + neutral := antigravity.NeutralizeSystemIdentity(text) + if neutral != text { + partMap["text"] = neutral + systemChanged = true + } + if strings.Contains(neutral, "You are Antigravity") { + identityFound = true } } } } } } + if identityFound { + if systemChanged { + return json.Marshal(request) + } + return body, nil + } // 获取默认身份提示词 identityPatch := antigravity.GetDefaultIdentityPatch() From e445cc3e2d9c9f330f2af069d6693bfdeb2245ad Mon Sep 17 00:00:00 2001 From: lyen1688 Date: Fri, 23 Oct 2026 19:16:57 +0800 Subject: [PATCH 034/297] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E6=8C=89=E6=93=8D?= =?UTF-8?q?=E4=BD=9C=E4=B8=8E=E8=B5=84=E6=BA=90=E8=8C=83=E5=9B=B4=E6=8E=88?= =?UTF-8?q?=E6=9D=83=E7=9A=84=E7=AE=A1=E7=90=86=E5=91=98=20API=20=E5=AF=86?= =?UTF-8?q?=E9=92=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + backend/cmd/server/wire_gen.go | 3 +- .../internal/handler/admin/account_handler.go | 33 +- .../handler/admin/announcement_handler.go | 2 +- .../admin/custom_admin_key_accounts.go | 284 ++++++++++++ .../admin/custom_admin_key_accounts_test.go | 150 +++++++ .../admin/custom_admin_key_codex_import.go | 189 ++++++++ .../custom_admin_key_codex_import_test.go | 249 +++++++++++ .../admin/custom_admin_key_commit_test.go | 199 +++++++++ .../admin/custom_admin_key_group_models.go | 167 +++++++ .../handler/admin/custom_admin_key_proxies.go | 163 +++++++ .../admin/custom_admin_key_proxies_test.go | 198 +++++++++ .../handler/admin/custom_admin_key_users.go | 47 ++ .../admin/custom_admin_key_users_test.go | 113 +++++ .../handler/admin/custom_admin_keys.go | 102 +++++ .../handler/admin/custom_admin_keys_test.go | 78 ++++ .../admin/custom_legacy_admin_key_test.go | 141 ++++++ .../handler/admin/idempotency_helper.go | 16 +- .../internal/handler/admin/promo_handler.go | 2 +- .../internal/handler/admin/proxy_handler.go | 9 + .../admin/scoped_admin_content_response.go | 47 ++ .../scoped_admin_content_response_test.go | 94 ++++ .../scoped_admin_subscription_response.go | 65 +++ ...scoped_admin_subscription_response_test.go | 164 +++++++ .../admin/scoped_admin_usage_response.go | 97 ++++ .../admin/scoped_admin_usage_response_test.go | 92 ++++ .../handler/admin/setting_handler_runtime.go | 20 +- .../handler/admin/subscription_handler.go | 20 +- .../internal/handler/admin/usage_handler.go | 6 +- .../internal/handler/admin/user_handler.go | 34 +- backend/internal/pkg/adminaccess/catalog.go | 106 +++++ backend/internal/pkg/adminaccess/policy.go | 154 +++++++ .../internal/pkg/adminaccess/policy_test.go | 144 ++++++ backend/internal/repository/account_repo.go | 43 ++ .../custom_account_proxy_selection.go | 46 ++ .../custom_account_proxy_selection_test.go | 129 ++++++ .../custom_admin_key_group_models.go | 98 ++++ .../custom_admin_key_group_models_test.go | 105 +++++ .../custom_admin_key_review_test.go | 225 ++++++++++ .../repository/custom_admin_key_scope.go | 247 ++++++++++ .../repository/custom_admin_key_scope_test.go | 257 +++++++++++ .../custom_admin_key_transaction.go | 19 + .../internal/repository/custom_admin_keys.go | 112 +++++ .../custom_admin_keys_postgres_test.go | 146 ++++++ .../repository/custom_admin_keys_test.go | 50 +++ .../repository/custom_proxy_options.go | 56 +++ .../repository/custom_proxy_sample_test.go | 111 +++++ .../repository/custom_proxy_search.go | 20 + backend/internal/repository/setting_repo.go | 14 + backend/internal/repository/wire.go | 1 + .../internal/server/middleware/admin_auth.go | 64 ++- .../custom_admin_key_rate_limit_test.go | 170 +++++++ .../middleware/custom_admin_keys_test.go | 117 +++++ .../server/middleware/panel_rate_limit.go | 55 ++- backend/internal/server/routes/admin.go | 12 +- .../routes/custom_admin_key_access_test.go | 420 ++++++++++++++++++ .../custom_admin_key_group_models_test.go | 203 +++++++++ ...ustom_admin_key_payment_rate_limit_test.go | 54 +++ .../custom_admin_key_user_responses_test.go | 134 ++++++ .../server/routes/custom_admin_keys.go | 18 + .../server/routes/custom_admin_keys_test.go | 35 ++ backend/internal/server/routes/payment.go | 1 + backend/internal/service/admin_account.go | 56 ++- backend/internal/service/admin_service.go | 2 + .../service/custom_admin_key_accounts.go | 366 +++++++++++++++ .../service/custom_admin_key_accounts_test.go | 325 ++++++++++++++ .../service/custom_admin_key_codex_import.go | 164 +++++++ .../custom_admin_key_codex_import_test.go | 174 ++++++++ .../service/custom_admin_key_group_models.go | 56 +++ .../custom_admin_key_group_models_test.go | 48 ++ .../custom_admin_key_proxy_selection.go | 72 +++ .../custom_admin_key_proxy_selection_test.go | 174 ++++++++ .../custom_admin_key_recovery_review_test.go | 77 ++++ .../service/custom_admin_key_testdb_test.go | 47 ++ .../service/custom_admin_key_transaction.go | 29 ++ .../custom_admin_key_transaction_test.go | 53 +++ backend/internal/service/custom_admin_keys.go | 253 +++++++++++ .../service/custom_admin_keys_test.go | 229 ++++++++++ .../internal/service/custom_proxy_options.go | 35 ++ backend/internal/service/setting_features.go | 18 +- backend/internal/service/setting_service.go | 1 + backend/internal/service/wire.go | 3 +- .../migrations/247_scoped_admin_api_keys.sql | 22 + docs/admin-api-keys.md | 145 ++++++ frontend/src/api/admin/adminAccessKeys.ts | 37 ++ .../settings/AdminAccessKeysSettings.vue | 193 ++++++++ .../__tests__/AdminAccessKeysSettings.spec.ts | 247 ++++++++++ .../src/i18n/locales/en/adminAccessKeys.ts | 73 +++ frontend/src/i18n/locales/en/index.ts | 2 + .../src/i18n/locales/zh/adminAccessKeys.ts | 73 +++ frontend/src/i18n/locales/zh/index.ts | 2 + frontend/src/views/admin/SettingsView.vue | 58 +-- 92 files changed, 9054 insertions(+), 131 deletions(-) create mode 100644 backend/internal/handler/admin/custom_admin_key_accounts.go create mode 100644 backend/internal/handler/admin/custom_admin_key_accounts_test.go create mode 100644 backend/internal/handler/admin/custom_admin_key_codex_import.go create mode 100644 backend/internal/handler/admin/custom_admin_key_codex_import_test.go create mode 100644 backend/internal/handler/admin/custom_admin_key_commit_test.go create mode 100644 backend/internal/handler/admin/custom_admin_key_group_models.go create mode 100644 backend/internal/handler/admin/custom_admin_key_proxies.go create mode 100644 backend/internal/handler/admin/custom_admin_key_proxies_test.go create mode 100644 backend/internal/handler/admin/custom_admin_key_users.go create mode 100644 backend/internal/handler/admin/custom_admin_key_users_test.go create mode 100644 backend/internal/handler/admin/custom_admin_keys.go create mode 100644 backend/internal/handler/admin/custom_admin_keys_test.go create mode 100644 backend/internal/handler/admin/custom_legacy_admin_key_test.go create mode 100644 backend/internal/handler/admin/scoped_admin_content_response.go create mode 100644 backend/internal/handler/admin/scoped_admin_content_response_test.go create mode 100644 backend/internal/handler/admin/scoped_admin_subscription_response.go create mode 100644 backend/internal/handler/admin/scoped_admin_subscription_response_test.go create mode 100644 backend/internal/handler/admin/scoped_admin_usage_response.go create mode 100644 backend/internal/handler/admin/scoped_admin_usage_response_test.go create mode 100644 backend/internal/pkg/adminaccess/catalog.go create mode 100644 backend/internal/pkg/adminaccess/policy.go create mode 100644 backend/internal/pkg/adminaccess/policy_test.go create mode 100644 backend/internal/repository/custom_account_proxy_selection.go create mode 100644 backend/internal/repository/custom_account_proxy_selection_test.go create mode 100644 backend/internal/repository/custom_admin_key_group_models.go create mode 100644 backend/internal/repository/custom_admin_key_group_models_test.go create mode 100644 backend/internal/repository/custom_admin_key_review_test.go create mode 100644 backend/internal/repository/custom_admin_key_scope.go create mode 100644 backend/internal/repository/custom_admin_key_scope_test.go create mode 100644 backend/internal/repository/custom_admin_key_transaction.go create mode 100644 backend/internal/repository/custom_admin_keys.go create mode 100644 backend/internal/repository/custom_admin_keys_postgres_test.go create mode 100644 backend/internal/repository/custom_admin_keys_test.go create mode 100644 backend/internal/repository/custom_proxy_options.go create mode 100644 backend/internal/repository/custom_proxy_sample_test.go create mode 100644 backend/internal/repository/custom_proxy_search.go create mode 100644 backend/internal/server/middleware/custom_admin_key_rate_limit_test.go create mode 100644 backend/internal/server/middleware/custom_admin_keys_test.go create mode 100644 backend/internal/server/routes/custom_admin_key_access_test.go create mode 100644 backend/internal/server/routes/custom_admin_key_group_models_test.go create mode 100644 backend/internal/server/routes/custom_admin_key_payment_rate_limit_test.go create mode 100644 backend/internal/server/routes/custom_admin_key_user_responses_test.go create mode 100644 backend/internal/server/routes/custom_admin_keys.go create mode 100644 backend/internal/server/routes/custom_admin_keys_test.go create mode 100644 backend/internal/service/custom_admin_key_accounts.go create mode 100644 backend/internal/service/custom_admin_key_accounts_test.go create mode 100644 backend/internal/service/custom_admin_key_codex_import.go create mode 100644 backend/internal/service/custom_admin_key_codex_import_test.go create mode 100644 backend/internal/service/custom_admin_key_group_models.go create mode 100644 backend/internal/service/custom_admin_key_group_models_test.go create mode 100644 backend/internal/service/custom_admin_key_proxy_selection.go create mode 100644 backend/internal/service/custom_admin_key_proxy_selection_test.go create mode 100644 backend/internal/service/custom_admin_key_recovery_review_test.go create mode 100644 backend/internal/service/custom_admin_key_testdb_test.go create mode 100644 backend/internal/service/custom_admin_key_transaction.go create mode 100644 backend/internal/service/custom_admin_key_transaction_test.go create mode 100644 backend/internal/service/custom_admin_keys.go create mode 100644 backend/internal/service/custom_admin_keys_test.go create mode 100644 backend/internal/service/custom_proxy_options.go create mode 100644 backend/migrations/247_scoped_admin_api_keys.sql create mode 100644 docs/admin-api-keys.md create mode 100644 frontend/src/api/admin/adminAccessKeys.ts create mode 100644 frontend/src/components/admin/settings/AdminAccessKeysSettings.vue create mode 100644 frontend/src/components/admin/settings/__tests__/AdminAccessKeysSettings.spec.ts create mode 100644 frontend/src/i18n/locales/en/adminAccessKeys.ts create mode 100644 frontend/src/i18n/locales/zh/adminAccessKeys.ts diff --git a/.gitignore b/.gitignore index 0c977fdfa3..93d301f157 100644 --- a/.gitignore +++ b/.gitignore @@ -133,6 +133,7 @@ deploy/docker-compose.override.yml .gocache/ vite.config.js docs/* +!docs/admin-api-keys.md !docs/PAYMENT.md !docs/PAYMENT_CN.md !docs/ADMIN_PAYMENT_INTEGRATION_API.md diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 53cef32052..49e42b4c7d 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -52,7 +52,8 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { settingRepository := repository.NewSettingRepository(client) groupRepository := repository.NewGroupRepository(client, db) proxyRepository := repository.NewProxyRepository(client, db) - settingService := service.ProvideSettingService(settingRepository, groupRepository, proxyRepository, configConfig) + scopedAdminKeyRepository := repository.NewScopedAdminKeyRepository(db) + settingService := service.ProvideSettingService(scopedAdminKeyRepository, settingRepository, groupRepository, proxyRepository, configConfig) emailCache := repository.NewEmailCache(redisClient) emailService := service.NewEmailService(settingRepository, emailCache) turnstileVerifier := repository.NewTurnstileVerifier() diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go index 4c2fbd37ca..c48a9f99cd 100644 --- a/backend/internal/handler/admin/account_handler.go +++ b/backend/internal/handler/admin/account_handler.go @@ -1419,7 +1419,9 @@ func (h *AccountHandler) refreshSingleAccount(ctx context.Context, account *serv tokenInfo, err := h.openaiOAuthService.RefreshAccountToken(ctx, account) if err != nil { // 刷新失败但 access_token 可能仍有效,尝试设置隐私 - h.adminService.EnsureOpenAIPrivacy(ctx, account) + service.AfterAccountCommit(ctx, func(committed context.Context) { + h.adminService.EnsureOpenAIPrivacy(committed, account) + }) return nil, "", err } @@ -1471,7 +1473,10 @@ func (h *AccountHandler) refreshSingleAccount(ctx context.Context, account *serv if updateErr != nil { return nil, "", fmt.Errorf("failed to update credentials: %w", updateErr) } - h.adminService.EnsureAntigravityPrivacy(ctx, updatedAccount) + h.invalidateScopedAccountToken(ctx, updatedAccount) + service.AfterAccountCommit(ctx, func(committed context.Context) { + h.adminService.EnsureAntigravityPrivacy(committed, updatedAccount) + }) return updatedAccount, "missing_project_id_temporary", nil } @@ -1527,17 +1532,19 @@ func (h *AccountHandler) refreshSingleAccount(ctx context.Context, account *serv return nil, "", err } - // 刷新成功后,清除 token 缓存,确保下次请求使用新 token - if h.tokenCacheInvalidator != nil { - if invalidateErr := h.tokenCacheInvalidator.InvalidateToken(ctx, updatedAccount); invalidateErr != nil { - log.Printf("[WARN] Failed to invalidate token cache for account %d: %v", updatedAccount.ID, invalidateErr) + service.AfterAccountCommit(ctx, func(ctx context.Context) { + // 刷新成功后,清除 token 缓存,确保下次请求使用新 token + if h.tokenCacheInvalidator != nil { + if invalidateErr := h.tokenCacheInvalidator.InvalidateToken(ctx, updatedAccount); invalidateErr != nil { + log.Printf("[WARN] Failed to invalidate token cache for account %d: %v", updatedAccount.ID, invalidateErr) + } } - } - // OpenAI OAuth: 刷新成功后检查并设置 privacy_mode - h.adminService.EnsureOpenAIPrivacy(ctx, updatedAccount) - // Antigravity OAuth: 刷新成功后检查并设置 privacy_mode - h.adminService.EnsureAntigravityPrivacy(ctx, updatedAccount) + // OpenAI OAuth: 刷新成功后检查并设置 privacy_mode + h.adminService.EnsureOpenAIPrivacy(ctx, updatedAccount) + // Antigravity OAuth: 刷新成功后检查并设置 privacy_mode + h.adminService.EnsureAntigravityPrivacy(ctx, updatedAccount) + }) return updatedAccount, "", nil } @@ -2804,6 +2811,10 @@ func (h *AccountHandler) GetAvailableModels(c *gin.Context) { return } + h.respondAvailableModels(c, account) +} + +func (h *AccountHandler) respondAvailableModels(c *gin.Context, account *service.Account) { // Handle OpenAI accounts if account.IsOpenAI() { // Prefer the shared, account-keyed upstream catalog. If discovery fails, diff --git a/backend/internal/handler/admin/announcement_handler.go b/backend/internal/handler/admin/announcement_handler.go index d3b9d17373..acd084813e 100644 --- a/backend/internal/handler/admin/announcement_handler.go +++ b/backend/internal/handler/admin/announcement_handler.go @@ -252,5 +252,5 @@ func (h *AnnouncementHandler) ListReadStatus(c *gin.Context) { return } - response.Paginated(c, items, paginationResult.Total, page, pageSize) + response.Paginated(c, adminAnnouncementReadResponse(c, items), paginationResult.Total, page, pageSize) } diff --git a/backend/internal/handler/admin/custom_admin_key_accounts.go b/backend/internal/handler/admin/custom_admin_key_accounts.go new file mode 100644 index 0000000000..dc4a2e21a6 --- /dev/null +++ b/backend/internal/handler/admin/custom_admin_key_accounts.go @@ -0,0 +1,284 @@ +package admin + +import ( + "context" + "encoding/json" + "slices" + "strconv" + "strings" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/Wei-Shaw/sub2api/internal/pkg/response" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" +) + +func scopedAdminAccountDTO(a *service.Account, p adminaccess.Policy) gin.H { + resource := adminaccess.Account{ID: a.ID, Type: a.Type, Platform: a.Platform, GroupIDs: a.GroupIDs} + groups := []int64{} + for _, g := range a.GroupIDs { + if p.AllowsGroup("accounts.read", resource, g) { + groups = append(groups, g) + } + } + result := gin.H{"id": a.ID, "name": a.Name, "notes": a.Notes, "platform": a.Platform, "type": a.Type, "status": a.Status, "schedulable": a.Schedulable, "concurrency": a.Concurrency, "priority": a.Priority, "group_ids": groups} + // 兼容原账户读取结构,仅返回模型映射,凭证及扩展字段继续脱敏。 + if p.AllowsAccount("accounts.read", resource) { + mapping := map[string]string{} + switch raw := a.Credentials["model_mapping"].(type) { + case map[string]string: + for source, target := range raw { + mapping[source] = target + } + case map[string]any: + for source, target := range raw { + if value, ok := target.(string); ok { + mapping[source] = value + } + } + } + result["credentials"] = gin.H{"model_mapping": mapping} + } + return result +} + +// ScopedAdminKeyAccounts 在原处理器前完成独立授权和安全输出。 +func (h *AccountHandler) ScopedAdminKeyAccounts(c *gin.Context) { + principal := adminaccess.FromContext(c.Request.Context()) + if principal == nil { + return + } + path := c.FullPath() + if !strings.HasPrefix(path, "/api/v1/admin/accounts") { + return + } + c.Abort() + base := "/api/v1/admin/accounts" + // 静态默认映射不读取任何账户;权限独立于账户查看及凭证写入。 + if path == base+"/antigravity/default-model-mapping" && c.Request.Method == "GET" { + if !adminaccess.RouteAllowed(principal.Policy, c.Request.Method, path) { + response.Error(c, 403, "默认模型读取未授权") + return + } + h.GetAntigravityDefaultModelMapping(c) + return + } + if path == base+"/import/codex-session" && c.Request.Method == "POST" { + h.scopedAdminImportCodexSession(c) + return + } + api, ok := h.adminService.(service.ScopedAdminAccounts) + if !ok { + response.Error(c, 503, "受限账户服务不可用") + return + } + ctx := c.Request.Context() + if path == base && c.Request.Method == "GET" { + page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) + size, _ := strconv.Atoi(c.DefaultQuery("page_size", "20")) + if page < 1 { + page = 1 + } + if size < 1 || size > 100 { + size = 20 + } + accounts, total, err := api.ScopedAdminList(ctx, pagination.PaginationParams{Page: page, PageSize: size}, c.Query("platform"), c.Query("type"), c.Query("status"), c.Query("search")) + if err != nil { + response.Error(c, 503, "账户查询失败") + return + } + items := make([]gin.H, 0, len(accounts)) + for i := range accounts { + if principal.Policy.AllowsAccount("accounts.read", adminaccess.Account{ID: accounts[i].ID, GroupIDs: accounts[i].GroupIDs, Type: accounts[i].Type, Platform: accounts[i].Platform}) { + items = append(items, scopedAdminAccountDTO(&accounts[i], principal.Policy)) + } + } + response.Success(c, gin.H{"items": items, "total": total, "page": page, "page_size": size}) + return + } + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + if (path == base+"/:id" || path == base+"/:id/models") && c.Request.Method == "GET" { + a, err := h.adminService.GetAccount(ctx, id) + if err != nil || a == nil || !principal.Policy.AllowsAccount("accounts.read", adminaccess.Account{ID: id, GroupIDs: accountGroupIDs(a), Type: accountType(a), Platform: accountPlatform(a)}) { + response.Error(c, 404, "账户不存在") + return + } + if path == base+"/:id/models" { + h.respondAvailableModels(c, a) + return + } + response.Success(c, scopedAdminAccountDTO(a, principal.Policy)) + return + } + if path == base+"/bulk-update" && c.Request.Method == "POST" { + h.scopedAdminBulkUpdate(c, api) + return + } + + fields := map[string]json.RawMessage{} + action := "" + var run func(context.Context, *service.Account) (*service.Account, error) + switch { + case path == base && c.Request.Method == "POST": + id = 0 + if c.ShouldBindJSON(&fields) != nil || fields == nil { + response.Error(c, 400, "请求格式无效") + return + } + case path == base+"/:id" && c.Request.Method == "PUT": + if c.ShouldBindJSON(&fields) != nil || len(fields) == 0 { + response.Error(c, 400, "请求格式无效") + return + } + case path == base+"/:id" && c.Request.Method == "DELETE": + action = "accounts.delete" + case path == base+"/:id/schedulable" && c.Request.Method == "POST": + if c.ShouldBindJSON(&fields) != nil || len(fields) != 1 || fields["schedulable"] == nil { + response.Error(c, 400, "仅支持 schedulable 字段") + return + } + case path == base+"/:id/clear-error" && c.Request.Method == "POST": + action = "accounts.recover" + case path == base+"/:id/refresh" && c.Request.Method == "POST": + action = "accounts.refresh" + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, 60*time.Second) + defer cancel() + a, err := h.adminService.GetAccount(ctx, id) + if err != nil || a == nil || !principal.Policy.AllowsAccount(action, adminaccess.Account{ID: id, GroupIDs: accountGroupIDs(a), Type: accountType(a), Platform: accountPlatform(a)}) { + response.Error(c, 404, "账户不存在") + return + } + + run = func(txctx context.Context, a *service.Account) (*service.Account, error) { + updated, _, err := h.refreshSingleAccount(txctx, a) + if err != nil { + code := infraerrors.Code(err) + if code != 400 && code != 403 && code != 404 && code != 409 && code != 503 { + return nil, infraerrors.New(502, "SCOPED_REFRESH_FAILED", "上游刷新失败") + } + } + return updated, err + } + default: + response.Error(c, 403, "此账户操作未开放给受限管理密钥") + return + } + if id <= 0 && path != base { + response.Error(c, 400, "账户 ID 无效") + return + } + a, err := api.ScopedAdminWrite(ctx, id, action, fields, run) + if err != nil { + scopedAdminAccountError(c, err) + return + } + if id > 0 && fields["credentials"] != nil { + h.invalidateScopedAccountToken(ctx, a) + } + response.Success(c, gin.H{"id": a.ID, "status": a.Status}) +} +func accountGroupIDs(a *service.Account) []int64 { + if a == nil { + return nil + } + return a.GroupIDs +} +func accountType(a *service.Account) string { + if a == nil { + return "" + } + return a.Type +} +func accountPlatform(a *service.Account) string { + if a == nil { + return "" + } + return a.Platform +} + +func scopedAdminAccountError(c *gin.Context, err error) { + code, message := scopedAdminAccountErrorDetails(err) + response.Error(c, code, message) +} + +func scopedAdminAccountErrorDetails(err error) (int, string) { + code := infraerrors.Code(err) + message := "账户服务暂不可用" + switch code { + case 400: + message = "请求参数无效" + case 403: + message = "操作未授权" + case 404: + message = "账户不存在" + case 409: + message = "账户正在处理,请稍后重试" + case 502: + message = "上游刷新失败" + default: + code = 503 + } + return code, message +} + +// scopedAdminBulkUpdate 沿用旧批量接口与结果结构,每个账户仍走锁内逐字段验权。 +func (h *AccountHandler) scopedAdminBulkUpdate(c *gin.Context, api service.ScopedAdminAccounts) { + var fields map[string]json.RawMessage + if c.ShouldBindJSON(&fields) != nil || fields == nil { + response.Error(c, 400, "请求格式无效") + return + } + var ids []int64 + if json.Unmarshal(fields["account_ids"], &ids) != nil || len(ids) == 0 || len(ids) > 100 { + response.Error(c, 400, "请明确指定 1 至 100 个账户 ID") + return + } + delete(fields, "account_ids") + // 不把全站筛选条件传给原批量服务,以免绕开账户范围。 + if _, exists := fields["filters"]; exists || len(fields) == 0 { + response.Error(c, 400, "受限批量更新须明确指定账户及修改字段") + return + } + uniqueIDs := make([]int64, 0, len(ids)) + for _, id := range ids { + if id <= 0 { + response.Error(c, 400, "账户 ID 无效") + return + } + if !slices.Contains(uniqueIDs, id) { + uniqueIDs = append(uniqueIDs, id) + } + } + result := service.BulkUpdateAccountsResult{SuccessIDs: []int64{}, FailedIDs: []int64{}, Results: []service.BulkUpdateAccountResult{}} + for _, id := range uniqueIDs { + account, err := api.ScopedAdminWrite(c.Request.Context(), id, "", fields, nil) + item := service.BulkUpdateAccountResult{AccountID: id, Success: err == nil} + if err != nil { + _, item.Error = scopedAdminAccountErrorDetails(err) + result.Failed++ + result.FailedIDs = append(result.FailedIDs, id) + } else { + if fields["credentials"] != nil { + h.invalidateScopedAccountToken(c.Request.Context(), account) + } + result.Success++ + result.SuccessIDs = append(result.SuccessIDs, id) + } + result.Results = append(result.Results, item) + } + response.Success(c, result) +} + +// 凭证写入必须在数据库提交成功后清理令牌缓存,回滚不能发布旧状态。 +func (h *AccountHandler) invalidateScopedAccountToken(ctx context.Context, account *service.Account) { + if h.tokenCacheInvalidator == nil || account == nil { + return + } + service.AfterAccountCommit(ctx, func(committed context.Context) { + _ = h.tokenCacheInvalidator.InvalidateToken(committed, account) + }) +} diff --git a/backend/internal/handler/admin/custom_admin_key_accounts_test.go b/backend/internal/handler/admin/custom_admin_key_accounts_test.go new file mode 100644 index 0000000000..08be6e6d31 --- /dev/null +++ b/backend/internal/handler/admin/custom_admin_key_accounts_test.go @@ -0,0 +1,150 @@ +//go:build unit + +package admin + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestScopedAdminAccountDTORedactsSecretsAndForeignGroups(t *testing.T) { + p := adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}}}} + a := &service.Account{ID: 9, Type: "oauth", GroupIDs: []int64{1, 2}, Credentials: map[string]any{"access_token": "TOP_SECRET", "refresh_token": "REFRESH_SECRET", "base_url": "URL_SECRET", "model_mapping": map[string]any{"alias": "target", "invalid": map[string]any{"token": "NESTED_SECRET"}}}, Extra: map[string]any{"private": "EXTRA_SECRET"}} + body, _ := json.Marshal(scopedAdminAccountDTO(a, p)) + s := string(body) + if strings.Contains(s, "SECRET") || strings.Contains(s, "extra") { + t.Fatalf("泄漏敏感字段: %s", s) + } + require.Contains(t, s, `"credentials":{"model_mapping":{"alias":"target"}}`) + if !strings.Contains(s, `"group_ids":[1]`) { + t.Fatalf("泄漏越权组: %s", s) + } +} + +func TestScopedAdminAccountErrorsAreClassifiedAndRedacted(t *testing.T) { + for _, code := range []int{400, 403, 404, 409, 502, 503, 500} { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + scopedAdminAccountError(c, infraerrors.New(code, "secret", "TOP_SECRET")) + want := code + if code == 500 { + want = 503 + } + if w.Code != want || strings.Contains(w.Body.String(), "TOP_SECRET") { + t.Fatalf("code=%d body=%s", w.Code, w.Body.String()) + } + } + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + scopedAdminAccountError(c, errors.New("TOP_SECRET")) + if w.Code != 503 || strings.Contains(w.Body.String(), "TOP_SECRET") { + t.Fatal(w.Body.String()) + } +} +func TestScopedAdminAccountMiddlewareKeepsJWTAndDeniesUnavailableService(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, restricted := range []bool{false, true} { + r := gin.New() + h := &AccountHandler{} + r.Use(func(c *gin.Context) { + if restricted { + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{})) + } + }) + r.Use(h.ScopedAdminKeyAccounts) + r.GET("/api/v1/admin/accounts", func(c *gin.Context) { c.Status(204) }) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts", nil)) + want := 204 + if restricted { + want = 503 + } + if w.Code != want { + t.Fatalf("restricted=%v status=%d", restricted, w.Code) + } + } +} + +// 批量入口必须使用受限服务,不得回落到嵌入的全权 BulkUpdateAccounts。 +type scopedBulkAccountService struct { + service.AdminService + calls []int64 + fields map[string]json.RawMessage +} + +func (s *scopedBulkAccountService) ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string) ([]service.Account, int64, error) { + panic("不应读取全站账户") +} +func (s *scopedBulkAccountService) ScopedAdminWrite(_ context.Context, id int64, _ string, fields map[string]json.RawMessage, _ func(context.Context, *service.Account) (*service.Account, error)) (*service.Account, error) { + s.calls = append(s.calls, id) + s.fields = fields + switch id { + case 2: + return nil, infraerrors.NotFound("SECRET", "TOP_SECRET") + case 3: + return nil, infraerrors.Forbidden("SECRET", "TOP_SECRET") + case 4: + return nil, errors.New("TOP_SECRET") + } + return &service.Account{ID: id}, nil +} + +func TestScopedAdminBulkUpdateValidatesTargetsAndRedactsResults(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, tc := range []struct { + body string + status int + ids []int64 + }{ + {`{"account_ids":[1,2,1,3,4],"credentials":{"model_mapping":{"alias":"target"}}}`, 200, []int64{1, 2, 3, 4}}, + {`null`, 400, nil}, + {`{"credentials":{"model_mapping":{}}}`, 400, nil}, + {`{"account_ids":[],"credentials":{"model_mapping":{}}}`, 400, nil}, + {`{"account_ids":[1,0],"credentials":{"model_mapping":{}}}`, 400, nil}, + {`{"account_ids":[1,-1],"credentials":{"model_mapping":{}}}`, 400, nil}, + {`{"account_ids":[1]}`, 400, nil}, + {`{"account_ids":[1],"filters":{},"credentials":{"model_mapping":{}}}`, 400, nil}, + {`{"account_ids":[1.5],"credentials":{"model_mapping":{}}}`, 400, nil}, + {`{"account_ids":[` + strings.Repeat("1,", 100) + `1],"credentials":{"model_mapping":{}}}`, 400, nil}, + } { + t.Run(tc.body, func(t *testing.T) { + svc := &scopedBulkAccountService{} + h := &AccountHandler{adminService: svc} + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest("POST", "/api/v1/admin/accounts/bulk-update", strings.NewReader(tc.body)) + h.scopedAdminBulkUpdate(c, svc) + require.Equal(t, tc.status, w.Code, w.Body.String()) + require.Equal(t, tc.ids, svc.calls) + require.NotContains(t, w.Body.String(), "SECRET") + if tc.status == 200 { + body, err := json.Marshal(svc.fields) + require.NoError(t, err) + require.JSONEq(t, `{"credentials":{"model_mapping":{"alias":"target"}}}`, string(body)) + var result struct { + Data service.BulkUpdateAccountsResult `json:"data"` + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result)) + require.Equal(t, 1, result.Data.Success) + require.Equal(t, 3, result.Data.Failed) + require.Equal(t, []int64{1}, result.Data.SuccessIDs) + require.Equal(t, []int64{2, 3, 4}, result.Data.FailedIDs) + require.Equal(t, "账户不存在", result.Data.Results[1].Error) + require.Equal(t, "操作未授权", result.Data.Results[2].Error) + require.Equal(t, "账户服务暂不可用", result.Data.Results[3].Error) + } + }) + } +} diff --git a/backend/internal/handler/admin/custom_admin_key_codex_import.go b/backend/internal/handler/admin/custom_admin_key_codex_import.go new file mode 100644 index 0000000000..a7c49b5683 --- /dev/null +++ b/backend/internal/handler/admin/custom_admin_key_codex_import.go @@ -0,0 +1,189 @@ +package admin + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/pkg/response" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" +) + +type scopedCodexSessionImportRequest struct { + CodexSessionImportRequest + ProxyMode string `json:"proxy_mode"` + RandomProxy bool `json:"random_proxy"` +} + +func validateScopedCodexRequest(req scopedCodexSessionImportRequest) error { + if _, err := service.NormalizeAccountProxyMode(req.ProxyMode, req.ProxyID, req.RandomProxy); err != nil { + return err + } + if req.GroupIDs == nil || (req.ConfirmMixedChannelRisk != nil && *req.ConfirmMixedChannelRisk) { + return infraerrors.BadRequest("SCOPED_CODEX_INPUT", "须明确提供 group_ids,不能跳过分组风险检查") + } + if (req.Concurrency != nil && *req.Concurrency < 0) || (req.Priority != nil && *req.Priority < 0) || (req.LoadFactor != nil && (*req.LoadFactor < 1 || *req.LoadFactor > 10000)) || (req.RateMultiplier != nil && *req.RateMultiplier < 0) { + return infraerrors.BadRequest("SCOPED_CODEX_INPUT", "导入参数无效") + } + for key := range req.CredentialExtras { + if key != "base_url" && key != "model_mapping" { + return infraerrors.BadRequest("SCOPED_CODEX_FIELD", "credential_extras 仅支持独立授权的 base_url 和 model_mapping") + } + } + for key, value := range req.Extra { + valid := false + switch key { + case "codex_fingerprint_mode", "openai_oauth_responses_websockets_v2_mode": + _, valid = value.(string) + case "openai_oauth_responses_websockets_v2_enabled": + _, valid = value.(bool) + } + if !valid { + return infraerrors.BadRequest("SCOPED_CODEX_FIELD", "extra 包含不支持的字段或值类型") + } + } + return nil +} + +func (h *AccountHandler) scopedAdminImportCodexSession(c *gin.Context) { + var req scopedCodexSessionImportRequest + if c.ShouldBindJSON(&req) != nil { + response.BadRequest(c, "导入请求格式无效") + return + } + if err := validateScopedCodexRequest(req); err != nil { + response.ErrorFrom(c, err) + return + } + entries, err := parseCodexSessionImportEntries(req.CodexSessionImportRequest) + if err != nil || len(entries) == 0 { + response.BadRequest(c, "请输入有效的 accessToken 或 Codex session JSON") + return + } + api, ok := h.adminService.(service.ScopedAdminCodexAccounts) + if !ok { + response.Error(c, 503, "受限导入服务不可用") + return + } + principal := adminaccess.FromContext(c.Request.Context()) + if principal == nil || !adminaccess.RouteAllowed(principal.Policy, c.Request.Method, c.FullPath()) { + response.Error(c, 403, "导入未授权") + return + } + // 隔离完整管理员、不同 Key 和权限修改前后的幂等结果。 + policy, _ := json.Marshal(principal.Policy) + digest := sha256.Sum256(policy) + scope := "scoped.codex:" + principal.KeyID + ":" + hex.EncodeToString(digest[:]) + executeAdminIdempotentJSON(c, scope, req, service.DefaultWriteIdempotencyTTL(), func(ctx context.Context) (any, error) { + result, err := h.importScopedCodexSessions(ctx, api, req, entries) + if err != nil { + code, message := scopedAdminAccountErrorDetails(err) + return nil, infraerrors.New(code, "SCOPED_CODEX_FAILED", message) + } + return result, nil + }) +} + +func (h *AccountHandler) importScopedCodexSessions(ctx context.Context, api service.ScopedAdminCodexAccounts, req scopedCodexSessionImportRequest, entries []codexImportEntry) (CodexSessionImportResult, error) { + proxyMode, err := service.NormalizeAccountProxyMode(req.ProxyMode, req.ProxyID, req.RandomProxy) + if err != nil { + return CodexSessionImportResult{}, err + } + result := CodexSessionImportResult{Total: len(entries), Items: make([]CodexSessionImportItem, 0, len(entries))} + updateExisting := req.UpdateExisting == nil || *req.UpdateExisting + seen := map[string]codexSeenIdentity{} + fail := func(entry int, err error) { + _, message := scopedAdminAccountErrorDetails(err) + result.Failed++ + result.Items = append(result.Items, CodexSessionImportItem{Index: entry, Action: "failed", Message: message}) + result.Errors = append(result.Errors, CodexSessionImportMessage{Index: entry, Message: message}) + } + for _, entry := range entries { + item, err := normalizeCodexImportEntry(entry) + if err != nil { + fail(entry.Index, infraerrors.BadRequest("SCOPED_CODEX_PARSE", "认证内容无效")) + continue + } + expires, credentialExpiry, autoPause, warnings, err := resolveCodexImportExpiry(req.CodexSessionImportRequest, item) + if err != nil { + fail(entry.Index, infraerrors.BadRequest("SCOPED_CODEX_EXPIRY", "认证有效期无效")) + continue + } + if credentialExpiry != nil { + item.Credentials["expires_at"] = credentialExpiry.Format(time.RFC3339) + } + if _, duplicate := firstSeenCodexIdentity(seen, item.IdentityKeys, item.UserID); duplicate { + result.Skipped++ + result.Items = append(result.Items, CodexSessionImportItem{Index: entry.Index, Action: "skipped", Message: "同批次重复导入项"}) + continue + } + markCodexIdentitySeen(seen, item.IdentityKeys, entry.Index, item.UserID) + credentials := mergeCodexImportMap(item.Credentials, req.CredentialExtras) + extra := mergeCodexImportMap(req.Extra, item.Extra) + name := buildCodexCreateAccountName(req.Name, item, entry.Index, len(entries)) + var account *service.Account + action := "created" + var existing *service.Account + if updateExisting { + candidates, lookupErr := api.ScopedAdminCodexCandidates(ctx, service.ScopedCodexIdentity{ + AccountID: item.AccountID, UserID: item.UserID, Email: item.Email, AccessToken: item.AccessToken, + AccessTokenOnly: item.RefreshToken == "" && item.AccessToken != "", AgentIdentity: item.IsAgentIdentity, + }) + if lookupErr != nil { + return result, lookupErr + } + existing, _ = buildCodexAccountIndex(candidates).Find(item.IdentityKeys, item.UserID) + } + if updateExisting && existing != nil { + action = "updated" + input := &service.UpdateAccountInput{ProxyMode: proxyMode, Credentials: credentials, Extra: extra, ProxyID: req.ProxyID, Concurrency: req.Concurrency, Priority: req.Priority, RateMultiplier: req.RateMultiplier, LoadFactor: req.LoadFactor, ExpiresAt: expires, AutoPauseOnExpired: autoPause} + if len(req.GroupIDs) > 0 { + input.GroupIDs = &req.GroupIDs + } + account, err = api.ScopedAdminUpdateCodex(ctx, existing.ID, input, func(current *service.Account, safe *service.UpdateAccountInput) error { + // 锁内重新匹配,不能将候选快照匹配结果应用到已被其他操作换绑的身份。 + fresh := buildCodexAccountIndex([]service.Account{*current}) + if matched, _ := fresh.Find(item.IdentityKeys, item.UserID); matched == nil { + return infraerrors.Conflict("SCOPED_CODEX_CHANGED", "账户身份已变更") + } + safe.Credentials = mergeCodexImportCredentials(current.Credentials, credentials, item) + safe.Extra = mergeCodexImportMap(current.Extra, extra) + if item.RefreshToken == "" && codexCredentialString(current.Credentials, "refresh_token") != "" { + safe.ExpiresAt = nil + safe.AutoPauseOnExpired = nil + } + return nil + }) + } else { + concurrency, priority := 3, 50 + if req.Concurrency != nil { + concurrency = *req.Concurrency + } + if req.Priority != nil { + priority = *req.Priority + } + account, err = api.ScopedAdminCreateCodex(ctx, &service.CreateAccountInput{ProxyMode: proxyMode, Name: name, Notes: req.Notes, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Credentials: credentials, Extra: extra, GroupIDs: req.GroupIDs, ProxyID: req.ProxyID, Concurrency: concurrency, Priority: priority, RateMultiplier: req.RateMultiplier, LoadFactor: req.LoadFactor, ExpiresAt: expires, AutoPauseOnExpired: autoPause, SkipDefaultGroupBind: true}) + } + if err != nil { + fail(entry.Index, err) + continue + } + if action == "updated" { + result.Updated++ + h.invalidateScopedAccountToken(ctx, account) + } else { + result.Created++ + } + // 不返回候选名称或任何已有凭证,仅返回本次操作结果。 + result.Items = append(result.Items, CodexSessionImportItem{Index: entry.Index, Action: action, AccountID: account.ID}) + for _, warning := range append(item.WarningTexts, warnings...) { + result.Warnings = append(result.Warnings, CodexSessionImportMessage{Index: entry.Index, Message: warning}) + } + } + return result, nil +} diff --git a/backend/internal/handler/admin/custom_admin_key_codex_import_test.go b/backend/internal/handler/admin/custom_admin_key_codex_import_test.go new file mode 100644 index 0000000000..614bda23f3 --- /dev/null +++ b/backend/internal/handler/admin/custom_admin_key_codex_import_test.go @@ -0,0 +1,249 @@ +package admin + +import ( + "context" + "encoding/json" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type scopedCodexMemoryService struct { + *codexImportMemoryAdminService + fresh *service.Account + err error + lookups []service.ScopedCodexIdentity +} + +func (s *scopedCodexMemoryService) ScopedAdminCodexCandidates(_ context.Context, identity service.ScopedCodexIdentity) ([]service.Account, error) { + s.lookups = append(s.lookups, identity) + return s.accounts, nil +} +func (s *scopedCodexMemoryService) ScopedAdminCreateCodex(ctx context.Context, input *service.CreateAccountInput) (*service.Account, error) { + if s.err != nil { + return nil, s.err + } + return s.CreateAccount(ctx, input) +} +func (s *scopedCodexMemoryService) ScopedAdminUpdateCodex(ctx context.Context, id int64, input *service.UpdateAccountInput, prepare func(*service.Account, *service.UpdateAccountInput) error) (*service.Account, error) { + current := s.fresh + if current == nil { + var err error + current, err = s.GetAccount(ctx, id) + if err != nil { + return nil, err + } + } + if err := prepare(current, input); err != nil { + return nil, err + } + return s.UpdateAccount(ctx, id, input) +} + +func TestScopedCodexImportCapturedRequestAndSafeResponse(t *testing.T) { + gin.SetMode(gin.TestMode) + memory := &scopedCodexMemoryService{codexImportMemoryAdminService: newCodexImportMemoryAdminService(nil)} + h := &AccountHandler{adminService: memory} + ctx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{KeyID: "fixture", Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.create", "accounts.credentials", "accounts.schedule", "accounts.network"}, AllGroups: true, AccountTypes: []string{"oauth"}}}}}) + r := gin.New() + r.Use(func(c *gin.Context) { c.Request = c.Request.WithContext(ctx) }) + r.Use(h.ScopedAdminKeyAccounts) + r.POST("/api/v1/admin/accounts/import/codex-session", func(c *gin.Context) { t.Fatal("不能回退到完整管理员导入") }) + content := `{"access_token":"private-access-fixture","refresh_token":"private-refresh-fixture","email":"test@example.com"}` + req := map[string]any{"content": content, "name": "推送账户", "notes": "测试", "group_ids": []int64{2, 14}, "concurrency": 40, "priority": 0, "expires_at": nil, "auto_pause_on_expired": true, "proxy_id": nil, "rate_multiplier": 1, "update_existing": true, "extra": map[string]any{"codex_fingerprint_mode": "off", "openai_oauth_responses_websockets_v2_enabled": true, "openai_oauth_responses_websockets_v2_mode": "shared"}} + raw, err := json.Marshal(req) + require.NoError(t, err) + call := func() *httptest.ResponseRecorder { + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("POST", "/api/v1/admin/accounts/import/codex-session", strings.NewReader(string(raw)))) + return w + } + w := call() + require.Equal(t, 200, w.Code, w.Body.String()) + require.Contains(t, w.Body.String(), `"created":1`) + require.NotContains(t, w.Body.String(), "private-") + require.Len(t, memory.createdAccounts, 1) + input := memory.createdAccounts[0] + require.Equal(t, []int64{2, 14}, input.GroupIDs) + require.Equal(t, 40, input.Concurrency) + require.True(t, input.SkipDefaultGroupBind) + require.Equal(t, "private-refresh-fixture", input.Credentials["refresh_token"]) + require.Equal(t, "off", input.Extra["codex_fingerprint_mode"]) + memory.err = infraerrors.BadRequest("UPSTREAM_SECRET", "private-refresh-fixture") + // update_existing=false 沿用原接口语义:新建;错误也必须脱敏。 + req["update_existing"] = false + raw, err = json.Marshal(req) + require.NoError(t, err) + w = call() + require.Equal(t, 200, w.Code) + require.Contains(t, w.Body.String(), `"failed":1`) + require.NotContains(t, w.Body.String(), "private-") +} + +func TestScopedCodexImportRevalidatesIdentityAndMergesFreshCredentials(t *testing.T) { + token := buildCodexAccessToken(t, "account", "user", time.Now().Add(time.Hour)) + stale := service.Account{ID: 1, Credentials: map[string]any{"access_token": token, "refresh_token": "stale"}, Extra: map[string]any{"quota_used": 1}} + fresh := stale + fresh.Credentials = map[string]any{"access_token": token, "refresh_token": "latest", "base_url": "https://example.com"} + fresh.Extra = map[string]any{"quota_used": 9} + for _, changed := range []bool{false, true} { + t.Run(map[bool]string{false: "锁内合并", true: "身份已更换"}[changed], func(t *testing.T) { + current := fresh + if changed { + current.Credentials = map[string]any{"access_token": "different", "refresh_token": "other"} + } + memory := &scopedCodexMemoryService{codexImportMemoryAdminService: newCodexImportMemoryAdminService([]service.Account{stale}), fresh: ¤t} + h := &AccountHandler{adminService: memory} + req := scopedCodexSessionImportRequest{CodexSessionImportRequest: CodexSessionImportRequest{Content: token, GroupIDs: []int64{1}}} + entries, err := parseCodexSessionImportEntries(req.CodexSessionImportRequest) + require.NoError(t, err) + result, err := h.importScopedCodexSessions(context.Background(), memory, req, entries) + require.NoError(t, err) + if changed { + require.Equal(t, 1, result.Failed) + require.Empty(t, memory.updatedAccounts) + return + } + require.Equal(t, 1, result.Updated) + require.Len(t, memory.updatedAccounts, 1) + input := memory.updatedAccounts[0].input + require.Equal(t, "latest", input.Credentials["refresh_token"]) + require.Equal(t, "https://example.com", input.Credentials["base_url"]) + require.Equal(t, 9, input.Extra["quota_used"]) + require.Nil(t, input.ExpiresAt) + require.Nil(t, input.AutoPauseOnExpired) + }) + } +} + +func TestScopedCodexRequestRejectsUnopenedFields(t *testing.T) { + for _, body := range []string{`{"content":"x"}`, `{"group_ids":[1],"confirm_mixed_channel_risk":true}`, `{"group_ids":[1],"extra":{"quota_used":0}}`, `{"group_ids":[1],"credential_extras":{"refresh_token":"x"}}`, `{"group_ids":[1],"extra":{"openai_oauth_responses_websockets_v2_enabled":"true"}}`} { + var req scopedCodexSessionImportRequest + require.NoError(t, json.Unmarshal([]byte(body), &req)) + require.Error(t, validateScopedCodexRequest(req), body) + } +} + +func TestScopedCodexImportIdempotencySeparatesKeysAndPolicy(t *testing.T) { + gin.SetMode(gin.TestMode) + previous := service.DefaultIdempotencyCoordinator() + t.Cleanup(func() { service.SetDefaultIdempotencyCoordinator(previous) }) + repo := newMemoryIdempotencyRepoStub() + service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(repo, service.DefaultIdempotencyConfig())) + memory := &scopedCodexMemoryService{codexImportMemoryAdminService: newCodexImportMemoryAdminService(nil)} + h := &AccountHandler{adminService: memory} + principal := &adminaccess.Principal{KeyID: "aaaaaaaaaaaaaaaaaaaaaaaa", Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.create", "accounts.credentials", "accounts.schedule", "accounts.network"}, GroupIDs: []int64{2}, AccountTypes: []string{"oauth"}}}}} + r := gin.New() + r.Use(func(c *gin.Context) { + if principal != nil { + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), principal)) + } + }) + r.Use(h.ScopedAdminKeyAccounts) + r.POST("/api/v1/admin/accounts/import/codex-session", h.ImportCodexSession) + call := func() *httptest.ResponseRecorder { + req := httptest.NewRequest("POST", "/api/v1/admin/accounts/import/codex-session", strings.NewReader(`{"content":"{\"access_token\":\"fixture-access\",\"refresh_token\":\"fixture-refresh\"}","group_ids":[2],"update_existing":false}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Idempotency-Key", "same-import") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, 200, w.Code, w.Body.String()) + require.NotContains(t, w.Body.String(), "fixture-") + return w + } + first := call() + require.Len(t, memory.createdAccounts, 1) + replay := call() + require.Equal(t, "true", replay.Header().Get("X-Idempotency-Replayed")) + require.JSONEq(t, first.Body.String(), replay.Body.String()) + require.Len(t, memory.createdAccounts, 1) + principal.KeyID = "bbbbbbbbbbbbbbbbbbbbbbbb" + other := call() + require.Empty(t, other.Header().Get("X-Idempotency-Replayed")) + require.Len(t, memory.createdAccounts, 2) + principal.Policy.Rules[0].Permissions = []string{"accounts.create"} + memory.err = infraerrors.Forbidden("SCOPED_CODEX_FORBIDDEN", "权限已收回") + restricted := call() + require.Empty(t, restricted.Header().Get("X-Idempotency-Replayed")) + require.Contains(t, restricted.Body.String(), `"failed":1`) + require.Len(t, memory.createdAccounts, 2) + principal = nil + memory.err = nil + full := call() + require.Empty(t, full.Header().Get("X-Idempotency-Replayed")) + require.Len(t, memory.createdAccounts, 3) + for _, record := range repo.data { + require.LessOrEqual(t, len(record.Scope), 128, "生产数据库 scope 最大长度") + } +} + +func TestScopedCodexImportProxyModeForwarding(t *testing.T) { + for _, tc := range []struct { + body, mode string + id int64 + }{ + {`"proxy_id":7`, "", 7}, {`"proxy_mode":"specified","proxy_id":7`, "specified", 7}, + {`"random_proxy":true`, "random", 0}, {`"proxy_mode":"random"`, "random", 0}, + {`"proxy_mode":"least_used"`, "least_used", 0}, {`"proxy_mode":"direct"`, "direct", 0}, + } { + t.Run(tc.body, func(t *testing.T) { + memory := &scopedCodexMemoryService{codexImportMemoryAdminService: newCodexImportMemoryAdminService(nil)} + h := &AccountHandler{adminService: memory} + var req scopedCodexSessionImportRequest + require.NoError(t, json.Unmarshal([]byte(`{"content":"{\"access_token\":\"fixture\",\"refresh_token\":\"refresh\"}","group_ids":[1],`+tc.body+`}`), &req)) + require.NoError(t, validateScopedCodexRequest(req)) + entries, err := parseCodexSessionImportEntries(req.CodexSessionImportRequest) + require.NoError(t, err) + result, err := h.importScopedCodexSessions(context.Background(), memory, req, entries) + require.NoError(t, err) + require.Equal(t, 1, result.Created) + require.Len(t, memory.createdAccounts, 1) + require.Equal(t, tc.mode, memory.createdAccounts[0].ProxyMode) + if tc.id > 0 { + require.Equal(t, tc.id, *memory.createdAccounts[0].ProxyID) + } + }) + } +} + +func TestScopedCodexImportLooksUpOnlyValidatedEntryIdentity(t *testing.T) { + token := buildCodexAccessToken(t, "workspace", "member", time.Now().Add(time.Hour)) + for _, tc := range []struct { + name string + content string + update bool + wantLookups int + wantSkipped int + onlyAccess bool + }{ + {"有效身份与批内重复", token + "\n" + token, true, 1, 1, true}, + {"无效内容无需读取候选", `{"refresh_token":"fixture"}`, true, 0, 0, false}, + {"禁用更新无需读取候选", token, false, 0, 0, true}, + {"有refresh保留身份匹配", `{"access_token":"` + token + `","refresh_token":"fixture"}`, true, 1, 0, false}, + } { + t.Run(tc.name, func(t *testing.T) { + memory := &scopedCodexMemoryService{codexImportMemoryAdminService: newCodexImportMemoryAdminService(nil)} + req := scopedCodexSessionImportRequest{CodexSessionImportRequest: CodexSessionImportRequest{Content: tc.content, GroupIDs: []int64{1}, UpdateExisting: &tc.update}} + entries, err := parseCodexSessionImportEntries(req.CodexSessionImportRequest) + require.NoError(t, err) + result, err := (&AccountHandler{adminService: memory}).importScopedCodexSessions(context.Background(), memory, req, entries) + require.NoError(t, err) + require.Equal(t, tc.wantSkipped, result.Skipped) + require.Len(t, memory.lookups, tc.wantLookups) + if tc.wantLookups > 0 { + lookup := memory.lookups[0] + require.Equal(t, "workspace", lookup.AccountID) + require.Equal(t, "member", lookup.UserID) + require.Equal(t, token, lookup.AccessToken) + require.Equal(t, tc.onlyAccess, lookup.AccessTokenOnly) + } + }) + } +} diff --git a/backend/internal/handler/admin/custom_admin_key_commit_test.go b/backend/internal/handler/admin/custom_admin_key_commit_test.go new file mode 100644 index 0000000000..ded090ed2d --- /dev/null +++ b/backend/internal/handler/admin/custom_admin_key_commit_test.go @@ -0,0 +1,199 @@ +//go:build unit + +package admin + +import ( + "context" + "encoding/json" + "errors" + "net/http/httptest" + "strings" + "testing" + "time" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + "github.com/DATA-DOG/go-sqlmock" + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type scopedCommitInvalidator struct { + ids []int64 + transactionContexts int +} + +func (s *scopedCommitInvalidator) InvalidateToken(ctx context.Context, account *service.Account) error { + s.ids = append(s.ids, account.ID) + if dbent.TxFromContext(ctx) != nil { + s.transactionContexts++ + } + return nil +} + +type scopedCommitAccounts struct { + service.AdminService + fail bool +} + +func (*scopedCommitAccounts) ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string) ([]service.Account, int64, error) { + panic("不应查询列表") +} +func (s *scopedCommitAccounts) ScopedAdminWrite(_ context.Context, id int64, _ string, _ map[string]json.RawMessage, _ func(context.Context, *service.Account) (*service.Account, error)) (*service.Account, error) { + if s.fail { + return nil, errors.New("模拟写入失败") + } + return &service.Account{ID: id, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth}, nil +} + +func TestScopedAdminCredentialWritesInvalidateAfterCommit(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, endpoint := range []string{"single", "bulk"} { + for _, mode := range []string{"commit", "rollback", "commit_failure", "write_failure", "name_only"} { + t.Run(endpoint+"/"+mode, func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer db.Close() + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + mock.ExpectBegin() + tx, err := client.Tx(context.Background()) + require.NoError(t, err) + ctx := dbent.NewTxContext(context.Background(), tx) + ctx = adminaccess.WithPrincipal(ctx, &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.credentials"}, AllGroups: true}}}}) + cache := &scopedCommitInvalidator{} + h := &AccountHandler{adminService: &scopedCommitAccounts{fail: mode == "write_failure"}, tokenCacheInvalidator: cache} + r := gin.New() + r.Use(func(c *gin.Context) { c.Request = c.Request.WithContext(ctx) }) + r.Use(h.ScopedAdminKeyAccounts) + r.PUT("/api/v1/admin/accounts/:id", func(*gin.Context) { t.Fatal("不得进入完整管理员处理器") }) + r.POST("/api/v1/admin/accounts/bulk-update", func(*gin.Context) { t.Fatal("不得进入完整管理员处理器") }) + method, path, body := "PUT", "/api/v1/admin/accounts/7", `{"credentials":{"access_token":"fixture"}}` + if mode == "name_only" { + body = `{"name":"新名称"}` + } + if endpoint == "bulk" { + method, path = "POST", "/api/v1/admin/accounts/bulk-update" + body = `{"account_ids":[7],` + body[1:] + } + req := httptest.NewRequest(method, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + want := 200 + if mode == "write_failure" && endpoint == "single" { + want = 503 + } + require.Equal(t, want, w.Code, w.Body.String()) + require.Empty(t, cache.ids, "事务提交前不得使令牌缓存失效") + if mode == "rollback" || mode == "write_failure" { + mock.ExpectRollback() + require.NoError(t, tx.Rollback()) + } else if mode == "commit_failure" { + mock.ExpectCommit().WillReturnError(errors.New("提交失败")) + require.Error(t, tx.Commit()) + } else { + mock.ExpectCommit() + require.NoError(t, tx.Commit()) + } + if mode == "commit" { + require.Equal(t, []int64{7}, cache.ids) + } else { + require.Empty(t, cache.ids) + } + require.Zero(t, cache.transactionContexts, "提交后的缓存清理不能携带已关闭事务") + require.NoError(t, mock.ExpectationsWereMet()) + }) + } + } +} + +type scopedRefreshPrivacyService struct { + *stubAdminService + privacy int +} + +func (s *scopedRefreshPrivacyService) EnsureOpenAIPrivacy(context.Context, *service.Account) string { + s.privacy++ + return "" +} +func (s *scopedRefreshPrivacyService) EnsureAntigravityPrivacy(context.Context, *service.Account) string { + s.privacy++ + return "" +} +func TestScopedAdminRefreshFailureDoesNotTriggerPrivacyBeforeRollback(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer db.Close() + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + mock.ExpectBegin() + tx, err := client.Tx(context.Background()) + require.NoError(t, err) + svc := &scopedRefreshPrivacyService{stubAdminService: newStubAdminService()} + h := &AccountHandler{adminService: svc, openaiOAuthService: service.NewOpenAIOAuthService(nil, nil)} + _, _, err = h.refreshSingleAccount(dbent.NewTxContext(context.Background(), tx), &service.Account{ID: 7, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth}) + require.Error(t, err) + require.Zero(t, svc.privacy, "刷新失败导致回滚时,不应提前调用上游隐私接口") + mock.ExpectRollback() + require.NoError(t, tx.Rollback()) + require.Zero(t, svc.privacy) + require.NoError(t, mock.ExpectationsWereMet()) + // 完整管理员没有外层事务,沿用原刷新失败后的隐私检查行为。 + _, _, err = h.refreshSingleAccount(context.Background(), &service.Account{ID: 7, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth}) + require.Error(t, err) + require.Equal(t, 1, svc.privacy) +} + +func TestScopedAdminCodexUpdatesInvalidateOnlyAfterCommit(t *testing.T) { + for _, mode := range []string{"commit", "rollback", "commit_failure", "identity_changed"} { + t.Run(mode, func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer db.Close() + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + mock.ExpectBegin() + tx, err := client.Tx(context.Background()) + require.NoError(t, err) + token := buildCodexAccessToken(t, "account", "user", time.Now().Add(time.Hour)) + existing := service.Account{ID: 7, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Credentials: map[string]any{"access_token": token, "auth_mode": service.OpenAIAuthModePersonalAccessToken}} + memory := &scopedCodexMemoryService{codexImportMemoryAdminService: newCodexImportMemoryAdminService([]service.Account{existing})} + if mode == "identity_changed" { + memory.fresh = &service.Account{ID: 7, Credentials: map[string]any{"access_token": "changed-private"}} + } + cache := &scopedCommitInvalidator{} + h := &AccountHandler{adminService: memory, tokenCacheInvalidator: cache} + req := scopedCodexSessionImportRequest{CodexSessionImportRequest: CodexSessionImportRequest{Content: token, GroupIDs: []int64{1}}} + entries, err := parseCodexSessionImportEntries(req.CodexSessionImportRequest) + require.NoError(t, err) + result, err := h.importScopedCodexSessions(dbent.NewTxContext(context.Background(), tx), memory, req, entries) + require.NoError(t, err) + require.Empty(t, cache.ids) + if mode == "rollback" || mode == "identity_changed" { + mock.ExpectRollback() + require.NoError(t, tx.Rollback()) + } else if mode == "commit_failure" { + mock.ExpectCommit().WillReturnError(errors.New("提交失败")) + require.Error(t, tx.Commit()) + } else { + mock.ExpectCommit() + require.NoError(t, tx.Commit()) + } + if mode == "commit" { + require.Equal(t, []int64{7}, cache.ids) + } else { + require.Empty(t, cache.ids) + } + if mode == "identity_changed" { + require.Equal(t, 1, result.Failed) + } else { + require.Equal(t, 1, result.Updated) + require.Equal(t, service.OpenAIAuthModePersonalAccessToken, memory.updatedAccounts[0].input.Credentials["auth_mode"]) + } + require.Zero(t, cache.transactionContexts) + require.NoError(t, mock.ExpectationsWereMet()) + }) + } +} diff --git a/backend/internal/handler/admin/custom_admin_key_group_models.go b/backend/internal/handler/admin/custom_admin_key_group_models.go new file mode 100644 index 0000000000..7b3b5b18ef --- /dev/null +++ b/backend/internal/handler/admin/custom_admin_key_group_models.go @@ -0,0 +1,167 @@ +package admin + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "slices" + "strconv" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/handler/dto" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/Wei-Shaw/sub2api/internal/pkg/response" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" +) + +func scopedAdminGroupModelsDTO(g *service.Group) gin.H { + return gin.H{"id": g.ID, "name": g.Name, "platform": g.Platform, "model_allowlist": g.ModelAllowlist} +} + +// ScopedAdminKeyGroupModels 接管分组模型接口,禁止复用可修改费率等字段的完整处理器。 +func (h *GroupHandler) ScopedAdminKeyGroupModels(c *gin.Context) { + p := adminaccess.FromContext(c.Request.Context()) + if p == nil { + return + } + base := "/api/v1/admin/groups/:id" + path := c.FullPath() + fullRead := slices.Contains(p.Policy.GlobalPermissions, "groups.read") + if c.Request.Method == http.MethodGet && (path == "/api/v1/admin/groups" || path == "/api/v1/admin/groups/all") { + if fullRead { + return + } + c.Abort() + h.scopedAdminListGroupModels(c) + return + } + // 完整分组读取继续沿用原处理器的简易模式响应。 + if fullRead && path == base && c.Request.Method == http.MethodGet && h.isSimpleMode() { + return + } + candidates := path == base+"/model-allowlist-candidates" + if !candidates && path != base { + return + } + c.Abort() + if h.rejectUnsupportedSimpleModeOperation(c, "advanced") { + return + } + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil || id < 0 || (id == 0 && !candidates) { + response.BadRequest(c, "分组 ID 无效") + return + } + if candidates && c.Request.Method == http.MethodGet && id == 0 { + if !slices.Contains(p.Policy.GlobalPermissions, "models.defaults.read") { + response.Error(c, 403, "默认模型读取未授权") + return + } + h.GetGroupModelAllowlistCandidates(c) + return + } + g, err := h.adminService.GetGroup(c.Request.Context(), id) + if err != nil || g == nil { + response.Error(c, 404, "分组不存在") + return + } + permission := "groups.models.read" + if c.Request.Method == http.MethodPut { + permission = "groups.models.write" + } + allowed := p.Policy.AllowsGroupConfig(permission, g.ID, g.Platform) || (c.Request.Method == http.MethodGet && fullRead) + if !allowed { + response.Error(c, 404, "分组不存在") + return + } + if c.Request.Method == http.MethodGet { + if candidates { + if platform := strings.TrimSpace(c.Query("platform")); platform != "" && platform != g.Platform { + response.BadRequest(c, "候选模型平台必须与分组一致") + return + } + h.GetGroupModelAllowlistCandidates(c) + return + } + if fullRead { + response.Success(c, dto.GroupFromServiceAdmin(g)) + } else { + response.Success(c, scopedAdminGroupModelsDTO(g)) + } + return + } + if c.Request.Method != http.MethodPut || candidates { + response.Error(c, 403, "此分组操作未开放给受限管理密钥") + return + } + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 65536) + var fields map[string]json.RawMessage + if c.ShouldBindJSON(&fields) != nil || len(fields) != 1 { + response.BadRequest(c, "仅支持单独提交 model_allowlist") + return + } + raw := fields["model_allowlist"] + var cfg *service.GroupModelAllowlist + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.DisallowUnknownFields() + if decoder.Decode(&cfg) != nil || cfg == nil { + response.BadRequest(c, "模型白名单格式无效") + return + } + api, ok := h.adminService.(interface { + ScopedAdminUpdateGroupModels(context.Context, int64, service.GroupModelAllowlist) (*service.Group, error) + }) + if !ok { + response.Error(c, 503, "受限分组模型服务不可用") + return + } + updated, err := api.ScopedAdminUpdateGroupModels(c.Request.Context(), id, *cfg) + if err != nil { + response.ErrorFrom(c, err) + return + } + response.Success(c, scopedAdminGroupModelsDTO(updated)) +} + +func (h *GroupHandler) scopedAdminListGroupModels(c *gin.Context) { + if h.rejectUnsupportedSimpleModeOperation(c, "advanced") { + return + } + api, ok := h.adminService.(interface { + ScopedAdminListGroupModels(context.Context, pagination.PaginationParams, bool, string, string, string) ([]service.Group, int64, error) + }) + if !ok { + response.Error(c, 503, "受限分组模型服务不可用") + return + } + page, size := response.ParsePagination(c) + all := strings.HasSuffix(c.FullPath(), "/all") + status := c.Query("status") + if all { + status = service.StatusActive + if c.Query("include_inactive") == "true" { + status = "" + } + } + search := strings.TrimSpace(c.Query("search")) + if len(search) > 100 { + search = search[:100] + } + groups, total, err := api.ScopedAdminListGroupModels(c.Request.Context(), pagination.PaginationParams{Page: page, PageSize: size}, all, c.Query("platform"), status, search) + if err != nil { + response.ErrorFrom(c, err) + return + } + out := make([]gin.H, 0, len(groups)) + for i := range groups { + out = append(out, scopedAdminGroupModelsDTO(&groups[i])) + } + if all { + response.Success(c, out) + } else { + response.Paginated(c, out, total, page, size) + } +} diff --git a/backend/internal/handler/admin/custom_admin_key_proxies.go b/backend/internal/handler/admin/custom_admin_key_proxies.go new file mode 100644 index 0000000000..970c5b29f7 --- /dev/null +++ b/backend/internal/handler/admin/custom_admin_key_proxies.go @@ -0,0 +1,163 @@ +package admin + +import ( + "context" + "fmt" + "slices" + "strconv" + "strings" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/pkg/response" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" +) + +// scopedProxyOption 显式列出可公开字段,不能复用含用户名、密码的管理 DTO。 +type scopedProxyOption struct { + ID int64 `json:"id"` + Name string `json:"name"` + Protocol string `json:"protocol"` + Host string `json:"host"` + Port int `json:"port"` + Status string `json:"status"` + ExpiresAt *time.Time `json:"expires_at"` +} + +func scopedProxyDTO(p service.Proxy) scopedProxyOption { + return scopedProxyOption{ID: p.ID, Name: p.Name, Protocol: p.Protocol, Host: p.Host, Port: p.Port, Status: p.Status, ExpiresAt: p.ExpiresAt} +} + +// scopedAdminProxyRead 对代理读取限定数量;无分页的 /all 从全池抽样。 +func (h *ProxyHandler) scopedAdminProxyRead(c *gin.Context) bool { + principal := adminaccess.FromContext(c.Request.Context()) + if principal == nil { + return false + } + if !slices.Contains(principal.Policy.GlobalPermissions, "proxies.read") { + response.Error(c, 403, "代理读取未授权") + return true + } + if raw := c.Param("id"); raw != "" { + id, err := strconv.ParseInt(raw, 10, 64) + if err != nil || id < 1 { + response.BadRequest(c, "代理 ID 无效") + return true + } + p, err := h.adminService.GetProxy(c.Request.Context(), id) + if err != nil || p == nil { + response.Error(c, 404, "代理不存在") + return true + } + response.Success(c, scopedProxyDTO(*p)) + return true + } + page, size := 1, 50 + for key, dest := range map[string]*int{"page": &page, "page_size": &size} { + if raw, ok := c.GetQuery(key); ok { + n, err := strconv.Atoi(raw) + if err != nil || n < 1 || n > 1000000 { + response.BadRequest(c, "分页参数必须为正整数且不超过 1000000") + return true + } + *dest = n + } + } + if size > 100 { + size = 100 + } + var proxies []service.Proxy + var total int64 + var err error + if raw, ok := c.Request.URL.Query()["ids"]; ok { + ids := []int64{} + for _, part := range strings.Split(strings.Join(raw, ","), ",") { + if strings.TrimSpace(part) == "" { + continue + } + id, e := strconv.ParseInt(strings.TrimSpace(part), 10, 64) + if e != nil || id < 1 { + response.BadRequest(c, "代理 ID 无效") + return true + } + if !slices.Contains(ids, id) { + ids = append(ids, id) + } + if len(ids) > 100 { + response.BadRequest(c, "一次最多读取 100 个已选代理") + return true + } + } + if len(ids) > 0 { + proxies, err = h.adminService.GetProxiesByIDs(c.Request.Context(), ids) + } + // 最多 100 个 ID 的回显按实际存在的记录分页,保留请求顺序。 + byID := make(map[int64]service.Proxy, len(proxies)) + for _, p := range proxies { + byID[p.ID] = p + } + proxies = nil + for _, id := range ids { + if p, ok := byID[id]; ok { + proxies = append(proxies, p) + } + } + total = int64(len(proxies)) + start := (page - 1) * size + if start < len(proxies) { + proxies = proxies[start:min(start+size, len(proxies))] + } else { + proxies = nil + } + } else { + search := strings.TrimSpace(c.Query("search")) + if len(search) > 100 { + response.BadRequest(c, "搜索关键词不能超过 100 字节") + return true + } + query := c.Request.URL.Query() + if strings.HasSuffix(c.FullPath(), "/proxies/all") && !query.Has("page") && !query.Has("page_size") { + sampler, ok := h.adminService.(interface { + SampleProxyOptions(context.Context, string) ([]service.Proxy, int64, error) + }) + if !ok { + response.Error(c, 503, "代理查询暂不可用") + return true + } + proxies, total, err = sampler.SampleProxyOptions(c.Request.Context(), search) + // 旧客户端重复加载时必须重新抽样,不能复用上一次缓存的候选。 + c.Header("Cache-Control", "no-store") + } else { + proxies, total, err = scopedProxyOptions(c.Request.Context(), h.adminService, page, size, search) + } + } + if err != nil { + response.Error(c, 503, "代理查询暂不可用") + return true + } + out := make([]scopedProxyOption, 0, min(len(proxies), size)) + for _, p := range proxies[:min(len(proxies), size)] { + out = append(out, scopedProxyDTO(p)) + } + if strings.HasSuffix(c.FullPath(), "/proxies/all") { + c.Header("X-Total-Count", strconv.FormatInt(total, 10)) + c.Header("X-Page", strconv.Itoa(page)) + c.Header("X-Page-Size", strconv.Itoa(size)) + c.Header("X-Total-Pages", strconv.FormatInt((total+int64(size)-1)/int64(size), 10)) + response.Success(c, out) + } else { + response.Paginated(c, out, total, page, size) + } + return true +} + +func scopedProxyOptions(ctx context.Context, admin service.AdminService, page, size int, search string) ([]service.Proxy, int64, error) { + api, ok := admin.(interface { + ListProxyOptions(context.Context, int, int, string) ([]service.Proxy, int64, error) + }) + if !ok { + return nil, 0, fmt.Errorf("代理查询不可用") + } + return api.ListProxyOptions(ctx, page, size, search) +} diff --git a/backend/internal/handler/admin/custom_admin_key_proxies_test.go b/backend/internal/handler/admin/custom_admin_key_proxies_test.go new file mode 100644 index 0000000000..8182cb058e --- /dev/null +++ b/backend/internal/handler/admin/custom_admin_key_proxies_test.go @@ -0,0 +1,198 @@ +//go:build unit + +package admin + +import ( + "context" + "encoding/json" + "net/http/httptest" + "strconv" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type scopedProxyReadTestService struct { + service.AdminService + page, size, calls int + ids []int64 +} + +func (s *scopedProxyReadTestService) ListProxyOptions(_ context.Context, page, size int, _ string) ([]service.Proxy, int64, error) { + s.page = page + s.size = size + s.calls++ + items := make([]service.Proxy, size) + for i := range items { + items[i] = service.Proxy{ID: int64((page-1)*size + i + 1), Host: "192.0.2.1", Username: "secret-user", Password: "secret-password", Status: service.StatusActive} + } + return items, 20001, nil +} +func (s *scopedProxyReadTestService) GetProxiesByIDs(_ context.Context, ids []int64) ([]service.Proxy, error) { + s.ids = ids + s.calls++ + items := []service.Proxy{} + for _, id := range ids { + if id == 999 { + continue + } + items = append(items, service.Proxy{ID: id, Username: "secret-user", Password: "secret-password"}) + } + return items, nil +} +func (s *scopedProxyReadTestService) GetProxy(_ context.Context, id int64) (*service.Proxy, error) { + s.calls++ + return &service.Proxy{ID: id, Username: "secret-user", Password: "secret-password"}, nil +} + +func TestScopedProxyReadBoundedPaginationAndProjection(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, tc := range []struct { + query string + status, page, size, count int + }{ + {"", 200, 1, 50, 50}, {"?page=2&page_size=50000", 200, 2, 100, 100}, {"?page=201&page_size=100", 200, 201, 100, 100}, + {"?page=-1", 400, 0, 0, 0}, {"?page_size=0", 400, 0, 0, 0}, {"?page_size=no", 400, 0, 0, 0}, {"?page=999999999999999999999", 400, 0, 0, 0}, + {"?ids=1,2,3&page=2&page_size=2", 200, 2, 2, 1}, {"?ids=", 200, 1, 50, 0}, + {"?ids=999,1&page_size=1", 200, 1, 1, 1}, {"?ids=1,2,2&page=4&page_size=1", 200, 4, 1, 0}, + } { + t.Run(tc.query, func(t *testing.T) { + svc := &scopedProxyReadTestService{} + h := NewProxyHandler(svc) + r := gin.New() + r.Use(func(c *gin.Context) { + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"proxies.read"}}})) + }) + r.GET("/proxies", h.List) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/proxies"+tc.query, nil)) + require.Equal(t, tc.status, w.Code, w.Body.String()) + require.NotContains(t, w.Body.String(), "secret-") + require.NotContains(t, w.Body.String(), "username") + require.NotContains(t, w.Body.String(), "password") + if tc.status != 200 { + require.Zero(t, svc.calls) + return + } + var body struct { + Data struct { + Items []map[string]any `json:"items"` + Page int `json:"page"` + PageSize int `json:"page_size"` + Total int64 `json:"total"` + } + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body)) + require.Equal(t, tc.page, body.Data.Page) + require.Equal(t, tc.size, body.Data.PageSize) + require.Len(t, body.Data.Items, tc.count) + if strings.Contains(tc.query, "ids=999,1") { + require.EqualValues(t, 1, body.Data.Total) + require.EqualValues(t, 1, body.Data.Items[0]["id"]) + } + if strings.Contains(tc.query, "ids=1,2,3") { + require.Equal(t, []int64{1, 2, 3}, svc.ids) + } + }) + } +} + +func TestScopedProxyReadRejectsLargeIDBatchAndRequiresPermission(t *testing.T) { + for _, allowed := range []bool{false, true} { + svc := &scopedProxyReadTestService{} + h := NewProxyHandler(svc) + r := gin.New() + p := &adminaccess.Principal{} + if allowed { + p.Policy.GlobalPermissions = []string{"proxies.read"} + } + r.Use(func(c *gin.Context) { + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(context.Background(), p)) + }) + r.GET("/proxies", h.GetAll) + r.GET("/proxies/:id", h.GetByID) + ids := []string{} + for i := 1; i <= 101; i++ { + ids = append(ids, strconv.Itoa(i)) + } + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/proxies?ids="+strings.Join(ids, ","), nil)) + if allowed { + require.Equal(t, 400, w.Code) + } else { + require.Equal(t, 403, w.Code) + } + require.Zero(t, svc.calls) + w = httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/proxies/1", nil)) + if allowed { + require.Equal(t, 200, w.Code) + require.NotContains(t, w.Body.String(), "secret-") + require.NotContains(t, w.Body.String(), "username") + } else { + require.Equal(t, 403, w.Code) + } + } +} + +type scopedProxySampleTestService struct { + scopedProxyReadTestService + samples int + search string +} + +func (s *scopedProxySampleTestService) SampleProxyOptions(_ context.Context, search string) ([]service.Proxy, int64, error) { + s.samples++ + s.search = search + return []service.Proxy{{ID: 12345, Host: "192.0.2.1", Username: "secret-user", Password: "secret-password"}}, 20000, nil +} +func TestScopedProxyAllSamplesOnlyWithoutPagination(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, tc := range []struct { + path, query string + sample bool + status int + }{ + {"/api/v1/admin/proxies/all", "", true, 200}, + {"/api/v1/admin/proxies/all", "?search=region", true, 200}, + {"/api/v1/admin/proxies/all", "?page=1", false, 200}, + {"/api/v1/admin/proxies/all", "?page_size=100", false, 200}, + {"/api/v1/admin/proxies/all", "?page=", false, 400}, + {"/api/v1/admin/proxies/all", "?ids=1,2", false, 200}, + {"/api/v1/admin/proxies", "", false, 200}, + } { + t.Run(tc.path+tc.query, func(t *testing.T) { + svc := &scopedProxySampleTestService{} + h := NewProxyHandler(svc) + r := gin.New() + r.Use(func(c *gin.Context) { + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"proxies.read"}}})) + }) + r.GET("/api/v1/admin/proxies/all", h.GetAll) + r.GET("/api/v1/admin/proxies", h.List) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", tc.path+tc.query, nil)) + require.Equal(t, tc.status, w.Code, w.Body.String()) + if tc.sample { + require.Equal(t, 1, svc.samples) + require.Zero(t, svc.calls) + require.Contains(t, w.Body.String(), `"data":[`) + require.Contains(t, w.Body.String(), `"id":12345`) + require.Equal(t, "20000", w.Header().Get("X-Total-Count")) + require.Equal(t, "50", w.Header().Get("X-Page-Size")) + require.Equal(t, "no-store", w.Header().Get("Cache-Control")) + if tc.query != "" { + require.Equal(t, "region", svc.search) + } + } else { + require.Zero(t, svc.samples) + } + require.NotContains(t, w.Body.String(), "secret-") + require.NotContains(t, w.Body.String(), "password") + }) + } +} diff --git a/backend/internal/handler/admin/custom_admin_key_users.go b/backend/internal/handler/admin/custom_admin_key_users.go new file mode 100644 index 0000000000..5a78d7c393 --- /dev/null +++ b/backend/internal/handler/admin/custom_admin_key_users.go @@ -0,0 +1,47 @@ +package admin + +import ( + "slices" + + "github.com/Wei-Shaw/sub2api/internal/handler/dto" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" +) + +// adminUserResponse 对受限密钥使用字段白名单,避免完整管理员 DTO 新增字段时隐式扩大授权。 +// 订阅及用量由各自的独立接口提供,用户资料接口不嵌入这些关联数据。 +func adminUserResponse(c *gin.Context, user *service.User) any { + principal := adminaccess.FromContext(c.Request.Context()) + if principal == nil { + return dto.UserFromServiceAdmin(user) + } + if user == nil { + return nil + } + out := gin.H{"id": user.ID} + permissions := principal.Policy.GlobalPermissions + if slices.Contains(permissions, "users.read") { + out["email"] = user.Email + out["username"] = user.Username + out["role"] = user.Role + out["status"] = user.Status + out["concurrency"] = user.Concurrency + out["rpm_limit"] = user.RPMLimit + out["last_active_at"] = user.LastActiveAt + out["created_at"] = user.CreatedAt + out["updated_at"] = user.UpdatedAt + out["deleted_at"] = user.DeletedAt + } + if slices.Contains(permissions, "users.balance.read") { + out["balance"] = user.Balance + out["frozen_balance"] = user.FrozenBalance + out["total_recharged"] = user.TotalRecharged + } + if slices.Contains(permissions, "groups.read") { + out["allowed_groups"] = user.AllowedGroups + out["restrict_public_groups"] = user.RestrictPublicGroups + out["group_rates"] = user.GroupRates + } + return out +} diff --git a/backend/internal/handler/admin/custom_admin_key_users_test.go b/backend/internal/handler/admin/custom_admin_key_users_test.go new file mode 100644 index 0000000000..497cae2822 --- /dev/null +++ b/backend/internal/handler/admin/custom_admin_key_users_test.go @@ -0,0 +1,113 @@ +//go:build unit + +package admin + +import ( + "context" + "encoding/json" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type scopedUserResponseService struct { + service.AdminService + filters service.UserListFilters + writes int +} + +func (*scopedUserResponseService) user() *service.User { + return &service.User{ID: 7, Email: "user@example.com", Notes: "内部备注", Balance: 123, + APIKeys: []service.APIKey{{Key: "内部密钥"}}, Subscriptions: []service.UserSubscription{{ID: 8, DailyUsageUSD: 10}}} +} +func (s *scopedUserResponseService) ListUsers(_ context.Context, _, _ int, filters service.UserListFilters, _, _ string) ([]service.User, int64, error) { + s.filters = filters + return []service.User{*s.user()}, 1, nil +} +func (s *scopedUserResponseService) GetUser(context.Context, int64) (*service.User, error) { + return s.user(), nil +} +func (s *scopedUserResponseService) UpdateUserBalance(context.Context, int64, float64, string, string) (*service.User, error) { + s.writes++ + return s.user(), nil +} + +func TestScopedAdminUserResponsePreservesFullAdminResponses(t *testing.T) { + gin.SetMode(gin.TestMode) + svc := &scopedUserResponseService{} + h := NewUserHandler(svc, nil, nil, nil, nil, nil, nil) + r := gin.New() + r.GET("/users", h.List) + r.GET("/users/:id", h.GetByID) + for _, path := range []string{"/users", "/users?include_subscriptions=true", "/users/7"} { + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", path, nil)) + require.Equal(t, 200, w.Code) + for _, field := range []string{`"notes":"内部备注"`, `"balance":123`, `"subscriptions":`, `"daily_usage_usd":10`, `"api_keys":`} { + require.Contains(t, w.Body.String(), field) + } + if path == "/users" { + require.Nil(t, svc.filters.IncludeSubscriptions) + } + if strings.Contains(path, "include_subscriptions") { + require.NotNil(t, svc.filters.IncludeSubscriptions) + require.True(t, *svc.filters.IncludeSubscriptions) + } + } +} + +func TestScopedAdminUserBalanceResponseRedactsCachedFullAdminResult(t *testing.T) { + gin.SetMode(gin.TestMode) + previous := service.DefaultIdempotencyCoordinator() + t.Cleanup(func() { service.SetDefaultIdempotencyCoordinator(previous) }) + for _, scopedFirst := range []bool{false, true} { + t.Run(map[bool]string{false: "完整管理员先执行", true: "受限Key先执行"}[scopedFirst], func(t *testing.T) { + service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(newMemoryIdempotencyRepoStub(), service.DefaultIdempotencyConfig())) + svc := &scopedUserResponseService{} + h := NewUserHandler(svc, nil, nil, nil, nil, nil, nil) + r := gin.New() + r.Use(func(c *gin.Context) { + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9}) + if c.GetHeader("X-Test-Scoped") == "true" { + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{ + KeyID: "test-key", Policy: adminaccess.Policy{GlobalPermissions: []string{"users.balance.write"}}, + })) + } + c.Next() + }) + r.POST("/users/:id/balance", h.UpdateBalance) + for i, scoped := range []bool{scopedFirst, !scopedFirst, true} { + req := httptest.NewRequest("POST", "/users/7/balance", strings.NewReader(`{"balance":1,"operation":"add"}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Idempotency-Key", "same-operation") + if scoped { + req.Header.Set("X-Test-Scoped", "true") + } + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, 200, w.Code, w.Body.String()) + if i > 0 { + require.Equal(t, "true", w.Header().Get("X-Idempotency-Replayed")) + } + var result struct { + Data map[string]json.RawMessage `json:"data"` + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result)) + if scoped { + require.Len(t, result.Data, 1) + require.JSONEq(t, `7`, string(result.Data["id"])) + } else { + require.Contains(t, result.Data, "notes") + require.Contains(t, result.Data, "balance") + } + } + require.Equal(t, 1, svc.writes, "重放只改变当前响应的权限投影,不能重复修改余额") + }) + } +} diff --git a/backend/internal/handler/admin/custom_admin_keys.go b/backend/internal/handler/admin/custom_admin_keys.go new file mode 100644 index 0000000000..8abedc09fb --- /dev/null +++ b/backend/internal/handler/admin/custom_admin_keys.go @@ -0,0 +1,102 @@ +package admin + +import ( + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/pkg/response" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" +) + +func requireAdminKeyJWT(c *gin.Context) bool { + if c.GetString("auth_method") != service.AuditAuthMethodJWT { + response.Error(c, 403, "仅管理员 JWT 会话可管理密钥") + return false + } + role, ok := middleware.GetUserRoleFromContext(c) + if !ok || role != "admin" { + response.Error(c, 403, "需要管理员权限") + return false + } + return true +} +func (h *SettingHandler) ListScopedAdminKeys(c *gin.Context) { + if !requireAdminKeyJWT(c) { + return + } + items, e := h.settingService.ListScopedAdminKeys(c.Request.Context()) + if e != nil { + response.ErrorFrom(c, e) + return + } + response.Success(c, gin.H{"items": items, "permissions": adminaccess.PermissionCatalog()}) +} +func (h *SettingHandler) CreateScopedAdminKey(c *gin.Context) { + if !requireAdminKeyJWT(c) { + return + } + var in service.ScopedAdminKeyInput + if e := c.ShouldBindJSON(&in); e != nil { + response.Error(c, 400, "请求格式无效") + return + } + subject, ok := middleware.GetAuthSubjectFromContext(c) + if !ok { + response.Error(c, 403, "需要管理员身份") + return + } + key, item, e := h.settingService.CreateScopedAdminKey(c.Request.Context(), in, subject.UserID) + if e != nil { + response.ErrorFrom(c, e) + return + } + response.Success(c, gin.H{"key": key, "item": item}) +} +func (h *SettingHandler) UpdateScopedAdminKey(c *gin.Context) { + if !requireAdminKeyJWT(c) { + return + } + var in service.ScopedAdminKeyInput + if e := c.ShouldBindJSON(&in); e != nil { + response.Error(c, 400, "请求格式无效") + return + } + item, e := h.settingService.UpdateScopedAdminKey(c.Request.Context(), c.Param("id"), in) + if e != nil { + response.ErrorFrom(c, e) + return + } + response.Success(c, item) +} +func (h *SettingHandler) RotateScopedAdminKey(c *gin.Context) { + if !requireAdminKeyJWT(c) { + return + } + key, item, e := h.settingService.RotateScopedAdminKey(c.Request.Context(), c.Param("id")) + if e != nil { + response.ErrorFrom(c, e) + return + } + response.Success(c, gin.H{"key": key, "item": item}) +} +func (h *SettingHandler) RevokeScopedAdminKey(c *gin.Context) { + if !requireAdminKeyJWT(c) { + return + } + if e := h.settingService.RevokeScopedAdminKey(c.Request.Context(), c.Param("id")); e != nil { + response.ErrorFrom(c, e) + return + } + response.Success(c, gin.H{"message": "管理密钥已永久撤销"}) +} + +func (h *SettingHandler) DeleteScopedAdminKeyRecord(c *gin.Context) { + if !requireAdminKeyJWT(c) { + return + } + if e := h.settingService.DeleteScopedAdminKeyRecord(c.Request.Context(), c.Param("id")); e != nil { + response.ErrorFrom(c, e) + return + } + response.Success(c, gin.H{"message": "密钥已从列表移除,历史操作记录仍会继续保留"}) +} diff --git a/backend/internal/handler/admin/custom_admin_keys_test.go b/backend/internal/handler/admin/custom_admin_keys_test.go new file mode 100644 index 0000000000..301257aaa0 --- /dev/null +++ b/backend/internal/handler/admin/custom_admin_keys_test.go @@ -0,0 +1,78 @@ +//go:build unit + +package admin + +import ( + "context" + "net/http/httptest" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestScopedAdminKeyHandlersRejectNonJWT(t *testing.T) { + h := &SettingHandler{} + for _, fn := range []gin.HandlerFunc{h.ListScopedAdminKeys, h.CreateScopedAdminKey, h.UpdateScopedAdminKey, h.RotateScopedAdminKey, h.RevokeScopedAdminKey, h.DeleteScopedAdminKeyRecord, h.GetAdminAPIKey, h.RegenerateAdminAPIKey, h.DeleteAdminAPIKey} { + for _, method := range []string{"", "admin_api_key"} { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Set("auth_method", method) + fn(c) + if w.Code != 403 { + t.Fatalf("%s 应拒绝,返回 %d", method, w.Code) + } + } + } +} + +type deleteScopedKeyRecordRepo struct { + service.ScopedAdminKeyRepository + err error + id string +} + +func (r *deleteScopedKeyRecordRepo) DeleteScopedAdminKeyRecord(_ context.Context, id string, at time.Time) error { + r.id = id + if at.IsZero() { + panic("删除时间不能为空") + } + return r.err +} + +func TestScopedAdminKeyDeleteRecordHandler(t *testing.T) { + for _, tc := range []struct { + name, role string + err error + status int + }{ + {"仅列表移除", "admin", nil, 200}, + {"未撤销或已移除", "admin", service.ErrScopedAdminKeyNotFound, 404}, + {"普通用户拒绝", "user", nil, 403}, + } { + t.Run(tc.name, func(t *testing.T) { + repo := &deleteScopedKeyRecordRepo{err: tc.err} + settings := service.NewSettingService(nil, nil) + settings.SetScopedAdminKeyRepository(repo) + h := &SettingHandler{settingService: settings} + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest("DELETE", "/api/v1/admin/settings/admin-api-keys/key-1/record", nil) + c.Params = gin.Params{{Key: "id", Value: "key-1"}} + c.Set("auth_method", service.AuditAuthMethodJWT) + c.Set("user_role", tc.role) + h.DeleteScopedAdminKeyRecord(c) + require.Equal(t, tc.status, w.Code) + if tc.role != "admin" { + require.Empty(t, repo.id) + } else { + require.Equal(t, "key-1", repo.id) + } + if tc.status == 200 { + require.Contains(t, w.Body.String(), "历史操作记录仍会继续保留") + } + }) + } +} diff --git a/backend/internal/handler/admin/custom_legacy_admin_key_test.go b/backend/internal/handler/admin/custom_legacy_admin_key_test.go new file mode 100644 index 0000000000..2ee229e86c --- /dev/null +++ b/backend/internal/handler/admin/custom_legacy_admin_key_test.go @@ -0,0 +1,141 @@ +//go:build unit + +package admin + +import ( + "context" + "database/sql" + "fmt" + "net/http/httptest" + "os" + "sync" + "testing" + "time" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + dbent "github.com/Wei-Shaw/sub2api/ent" + _ "github.com/Wei-Shaw/sub2api/ent/runtime" + "github.com/Wei-Shaw/sub2api/internal/repository" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + _ "github.com/lib/pq" + "github.com/stretchr/testify/require" +) + +// 在轮换读取旧值后暂停,让删除在恢复轮换之前完整提交。 +type legacyKeyReadBarrier struct { + service.SettingRepository + read chan struct{} + resume chan struct{} + once sync.Once +} + +func (r *legacyKeyReadBarrier) GetValue(ctx context.Context, key string) (string, error) { + value, err := r.SettingRepository.GetValue(ctx, key) + if key == service.SettingKeyAdminAPIKey && err == nil { + r.once.Do(func() { close(r.read); <-r.resume }) + } + return value, err +} + +func (r *legacyKeyReadBarrier) ReplaceExistingAdminAPIKey(ctx context.Context, value string) (bool, error) { + return r.SettingRepository.(interface { + ReplaceExistingAdminAPIKey(context.Context, string) (bool, error) + }).ReplaceExistingAdminAPIKey(ctx, value) +} + +func legacyKeyRequest(handler gin.HandlerFunc) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest("POST", "/api/v1/admin/settings/admin-api-key/regenerate", nil) + c.Set("auth_method", service.AuditAuthMethodJWT) + c.Set("user_role", "admin") + handler(c) + return w +} + +func TestLegacyAdminKeyRotationPostgres(t *testing.T) { + dsn := os.Getenv("SCOPED_ADMIN_TEST_DSN") + if dsn == "" { + t.Skip("需要独立 SCOPED_ADMIN_TEST_DSN") + } + base, err := sql.Open("postgres", dsn) + require.NoError(t, err) + schema := fmt.Sprintf("legacy_key_test_%d", time.Now().UnixNano()) + _, err = base.Exec(`CREATE SCHEMA ` + schema) + require.NoError(t, err) + db, err := sql.Open("postgres", dsn+" search_path="+schema) + require.NoError(t, err) + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + t.Cleanup(func() { _ = client.Close(); _, _ = base.Exec(`DROP SCHEMA ` + schema + ` CASCADE`); _ = base.Close() }) + _, err = db.Exec(`CREATE TABLE settings(id BIGSERIAL PRIMARY KEY, key VARCHAR(100) UNIQUE NOT NULL, value TEXT NOT NULL, updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`) + require.NoError(t, err) + repo := repository.NewSettingRepository(client) + settings := service.NewSettingService(repo, nil) + h := &SettingHandler{settingService: settings} + ctx := context.Background() + + t.Run("删除先完成不得被轮换重建", func(t *testing.T) { + require.NoError(t, repo.Set(ctx, service.SettingKeyAdminAPIKey, "admin-test-old-key")) + barrier := &legacyKeyReadBarrier{SettingRepository: repo, read: make(chan struct{}), resume: make(chan struct{})} + var release sync.Once + unblock := func() { release.Do(func() { close(barrier.resume) }) } + defer unblock() + rotating := &SettingHandler{settingService: service.NewSettingService(barrier, nil)} + done := make(chan *httptest.ResponseRecorder, 1) + go func() { done <- legacyKeyRequest(rotating.RegenerateAdminAPIKey) }() + select { + case <-barrier.read: + case <-time.After(5 * time.Second): + t.Fatal("轮换未进入读取屏障") + } + require.Equal(t, 200, legacyKeyRequest(h.DeleteAdminAPIKey).Code) + var afterDelete int + require.NoError(t, db.QueryRow(`SELECT COUNT(*) FROM settings WHERE key=$1`, service.SettingKeyAdminAPIKey).Scan(&afterDelete)) + require.Zero(t, afterDelete, "恢复轮换前删除必须已经落库") + unblock() + var response *httptest.ResponseRecorder + select { + case response = <-done: + case <-time.After(5 * time.Second): + t.Fatal("轮换未结束") + } + var count int + require.NoError(t, db.QueryRow(`SELECT COUNT(*) FROM settings WHERE key=$1`, service.SettingKeyAdminAPIKey).Scan(&count)) + require.Zero(t, count, "已删除旧版密钥被轮换重新创建") + require.Equal(t, 403, response.Code) + require.NotContains(t, response.Body.String(), `"key":`) + }) + + t.Run("已有密钥可轮换且随后可删除", func(t *testing.T) { + require.NoError(t, repo.Set(ctx, service.SettingKeyAdminAPIKey, "admin-test-old-key")) + response := legacyKeyRequest(h.RegenerateAdminAPIKey) + require.Equal(t, 200, response.Code) + key, err := settings.GetAdminAPIKey(ctx) + require.NoError(t, err) + require.NotEqual(t, "admin-test-old-key", key) + require.NotEmpty(t, key) + require.Contains(t, response.Body.String(), key) + require.Equal(t, 200, legacyKeyRequest(h.DeleteAdminAPIKey).Code) + key, err = settings.GetAdminAPIKey(ctx) + require.NoError(t, err) + require.Empty(t, key) + }) + + t.Run("缺失与空值不能新建", func(t *testing.T) { + for _, emptyRow := range []bool{false, true} { + require.NoError(t, settings.DeleteAdminAPIKey(ctx)) + if emptyRow { + require.NoError(t, repo.Set(ctx, service.SettingKeyAdminAPIKey, "")) + } + require.Equal(t, 403, legacyKeyRequest(h.RegenerateAdminAPIKey).Code) + key, err := settings.GenerateAdminAPIKey(ctx) + require.Error(t, err, "服务层也必须拒绝从无到有创建") + require.Empty(t, key) + stored, err := settings.GetAdminAPIKey(ctx) + require.NoError(t, err) + require.Empty(t, stored) + } + }) +} diff --git a/backend/internal/handler/admin/idempotency_helper.go b/backend/internal/handler/admin/idempotency_helper.go index 8017e7211e..db104a7d6c 100644 --- a/backend/internal/handler/admin/idempotency_helper.go +++ b/backend/internal/handler/admin/idempotency_helper.go @@ -115,6 +115,18 @@ func executeAdminIdempotentJSONWithMode( mode idempotencyStoreUnavailableMode, execute func(context.Context) (any, error), ) { + executeAdminIdempotentJSONWithProjection(c, scope, payload, ttl, executionTimeout, mode, execute, nil) +} + +// executeAdminIdempotentJSONWithResponse 在实际执行及缓存重放之后统一约束响应。 +func executeAdminIdempotentJSONWithResponse(c *gin.Context, scope string, payload any, ttl time.Duration, execute func(context.Context) (any, error), present func(any) any) { + executeAdminIdempotentJSONWithProjection(c, scope, payload, ttl, 0, idempotencyStoreUnavailableFailClose, execute, present) +} + +func executeAdminIdempotentJSONWithProjection(c *gin.Context, scope string, payload any, ttl time.Duration, executionTimeout time.Duration, mode idempotencyStoreUnavailableMode, execute func(context.Context) (any, error), present func(any) any) { + if present == nil { + present = func(data any) any { return data } + } result, err := executeAdminIdempotentWithTimeout(c, scope, payload, ttl, executionTimeout, execute) if err != nil { if infraerrors.Code(err) == infraerrors.Code(service.ErrIdempotencyStoreUnavail) { @@ -131,7 +143,7 @@ func executeAdminIdempotentJSONWithMode( return } c.Header("X-Idempotency-Degraded", "store-unavailable") - response.Success(c, data) + response.Success(c, present(data)) return } } @@ -144,5 +156,5 @@ func executeAdminIdempotentJSONWithMode( if result != nil && result.Replayed { c.Header("X-Idempotency-Replayed", "true") } - response.Success(c, result.Data) + response.Success(c, present(result.Data)) } diff --git a/backend/internal/handler/admin/promo_handler.go b/backend/internal/handler/admin/promo_handler.go index 34a44a81f1..3e8be8641c 100644 --- a/backend/internal/handler/admin/promo_handler.go +++ b/backend/internal/handler/admin/promo_handler.go @@ -207,5 +207,5 @@ func (h *PromoHandler) GetUsages(c *gin.Context) { for i := range usages { out = append(out, *dto.PromoCodeUsageFromService(&usages[i])) } - response.Paginated(c, out, paginationResult.Total, page, pageSize) + response.Paginated(c, adminPromoUsagesResponse(c, out), paginationResult.Total, page, pageSize) } diff --git a/backend/internal/handler/admin/proxy_handler.go b/backend/internal/handler/admin/proxy_handler.go index 3902eaf2f8..d16453d3b2 100644 --- a/backend/internal/handler/admin/proxy_handler.go +++ b/backend/internal/handler/admin/proxy_handler.go @@ -57,6 +57,9 @@ type UpdateProxyRequest struct { // List handles listing all proxies with pagination // GET /api/v1/admin/proxies func (h *ProxyHandler) List(c *gin.Context) { + if h.scopedAdminProxyRead(c) { + return + } page, pageSize := response.ParsePagination(c) protocol := c.Query("protocol") status := c.Query("status") @@ -86,6 +89,9 @@ func (h *ProxyHandler) List(c *gin.Context) { // GET /api/v1/admin/proxies/all // Optional query param: with_count=true to include account count per proxy func (h *ProxyHandler) GetAll(c *gin.Context) { + if h.scopedAdminProxyRead(c) { + return + } withCount := c.Query("with_count") == "true" if withCount { @@ -118,6 +124,9 @@ func (h *ProxyHandler) GetAll(c *gin.Context) { // GetByID handles getting a proxy by ID // GET /api/v1/admin/proxies/:id func (h *ProxyHandler) GetByID(c *gin.Context) { + if h.scopedAdminProxyRead(c) { + return + } proxyID, err := strconv.ParseInt(c.Param("id"), 10, 64) if err != nil { response.BadRequest(c, "Invalid proxy ID") diff --git a/backend/internal/handler/admin/scoped_admin_content_response.go b/backend/internal/handler/admin/scoped_admin_content_response.go new file mode 100644 index 0000000000..69e037f8be --- /dev/null +++ b/backend/internal/handler/admin/scoped_admin_content_response.go @@ -0,0 +1,47 @@ +package admin + +import ( + "time" + + "github.com/Wei-Shaw/sub2api/internal/handler/dto" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" +) + +// 受限密钥仅接收记录自身字段;不嵌入完整用户资料或实时财务数据。 +type scopedPromoUsageResponse struct { + ID int64 `json:"id"` + PromoCodeID int64 `json:"promo_code_id"` + UserID int64 `json:"user_id"` + BonusAmount float64 `json:"bonus_amount"` + UsedAt time.Time `json:"used_at"` +} + +func adminPromoUsagesResponse(c *gin.Context, items []dto.PromoCodeUsage) any { + if adminaccess.FromContext(c.Request.Context()) == nil { + return items + } + out := make([]scopedPromoUsageResponse, 0, len(items)) + for _, item := range items { + out = append(out, scopedPromoUsageResponse{ID: item.ID, PromoCodeID: item.PromoCodeID, UserID: item.UserID, BonusAmount: item.BonusAmount, UsedAt: item.UsedAt}) + } + return out +} + +type scopedAnnouncementReadResponse struct { + UserID int64 `json:"user_id"` + Eligible bool `json:"eligible"` + ReadAt *time.Time `json:"read_at,omitempty"` +} + +func adminAnnouncementReadResponse(c *gin.Context, items []service.AnnouncementUserReadStatus) any { + if adminaccess.FromContext(c.Request.Context()) == nil { + return items + } + out := make([]scopedAnnouncementReadResponse, 0, len(items)) + for _, item := range items { + out = append(out, scopedAnnouncementReadResponse{UserID: item.UserID, Eligible: item.Eligible, ReadAt: item.ReadAt}) + } + return out +} diff --git a/backend/internal/handler/admin/scoped_admin_content_response_test.go b/backend/internal/handler/admin/scoped_admin_content_response_test.go new file mode 100644 index 0000000000..2055ea1f9e --- /dev/null +++ b/backend/internal/handler/admin/scoped_admin_content_response_test.go @@ -0,0 +1,94 @@ +//go:build unit + +package admin + +import ( + "context" + "encoding/json" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "net/http/httptest" + "testing" + "time" +) + +type scopedContentPromoRepo struct{ service.PromoCodeRepository } + +func (scopedContentPromoRepo) ListUsagesByPromoCode(context.Context, int64, pagination.PaginationParams) ([]service.PromoCodeUsage, *pagination.PaginationResult, error) { + return []service.PromoCodeUsage{{ID: 1, PromoCodeID: 2, UserID: 3, BonusAmount: 4, User: &service.User{ID: 3, Email: "private@example.com", Balance: 999, FrozenBalance: 888, TotalRecharged: 777}}}, &pagination.PaginationResult{Total: 1}, nil +} + +type scopedContentUsers struct{ service.UserRepository } + +func (scopedContentUsers) ListWithFilters(context.Context, pagination.PaginationParams, service.UserListFilters) ([]service.User, *pagination.PaginationResult, error) { + return []service.User{{ID: 3, Email: "private@example.com", Balance: 999}}, &pagination.PaginationResult{Total: 1}, nil +} + +type scopedContentSubs struct { + service.UserSubscriptionRepository +} + +func (scopedContentSubs) ListActiveByUserID(context.Context, int64) ([]service.UserSubscription, error) { + return nil, nil +} + +type scopedContentReads struct { + service.AnnouncementReadRepository +} + +func (scopedContentReads) GetReadMapByUsers(context.Context, int64, []int64) (map[int64]time.Time, error) { + return map[int64]time.Time{3: time.Unix(100, 0).UTC()}, nil +} +func TestScopedAdminContentHandlersResponseBoundary(t *testing.T) { + gin.SetMode(gin.TestMode) + promo := NewPromoHandler(service.NewPromoService(scopedContentPromoRepo{}, nil, nil, nil, nil)) + announcement := NewAnnouncementHandler(service.NewAnnouncementService(&announcementRepoCapture{}, scopedContentReads{}, scopedContentUsers{}, scopedContentSubs{})) + for _, endpoint := range []struct { + name, path, request string + handler gin.HandlerFunc + }{{"优惠码", "/promo-codes/:id/usages", "/promo-codes/2/usages", promo.GetUsages}, {"公告", "/announcements/:id/read-status", "/announcements/2/read-status", announcement.ListReadStatus}} { + for _, scoped := range []bool{false, true} { + t.Run(endpoint.name+map[bool]string{true: "受限", false: "普通"}[scoped], func(t *testing.T) { + r := gin.New() + r.Use(func(c *gin.Context) { + if scoped { + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"promo.read", "announcements.read"}}})) + } + c.Next() + }) + r.GET(endpoint.path, endpoint.handler) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", endpoint.request, nil)) + require.Equal(t, 200, w.Code) + var body struct { + Data struct { + Items []map[string]json.RawMessage `json:"items"` + } `json:"data"` + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body)) + require.Len(t, body.Data.Items, 1) + item := body.Data.Items[0] + if scoped { + require.NotContains(t, w.Body.String(), "private@example.com") + require.NotContains(t, w.Body.String(), "999") + require.NotContains(t, item, "user") + require.NotContains(t, item, "balance") + require.Contains(t, item, "user_id") + if endpoint.name == "优惠码" { + require.Contains(t, item, "bonus_amount") + require.Contains(t, item, "used_at") + } else { + require.Contains(t, item, "eligible") + require.Contains(t, item, "read_at") + } + } else { + require.Contains(t, w.Body.String(), "private@example.com") + require.Contains(t, w.Body.String(), "999") + } + }) + } + } +} diff --git a/backend/internal/handler/admin/scoped_admin_subscription_response.go b/backend/internal/handler/admin/scoped_admin_subscription_response.go new file mode 100644 index 0000000000..8c467fbba1 --- /dev/null +++ b/backend/internal/handler/admin/scoped_admin_subscription_response.go @@ -0,0 +1,65 @@ +package admin + +import ( + "encoding/json" + "slices" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/gin-gonic/gin" +) + +func scopedAdminWriteOnly(c *gin.Context, readPermission string) bool { + p := adminaccess.FromContext(c.Request.Context()) + return p != nil && !slices.Contains(p.Policy.GlobalPermissions, readPermission) +} + +// adminSubscriptionResponse 在缓存重放后也应用字段白名单,不嵌入用户、分配人或分组配置。 +// 写权限只确认订阅 ID;订阅用量等字段必须另有读取权限。 +func adminSubscriptionResponse(c *gin.Context, data any) any { + if adminaccess.FromContext(c.Request.Context()) == nil { + return data + } + raw, err := json.Marshal(data) + if err != nil { + return nil + } + return projectSubscriptionJSON(raw, !scopedAdminWriteOnly(c, "subscriptions.read")) +} + +func projectSubscriptionJSON(raw json.RawMessage, readable bool) any { + var list []json.RawMessage + if len(raw) > 0 && raw[0] == '[' && json.Unmarshal(raw, &list) == nil { + out := make([]any, 0, len(list)) + for _, item := range list { + out = append(out, projectSubscriptionJSON(item, readable)) + } + return out + } + var fields map[string]json.RawMessage + if json.Unmarshal(raw, &fields) != nil || fields == nil { + return nil + } + out := make(map[string]any) + if subscriptions, ok := fields["subscriptions"]; ok { + for _, key := range []string{"success_count", "created_count", "reused_count", "failed_count", "errors", "statuses"} { + if value, exists := fields[key]; exists { + out[key] = value + } + } + out["subscriptions"] = projectSubscriptionJSON(subscriptions, readable) + return out + } + keys := []string{"id"} + if readable { + keys = append(keys, "user_id", "group_id", "starts_at", "expires_at", "status", + "daily_window_start", "weekly_window_start", "monthly_window_start", + "daily_usage_usd", "weekly_usage_usd", "monthly_usage_usd", + "created_at", "updated_at", "revoked_at", "assigned_by", "assigned_at", "notes") + } + for _, key := range keys { + if value, exists := fields[key]; exists { + out[key] = value + } + } + return out +} diff --git a/backend/internal/handler/admin/scoped_admin_subscription_response_test.go b/backend/internal/handler/admin/scoped_admin_subscription_response_test.go new file mode 100644 index 0000000000..0756d674ca --- /dev/null +++ b/backend/internal/handler/admin/scoped_admin_subscription_response_test.go @@ -0,0 +1,164 @@ +//go:build unit + +package admin + +import ( + "context" + "encoding/json" + "github.com/Wei-Shaw/sub2api/internal/handler/dto" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type scopedSubscriptionRepo struct { + service.UserSubscriptionRepository + writes int +} + +func (*scopedSubscriptionRepo) GetByID(context.Context, int64) (*service.UserSubscription, error) { + return &service.UserSubscription{ID: 1, UserID: 2, GroupID: 3, DailyUsageUSD: 4, ExpiresAt: time.Now().Add(time.Hour), + User: &service.User{ID: 2, Email: "private-user@example.com", Balance: 987}, + AssignedByUser: &service.User{ID: 8, Email: "private-admin@example.com", Balance: 654}, + Group: &service.Group{ID: 3, Name: "group", RateMultiplier: 42}}, nil +} +func TestScopedAdminSubscriptionDoesNotExposeAssociatedUserAndPricing(t *testing.T) { + gin.SetMode(gin.TestMode) + s := service.NewSubscriptionService(nil, &scopedSubscriptionRepo{}, nil, nil, nil) + defer s.Stop() + h := NewSubscriptionHandler(s) + for _, scoped := range []bool{false, true} { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest("GET", "/subscriptions/1", nil) + c.Params = gin.Params{{Key: "id", Value: "1"}} + if scoped { + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"subscriptions.read"}}})) + } + h.GetByID(c) + require.Equal(t, 200, w.Code) + require.Contains(t, w.Body.String(), `"daily_usage_usd":4`) + for _, field := range []string{"private-user@example.com", "private-admin@example.com", `"balance"`, `"rate_multiplier"`} { + if scoped { + require.NotContains(t, w.Body.String(), field) + } else { + require.Contains(t, w.Body.String(), field) + } + } + } +} +func TestScopedAdminQuotaWriteDoesNotGrantQuotaRead(t *testing.T) { + repo := &upsertCapturingQuotaRepo{listRecords: []service.UserPlatformQuotaRecord{{UserID: 42, Platform: "anthropic"}}} + h := buildTestHandler(repo, &billingCacheStub{}) + c, w := putReq(t, `{"quotas":[{"platform":"anthropic","daily_limit_usd":10}]}`) + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"users.quotas.write"}}})) + h.UpdateUserPlatformQuotas(c) + require.Equal(t, 200, w.Code) + require.NotContains(t, w.Body.String(), "platform_quotas") + require.NotContains(t, w.Body.String(), "usage") + require.Len(t, repo.upsertCalls, 1) +} + +func (r *scopedSubscriptionRepo) GetByIDForUpdate(ctx context.Context, id int64) (*service.UserSubscription, error) { + return r.GetByID(ctx, id) +} +func (r *scopedSubscriptionRepo) ExtendExpiry(context.Context, int64, time.Time) error { + r.writes++ + return nil +} + +func TestScopedAdminSubscriptionExtendReplayRespectsReadPermission(t *testing.T) { + gin.SetMode(gin.TestMode) + previous := service.DefaultIdempotencyCoordinator() + t.Cleanup(func() { service.SetDefaultIdempotencyCoordinator(previous) }) + service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(newMemoryIdempotencyRepoStub(), service.DefaultIdempotencyConfig())) + repo := &scopedSubscriptionRepo{} + svc := service.NewSubscriptionService(nil, repo, nil, nil, nil) + defer svc.Stop() + h := NewSubscriptionHandler(svc) + r := gin.New() + r.Use(func(c *gin.Context) { + if c.GetHeader("X-Test-Mode") != "admin" { + permissions := []string{"subscriptions.extend"} + if c.GetHeader("X-Test-Mode") == "read" { + permissions = append(permissions, "subscriptions.read") + } + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: permissions}})) + } + }) + r.POST("/subscriptions/:id/extend", h.Extend) + for i, mode := range []string{"admin", "write", "read"} { + req := httptest.NewRequest("POST", "/subscriptions/1/extend", strings.NewReader(`{"days":1}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Idempotency-Key", "same-extension") + req.Header.Set("X-Test-Mode", mode) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, 200, w.Code, w.Body.String()) + if i > 0 { + require.Equal(t, "true", w.Header().Get("X-Idempotency-Replayed")) + } + var result struct { + Data map[string]json.RawMessage `json:"data"` + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result)) + if mode == "admin" { + require.Contains(t, result.Data, "user") + } else { + require.NotContains(t, result.Data, "user") + require.NotContains(t, result.Data, "group") + require.NotContains(t, result.Data, "assigned_by_user") + if mode == "write" { + require.Len(t, result.Data, 1) + } else { + require.Contains(t, result.Data, "daily_usage_usd") + } + } + } + require.Equal(t, 1, repo.writes) +} + +func TestScopedAdminSubscriptionBulkProjectionPreservesIDs(t *testing.T) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest("GET", "/", nil) + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{})) + sub, _ := (&scopedSubscriptionRepo{}).GetByID(context.Background(), 1) + sub.ID = 9007199254740993 + data := &dto.BulkAssignResult{SuccessCount: 1, Subscriptions: []dto.AdminUserSubscription{*dto.UserSubscriptionFromServiceAdmin(sub)}} + raw, err := json.Marshal(adminSubscriptionResponse(c, data)) + require.NoError(t, err) + require.Contains(t, string(raw), `"id":9007199254740993`) + require.Contains(t, string(raw), `"success_count":1`) + for _, field := range []string{"daily_usage_usd", "user_id", "balance", "group", "private-user"} { + require.NotContains(t, string(raw), field) + } +} + +func TestScopedAdminQuotaResetRequiresReadToReturnUsage(t *testing.T) { + for _, readable := range []bool{false, true} { + repo := &upsertCapturingQuotaRepo{listRecords: []service.UserPlatformQuotaRecord{{UserID: 42, Platform: "anthropic"}}} + cache := &billingCacheStub{} + h := buildTestHandler(repo, cache) + c, w := postReq(t, `{"platform":"anthropic","window":"daily"}`) + permissions := []string{"users.quotas.write"} + if readable { + permissions = append(permissions, "users.quotas.read") + } + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: permissions}})) + h.ResetUserPlatformQuotaWindow(c) + require.Equal(t, 200, w.Code, w.Body.String()) + require.Len(t, repo.resetCalls, 1) + require.Len(t, cache.deleteCalls, 1) + if readable { + require.Contains(t, w.Body.String(), "platform_quotas") + } else { + require.NotContains(t, w.Body.String(), "platform_quotas") + } + } +} diff --git a/backend/internal/handler/admin/scoped_admin_usage_response.go b/backend/internal/handler/admin/scoped_admin_usage_response.go new file mode 100644 index 0000000000..902ae310a7 --- /dev/null +++ b/backend/internal/handler/admin/scoped_admin_usage_response.go @@ -0,0 +1,97 @@ +package admin + +import ( + "github.com/Wei-Shaw/sub2api/internal/handler/dto" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" +) + +// scopedAdminUsageLogResponse 仅公开该次请求的用量、计费快照和请求元数据。 +// 关联资源只返回 ID;新增通用 DTO 字段不会自动获得受限密钥的读取权限。 +func scopedAdminUsageLogResponse(record *service.UsageLog) gin.H { + if record == nil { + return nil + } + // 在转换前移除关联,避免构造含原始密钥、用户余额等内容的嵌套 DTO。 + flat := *record + flat.User, flat.APIKey, flat.Group, flat.Subscription, flat.Account = nil, nil, nil, nil, nil + usage := dto.UsageLogFromServiceAdmin(&flat) + return gin.H{ + "id": usage.ID, + "user_id": usage.UserID, + "api_key_id": usage.APIKeyID, + "account_id": usage.AccountID, + "request_id": usage.RequestID, + "model": usage.Model, + "service_tier": usage.ServiceTier, + "reasoning_effort": usage.ReasoningEffort, + "inbound_endpoint": usage.InboundEndpoint, + "upstream_endpoint": usage.UpstreamEndpoint, + "group_id": usage.GroupID, + "subscription_id": usage.SubscriptionID, + "input_tokens": usage.InputTokens, + "output_tokens": usage.OutputTokens, + "cache_creation_tokens": usage.CacheCreationTokens, + "cache_read_tokens": usage.CacheReadTokens, + "cache_creation_5m_tokens": usage.CacheCreation5mTokens, + "cache_creation_1h_tokens": usage.CacheCreation1hTokens, + "input_cost": usage.InputCost, + "output_cost": usage.OutputCost, + "cache_creation_cost": usage.CacheCreationCost, + "cache_read_cost": usage.CacheReadCost, + "total_cost": usage.TotalCost, + "actual_cost": usage.ActualCost, + "rate_multiplier": usage.RateMultiplier, + "long_context_billing_applied": usage.LongContextBillingApplied, + "billing_type": usage.BillingType, + "request_type": usage.RequestType, + "stream": usage.Stream, + "openai_ws_mode": usage.OpenAIWSMode, + "native_compaction_v2": usage.NativeCompactionV2, + "duration_ms": usage.DurationMs, + "first_token_ms": usage.FirstTokenMs, + "image_count": usage.ImageCount, + "image_size": usage.ImageSize, + "image_input_size": usage.ImageInputSize, + "image_output_size": usage.ImageOutputSize, + "image_input_tokens": usage.ImageInputTokens, + "image_input_cost": usage.ImageInputCost, + "image_output_tokens": usage.ImageOutputTokens, + "image_output_cost": usage.ImageOutputCost, + "image_size_source": usage.ImageSizeSource, + "image_size_breakdown": usage.ImageSizeBreakdown, + "media_type": usage.MediaType, + "user_agent": usage.UserAgent, + "ip_address": usage.IPAddress, + "session_id": usage.SessionID, + "cache_ttl_overridden": usage.CacheTTLOverridden, + "billing_mode": usage.BillingMode, + "created_at": usage.CreatedAt, + "upstream_model": usage.UpstreamModel, + "upstream_reasoning_effort": usage.UpstreamReasoningEffort, + "upstream_response_model": usage.UpstreamResponseModel, + "upstream_model_mismatch": usage.UpstreamModelMismatch, + "channel_id": usage.ChannelID, + "model_mapping_chain": usage.ModelMappingChain, + "upstream_request_id": usage.UpstreamRequestID, + "billing_tier": usage.BillingTier, + "account_rate_multiplier": usage.AccountRateMultiplier, + "account_stats_cost": usage.AccountStatsCost, + } +} + +func adminUsageLogResponses(c *gin.Context, records []service.UsageLog) any { + if adminaccess.FromContext(c.Request.Context()) != nil { + out := make([]gin.H, 0, len(records)) + for i := range records { + out = append(out, scopedAdminUsageLogResponse(&records[i])) + } + return out + } + out := make([]dto.AdminUsageLog, 0, len(records)) + for i := range records { + out = append(out, *dto.UsageLogFromServiceAdmin(&records[i])) + } + return out +} diff --git a/backend/internal/handler/admin/scoped_admin_usage_response_test.go b/backend/internal/handler/admin/scoped_admin_usage_response_test.go new file mode 100644 index 0000000000..c43e9015f4 --- /dev/null +++ b/backend/internal/handler/admin/scoped_admin_usage_response_test.go @@ -0,0 +1,92 @@ +//go:build unit + +package admin + +import ( + "context" + "encoding/json" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/Wei-Shaw/sub2api/internal/pkg/usagestats" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type scopedUsageResponseRepo struct { + service.UsageLogRepository + records []service.UsageLog +} + +func (r *scopedUsageResponseRepo) ListWithFilters(context.Context, pagination.PaginationParams, usagestats.UsageLogFilters) ([]service.UsageLog, *pagination.PaginationResult, error) { + return r.records, &pagination.PaginationResult{Total: int64(len(r.records))}, nil +} +func TestScopedAdminUsageListDoesNotGrantNestedResourceRead(t *testing.T) { + gin.SetMode(gin.TestMode) + privateUser := &service.User{ID: 7, Email: "private-email@example.invalid", Balance: 97531, Notes: "private-user-notes"} + privateKey := &service.APIKey{ID: 8, Key: "private-api-key-secret", Name: "private-key-name", User: privateUser} + privateGroup := &service.Group{ID: 9, Name: "private-group-name", Description: "private-group-description", RateMultiplier: 7} + privateSub := &service.UserSubscription{ID: 10, User: privateUser, Group: privateGroup, DailyUsageUSD: 100} + privateAccount := &service.Account{ID: 11, Name: "private-account-name", Credentials: map[string]any{"access_token": "private-account-token"}} + for _, scoped := range []bool{true, false} { + t.Run(map[bool]string{true: "受限用量读取", false: "完整管理员保留响应"}[scoped], func(t *testing.T) { + repo := &scopedUsageResponseRepo{records: []service.UsageLog{{ID: 12, UserID: 7, APIKeyID: 8, AccountID: 11, RequestID: "request-public", RequestedModel: "requested-model", Model: "effective-model", InputTokens: 123, OutputTokens: 456, TotalCost: 1.25, ActualCost: 1, User: privateUser, APIKey: privateKey, Group: privateGroup, Subscription: privateSub, Account: privateAccount}}} + h := NewUsageHandler(service.NewUsageService(repo, nil, nil, nil), nil, nil, nil) + r := gin.New() + r.Use(func(c *gin.Context) { + if scoped { + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"usage.read"}}})) + } + }) + r.GET("/api/v1/admin/usage", h.List) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/admin/usage", nil)) + require.Equal(t, 200, w.Code, w.Body.String()) + var result struct { + Data struct { + Items []map[string]json.RawMessage `json:"items"` + Total int64 `json:"total"` + } `json:"data"` + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result)) + require.Len(t, result.Data.Items, 1) + require.EqualValues(t, 1, result.Data.Total) + item := result.Data.Items[0] + require.JSONEq(t, `123`, string(item["input_tokens"])) + require.JSONEq(t, `456`, string(item["output_tokens"])) + require.JSONEq(t, `1.25`, string(item["total_cost"])) + require.JSONEq(t, `"requested-model"`, string(item["model"])) + require.JSONEq(t, `8`, string(item["api_key_id"])) + if scoped { + require.NotContains(t, w.Body.String(), "private-") + require.NotContains(t, w.Body.String(), "97531") + for _, field := range []string{"user", "api_key", "group", "subscription", "account", "balance", "credentials"} { + require.NotContains(t, item, field) + } + } else { + require.Contains(t, w.Body.String(), "private-api-key-secret") + require.Contains(t, w.Body.String(), "private-email@example.invalid") + require.Contains(t, item, "user") + require.Contains(t, item, "api_key") + require.Contains(t, item, "account") + } + require.Equal(t, "private-api-key-secret", repo.records[0].APIKey.Key, "输出投影不得修改服务返回对象") + }) + } +} +func TestScopedAdminUsageListEmptyRemainsArray(t *testing.T) { + gin.SetMode(gin.TestMode) + h := NewUsageHandler(service.NewUsageService(&scopedUsageResponseRepo{}, nil, nil, nil), nil, nil, nil) + r := gin.New() + r.Use(func(c *gin.Context) { + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{})) + }) + r.GET("/usage", h.List) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/usage", nil)) + require.Equal(t, 200, w.Code) + require.Contains(t, w.Body.String(), `"items":[]`) +} diff --git a/backend/internal/handler/admin/setting_handler_runtime.go b/backend/internal/handler/admin/setting_handler_runtime.go index 972604e0a8..3cc4ef4b60 100644 --- a/backend/internal/handler/admin/setting_handler_runtime.go +++ b/backend/internal/handler/admin/setting_handler_runtime.go @@ -13,6 +13,9 @@ import ( // GetAdminAPIKey 获取管理员 API Key 状态 // GET /api/v1/admin/settings/admin-api-key func (h *SettingHandler) GetAdminAPIKey(c *gin.Context) { + if !requireAdminKeyJWT(c) { + return + } maskedKey, exists, err := h.settingService.GetAdminAPIKeyStatus(c.Request.Context()) if err != nil { response.ErrorFrom(c, err) @@ -25,9 +28,21 @@ func (h *SettingHandler) GetAdminAPIKey(c *gin.Context) { }) } -// RegenerateAdminAPIKey 生成/重新生成管理员 API Key +// RegenerateAdminAPIKey 轮换已存在的旧版管理员 API Key // POST /api/v1/admin/settings/admin-api-key/regenerate func (h *SettingHandler) RegenerateAdminAPIKey(c *gin.Context) { + if !requireAdminKeyJWT(c) { + return + } + _, exists, err := h.settingService.GetAdminAPIKeyStatus(c.Request.Context()) + if err != nil { + response.ErrorFrom(c, err) + return + } + if !exists { + response.Error(c, 403, "旧版密钥已停止新建,请创建权限管理密钥") + return + } key, err := h.settingService.GenerateAdminAPIKey(c.Request.Context()) if err != nil { response.ErrorFrom(c, err) @@ -42,6 +57,9 @@ func (h *SettingHandler) RegenerateAdminAPIKey(c *gin.Context) { // DeleteAdminAPIKey 删除管理员 API Key // DELETE /api/v1/admin/settings/admin-api-key func (h *SettingHandler) DeleteAdminAPIKey(c *gin.Context) { + if !requireAdminKeyJWT(c) { + return + } if err := h.settingService.DeleteAdminAPIKey(c.Request.Context()); err != nil { response.ErrorFrom(c, err) return diff --git a/backend/internal/handler/admin/subscription_handler.go b/backend/internal/handler/admin/subscription_handler.go index 2174e18840..2de88893e7 100644 --- a/backend/internal/handler/admin/subscription_handler.go +++ b/backend/internal/handler/admin/subscription_handler.go @@ -94,7 +94,7 @@ func (h *SubscriptionHandler) List(c *gin.Context) { for i := range subscriptions { out = append(out, *dto.UserSubscriptionFromServiceAdmin(&subscriptions[i])) } - response.PaginatedWithResult(c, out, toResponsePagination(pagination)) + response.PaginatedWithResult(c, adminSubscriptionResponse(c, out), toResponsePagination(pagination)) } // GetByID handles getting a subscription by ID @@ -112,7 +112,7 @@ func (h *SubscriptionHandler) GetByID(c *gin.Context) { return } - response.Success(c, dto.UserSubscriptionFromServiceAdmin(subscription)) + response.Success(c, adminSubscriptionResponse(c, dto.UserSubscriptionFromServiceAdmin(subscription))) } // GetProgress handles getting subscription usage progress @@ -157,7 +157,7 @@ func (h *SubscriptionHandler) Assign(c *gin.Context) { return } - response.Success(c, dto.UserSubscriptionFromServiceAdmin(subscription)) + response.Success(c, adminSubscriptionResponse(c, dto.UserSubscriptionFromServiceAdmin(subscription))) } // BulkAssign handles bulk assigning subscriptions to multiple users @@ -184,7 +184,7 @@ func (h *SubscriptionHandler) BulkAssign(c *gin.Context) { return } - response.Success(c, dto.BulkAssignResultFromService(result)) + response.Success(c, adminSubscriptionResponse(c, dto.BulkAssignResultFromService(result))) } // BulkAction applies one operation to selected subscriptions, returning each outcome. @@ -226,13 +226,13 @@ func (h *SubscriptionHandler) Extend(c *gin.Context) { SubscriptionID: subscriptionID, Body: req, } - executeAdminIdempotentJSON(c, "admin.subscriptions.extend", idempotencyPayload, service.DefaultWriteIdempotencyTTL(), func(ctx context.Context) (any, error) { + executeAdminIdempotentJSONWithResponse(c, "admin.subscriptions.extend", idempotencyPayload, service.DefaultWriteIdempotencyTTL(), func(ctx context.Context) (any, error) { subscription, execErr := h.subscriptionService.ExtendSubscription(ctx, subscriptionID, req.Days) if execErr != nil { return nil, execErr } return dto.UserSubscriptionFromServiceAdmin(subscription), nil - }) + }, func(data any) any { return adminSubscriptionResponse(c, data) }) } // ResetSubscriptionQuotaRequest represents the reset quota request @@ -264,7 +264,7 @@ func (h *SubscriptionHandler) ResetQuota(c *gin.Context) { response.ErrorFrom(c, err) return } - response.Success(c, dto.UserSubscriptionFromServiceAdmin(sub)) + response.Success(c, adminSubscriptionResponse(c, dto.UserSubscriptionFromServiceAdmin(sub))) } // Revoke handles revoking a subscription. @@ -301,7 +301,7 @@ func (h *SubscriptionHandler) Restore(c *gin.Context) { return } - response.Success(c, dto.UserSubscriptionFromServiceAdmin(subscription)) + response.Success(c, adminSubscriptionResponse(c, dto.UserSubscriptionFromServiceAdmin(subscription))) } // ListByGroup handles listing subscriptions for a specific group @@ -325,7 +325,7 @@ func (h *SubscriptionHandler) ListByGroup(c *gin.Context) { for i := range subscriptions { out = append(out, *dto.UserSubscriptionFromServiceAdmin(&subscriptions[i])) } - response.PaginatedWithResult(c, out, toResponsePagination(pagination)) + response.PaginatedWithResult(c, adminSubscriptionResponse(c, out), toResponsePagination(pagination)) } // ListByUser handles listing subscriptions for a specific user @@ -347,7 +347,7 @@ func (h *SubscriptionHandler) ListByUser(c *gin.Context) { for i := range subscriptions { out = append(out, *dto.UserSubscriptionFromServiceAdmin(&subscriptions[i])) } - response.Success(c, out) + response.Success(c, adminSubscriptionResponse(c, out)) } // Helper function to get admin ID from context diff --git a/backend/internal/handler/admin/usage_handler.go b/backend/internal/handler/admin/usage_handler.go index 4fe37f087f..eb06d59cd4 100644 --- a/backend/internal/handler/admin/usage_handler.go +++ b/backend/internal/handler/admin/usage_handler.go @@ -213,11 +213,7 @@ func (h *UsageHandler) List(c *gin.Context) { return } - out := make([]dto.AdminUsageLog, 0, len(records)) - for i := range records { - out = append(out, *dto.UsageLogFromServiceAdmin(&records[i])) - } - response.Paginated(c, out, result.Total, page, pageSize) + response.Paginated(c, adminUsageLogResponses(c, records), result.Total, page, pageSize) } // Stats handles getting usage statistics with filters diff --git a/backend/internal/handler/admin/user_handler.go b/backend/internal/handler/admin/user_handler.go index 817bfa9117..ceffd27947 100644 --- a/backend/internal/handler/admin/user_handler.go +++ b/backend/internal/handler/admin/user_handler.go @@ -12,6 +12,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/handler/dto" "github.com/Wei-Shaw/sub2api/internal/handler/quotaview" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" "github.com/Wei-Shaw/sub2api/internal/pkg/response" "github.com/Wei-Shaw/sub2api/internal/server/middleware" "github.com/Wei-Shaw/sub2api/internal/service" @@ -150,6 +151,11 @@ func (h *UserHandler) List(c *gin.Context) { includeSubscriptions := parseBoolQueryWithDefault(raw, true) filters.IncludeSubscriptions = &includeSubscriptions } + principal := adminaccess.FromContext(c.Request.Context()) + if principal != nil { + includeSubscriptions := false + filters.IncludeSubscriptions = &includeSubscriptions + } users, total, err := h.adminService.ListUsers(c.Request.Context(), page, pageSize, filters, sortBy, sortOrder) if err != nil { @@ -157,6 +163,15 @@ func (h *UserHandler) List(c *gin.Context) { return } + if principal != nil { + out := make([]any, len(users)) + for i := range users { + out[i] = adminUserResponse(c, &users[i]) + } + response.Paginated(c, out, total, page, pageSize) + return + } + // Batch get current concurrency (nil map if unavailable) var loadInfo map[int64]*service.UserLoadInfo if len(users) > 0 && h.concurrencyService != nil { @@ -227,7 +242,7 @@ func (h *UserHandler) GetByID(c *gin.Context) { return } - response.Success(c, dto.UserFromServiceAdmin(user)) + response.Success(c, adminUserResponse(c, user)) } // BindAuthIdentity manually binds a canonical auth identity to a user. @@ -407,12 +422,18 @@ func (h *UserHandler) UpdateBalance(c *gin.Context) { UserID: userID, Body: req, } - executeAdminIdempotentJSON(c, "admin.users.balance.update", idempotencyPayload, service.DefaultWriteIdempotencyTTL(), func(ctx context.Context) (any, error) { + executeAdminIdempotentJSONWithResponse(c, "admin.users.balance.update", idempotencyPayload, service.DefaultWriteIdempotencyTTL(), func(ctx context.Context) (any, error) { user, execErr := h.adminService.UpdateUserBalance(ctx, userID, req.Balance, req.Operation, req.Notes) if execErr != nil { return nil, execErr } return dto.UserFromServiceAdmin(user), nil + }, func(data any) any { + // 成功确认不隐式授予用户资料或余额读取权限;缓存重放也必须经过此边界。 + if adminaccess.FromContext(c.Request.Context()) != nil { + return gin.H{"id": userID} + } + return data }) } @@ -884,6 +905,10 @@ func (h *UserHandler) UpdateUserPlatformQuotas(c *gin.Context) { } // 返回最新状态 + if scopedAdminWriteOnly(c, "users.quotas.read") { + response.Success(c, gin.H{"id": userID}) + return + } now := time.Now().UTC() records2, err := h.userPlatformQuotaRepo.ListByUser(ctx, userID) if err != nil { @@ -966,6 +991,11 @@ func (h *UserHandler) ResetUserPlatformQuotaWindow(c *gin.Context) { } } + if scopedAdminWriteOnly(c, "users.quotas.read") { + response.Success(c, gin.H{"id": userID}) + return + } + records, err := h.userPlatformQuotaRepo.ListByUser(ctx, userID) if err != nil { response.ErrorFrom(c, err) diff --git a/backend/internal/pkg/adminaccess/catalog.go b/backend/internal/pkg/adminaccess/catalog.go new file mode 100644 index 0000000000..d8dbe44b55 --- /dev/null +++ b/backend/internal/pkg/adminaccess/catalog.go @@ -0,0 +1,106 @@ +package adminaccess + +import "slices" + +type Permission struct { + ID string `json:"id"` + Label string `json:"label"` + Category string `json:"category"` + Scope string `json:"scope"` +} + +type permissionDefinition struct { + Permission + Routes []string +} + +// 接口按方法和 Gin 完整路径精确登记;新增接口不会继承同目录权限。 +// 全站权限与账户规则独立,选中分组绝不会隐式授予全站操作。 +var definitions = []permissionDefinition{ + {Permission{"accounts.read", "查看账户(脱敏)", "账户", "account"}, []string{"GET /accounts", "GET /accounts/:id", "GET /accounts/:id/models"}}, + {Permission{"accounts.create", "创建账户", "账户", "account"}, []string{"POST /accounts", "POST /accounts/import/codex-session"}}, + {Permission{"accounts.update", "编辑名称与备注", "账户", "account"}, []string{"PUT /accounts/:id"}}, + {Permission{"accounts.credentials", "写入凭证(不包含读取)", "账户", "account"}, []string{"PUT /accounts/:id"}}, + {Permission{"accounts.models.write", "编辑账户白名单模型 ID 与映射", "账户", "account"}, []string{"PUT /accounts/:id", "POST /accounts/bulk-update"}}, + {Permission{"accounts.network", "修改接入地址、代理与连接选项", "账户", "account"}, []string{"PUT /accounts/:id"}}, + {Permission{"accounts.status", "启用、停用与调度开关", "账户", "account"}, []string{"PUT /accounts/:id", "POST /accounts/:id/schedulable"}}, + {Permission{"accounts.schedule", "修改并发、优先级与有效期", "账户", "account"}, []string{"PUT /accounts/:id"}}, + {Permission{"accounts.refresh", "刷新 OAuth 凭证", "账户", "account"}, []string{"POST /accounts/:id/refresh"}}, + {Permission{"accounts.recover", "清除账户错误与限流状态", "账户", "account"}, []string{"POST /accounts/:id/clear-error"}}, + {Permission{"accounts.delete", "删除账户(影响共享分组)", "账户", "account"}, []string{"DELETE /accounts/:id"}}, + {Permission{"accounts.groups", "调整授权分组关联", "账户", "account"}, []string{"PUT /accounts/:id"}}, + {Permission{"groups.models.read", "读取所选分组模型白名单与候选 ID", "分组模型", "group"}, []string{"GET /groups", "GET /groups/all", "GET /groups/:id", "GET /groups/:id/model-allowlist-candidates"}}, + {Permission{"groups.models.write", "编辑所选分组模型白名单(影响整个分组)", "分组模型", "group"}, []string{"PUT /groups/:id"}}, + {Permission{"proxies.read", "读取代理 IP 候选(分页,不含认证凭证)", "代理", "global"}, []string{"GET /proxies", "GET /proxies/all", "GET /proxies/:id"}}, + {Permission{"models.defaults.read", "读取默认白名单模型 ID(含默认映射)", "模型", "global"}, []string{"GET /accounts/antigravity/default-model-mapping", "GET /groups/:id/model-allowlist-candidates"}}, + {Permission{"dashboard.read", "读取全站经营报表", "报表", "global"}, []string{"GET /dashboard/snapshot-v2", "GET /dashboard/stats", "GET /dashboard/realtime", "GET /dashboard/trend", "GET /dashboard/models", "GET /dashboard/groups", "GET /dashboard/api-keys-trend", "GET /dashboard/users-trend", "GET /dashboard/users-ranking", "POST /dashboard/users-usage", "POST /dashboard/api-keys-usage", "GET /dashboard/user-breakdown"}}, + {Permission{"users.read", "读取全站用户资料(含联系方式)", "用户", "global"}, []string{"GET /users", "GET /users/:id", "GET /users/:id/rpm-status", "GET /users/:id/attributes"}}, + {Permission{"users.balance.read", "读取全站用户余额及流水", "财务", "global"}, []string{"GET /users/:id/balance-history"}}, + {Permission{"users.balance.write", "增减任意用户余额", "财务", "global"}, []string{"POST /users/:id/balance"}}, + {Permission{"users.quotas.read", "读取全站用户平台额度", "用户", "global"}, []string{"GET /users/:id/platform-quotas"}}, + {Permission{"users.quotas.write", "修改与重置全站用户平台额度", "用户", "global"}, []string{"PUT /users/:id/platform-quotas", "POST /users/:id/platform-quotas/reset"}}, + {Permission{"groups.read", "读取所有分组配置", "分组", "global"}, []string{"GET /groups", "GET /groups/all", "GET /groups/:id", "GET /groups/:id/rate-multipliers", "GET /groups/:id/composite-routes", "GET /groups/:id/model-allowlist-candidates"}}, + {Permission{"usage.read", "读取全站用量明细及用户用量", "报表", "global"}, []string{"GET /usage", "GET /usage/stats", "GET /users/:id/usage"}}, + {Permission{"payment.read", "读取全站支付订单与报表", "财务", "global"}, []string{"GET /payment/dashboard", "GET /payment/orders", "GET /payment/orders/:id"}}, + {Permission{"payment.cancel", "取消支付订单", "财务", "global"}, []string{"POST /payment/orders/:id/cancel"}}, + {Permission{"payment.fulfill", "重新履约支付订单", "财务", "global"}, []string{"POST /payment/orders/:id/retry"}}, + {Permission{"payment.refund", "发起退款及确认退款结果", "财务", "global"}, []string{"POST /payment/orders/:id/refund", "POST /payment/orders/:id/refund/query"}}, + {Permission{"payment.plans.read", "读取全部支付套餐", "财务", "global"}, []string{"GET /payment/plans"}}, + {Permission{"payment.plans.write", "创建、修改和删除支付套餐", "财务", "global"}, []string{"POST /payment/plans", "PUT /payment/plans/:id", "DELETE /payment/plans/:id"}}, + {Permission{"subscriptions.read", "读取全站订阅记录", "订阅", "global"}, []string{"GET /subscriptions", "GET /subscriptions/:id", "GET /subscriptions/:id/progress", "GET /groups/:id/subscriptions", "GET /users/:id/subscriptions"}}, + {Permission{"subscriptions.assign", "分配全站用户订阅", "订阅", "global"}, []string{"POST /subscriptions/assign", "POST /subscriptions/bulk-assign"}}, + {Permission{"subscriptions.extend", "延长订阅有效期", "订阅", "global"}, []string{"POST /subscriptions/:id/extend"}}, + {Permission{"subscriptions.revoke", "撤销订阅", "订阅", "global"}, []string{"POST /subscriptions/:id/revoke", "DELETE /subscriptions/:id"}}, + {Permission{"subscriptions.restore", "恢复订阅", "订阅", "global"}, []string{"POST /subscriptions/:id/restore"}}, + {Permission{"subscriptions.reset", "重置订阅额度", "订阅", "global"}, []string{"POST /subscriptions/:id/reset-quota"}}, + {Permission{"announcements.read", "读取所有公告与阅读记录", "内容", "global"}, []string{"GET /announcements", "GET /announcements/:id", "GET /announcements/:id/read-status"}}, + {Permission{"announcements.write", "创建、发布与修改公告", "内容", "global"}, []string{"POST /announcements", "PUT /announcements/:id"}}, + {Permission{"announcements.delete", "删除公告", "内容", "global"}, []string{"DELETE /announcements/:id"}}, + {Permission{"promo.read", "读取优惠码及使用记录", "财务", "global"}, []string{"GET /promo-codes", "GET /promo-codes/:id", "GET /promo-codes/:id/usages"}}, + {Permission{"promo.write", "创建与修改优惠码权益", "财务", "global"}, []string{"POST /promo-codes", "PUT /promo-codes/:id"}}, + {Permission{"promo.delete", "删除优惠码", "财务", "global"}, []string{"DELETE /promo-codes/:id"}}, + {Permission{"ops.read", "读取全站运维指标", "监控", "global"}, []string{"GET /ops/concurrency", "GET /ops/user-concurrency", "GET /ops/account-availability", "GET /ops/realtime-traffic", "GET /ops/ingress-rejections", "GET /ops/ingress-rejections/health", "GET /ops/auth-cache-invalidation/health", "GET /ops/dashboard/snapshot-v2", "GET /ops/dashboard/overview", "GET /ops/dashboard/throughput-trend", "GET /ops/dashboard/latency-histogram", "GET /ops/dashboard/error-trend", "GET /ops/dashboard/error-distribution", "GET /ops/dashboard/openai-token-stats"}}, + {Permission{"ops.errors.read", "读取全站请求错误详情(敏感)", "监控", "global"}, []string{"GET /ops/errors", "GET /ops/errors/:id", "GET /ops/request-errors", "GET /ops/request-errors/:id", "GET /ops/request-errors/:id/upstream-errors", "GET /ops/upstream-errors", "GET /ops/upstream-errors/:id", "GET /ops/requests"}}, + {Permission{"ops.errors.resolve", "标记请求错误处理状态", "监控", "global"}, []string{"PUT /ops/errors/:id/resolve", "PUT /ops/request-errors/:id/resolve", "PUT /ops/upstream-errors/:id/resolve"}}, + {Permission{"ops.alerts.read", "读取全站告警规则与事件", "监控", "global"}, []string{"GET /ops/alert-rules", "GET /ops/alert-events", "GET /ops/alert-events/:id"}}, + {Permission{"ops.alerts.write", "修改告警规则、状态与静默", "监控", "global"}, []string{"POST /ops/alert-rules", "PUT /ops/alert-rules/:id", "DELETE /ops/alert-rules/:id", "PUT /ops/alert-events/:id/status", "POST /ops/alert-silences"}}, + {Permission{"system.read", "读取系统版本与可更新版本", "系统", "global"}, []string{"GET /system/version", "GET /system/check-updates", "GET /system/rollback-versions"}}, +} + +func PermissionCatalog() []Permission { + result := make([]Permission, 0, len(definitions)) + for _, definition := range definitions { + result = append(result, definition.Permission) + } + return result +} + +// RouteAllowed 只检查动作准入;账户资源及字段必须再由专用处理器检查。 +func RouteAllowed(policy Policy, method, path string) bool { + target := method + " " + path + for _, definition := range definitions { + matched := false + for _, route := range definition.Routes { + // route 的方法前缀与资源路径固定,不做前缀通配或按 HTTP 方法推断读写。 + for i, ch := range route { + if ch == ' ' { + matched = target == route[:i]+" /api/v1/admin"+route[i+1:] + break + } + } + if matched { + break + } + } + if !matched { + continue + } + if definition.Scope == "global" && slices.Contains(policy.GlobalPermissions, definition.ID) { + return true + } + if (definition.Scope == "account" || definition.Scope == "group") && len(policy.RulesFor(definition.ID)) > 0 { + return true + } + } + return false +} diff --git a/backend/internal/pkg/adminaccess/policy.go b/backend/internal/pkg/adminaccess/policy.go new file mode 100644 index 0000000000..2eaf07b5ed --- /dev/null +++ b/backend/internal/pkg/adminaccess/policy.go @@ -0,0 +1,154 @@ +// Package adminaccess 定义管理密钥的显式授权,不依赖 HTTP 或数据库实现。 +package adminaccess + +import ( + "context" + "fmt" + "slices" + "strings" +) + +type Rule struct { + Permissions []string `json:"permissions"` + GroupIDs []int64 `json:"group_ids"` + AllGroups bool `json:"all_groups"` + IncludeUngrouped bool `json:"include_ungrouped"` + AccountTypes []string `json:"account_types"` + Platforms []string `json:"platforms"` +} + +type Policy struct { + Rules []Rule `json:"rules"` + GlobalPermissions []string `json:"global_permissions"` +} + +type Principal struct { + KeyID string + KeyName string + CreatorID int64 + Policy Policy +} + +type Account struct { + ID int64 + GroupIDs []int64 + Type string + Platform string +} + +type principalContextKey struct{} + +func WithPrincipal(ctx context.Context, principal *Principal) context.Context { + return context.WithValue(ctx, principalContextKey{}, principal) +} + +func FromContext(ctx context.Context) *Principal { + principal, _ := ctx.Value(principalContextKey{}).(*Principal) + return principal +} + +// Matches 保持分组、类型和平台在同一规则中匹配,不拆开合并授权条件。 +func (r Rule) Matches(a Account) bool { + if !slices.Contains(r.AccountTypes, a.Type) || (len(r.Platforms) > 0 && !slices.Contains(r.Platforms, a.Platform)) { + return false + } + if len(a.GroupIDs) == 0 { + return r.IncludeUngrouped + } + if r.AllGroups { + return true + } + for _, id := range a.GroupIDs { + if id > 0 && slices.Contains(r.GroupIDs, id) { + return true + } + } + return false +} + +func (p Policy) RulesFor(permission string) []Rule { + rules := make([]Rule, 0) + for _, r := range p.Rules { + if slices.Contains(r.Permissions, permission) { + rules = append(rules, r) + } + } + return rules +} + +func (p Policy) AllowsAccount(permission string, a Account) bool { + for _, r := range p.RulesFor(permission) { + if r.Matches(a) { + return true + } + } + return false +} + +// AllowsGroup 只有当前账户及目标分组在同一授权规则内,才能调整该关联。 +func (p Policy) AllowsGroup(permission string, a Account, groupID int64) bool { + if groupID <= 0 { + return false + } + for _, r := range p.RulesFor(permission) { + if r.Matches(a) && (r.AllGroups || slices.Contains(r.GroupIDs, groupID)) { + return true + } + } + return false +} + +// AllowsGroupConfig 只授权显式勾选的分组配置动作;账户类型不适用于整个分组的配置。 +// 分组与平台仍须命中同一规则,不能从不同规则拼接授权。 +func (p Policy) AllowsGroupConfig(permission string, id int64, platform string) bool { + if id <= 0 { + return false + } + for _, r := range p.RulesFor(permission) { + if (r.AllGroups || slices.Contains(r.GroupIDs, id)) && (len(r.Platforms) == 0 || slices.Contains(r.Platforms, platform)) { + return true + } + } + return false +} + +func ValidatePolicy(p Policy) error { + if len(p.Rules) > 32 || len(p.GlobalPermissions) > 128 { + return fmt.Errorf("授权规则数量超过限制") + } + catalog := make(map[string]string) + for _, permission := range PermissionCatalog() { + catalog[permission.ID] = permission.Scope + } + for _, permission := range p.GlobalPermissions { + if catalog[permission] != "global" { + return fmt.Errorf("无效的全站权限:%s", permission) + } + } + for _, r := range p.Rules { + if len(r.Permissions) > 64 || len(r.GroupIDs) > 1000 || len(r.AccountTypes) > 32 || len(r.Platforms) > 64 { + return fmt.Errorf("授权范围超过限制") + } + for _, permission := range r.Permissions { + if catalog[permission] != "account" && catalog[permission] != "group" { + return fmt.Errorf("无效的资源权限:%s", permission) + } + } + for _, id := range r.GroupIDs { + if id <= 0 { + return fmt.Errorf("分组 ID 必须是正整数") + } + } + for _, kind := range r.AccountTypes { + if !slices.Contains([]string{"oauth", "setup-token", "apikey", "upstream", "bedrock", "service_account"}, kind) { + return fmt.Errorf("无效的账户类型:%s", kind) + } + } + for _, platform := range r.Platforms { + if strings.TrimSpace(platform) != platform || platform == "" || len(platform) > 64 || platform == "*" { + return fmt.Errorf("无效的平台") + } + } + } + return nil +} diff --git a/backend/internal/pkg/adminaccess/policy_test.go b/backend/internal/pkg/adminaccess/policy_test.go new file mode 100644 index 0000000000..ef415487c0 --- /dev/null +++ b/backend/internal/pkg/adminaccess/policy_test.go @@ -0,0 +1,144 @@ +//go:build unit + +package adminaccess + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestScopedAdminPolicyDefaultDeny(t *testing.T) { + selectedGroupsOnly := Policy{Rules: []Rule{{GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}}}} + for _, policy := range []Policy{{}, selectedGroupsOnly} { + for _, route := range []struct{ method, path string }{ + {"GET", "/api/v1/admin/accounts"}, {"GET", "/api/v1/admin/accounts/:id"}, + {"PUT", "/api/v1/admin/settings"}, {"GET", "/api/v1/admin/users"}, + {"POST", "/api/v1/admin/payment/orders/:id/refund"}, + {"POST", "/api/v1/admin/settings/admin-api-keys"}, + } { + require.False(t, RouteAllowed(policy, route.method, route.path), route.path) + } + } +} + +func TestScopedAdminModelPermissionsAreIndependent(t *testing.T) { + write := Policy{Rules: []Rule{{Permissions: []string{"accounts.models.write"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}}}} + read := Policy{GlobalPermissions: []string{"models.defaults.read"}} + require.NoError(t, ValidatePolicy(write)) + require.NoError(t, ValidatePolicy(read)) + require.True(t, RouteAllowed(write, "PUT", "/api/v1/admin/accounts/:id")) + for _, path := range []string{"/api/v1/admin/accounts/antigravity/default-model-mapping"} { + require.True(t, RouteAllowed(read, "GET", path)) + require.False(t, RouteAllowed(write, "GET", path)) + require.False(t, RouteAllowed(Policy{}, "GET", path)) + } + for _, policy := range []Policy{write, read} { + require.False(t, RouteAllowed(policy, "PUT", "/api/v1/admin/model-catalog/:platform")) + require.False(t, RouteAllowed(policy, "DELETE", "/api/v1/admin/model-catalog/:platform")) + require.False(t, RouteAllowed(policy, "GET", "/api/v1/admin/accounts/:id/models")) + require.False(t, RouteAllowed(policy, "POST", "/api/v1/admin/accounts/:id/models/sync-upstream")) + } +} + +func TestScopedAdminPolicyAccountRulesNeverCrossProduct(t *testing.T) { + p := Policy{Rules: []Rule{ + {Permissions: []string{"accounts.read", "accounts.refresh"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}, + {Permissions: []string{"accounts.read"}, GroupIDs: []int64{2}, AccountTypes: []string{"apikey"}}, + }} + for _, tc := range []struct { + name, permission string + account Account + allowed bool + }{ + {"组内OAuth", "accounts.refresh", Account{GroupIDs: []int64{1}, Type: "oauth", Platform: "openai"}, true}, + {"共享账户任一组匹配", "accounts.refresh", Account{GroupIDs: []int64{1, 9}, Type: "oauth", Platform: "openai"}, true}, + {"其他类型拒绝", "accounts.refresh", Account{GroupIDs: []int64{1}, Type: "apikey", Platform: "openai"}, false}, + {"其他组拒绝", "accounts.refresh", Account{GroupIDs: []int64{9}, Type: "oauth", Platform: "openai"}, false}, + {"其他平台拒绝", "accounts.refresh", Account{GroupIDs: []int64{1}, Type: "oauth", Platform: "anthropic"}, false}, + {"不能借另一规则提权", "accounts.refresh", Account{GroupIDs: []int64{2}, Type: "apikey", Platform: "openai"}, false}, + {"setup-token不能冒充OAuth", "accounts.read", Account{GroupIDs: []int64{1}, Type: "setup-token", Platform: "openai"}, false}, + {"未分组默认拒绝", "accounts.read", Account{Type: "oauth", Platform: "openai"}, false}, + } { + t.Run(tc.name, func(t *testing.T) { require.Equal(t, tc.allowed, p.AllowsAccount(tc.permission, tc.account)) }) + } + require.True(t, RouteAllowed(p, "GET", "/api/v1/admin/accounts")) + require.False(t, RouteAllowed(p, "DELETE", "/api/v1/admin/accounts/:id")) + require.False(t, RouteAllowed(p, "GET", "/api/v1/admin/groups")) + require.False(t, RouteAllowed(p, "POST", "/api/v1/admin/openai/refresh-token")) +} + +func TestScopedAdminPolicyGroupChanges(t *testing.T) { + a := Account{GroupIDs: []int64{1, 2}, Type: "oauth", Platform: "openai"} + p := Policy{Rules: []Rule{{Permissions: []string{"accounts.groups"}, GroupIDs: []int64{1, 3}, AccountTypes: []string{"oauth"}}}} + require.True(t, p.AllowsGroup("accounts.groups", a, 1)) + require.True(t, p.AllowsGroup("accounts.groups", a, 3)) + require.False(t, p.AllowsGroup("accounts.groups", a, 2)) + require.False(t, p.AllowsGroup("accounts.groups", Account{GroupIDs: []int64{2}, Type: "oauth"}, 1)) + require.False(t, p.AllowsGroup("accounts.groups", a, 0)) +} + +func TestScopedAdminPolicyExplicitAllAndUngrouped(t *testing.T) { + p := Policy{Rules: []Rule{{Permissions: []string{"accounts.read"}, AllGroups: true, AccountTypes: []string{"oauth"}}}} + require.True(t, p.AllowsAccount("accounts.read", Account{GroupIDs: []int64{999}, Type: "oauth"})) + require.False(t, p.AllowsAccount("accounts.read", Account{Type: "oauth"})) + p.Rules[0].IncludeUngrouped = true + require.True(t, p.AllowsAccount("accounts.read", Account{Type: "oauth"})) + p.Rules[0].AccountTypes = nil + require.False(t, p.AllowsAccount("accounts.read", Account{Type: "oauth"})) +} + +func TestScopedAdminPolicyValidationAndGlobalIsolation(t *testing.T) { + require.NoError(t, ValidatePolicy(Policy{})) + for _, p := range []Policy{ + {GlobalPermissions: []string{"*"}}, {GlobalPermissions: []string{"accounts.read"}}, + {Rules: []Rule{{Permissions: []string{"users.read"}}}}, + {Rules: []Rule{{Permissions: []string{"accounts.read"}, GroupIDs: []int64{-1}}}}, + {Rules: []Rule{{AccountTypes: []string{"future_type"}}}}, + } { + require.Error(t, ValidatePolicy(p)) + } + p := Policy{GlobalPermissions: []string{"users.read"}} + require.NoError(t, ValidatePolicy(p)) + require.True(t, RouteAllowed(p, "GET", "/api/v1/admin/users")) + require.False(t, RouteAllowed(p, "PUT", "/api/v1/admin/users/:id")) + require.False(t, RouteAllowed(p, "POST", "/api/v1/admin/users/:id/balance")) + require.False(t, RouteAllowed(p, "GET", "/api/v1/admin/accounts/:id")) + all := Policy{} + for _, perm := range PermissionCatalog() { + if perm.Scope == "global" { + all.GlobalPermissions = append(all.GlobalPermissions, perm.ID) + } else { + all.Rules = append(all.Rules, Rule{Permissions: []string{perm.ID}, AllGroups: true, IncludeUngrouped: true, AccountTypes: []string{"oauth", "apikey"}}) + } + } + for _, path := range []string{"/api/v1/admin/future-endpoint", "/api/v1/admin/settings/admin-api-key/regenerate", "/api/v1/admin/settings/admin-api-keys", "/api/v1/admin/system/restart", "/api/v1/admin/accounts/data", "/api/v1/admin/backups/:id/download-url"} { + for _, method := range []string{"GET", "POST", "PUT", "DELETE"} { + require.False(t, RouteAllowed(all, method, path), method+" "+path) + } + } +} + +func TestScopedAdminPrincipalContext(t *testing.T) { + require.Nil(t, FromContext(context.Background())) + p := &Principal{KeyID: "key-1", KeyName: "只读"} + require.Same(t, p, FromContext(WithPrincipal(context.Background(), p))) +} + +func TestScopedAdminGroupModelsAreExplicitAndScoped(t *testing.T) { + p := Policy{Rules: []Rule{ + {Permissions: []string{"groups.models.read"}, GroupIDs: []int64{2}, Platforms: []string{"openai"}}, + {Permissions: []string{"groups.models.write"}, GroupIDs: []int64{3}, Platforms: []string{"anthropic"}}, + }} + require.NoError(t, ValidatePolicy(p)) + require.True(t, p.AllowsGroupConfig("groups.models.read", 2, "openai")) + require.False(t, p.AllowsGroupConfig("groups.models.write", 2, "openai")) + require.False(t, p.AllowsGroupConfig("groups.models.read", 3, "openai")) + require.False(t, p.AllowsGroupConfig("groups.models.read", 2, "anthropic")) + require.False(t, p.AllowsGroupConfig("groups.models.read", 0, "openai")) + require.False(t, p.AllowsAccount("accounts.read", Account{GroupIDs: []int64{2}, Type: "oauth", Platform: "openai"})) + require.True(t, RouteAllowed(p, "GET", "/api/v1/admin/groups")) + require.False(t, RouteAllowed(p, "DELETE", "/api/v1/admin/groups/:id")) + require.Error(t, ValidatePolicy(Policy{GlobalPermissions: []string{"groups.models.write"}})) +} diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index 781928aea2..d3f8b5d9a9 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -25,6 +25,7 @@ import ( dbgroup "github.com/Wei-Shaw/sub2api/ent/group" dbpredicate "github.com/Wei-Shaw/sub2api/ent/predicate" dbproxy "github.com/Wei-Shaw/sub2api/ent/proxy" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" "github.com/Wei-Shaw/sub2api/internal/service" @@ -125,6 +126,9 @@ func newAccountRepositoryWithSQL(client *dbent.Client, sqlq sqlExecutor, schedul } func (r *accountRepository) Create(ctx context.Context, account *service.Account) error { + if scoped := r.accountTransactionScope(ctx); scoped != r { + return scoped.Create(ctx, account) + } if err := createAccountRecord(ctx, r.client, account); err != nil { return err } @@ -263,6 +267,9 @@ func (r *accountRepository) CreateWithAccountGroups(ctx context.Context, account } func (r *accountRepository) GetByID(ctx context.Context, id int64) (*service.Account, error) { + if scoped := r.accountTransactionScope(ctx); scoped != r { + return scoped.GetByID(ctx, id) + } m, err := r.client.Account.Query().Where(dbaccount.IDEQ(id)).Only(ctx) if err != nil { return nil, translatePersistenceError(err, service.ErrAccountNotFound, nil) @@ -439,6 +446,9 @@ func (r *accountRepository) ListCRSAccountIDs(ctx context.Context) (map[string]i } func (r *accountRepository) Update(ctx context.Context, account *service.Account) error { + if scoped := r.accountTransactionScope(ctx); scoped != r { + return scoped.Update(ctx, account) + } return r.updateAccount(ctx, account, nil, nil, account.RateMultiplier) } @@ -958,6 +968,9 @@ func (r *accountRepository) UpdateCredentials(ctx context.Context, id int64, cre } func (r *accountRepository) Delete(ctx context.Context, id int64) error { + if scoped := r.accountTransactionScope(ctx); scoped != r { + return scoped.Delete(ctx, id) + } groupIDs, err := r.loadAccountGroupIDs(ctx, id) if err != nil { return err @@ -1846,6 +1859,9 @@ func (r *accountRepository) syncSchedulerAccountSnapshots(ctx context.Context, a } func (r *accountRepository) ClearError(ctx context.Context, id int64) error { + if scoped := r.accountTransactionScope(ctx); scoped != r { + return scoped.ClearError(ctx, id) + } _, err := r.client.Account.Update(). Where(dbaccount.IDEQ(id)). SetStatus(service.StatusActive). @@ -1929,6 +1945,12 @@ func (r *accountRepository) GetGroups(ctx context.Context, accountID int64) ([]s } func (r *accountRepository) BindGroups(ctx context.Context, accountID int64, groupIDs []int64) error { + if scoped := r.accountTransactionScope(ctx); scoped != r { + return scoped.BindGroups(ctx, accountID, groupIDs) + } + if adminaccess.FromContext(ctx) != nil { + return r.scopedAdminBindGroups(ctx, accountID, groupIDs) + } existingGroupIDs, err := r.loadAccountGroupIDs(ctx, accountID) if err != nil { return err @@ -2551,6 +2573,9 @@ func (r *accountRepository) SetGrokCredentialTempUnschedulableIfMatch( } func (r *accountRepository) ClearTempUnschedulable(ctx context.Context, id int64) error { + if scoped := r.accountTransactionScope(ctx); scoped != r { + return scoped.ClearTempUnschedulable(ctx, id) + } _, err := r.sql.ExecContext(ctx, ` UPDATE accounts SET temp_unschedulable_until = NULL, @@ -2570,6 +2595,9 @@ func (r *accountRepository) ClearTempUnschedulable(ctx context.Context, id int64 } func (r *accountRepository) ClearRateLimit(ctx context.Context, id int64) error { + if scoped := r.accountTransactionScope(ctx); scoped != r { + return scoped.ClearRateLimit(ctx, id) + } _, err := r.client.Account.Update(). Where(dbaccount.IDEQ(id)). ClearRateLimitedAt(). @@ -2587,6 +2615,9 @@ func (r *accountRepository) ClearRateLimit(ctx context.Context, id int64) error } func (r *accountRepository) ClearAntigravityQuotaScopes(ctx context.Context, id int64) error { + if scoped := r.accountTransactionScope(ctx); scoped != r { + return scoped.ClearAntigravityQuotaScopes(ctx, id) + } client := clientFromContext(ctx, r.client) result, err := client.ExecContext( ctx, @@ -2611,6 +2642,9 @@ func (r *accountRepository) ClearAntigravityQuotaScopes(ctx context.Context, id } func (r *accountRepository) ClearModelRateLimits(ctx context.Context, id int64) error { + if scoped := r.accountTransactionScope(ctx); scoped != r { + return scoped.ClearModelRateLimits(ctx, id) + } client := clientFromContext(ctx, r.client) result, err := client.ExecContext( ctx, @@ -2673,6 +2707,9 @@ func (r *accountRepository) UpdateSessionWindowEnd(ctx context.Context, id int64 } func (r *accountRepository) SetSchedulable(ctx context.Context, id int64, schedulable bool) error { + if scoped := r.accountTransactionScope(ctx); scoped != r { + return scoped.SetSchedulable(ctx, id, schedulable) + } _, err := r.client.Account.Update(). Where(dbaccount.IDEQ(id)). SetSchedulable(schedulable). @@ -2731,6 +2768,9 @@ func (r *accountRepository) AutoPauseExpiredAccounts(ctx context.Context, now ti } func (r *accountRepository) UpdateExtra(ctx context.Context, id int64, updates map[string]any) error { + if scoped := r.accountTransactionScope(ctx); scoped != r { + return scoped.UpdateExtra(ctx, id, updates) + } updates = stripCodexFingerprintSeedFromExtraUpdate(updates) if len(updates) == 0 { return nil @@ -4072,6 +4112,9 @@ func (r *accountRepository) RevertProxyFallback(ctx context.Context, accountID i // ⚠️ 新增影子维度时:须更新此函数(或新增维度专用列举),并检查所有调用点(级联删除/一母一影校验/type 守卫),否则会静默漏掉新维度。 // 软删除行由 SoftDeleteMixin 拦截器自动排除,无需手写 deleted_at IS NULL。 func (r *accountRepository) ListShadowsByParent(ctx context.Context, parentID int64) ([]*service.Account, error) { + if scoped := r.accountTransactionScope(ctx); scoped != r { + return scoped.ListShadowsByParent(ctx, parentID) + } rows, err := r.client.Account.Query(). Where(dbaccount.ParentAccountIDEQ(parentID), dbaccount.QuotaDimensionEQ(dbaccount.QuotaDimensionSpark)). All(ctx) diff --git a/backend/internal/repository/custom_account_proxy_selection.go b/backend/internal/repository/custom_account_proxy_selection.go new file mode 100644 index 0000000000..c4d27de494 --- /dev/null +++ b/backend/internal/repository/custom_account_proxy_selection.go @@ -0,0 +1,46 @@ +package repository + +import ( + "context" + "fmt" + + dbent "github.com/Wei-Shaw/sub2api/ent" +) + +// SelectAccountProxy 在数据库内选出单个 ID,不把整个代理池或密码载入应用。 +// 最空闲选择持有事务级锁到绑定提交,防止并发推送全部观察到同一份空闲计数。 +func (r *proxyRepository) SelectAccountProxy(ctx context.Context, mode string) (int64, error) { + tx := dbent.TxFromContext(ctx) + if tx == nil { + return 0, fmt.Errorf("代理选择需要写事务") + } + client := tx.Client() + query := `SELECT p.id FROM proxies p WHERE p.deleted_at IS NULL AND p.status='active' AND (p.expires_at IS NULL OR p.expires_at>NOW()) ORDER BY random() LIMIT 1` + switch mode { + case "random": + case "least_used": + if _, err := client.ExecContext(ctx, `SELECT pg_advisory_xact_lock(742319830125)`); err != nil { + return 0, err + } + query = `WITH bindings AS ( + SELECT a.id AS account_id,a.proxy_id FROM accounts a WHERE a.deleted_at IS NULL AND a.proxy_id IS NOT NULL + ), counts AS (SELECT proxy_id,COUNT(*) AS n FROM bindings GROUP BY proxy_id) + SELECT p.id FROM proxies p LEFT JOIN counts c ON c.proxy_id=p.id + WHERE p.deleted_at IS NULL AND p.status='active' AND (p.expires_at IS NULL OR p.expires_at>NOW()) + ORDER BY COALESCE(c.n,0),p.id LIMIT 1` + default: + return 0, fmt.Errorf("不支持的代理选择模式") + } + rows, err := client.QueryContext(ctx, query) + if err != nil { + return 0, err + } + defer func() { _ = rows.Close() }() + var id int64 + if rows.Next() { + if err = rows.Scan(&id); err != nil { + return 0, err + } + } + return id, rows.Err() +} diff --git a/backend/internal/repository/custom_account_proxy_selection_test.go b/backend/internal/repository/custom_account_proxy_selection_test.go new file mode 100644 index 0000000000..29317f9a93 --- /dev/null +++ b/backend/internal/repository/custom_account_proxy_selection_test.go @@ -0,0 +1,129 @@ +//go:build unit + +package repository + +import ( + "context" + "testing" + "time" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/stretchr/testify/require" +) + +func TestAccountProxySelectionLargePoolAndTransactionalLeastUsed(t *testing.T) { + db := scopedAdminKeyTestDB(t) + _, err := db.Exec(`CREATE TABLE proxies( + id BIGINT PRIMARY KEY,name TEXT DEFAULT '',protocol TEXT DEFAULT 'http',host TEXT DEFAULT '192.0.2.1',port INT DEFAULT 8080, + username TEXT DEFAULT 'SECRET_USER',password TEXT DEFAULT 'SECRET_PASSWORD',status TEXT DEFAULT 'active', + expires_at TIMESTAMPTZ,deleted_at TIMESTAMPTZ,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW(), + fallback_mode TEXT DEFAULT 'none',backup_proxy_id BIGINT,expiry_warn_days INT DEFAULT 7); + CREATE TABLE accounts(id BIGINT PRIMARY KEY,proxy_id BIGINT,deleted_at TIMESTAMPTZ); + INSERT INTO proxies(id) SELECT generate_series(1,20005); + UPDATE proxies SET status='inactive' WHERE id=1; + UPDATE proxies SET status='inactive' WHERE id=2; + UPDATE proxies SET expires_at=NOW()-INTERVAL '1 hour' WHERE id=3; + UPDATE proxies SET deleted_at=NOW() WHERE id=4; + INSERT INTO accounts VALUES(1,5,NULL),(2,6,NULL),(3,7,NULL),(4,8,NOW()); +`) + require.NoError(t, err) + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + repo := newProxyRepositoryWithSQL(client, db) + // 真实 2 万条池只返回指定页;不用账户聚合管理列表。 + items, page, err := repo.ListOptions(context.Background(), pagination.PaginationParams{Page: 2, PageSize: 100}, "") + require.NoError(t, err) + require.Len(t, items, 100) + require.EqualValues(t, 20002, page.Total) + require.EqualValues(t, 19905, items[0].ID) + _, err = repo.SelectAccountProxy(context.Background(), "random") + require.Error(t, err) + tx, err := client.Tx(context.Background()) + require.NoError(t, err) + defer tx.Rollback() + ctx := dbent.NewTxContext(context.Background(), tx) + selected, err := repo.SelectAccountProxy(ctx, "least_used") + require.NoError(t, err) + require.EqualValues(t, 8, selected, "软删账户不占用") + _, err = tx.Client().ExecContext(ctx, `INSERT INTO accounts VALUES(10,$1,NULL)`, selected) + require.NoError(t, err) + // 第二个事务必须等待第一个事务绑定提交,随后观察到新的计数。 + started := make(chan struct{}) + done := make(chan struct { + id int64 + err error + }, 1) + go func() { + other, err := client.Tx(context.Background()) + if err != nil { + done <- struct { + id int64 + err error + }{0, err} + return + } + defer other.Rollback() + c, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + c = dbent.NewTxContext(c, other) + close(started) + id, err := repo.SelectAccountProxy(c, "least_used") + done <- struct { + id int64 + err error + }{id, err} + }() + <-started + select { + case result := <-done: + t.Fatalf("选择不应越过尚未提交的分配: %+v", result) + case <-time.After(30 * time.Millisecond): + } + require.NoError(t, tx.Commit()) + result := <-done + require.NoError(t, result.err) + require.EqualValues(t, 9, result.id) + // 候选查询不能通过用户名搜索探测认证字段。 + scopedCtx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"proxies.read"}}}) + matches, meta, err := repo.ListOptions(scopedCtx, pagination.PaginationParams{Page: 1, PageSize: 100}, "SECRET_USER") + require.NoError(t, err) + require.Empty(t, matches) + require.Zero(t, meta.Total) + matches, meta, err = repo.ListOptions(context.Background(), pagination.PaginationParams{Page: 1, PageSize: 100}, "SECRET_USER") + require.NoError(t, err) + require.Empty(t, matches) + require.Zero(t, meta.Total) + // 限定唯一可用候选,确定性验证随机排除过期、停用及已删除。 + _, err = db.Exec(`UPDATE proxies SET status='inactive' WHERE id>9;UPDATE proxies SET status='inactive' WHERE id IN (5,6,7,8)`) + require.NoError(t, err) + tx, err = client.Tx(context.Background()) + require.NoError(t, err) + ctx = dbent.NewTxContext(context.Background(), tx) + selected, err = repo.SelectAccountProxy(ctx, "random") + require.NoError(t, err) + require.EqualValues(t, 9, selected) + require.NoError(t, tx.Rollback()) + // 绑定数相同时按 ID 稳定选择。 + _, err = db.Exec(`UPDATE proxies SET status='active' WHERE id IN(5,6,7);UPDATE proxies SET status='inactive' WHERE id=9`) + require.NoError(t, err) + tx, err = client.Tx(context.Background()) + require.NoError(t, err) + ctx = dbent.NewTxContext(context.Background(), tx) + selected, err = repo.SelectAccountProxy(ctx, "least_used") + require.NoError(t, err) + require.EqualValues(t, 5, selected) + require.NoError(t, tx.Rollback()) + _, err = db.Exec(`UPDATE proxies SET status='inactive'`) + require.NoError(t, err) + tx, err = client.Tx(context.Background()) + require.NoError(t, err) + ctx = dbent.NewTxContext(context.Background(), tx) + selected, err = repo.SelectAccountProxy(ctx, "random") + require.NoError(t, err) + require.Zero(t, selected) + require.NoError(t, tx.Rollback()) + require.NoError(t, db.Ping(), "测试结束连接可用") +} diff --git a/backend/internal/repository/custom_admin_key_group_models.go b/backend/internal/repository/custom_admin_key_group_models.go new file mode 100644 index 0000000000..f7d219f987 --- /dev/null +++ b/backend/internal/repository/custom_admin_key_group_models.go @@ -0,0 +1,98 @@ +package repository + +import ( + "context" + "time" + + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/ent/group" + "github.com/Wei-Shaw/sub2api/ent/predicate" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/Wei-Shaw/sub2api/internal/service" +) + +func (r *groupRepository) ScopedAdminUpdateGroupModels(ctx context.Context, id int64, cfg service.GroupModelAllowlist) (*service.Group, error) { + p := adminaccess.FromContext(ctx) + if p == nil { + return nil, infraerrors.Forbidden("SCOPED_GROUP_MODELS_FORBIDDEN", "缺少受限身份") + } + tx, err := r.client.Tx(ctx) + if err != nil { + return nil, err + } + defer func() { _ = tx.Rollback() }() + txctx := dbent.NewTxContext(ctx, tx) + row, err := tx.Client().Group.Query().Where(group.IDEQ(id), group.DeletedAtIsNil()). + Select(group.FieldID, group.FieldName, group.FieldPlatform, group.FieldModelAllowlist).ForUpdate().Only(txctx) + if err != nil { + return nil, translatePersistenceError(err, service.ErrGroupNotFound, nil) + } + if !p.Policy.AllowsGroupConfig("groups.models.write", row.ID, row.Platform) { + return nil, infraerrors.NotFound("SCOPED_GROUP_NOT_FOUND", "分组不存在") + } + // 只写这一个业务字段,避免完整分组 Update 覆盖并发变化或修改费率等敏感配置。 + if _, err = tx.Client().Group.Update().Where(group.IDEQ(id), group.DeletedAtIsNil()).SetModelAllowlist(service.DomainGroupModelAllowlist(cfg)).SetUpdatedAt(time.Now()).Save(txctx); err != nil { + return nil, err + } + if err = enqueueSchedulerOutbox(txctx, tx.Client(), service.SchedulerOutboxEventGroupChanged, nil, &id, nil); err != nil { + return nil, err + } + if err = tx.Commit(); err != nil { + return nil, err + } + return &service.Group{ID: row.ID, Name: row.Name, Platform: row.Platform, ModelAllowlist: cfg}, nil +} + +// ScopedAdminListGroupModels 在数据库内过滤范围,分页和总数均只包含已授权分组。 +func (r *groupRepository) ScopedAdminListGroupModels(ctx context.Context, params pagination.PaginationParams, all bool, platform, status, search string) ([]service.Group, int64, error) { + p := adminaccess.FromContext(ctx) + if p == nil { + return nil, 0, infraerrors.Forbidden("SCOPED_GROUP_MODELS_FORBIDDEN", "缺少受限身份") + } + alternatives := []predicate.Group{} + for _, rule := range p.Policy.RulesFor("groups.models.read") { + terms := []predicate.Group{group.IDGT(0)} + if !rule.AllGroups { + if len(rule.GroupIDs) == 0 { + continue + } + terms = append(terms, group.IDIn(rule.GroupIDs...)) + } + if len(rule.Platforms) > 0 { + terms = append(terms, group.PlatformIn(rule.Platforms...)) + } + alternatives = append(alternatives, group.And(terms...)) + } + if len(alternatives) == 0 { + return []service.Group{}, 0, nil + } + q := r.client.Group.Query().Where(group.DeletedAtIsNil(), group.Or(alternatives...)) + if platform != "" { + q.Where(group.PlatformEQ(platform)) + } + if status != "" { + q.Where(group.StatusEQ(status)) + } + if search != "" { + q.Where(group.NameContainsFold(search)) + } + total, err := q.Clone().Count(ctx) + if err != nil { + return nil, 0, err + } + q.Select(group.FieldID, group.FieldName, group.FieldPlatform, group.FieldModelAllowlist).Order(group.ByID()) + if !all { + q.Offset(params.Offset()).Limit(params.Limit()) + } + rows, err := q.All(ctx) + if err != nil { + return nil, 0, err + } + result := make([]service.Group, 0, len(rows)) + for _, row := range rows { + result = append(result, service.Group{ID: row.ID, Name: row.Name, Platform: row.Platform, ModelAllowlist: service.GroupModelAllowlistFromDomain(row.ModelAllowlist)}) + } + return result, int64(total), nil +} diff --git a/backend/internal/repository/custom_admin_key_group_models_test.go b/backend/internal/repository/custom_admin_key_group_models_test.go new file mode 100644 index 0000000000..71554d0696 --- /dev/null +++ b/backend/internal/repository/custom_admin_key_group_models_test.go @@ -0,0 +1,105 @@ +//go:build unit + +package repository + +import ( + "context" + "database/sql" + "fmt" + "os" + "testing" + "time" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestScopedAdminGroupModelsPostgresScopeAndAtomicWrite(t *testing.T) { + dsn := os.Getenv("SCOPED_ADMIN_TEST_DSN") + if dsn == "" { + t.Skip("需要独立 SCOPED_ADMIN_TEST_DSN") + } + base, err := sql.Open("postgres", dsn) + require.NoError(t, err) + schema := fmt.Sprintf("scoped_models_test_%d", time.Now().UnixNano()) + _, err = base.Exec(`CREATE SCHEMA ` + schema) + require.NoError(t, err) + db, err := sql.Open("postgres", dsn+" search_path="+schema) + require.NoError(t, err) + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + t.Cleanup(func() { + _ = client.Close() + _, _ = base.Exec(`DROP SCHEMA ` + schema + ` CASCADE`) + _ = base.Close() + }) + _, err = db.Exec(`CREATE TABLE groups(id BIGINT PRIMARY KEY, name TEXT DEFAULT '模型组', platform TEXT DEFAULT 'openai', + model_allowlist JSONB DEFAULT '{}', rate_multiplier NUMERIC DEFAULT 9, status TEXT DEFAULT 'active', updated_at TIMESTAMPTZ DEFAULT NOW(), deleted_at TIMESTAMPTZ); + CREATE TABLE scheduler_outbox(id BIGSERIAL PRIMARY KEY, event_type TEXT, account_id BIGINT, group_id BIGINT, payload JSONB, dedup_key TEXT); + CREATE UNIQUE INDEX outbox_dedup ON scheduler_outbox(dedup_key) WHERE dedup_key IS NOT NULL; + INSERT INTO groups(id,platform,deleted_at) VALUES (2,'openai',NULL),(3,'openai',NULL),(4,'anthropic',NULL),(5,'openai',NOW());`) + require.NoError(t, err) + repo := newGroupRepositoryWithSQL(client, db) + principal := &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"groups.models.write"}, GroupIDs: []int64{2, 4, 5}, Platforms: []string{"openai"}}}}} + ctx := adminaccess.WithPrincipal(context.Background(), principal) + // 列表范围与总数必须一起过滤,不能将不同规则的平台和分组交叉拼接。 + readPrincipal := &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{ + {Permissions: []string{"groups.models.read"}, GroupIDs: []int64{2, 4, 5}, Platforms: []string{"openai"}}, + {Permissions: []string{"groups.models.read"}, GroupIDs: []int64{3}, Platforms: []string{"anthropic"}}, + }}} + readctx := adminaccess.WithPrincipal(context.Background(), readPrincipal) + params := pagination.PaginationParams{Page: 1, PageSize: 1} + rows, total, err := repo.ScopedAdminListGroupModels(readctx, params, false, "", "", "") + require.NoError(t, err) + require.Equal(t, int64(1), total) + require.Len(t, rows, 1) + require.Equal(t, int64(2), rows[0].ID) + rows, total, err = repo.ScopedAdminListGroupModels(readctx, pagination.PaginationParams{Page: 2, PageSize: 1}, false, "", "", "") + require.NoError(t, err) + require.Equal(t, int64(1), total) + require.Empty(t, rows) + for _, filter := range []struct{ platform, status, search string }{{"anthropic", "", ""}, {"", "inactive", ""}, {"", "", "未匹配"}} { + rows, total, err = repo.ScopedAdminListGroupModels(readctx, params, true, filter.platform, filter.status, filter.search) + require.NoError(t, err) + require.Zero(t, total) + require.Empty(t, rows) + } + rows, total, err = repo.ScopedAdminListGroupModels(ctx, params, true, "", "", "") + require.NoError(t, err) + require.Zero(t, total) + require.Empty(t, rows, "只写权限不能读取列表") + _, _, err = repo.ScopedAdminListGroupModels(context.Background(), params, true, "", "", "") + require.Equal(t, 403, infraerrors.Code(err)) + cfg := service.GroupModelAllowlist{Enabled: true, Models: []string{"custom-model", "other-model"}} + for _, id := range []int64{3, 4, 5, 99} { + _, err = repo.ScopedAdminUpdateGroupModels(ctx, id, cfg) + require.Equal(t, 404, infraerrors.Code(err)) + } + _, err = repo.ScopedAdminUpdateGroupModels(context.Background(), 2, cfg) + require.Equal(t, 403, infraerrors.Code(err)) + updated, err := repo.ScopedAdminUpdateGroupModels(ctx, 2, cfg) + require.NoError(t, err) + require.Equal(t, cfg, updated.ModelAllowlist) + var configJSON, status string + var rate float64 + require.NoError(t, db.QueryRow(`SELECT model_allowlist::text,rate_multiplier,status FROM groups WHERE id=2`).Scan(&configJSON, &rate, &status)) + require.JSONEq(t, `{"enabled":true,"models":["custom-model","other-model"]}`, configJSON) + require.Equal(t, 9.0, rate) + require.Equal(t, "active", status) + var events int + require.NoError(t, db.QueryRow(`SELECT count(*) FROM scheduler_outbox WHERE group_id=2`).Scan(&events)) + require.Equal(t, 1, events) + // outbox 写入失败必须一起回滚模型配置。 + _, err = db.Exec(`DROP TABLE scheduler_outbox`) + require.NoError(t, err) + _, err = repo.ScopedAdminUpdateGroupModels(ctx, 2, service.GroupModelAllowlist{Models: []string{"must-rollback"}}) + require.Error(t, err) + var after string + require.NoError(t, db.QueryRow(`SELECT model_allowlist::text FROM groups WHERE id=2`).Scan(&after)) + require.JSONEq(t, configJSON, after) +} diff --git a/backend/internal/repository/custom_admin_key_review_test.go b/backend/internal/repository/custom_admin_key_review_test.go new file mode 100644 index 0000000000..fabf36b073 --- /dev/null +++ b/backend/internal/repository/custom_admin_key_review_test.go @@ -0,0 +1,225 @@ +//go:build unit + +package repository + +import ( + "context" + "database/sql" + "encoding/json" + "fmt" + "os" + "sync" + "testing" + "time" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/schema" + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/ent/migrate" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestScopedAdminReviewGroupPriorityAndStatus(t *testing.T) { + dsn := os.Getenv("SCOPED_ADMIN_TEST_DSN") + if dsn == "" { + t.Skip("需要独立 SCOPED_ADMIN_TEST_DSN") + } + base, err := sql.Open("postgres", dsn) + require.NoError(t, err) + name := fmt.Sprintf("scoped_review_%d", time.Now().UnixNano()) + _, err = base.Exec(`CREATE SCHEMA ` + name) + require.NoError(t, err) + db, err := sql.Open("postgres", dsn+" search_path="+name) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close(); _, _ = base.Exec(`DROP SCHEMA ` + name + ` CASCADE`); _ = base.Close() }) + driver := entsql.OpenDB(dialect.Postgres, db) + client := dbent.NewClient(dbent.Driver(driver)) + require.NoError(t, migrate.Create(context.Background(), migrate.NewSchema(driver), []*schema.Table{migrate.ProxiesTable, migrate.AccountsTable, migrate.GroupsTable, migrate.AccountGroupsTable}, migrate.WithForeignKeys(false))) + _, err = db.Exec(`CREATE TABLE scheduler_outbox(id BIGSERIAL PRIMARY KEY,event_type TEXT,account_id BIGINT,group_id BIGINT,payload JSONB,dedup_key TEXT,created_at TIMESTAMPTZ DEFAULT NOW());CREATE UNIQUE INDEX review_outbox_dedup ON scheduler_outbox(dedup_key) WHERE dedup_key IS NOT NULL`) + require.NoError(t, err) + cache := &scopedReviewSchedulerCache{accounts: make(map[int64]*service.Account)} + repo := NewAdminAccountRepository(client, db, cache) + groups := NewAdminGroupRepository(client, db) + admin := service.NewAdminService(nil, nil, groups, repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, client, nil, nil, nil, nil, nil, nil, nil, nil, nil) + scoped := admin.(service.ScopedAdminAccounts) + ctx := context.Background() + a, err := client.Group.Create().SetName("授权组").Save(ctx) + require.NoError(t, err) + b, err := client.Group.Create().SetName("未授权组").Save(ctx) + require.NoError(t, err) + c, err := client.Group.Create().SetName("新增授权组").Save(ctx) + require.NoError(t, err) + account, err := admin.CreateAccount(ctx, &service.CreateAccountInput{Name: "共享账户", Platform: "openai", Type: "apikey", Credentials: map[string]any{"api_key": "test"}, GroupIDs: []int64{a.ID, b.ID}, Concurrency: 1, Priority: 1}) + require.NoError(t, err) + originalTime := time.Date(2025, 1, 2, 3, 4, 5, 0, time.UTC) + _, err = db.Exec(`UPDATE account_groups SET priority=73,created_at=$2 WHERE group_id=$1`, b.ID, originalTime) + require.NoError(t, err) + principal := &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.groups", "accounts.status"}, GroupIDs: []int64{a.ID, c.ID}, AccountTypes: []string{"apikey"}}}}} + ctx = adminaccess.WithPrincipal(ctx, principal) + t.Run("非法状态不得落库", func(t *testing.T) { + for _, raw := range []string{`"garbage"`, `""`, `null`, `12`, `" active "`} { + _, err := scoped.ScopedAdminWrite(ctx, account.ID, "", map[string]json.RawMessage{"status": json.RawMessage(raw)}, nil) + require.Equal(t, 400, infraerrors.Code(err), raw) + } + stored, err := repo.GetByID(ctx, account.ID) + require.NoError(t, err) + require.Equal(t, "active", stored.Status) + for _, status := range []string{"inactive", "error", "active"} { + raw, _ := json.Marshal(status) + _, err := scoped.ScopedAdminWrite(ctx, account.ID, "", map[string]json.RawMessage{"status": raw}, nil) + require.NoError(t, err) + } + }) + t.Run("修改授权关联保留其他关联元数据", func(t *testing.T) { + for _, ids := range [][]int64{{a.ID, c.ID}, {c.ID}, {}} { + raw, _ := json.Marshal(ids) + _, err := scoped.ScopedAdminWrite(ctx, account.ID, "", map[string]json.RawMessage{"group_ids": raw}, nil) + require.NoError(t, err) + var priority int + var created time.Time + require.NoError(t, db.QueryRow(`SELECT priority,created_at FROM account_groups WHERE account_id=$1 AND group_id=$2`, account.ID, b.ID).Scan(&priority, &created)) + require.Equal(t, 73, priority, "未授权分组调度优先级不能变化") + require.True(t, originalTime.Equal(created), "未授权关联不应被重建") + } + }) + t.Run("受限创建绑定与失败回滚", func(t *testing.T) { + createCtx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.create", "accounts.credentials"}, GroupIDs: []int64{a.ID, 999999}, AccountTypes: []string{"apikey"}}}}}) + for _, groupID := range []int64{a.ID, 999999} { + var fields map[string]json.RawMessage + require.NoError(t, json.Unmarshal([]byte(fmt.Sprintf(`{"name":"创建验收-%d","platform":"openai","type":"apikey","credentials":{"api_key":"test"},"group_ids":[%d]}`, groupID, groupID)), &fields)) + created, createErr := scoped.ScopedAdminWrite(createCtx, 0, "", fields, nil) + if groupID == a.ID { + require.NoError(t, createErr) + stored, getErr := repo.GetByID(createCtx, created.ID) + require.NoError(t, getErr) + require.Equal(t, []int64{a.ID}, stored.GroupIDs) + } else { + require.Error(t, createErr) + var count int + require.NoError(t, db.QueryRow(`SELECT COUNT(*) FROM accounts WHERE name=$1`, fmt.Sprintf("创建验收-%d", groupID)).Scan(&count)) + require.Zero(t, count) + } + } + }) + t.Run("删除提交后立即清缓存且失败保留缓存", func(t *testing.T) { + _, err := db.Exec(`CREATE TABLE scheduled_test_plans(account_id BIGINT); + CREATE FUNCTION reject_review_delete() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION '模拟提交失败'; RETURN NULL; END $$; + CREATE CONSTRAINT TRIGGER reject_review_delete AFTER UPDATE ON accounts DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (NEW.name='删除回滚' AND NEW.deleted_at IS NOT NULL) EXECUTE FUNCTION reject_review_delete();`) + require.NoError(t, err) + deleteCtx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.delete"}, GroupIDs: []int64{a.ID}, AccountTypes: []string{"apikey"}}}}}) + for _, name := range []string{"删除回滚", "删除成功"} { + created, err := admin.CreateAccount(context.Background(), &service.CreateAccountInput{Name: name, Platform: "openai", Type: "apikey", Credentials: map[string]any{"api_key": "test"}, GroupIDs: []int64{a.ID}, Concurrency: 1, Priority: 1}) + require.NoError(t, err) + cache.accounts[created.ID] = created + cache.beforeDelete = func(id int64) { + var deleted bool + require.NoError(t, db.QueryRow(`SELECT deleted_at IS NOT NULL FROM accounts WHERE id=$1`, id).Scan(&deleted)) + require.True(t, deleted, "缓存只能在提交后删除") + } + _, err = scoped.ScopedAdminWrite(deleteCtx, created.ID, "accounts.delete", nil, nil) + if name == "删除回滚" { + require.ErrorContains(t, err, "模拟提交失败") + require.Contains(t, cache.accounts, created.ID) + _, err = repo.GetByID(context.Background(), created.ID) + require.NoError(t, err) + } else { + require.NoError(t, err) + require.NotContains(t, cache.accounts, created.ID, "返回成功前应清除已删除账户的调度快照") + require.Contains(t, cache.deleted, created.ID) + } + } + }) + +} + +type scopedRotationBarrier struct { + service.ScopedAdminKeyRepository + arrived chan struct{} + release chan struct{} +} + +func (r *scopedRotationBarrier) GetScopedAdminKey(ctx context.Context, id string) (*service.ScopedAdminKey, error) { + item, err := r.ScopedAdminKeyRepository.GetScopedAdminKey(ctx, id) + r.arrived <- struct{}{} + select { + case <-r.release: + case <-ctx.Done(): + return nil, ctx.Err() + } + return item, err +} +func TestScopedAdminReviewConcurrentRotation(t *testing.T) { + db := scopedAdminKeyTestDB(t) + repo := NewScopedAdminKeyRepository(db) + settings := service.NewSettingService(nil, nil) + settings.SetScopedAdminKeyRepository(repo) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _, item, err := settings.CreateScopedAdminKey(ctx, service.ScopedAdminKeyInput{Name: "并发轮换", Enabled: true}, 9) + require.NoError(t, err) + barrier := &scopedRotationBarrier{ScopedAdminKeyRepository: repo, arrived: make(chan struct{}, 2), release: make(chan struct{})} + settings.SetScopedAdminKeyRepository(barrier) + type result struct { + key string + err error + } + results := make(chan result, 2) + var wg sync.WaitGroup + for i := 0; i < 2; i++ { + wg.Add(1) + go func() { + defer wg.Done() + key, _, e := settings.RotateScopedAdminKey(ctx, item.ID) + results <- result{key, e} + }() + } + for i := 0; i < 2; i++ { + select { + case <-barrier.arrived: + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + } + close(barrier.release) + wg.Wait() + close(results) + settings.SetScopedAdminKeyRepository(repo) + successes, conflicts := 0, 0 + for result := range results { + if result.err == nil { + successes++ + _, e := settings.AuthenticateScopedAdminKey(ctx, result.key, "192.0.2.1") + require.NoError(t, e, "成功返回的密钥必须仍有效") + } else { + conflicts++ + require.Equal(t, 409, infraerrors.Code(result.err)) + require.Empty(t, result.key) + } + } + require.Equal(t, 1, successes) + require.Equal(t, 1, conflicts) +} + +type scopedReviewSchedulerCache struct { + service.SchedulerCache + accounts map[int64]*service.Account + deleted []int64 + beforeDelete func(int64) +} + +func (c *scopedReviewSchedulerCache) SetAccount(_ context.Context, a *service.Account) error { + c.accounts[a.ID] = a + return nil +} +func (c *scopedReviewSchedulerCache) DeleteAccount(_ context.Context, id int64) error { + if c.beforeDelete != nil { + c.beforeDelete(id) + } + delete(c.accounts, id) + c.deleted = append(c.deleted, id) + return nil +} diff --git a/backend/internal/repository/custom_admin_key_scope.go b/backend/internal/repository/custom_admin_key_scope.go new file mode 100644 index 0000000000..79e9fd19fe --- /dev/null +++ b/backend/internal/repository/custom_admin_key_scope.go @@ -0,0 +1,247 @@ +package repository + +import ( + "context" + "encoding/json" + "fmt" + "slices" + "strings" + + entsql "entgo.io/ent/dialect/sql" + dbent "github.com/Wei-Shaw/sub2api/ent" + dbaccount "github.com/Wei-Shaw/sub2api/ent/account" + dbaccountgroup "github.com/Wei-Shaw/sub2api/ent/accountgroup" + dbpredicate "github.com/Wei-Shaw/sub2api/ent/predicate" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/Wei-Shaw/sub2api/internal/service" +) + +func (r *accountRepository) ScopedAdminList(ctx context.Context, p pagination.PaginationParams, platform, kind, status, search string) ([]service.Account, int64, error) { + principal := adminaccess.FromContext(ctx) + if principal == nil { + return nil, 0, fmt.Errorf("缺少受限身份") + } + alternatives := scopedAdminAccountPredicates(principal.Policy, "accounts.read") + if len(alternatives) == 0 { + return []service.Account{}, 0, nil + } + q := r.accountListFilteredQuery(platform, kind, status, search, 0, "").Where(dbaccount.Or(alternatives...)) + total, err := q.Clone().Count(ctx) + if err != nil { + return nil, 0, err + } + // SQL 只投影模型映射子字段,不加载 Token、API Key、接入地址或其他凭证。 + var rows []struct { + ID int64 + Name string + Notes *string + Platform string + Type string + Status string + Schedulable bool + Concurrency int + Priority int + ModelMapping json.RawMessage `json:"model_mapping"` + } + err = q.Offset(p.Offset()).Limit(p.Limit()).Order(dbaccount.ByID()). + Select(dbaccount.FieldID, dbaccount.FieldName, dbaccount.FieldNotes, dbaccount.FieldPlatform, dbaccount.FieldType, dbaccount.FieldStatus, dbaccount.FieldSchedulable, dbaccount.FieldConcurrency, dbaccount.FieldPriority). + Aggregate(func(s *entsql.Selector) string { + return s.C(dbaccount.FieldCredentials) + "->'model_mapping' AS model_mapping" + }).Scan(ctx, &rows) + if err != nil { + return nil, 0, err + } + accounts := make([]service.Account, 0, len(rows)) + for _, row := range rows { + groups, e := r.loadAccountGroupIDs(ctx, row.ID) + if e != nil { + return nil, 0, e + } + var rawMapping map[string]any + mapping := map[string]string{} + if json.Unmarshal(row.ModelMapping, &rawMapping) == nil { + for source, target := range rawMapping { + if value, ok := target.(string); ok { + mapping[source] = value + } + } + } + var credentials map[string]any + if len(mapping) > 0 { + credentials = map[string]any{"model_mapping": mapping} + } + accounts = append(accounts, service.Account{ID: row.ID, Name: row.Name, Notes: row.Notes, Platform: row.Platform, Type: row.Type, Status: row.Status, Schedulable: row.Schedulable, Concurrency: row.Concurrency, Priority: row.Priority, GroupIDs: groups, Credentials: credentials}) + } + return accounts, int64(total), nil +} + +// ScopedAdminCommitted 提交后按实际操作删除或更新缓存,避免对已删除账户读取快照。 +func (r *accountRepository) ScopedAdminCommitted(ctx context.Context, id int64, deleted bool) { + if deleted { + r.deleteSchedulerAccountSnapshot(ctx, id) + return + } + r.syncSchedulerAccountSnapshot(ctx, id) +} + +// scopedAdminBindGroups 只增删变化的关联,保留现有关联的优先级和创建时间。 +// 调用者已在受限事务内验权并合并不可操作的分组,不得回退到全量重建。 +func (r *accountRepository) scopedAdminBindGroups(ctx context.Context, accountID int64, groupIDs []int64) error { + if dbent.TxFromContext(ctx) == nil { + return fmt.Errorf("受限分组写入需要数据库事务") + } + existing, err := r.loadAccountGroupIDs(ctx, accountID) + if err != nil { + return err + } + added, removed := []int64{}, []int64{} + for _, id := range groupIDs { + if !slices.Contains(existing, id) && !slices.Contains(added, id) { + added = append(added, id) + } + } + for _, id := range existing { + if !slices.Contains(groupIDs, id) { + removed = append(removed, id) + } + } + if len(added) == 0 && len(removed) == 0 { + return nil + } + if err := lockLiveGroups(ctx, r.client, added); err != nil { + return err + } + if len(removed) > 0 { + if _, err := r.client.AccountGroup.Delete().Where(dbaccountgroup.AccountIDEQ(accountID), dbaccountgroup.GroupIDIn(removed...)).Exec(ctx); err != nil { + return err + } + } + for _, id := range added { + if _, err := r.client.AccountGroup.Create().SetAccountID(accountID).SetGroupID(id).SetPriority(slices.Index(groupIDs, id) + 1).Save(ctx); err != nil { + return err + } + } + return enqueueSchedulerOutbox(ctx, r.sql, service.SchedulerOutboxEventAccountGroupsChanged, &accountID, nil, buildSchedulerGroupPayload(mergeGroupIDs(existing, groupIDs))) +} + +// scopedAdminAccountPredicates 保证读取和导入候选查询使用相同的范围语义。 +func scopedAdminAccountPredicates(policy adminaccess.Policy, permission string) []dbpredicate.Account { + alternatives := []dbpredicate.Account{} + for _, rule := range policy.RulesFor(permission) { + if len(rule.AccountTypes) == 0 { + continue + } + terms := []dbpredicate.Account{dbaccount.TypeIn(rule.AccountTypes...)} + if len(rule.Platforms) > 0 { + terms = append(terms, dbaccount.PlatformIn(rule.Platforms...)) + } + if rule.AllGroups && !rule.IncludeUngrouped { + terms = append(terms, dbaccount.HasAccountGroups()) + } + if !rule.AllGroups { + groups := []dbpredicate.Account{} + if len(rule.GroupIDs) > 0 { + groups = append(groups, dbaccount.HasAccountGroupsWith(dbaccountgroup.GroupIDIn(rule.GroupIDs...))) + } + if rule.IncludeUngrouped { + groups = append(groups, dbaccount.Not(dbaccount.HasAccountGroups())) + } + if len(groups) == 0 { + continue + } + terms = append(terms, dbaccount.Or(groups...)) + } + alternatives = append(alternatives, dbaccount.And(terms...)) + } + return alternatives +} + +// ScopedAdminCodexCandidates 按导入身份逐级匹配,最多返回一个候选的身份字段。 +// 不向应用加载其他账户的凭证;真正合并凭证仍在写事务锁内进行。 +func (r *accountRepository) ScopedAdminCodexCandidates(ctx context.Context, identity service.ScopedCodexIdentity) ([]service.Account, error) { + principal := adminaccess.FromContext(ctx) + if principal == nil { + return nil, fmt.Errorf("缺少受限身份") + } + scope := scopedAdminAccountPredicates(principal.Policy, "accounts.credentials") + if len(scope) == 0 { + return []service.Account{}, nil + } + for _, match := range scopedCodexIdentityPredicates(identity) { + var rows []struct { + ID int64 + Credentials json.RawMessage + } + err := r.accountListFilteredQuery(service.PlatformOpenAI, service.AccountTypeOAuth, "", "", 0, ""). + Where(dbaccount.Or(scope...), match).Order(dbaccount.ByID(entsql.OrderDesc())).Limit(1). + Select(dbaccount.FieldID).Aggregate(func(s *entsql.Selector) string { + c := s.C(dbaccount.FieldCredentials) + return "jsonb_build_object('chatgpt_account_id', " + c + "->'chatgpt_account_id', 'chatgpt_user_id', " + c + "->'chatgpt_user_id', 'email', " + c + "->'email', 'access_token', " + c + "->'access_token') AS credentials" + }).Scan(ctx, &rows) + if err != nil { + return nil, err + } + if len(rows) != 0 { + var credentials map[string]any + if err := json.Unmarshal(rows[0].Credentials, &credentials); err != nil { + return nil, err + } + return []service.Account{{ID: rows[0].ID, Credentials: credentials}}, nil + } + } + return []service.Account{}, nil +} + +// 与导入器的 account_user / user / email / access / account 优先级保持一致。 +// account 回退必须排除明确属于其他用户的账户;仅 access token 和 Agent Identity 各有独立匹配规则。 +func scopedCodexIdentityPredicates(identity service.ScopedCodexIdentity) []dbpredicate.Account { + accountID, userID := strings.TrimSpace(identity.AccountID), strings.TrimSpace(identity.UserID) + email, token := strings.ToLower(strings.TrimSpace(identity.Email)), strings.TrimSpace(identity.AccessToken) + // 与 Go strings.TrimSpace 的 Unicode 空白集合一致,兼容旧凭证中的首尾空白。 + const whitespace = "\t\n\v\f\r \u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000" + field := func(key string) string { + // 字段名均为下方固定常量;非法 JSON 类型按导入器规则视为空值。 + raw := `"accounts"."credentials"->'` + key + `'` + value := `"accounts"."credentials"->>'` + key + `'` + // 旧 JSON 数值经 Go 解码为 float64:保留同样的精度,展开指数并去掉尾随小数零。 + number := "trim_scale(((" + value + ")::double precision)::text::numeric)::text" + return "btrim(CASE jsonb_typeof(" + raw + ") WHEN 'string' THEN " + value + " WHEN 'number' THEN " + number + " ELSE '' END, '" + whitespace + "')" + } + a, u, e, access := field("chatgpt_account_id"), field("chatgpt_user_id"), field("email"), field("access_token") + match := func(expr string, args ...any) dbpredicate.Account { + parts := strings.Split(expr, "?") + return func(s *entsql.Selector) { + s.Where(entsql.P(func(b *entsql.Builder) { + for i, part := range parts { + b.WriteString(part) + if i < len(args) { + b.Arg(args[i]) + } + } + })) + } + } + predicates := []dbpredicate.Account{} + if !identity.AgentIdentity && !identity.AccessTokenOnly { + switch { + case accountID != "" && userID != "": + predicates = append(predicates, match(a+" = ? AND "+u+" = ?", accountID, userID)) + case userID != "": + predicates = append(predicates, match(a+" = '' AND "+u+" = ?", userID)) + case accountID == "" && email != "": + predicates = append(predicates, match(a+" = '' AND "+u+" = '' AND lower("+e+") = ?", email)) + } + } + if !identity.AgentIdentity && token != "" { + predicates = append(predicates, match(access+" = ?", token)) + } + if accountID != "" && (identity.AgentIdentity || !identity.AccessTokenOnly) { + if userID == "" { + predicates = append(predicates, match(a+" = ?", accountID)) + } else { + predicates = append(predicates, match(a+" = ? AND ("+u+" = '' OR "+u+" = ?)", accountID, userID)) + } + } + return predicates +} diff --git a/backend/internal/repository/custom_admin_key_scope_test.go b/backend/internal/repository/custom_admin_key_scope_test.go new file mode 100644 index 0000000000..06c192c9a0 --- /dev/null +++ b/backend/internal/repository/custom_admin_key_scope_test.go @@ -0,0 +1,257 @@ +//go:build unit + +package repository + +import ( + "context" + "database/sql" + "fmt" + "os" + "strings" + "testing" + "time" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + "github.com/DATA-DOG/go-sqlmock" + dbent "github.com/Wei-Shaw/sub2api/ent" + _ "github.com/Wei-Shaw/sub2api/ent/runtime" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestScopedAdminAccountListScopesCountAndPageInSQL(t *testing.T) { + var countScope string + matcher := sqlmock.QueryMatcherFunc(func(expected, actual string) error { + if !strings.Contains(actual, `"type"`) || !strings.Contains(actual, `"account_groups"`) || !strings.Contains(actual, " OR ") { + return fmt.Errorf("查询缺少完整规则: %s", actual) + } + where := actual[strings.Index(actual, " WHERE "):] + if i := strings.Index(where, " ORDER BY "); i >= 0 { + where = where[:i] + } + if i := strings.Index(where, " LIMIT "); i >= 0 { + where = where[:i] + } + if expected == "count" { + countScope = where + } else { + if where != countScope { + return fmt.Errorf("分页和统计范围不同") + } + // 允许模型映射子字段投影,禁止读取完整 credentials。 + projected := strings.ReplaceAll(actual, `"accounts"."credentials"->'model_mapping' AS model_mapping`, "model_mapping") + if strings.Contains(projected, `"credentials"`) || strings.Contains(projected, `"extra"`) { + return fmt.Errorf("读取了敏感字段") + } + } + return nil + }) + db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(matcher)) + if err != nil { + t.Fatal(err) + } + defer db.Close() + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + defer client.Close() + repo := newAccountRepositoryWithSQL(client, db, nil) + mock.ExpectQuery("count").WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(0)) + mock.ExpectQuery("page").WillReturnRows(sqlmock.NewRows([]string{"id"})) + principal := &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{ + {Permissions: []string{"accounts.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}}, + {Permissions: []string{"accounts.read"}, GroupIDs: []int64{2}, AccountTypes: []string{"apikey"}}, + }}} + _, total, err := repo.ScopedAdminList(adminaccess.WithPrincipal(context.Background(), principal), pagination.PaginationParams{Page: 1, PageSize: 20}, "", "", "", "") + if err != nil { + t.Fatal(err) + } + if total != 0 { + t.Fatal(total) + } + if err = mock.ExpectationsWereMet(); err != nil { + t.Fatal(err) + } +} + +func TestScopedAdminAccountListPostgresRulesAndPagination(t *testing.T) { + dsn := os.Getenv("SCOPED_ADMIN_TEST_DSN") + if dsn == "" { + t.Skip("需要独立 SCOPED_ADMIN_TEST_DSN") + } + base, err := sql.Open("postgres", dsn) + require.NoError(t, err) + schema := fmt.Sprintf("scoped_list_test_%d", time.Now().UnixNano()) + _, err = base.Exec(`CREATE SCHEMA ` + schema) + require.NoError(t, err) + db, err := sql.Open("postgres", dsn+" search_path="+schema) + require.NoError(t, err) + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + t.Cleanup(func() { + _ = client.Close() + _, _ = base.Exec(`DROP SCHEMA ` + schema + ` CASCADE`) + _ = base.Close() + }) + // 最小数据集刻意交叉分组、类型和平台,防止不同规则被拆开组合。 + _, err = db.Exec(`CREATE TABLE accounts ( + id BIGINT PRIMARY KEY, name TEXT NOT NULL DEFAULT '', notes TEXT, platform TEXT NOT NULL, + type TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'active', schedulable BOOLEAN NOT NULL DEFAULT true, + concurrency INT NOT NULL DEFAULT 1, priority INT NOT NULL DEFAULT 1, credentials JSONB DEFAULT '{}', deleted_at TIMESTAMPTZ + ); + CREATE TABLE account_groups(account_id BIGINT, group_id BIGINT, priority INT DEFAULT 50, created_at TIMESTAMPTZ DEFAULT NOW()); + INSERT INTO accounts(id,platform,type) VALUES + (1,'openai','oauth'), (2,'openai','apikey'), (3,'openai','oauth'), + (4,'openai','apikey'), (5,'anthropic','oauth'), (6,'openai','oauth'); + INSERT INTO account_groups(account_id,group_id) VALUES (1,1),(1,2),(2,1),(3,2),(4,2),(5,1);`) + require.NoError(t, err) + _, err = db.Exec(`UPDATE accounts SET credentials = '{"model_mapping":{"alias":"target","invalid":{"token":"NESTED_SECRET"}},"access_token":"TOKEN_SECRET","refresh_token":"REFRESH_SECRET","api_key":"KEY_SECRET","base_url":"URL_SECRET"}' WHERE id=1`) + require.NoError(t, err) + repo := newAccountRepositoryWithSQL(client, db, nil) + principal := &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{ + {Permissions: []string{"accounts.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}, + {Permissions: []string{"accounts.read"}, GroupIDs: []int64{2}, AccountTypes: []string{"apikey"}, Platforms: []string{"openai"}}, + }}} + ctx := adminaccess.WithPrincipal(context.Background(), principal) + for page, wantID := range []int64{1, 4} { + rows, total, listErr := repo.ScopedAdminList(ctx, pagination.PaginationParams{Page: page + 1, PageSize: 1}, "", "", "", "") + require.NoError(t, listErr) + require.EqualValues(t, 2, total) + require.Len(t, rows, 1) + require.Equal(t, wantID, rows[0].ID) + if wantID == 1 { + require.Equal(t, map[string]any{"model_mapping": map[string]string{"alias": "target"}}, rows[0].Credentials) + } else { + require.Empty(t, rows[0].Credentials) + } + } + // 缺失、清空及错误形状都应保留可读取列表,不回传嵌套对象或凭证。 + for _, credentials := range []string{`{}`, `{"model_mapping":null}`, `{"model_mapping":{}}`, `{"model_mapping":[]}`, `{"model_mapping":"invalid"}`, `{"model_mapping":{"bad":{"token":"SECRET"},"number":1},"access_token":"SECRET"}`} { + _, err = db.Exec(`UPDATE accounts SET credentials=$1::jsonb WHERE id=4`, credentials) + require.NoError(t, err) + rows, total, listErr := repo.ScopedAdminList(ctx, pagination.PaginationParams{Page: 2, PageSize: 1}, "", "", "", "") + require.NoError(t, listErr) + require.EqualValues(t, 2, total) + require.Len(t, rows, 1) + require.EqualValues(t, 4, rows[0].ID) + require.Empty(t, rows[0].Credentials) + } + principal.Policy.Rules = []adminaccess.Rule{{Permissions: []string{"accounts.read"}, AllGroups: true, AccountTypes: []string{"oauth"}}} + rows, total, err := repo.ScopedAdminList(ctx, pagination.DefaultPagination(), "", "", "", "") + require.NoError(t, err) + require.EqualValues(t, 3, total, "全部分组不包含无分组账户") + require.Len(t, rows, 3) + principal.Policy.Rules[0].IncludeUngrouped = true + _, total, err = repo.ScopedAdminList(ctx, pagination.DefaultPagination(), "", "", "", "") + require.NoError(t, err) + require.EqualValues(t, 4, total) +} + +func TestScopedAdminCodexCandidatesQueryIsBounded(t *testing.T) { + matcher := sqlmock.QueryMatcherFunc(func(_, actual string) error { + where := actual[strings.Index(actual, " WHERE "):] + if !strings.Contains(where, "credentials") || !strings.Contains(actual, " LIMIT ") { + return fmt.Errorf("导入候选未按身份筛选并限制数量: %s", actual) + } + return nil + }) + db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(matcher)) + require.NoError(t, err) + defer db.Close() + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + defer client.Close() + repo := newAccountRepositoryWithSQL(client, db, nil) + ctx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.credentials"}, AccountTypes: []string{"oauth"}, AllGroups: true, IncludeUngrouped: true}}}}) + mock.ExpectQuery("候选身份").WillReturnRows(sqlmock.NewRows([]string{"id", "credentials"})) + _, err = repo.ScopedAdminCodexCandidates(ctx, service.ScopedCodexIdentity{AccessToken: "inside", AccessTokenOnly: true}) + require.NoError(t, err) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestScopedAdminCodexCandidatesUseCredentialWriteScope(t *testing.T) { + db := scopedAdminKeyTestDB(t) + _, err := db.Exec(`CREATE TABLE accounts(id BIGINT PRIMARY KEY,platform TEXT,type TEXT,credentials JSONB DEFAULT '{}',deleted_at TIMESTAMPTZ); + CREATE TABLE account_groups(account_id BIGINT,group_id BIGINT); + INSERT INTO accounts(id,platform,type,credentials) VALUES + (1,'openai','oauth','{"access_token":"inside"}'),(2,'openai','oauth','{"access_token":"outside"}'), + (3,'openai','apikey','{}'),(4,'anthropic','oauth','{}'),(5,'openai','oauth','{}'),(6,'openai','oauth','{}'); + INSERT INTO account_groups VALUES(1,1),(1,2),(2,2),(3,1),(4,1),(6,1); + UPDATE accounts SET deleted_at=NOW() WHERE id=6; + UPDATE accounts SET credentials='{"access_token":"inside"}';`) + require.NoError(t, err) + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + repo := newAccountRepositoryWithSQL(client, db, nil) + principal := &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.credentials"}, AccountTypes: []string{"oauth"}, GroupIDs: []int64{1}}, {Permissions: []string{"accounts.read"}, AccountTypes: []string{"oauth"}, GroupIDs: []int64{2}}}}} + ctx := adminaccess.WithPrincipal(context.Background(), principal) + rows, err := repo.ScopedAdminCodexCandidates(ctx, service.ScopedCodexIdentity{AccessToken: "inside", AccessTokenOnly: true}) + require.NoError(t, err) + require.Len(t, rows, 1) + require.EqualValues(t, 1, rows[0].ID) + require.Equal(t, "inside", rows[0].Credentials["access_token"]) + principal.Policy.Rules[0].IncludeUngrouped = true + rows, err = repo.ScopedAdminCodexCandidates(ctx, service.ScopedCodexIdentity{AccessToken: "inside", AccessTokenOnly: true}) + require.NoError(t, err) + require.Len(t, rows, 1) + require.EqualValues(t, 5, rows[0].ID) + principal.Policy.Rules[0].Permissions = []string{"accounts.read"} + rows, err = repo.ScopedAdminCodexCandidates(ctx, service.ScopedCodexIdentity{AccessToken: "inside", AccessTokenOnly: true}) + require.NoError(t, err) + require.Empty(t, rows) +} + +func TestScopedAdminCodexCandidatesMatchIdentityWithoutLoadingUnrelatedCredentials(t *testing.T) { + db := scopedAdminKeyTestDB(t) + _, err := db.Exec(`CREATE TABLE accounts(id BIGINT PRIMARY KEY,platform TEXT,type TEXT,credentials JSONB DEFAULT '{}',deleted_at TIMESTAMPTZ); + CREATE TABLE account_groups(account_id BIGINT,group_id BIGINT); + INSERT INTO accounts(id,platform,type,credentials) VALUES + (1,'openai','oauth','{"chatgpt_account_id":"workspace","chatgpt_user_id":"member","access_token":"old","refresh_token":"must-not-load","large_extra":"must-not-load"}'), + (2,'openai','oauth','{"chatgpt_account_id":"workspace","chatgpt_user_id":"other","access_token":"shared"}'), + (3,'openai','oauth','{"chatgpt_account_id":"workspace","access_token":"legacy"}'), + (4,'openai','oauth','{"chatgpt_user_id":"member","access_token":"user-only"}'), + (5,'openai','oauth','{"email":" Test@Example.COM ","access_token":"email-only"}'), + (6,'openai','oauth','{"chatgpt_account_id":"elsewhere","chatgpt_user_id":"member","email":"test@example.com","access_token":"different-workspace"}'), + (7,'openai','oauth','{"chatgpt_account_id":123.00,"chatgpt_user_id":9007199254740993,"access_token":"numeric-legacy"}'); + INSERT INTO accounts SELECT id,'openai','oauth',jsonb_build_object('access_token','unrelated-'||id,'refresh_token',repeat('x',8192)),NULL FROM generate_series(100,1100) AS id;`) + require.NoError(t, err) + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + repo := newAccountRepositoryWithSQL(client, db, nil) + ctx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.credentials"}, AccountTypes: []string{"oauth"}, AllGroups: true, IncludeUngrouped: true}}}}) + for _, tc := range []struct { + name string + identity service.ScopedCodexIdentity + want int64 + }{ + {"精确组合优先于token及account回退", service.ScopedCodexIdentity{AccountID: "workspace", UserID: "member", AccessToken: "shared"}, 1}, + {"仅token不能借用相同workspace", service.ScopedCodexIdentity{AccountID: "workspace", UserID: "member", AccessToken: "missing", AccessTokenOnly: true}, 0}, + {"token命中不施加account用户冲突", service.ScopedCodexIdentity{AccountID: "workspace", UserID: "member", AccessToken: "shared", AccessTokenOnly: true}, 2}, + {"account回退允许缺失用户", service.ScopedCodexIdentity{AccountID: "workspace", UserID: "new-member", AccessToken: "missing"}, 3}, + {"仅user不匹配其他workspace", service.ScopedCodexIdentity{UserID: "member", AccessToken: "missing"}, 4}, + {"email忽略大小写空格但不借用workspace", service.ScopedCodexIdentity{Email: "test@example.com", AccessToken: "missing"}, 5}, + {"AgentIdentity仅account", service.ScopedCodexIdentity{AccountID: "workspace", AccessToken: "different-workspace", AgentIdentity: true}, 3}, + {"AgentIdentity不回退token", service.ScopedCodexIdentity{AccountID: "missing", AccessToken: "shared", AgentIdentity: true}, 0}, + {"空身份不查询全量", service.ScopedCodexIdentity{}, 0}, + {"数值身份遵循原float64归一化", service.ScopedCodexIdentity{AccountID: "123", UserID: "9007199254740992", AccessToken: "rotated-token"}, 7}, + {"不同workspace不能以user合并", service.ScopedCodexIdentity{AccountID: "new-workspace", UserID: "member"}, 0}, + } { + t.Run(tc.name, func(t *testing.T) { + rows, err := repo.ScopedAdminCodexCandidates(ctx, tc.identity) + require.NoError(t, err) + if tc.want == 0 { + require.Empty(t, rows) + return + } + require.Len(t, rows, 1) + require.Equal(t, tc.want, rows[0].ID) + require.NotContains(t, rows[0].Credentials, "refresh_token") + require.NotContains(t, rows[0].Credentials, "large_extra") + }) + } + // 同一身份有大量旧副本时仍只取 ID 最大者;首尾 Unicode 空白与导入器一致。 + _, err = db.Exec(`INSERT INTO accounts SELECT id,'openai','oauth',jsonb_build_object('chatgpt_account_id', E'\tworkspace ','chatgpt_user_id','member','access_token','duplicate','refresh_token',repeat('x',8192)),NULL FROM generate_series(2000,3000) AS id;`) + require.NoError(t, err) + rows, err := repo.ScopedAdminCodexCandidates(ctx, service.ScopedCodexIdentity{AccountID: "workspace", UserID: "member"}) + require.NoError(t, err) + require.Len(t, rows, 1) + require.EqualValues(t, 3000, rows[0].ID) + require.Len(t, rows[0].Credentials, 4) +} diff --git a/backend/internal/repository/custom_admin_key_transaction.go b/backend/internal/repository/custom_admin_key_transaction.go new file mode 100644 index 0000000000..e3eaee8374 --- /dev/null +++ b/backend/internal/repository/custom_admin_key_transaction.go @@ -0,0 +1,19 @@ +package repository + +import ( + "context" + dbent "github.com/Wei-Shaw/sub2api/ent" +) + +// accountTransactionScope 同时切换 ORM、原生 SQL 和关联查询,禁止在提交前发布缓存。 +func (r *accountRepository) accountTransactionScope(ctx context.Context) *accountRepository { + tx := dbent.TxFromContext(ctx) + if tx == nil || r.client == tx.Client() { + return r + } + scoped := *r + scoped.client = tx.Client() + scoped.sql = tx.Client() + scoped.schedulerCache = nil + return &scoped +} diff --git a/backend/internal/repository/custom_admin_keys.go b/backend/internal/repository/custom_admin_keys.go new file mode 100644 index 0000000000..18d459ed5b --- /dev/null +++ b/backend/internal/repository/custom_admin_keys.go @@ -0,0 +1,112 @@ +package repository + +import ( + "context" + "database/sql" + "encoding/json" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" +) + +type scopedAdminKeyRepository struct{ db *sql.DB } + +func NewScopedAdminKeyRepository(db *sql.DB) service.ScopedAdminKeyRepository { + return &scopedAdminKeyRepository{db: db} +} + +const scopedAdminKeyColumns = `id,name,description,key_prefix,key_hash,enabled,expires_at,allowed_ips,policy,created_by,created_at,updated_at,last_used_at,last_used_ip,revoked_at` + +func scanScopedAdminKey(row interface{ Scan(...any) error }) (*service.ScopedAdminKey, error) { + k := &service.ScopedAdminKey{} + var ips, policy []byte + err := row.Scan(&k.ID, &k.Name, &k.Description, &k.KeyPrefix, &k.Hash, &k.Enabled, &k.ExpiresAt, &ips, &policy, &k.CreatedBy, &k.CreatedAt, &k.UpdatedAt, &k.LastUsedAt, &k.LastUsedIP, &k.RevokedAt) + if err == sql.ErrNoRows { + return nil, service.ErrScopedAdminKeyNotFound + } + if err != nil { + return nil, err + } + if err = json.Unmarshal(ips, &k.AllowedIPs); err != nil { + return nil, err + } + if err = json.Unmarshal(policy, &k.Policy); err != nil { + return nil, err + } + return k, nil +} +func (r *scopedAdminKeyRepository) ListScopedAdminKeys(ctx context.Context) ([]*service.ScopedAdminKey, error) { + rows, e := r.db.QueryContext(ctx, `SELECT `+scopedAdminKeyColumns+` FROM scoped_admin_api_keys WHERE deleted_at IS NULL ORDER BY created_at DESC`) + if e != nil { + return nil, e + } + defer func() { _ = rows.Close() }() + items := []*service.ScopedAdminKey{} + for rows.Next() { + k, e := scanScopedAdminKey(rows) + if e != nil { + return nil, e + } + items = append(items, k) + } + return items, rows.Err() +} +func (r *scopedAdminKeyRepository) GetScopedAdminKey(ctx context.Context, id string) (*service.ScopedAdminKey, error) { + return scanScopedAdminKey(r.db.QueryRowContext(ctx, `SELECT `+scopedAdminKeyColumns+` FROM scoped_admin_api_keys WHERE id=$1`, id)) +} +func (r *scopedAdminKeyRepository) InsertScopedAdminKey(ctx context.Context, k *service.ScopedAdminKey) error { + ips, e := json.Marshal(k.AllowedIPs) + if e != nil { + return e + } + policy, e := json.Marshal(k.Policy) + if e != nil { + return e + } + _, e = r.db.ExecContext(ctx, `INSERT INTO scoped_admin_api_keys (id,name,description,key_prefix,key_hash,enabled,expires_at,allowed_ips,policy,created_by,created_at,updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)`, k.ID, k.Name, k.Description, k.KeyPrefix, k.Hash, k.Enabled, k.ExpiresAt, string(ips), string(policy), k.CreatedBy, k.CreatedAt, k.UpdatedAt) + return e +} +func scopedAdminKeyResult(result sql.Result, e error) error { + if e != nil { + return e + } + n, e := result.RowsAffected() + if e != nil { + return e + } + if n == 0 { + return service.ErrScopedAdminKeyNotFound + } + return nil +} +func (r *scopedAdminKeyRepository) UpdateScopedAdminKey(ctx context.Context, k *service.ScopedAdminKey) error { + ips, e := json.Marshal(k.AllowedIPs) + if e != nil { + return e + } + policy, e := json.Marshal(k.Policy) + if e != nil { + return e + } + return scopedAdminKeyResult(r.db.ExecContext(ctx, `UPDATE scoped_admin_api_keys SET name=$2,description=$3,enabled=$4,expires_at=$5,allowed_ips=$6,policy=$7,updated_at=$8 WHERE id=$1 AND revoked_at IS NULL`, k.ID, k.Name, k.Description, k.Enabled, k.ExpiresAt, string(ips), string(policy), k.UpdatedAt)) +} +func (r *scopedAdminKeyRepository) TouchScopedAdminKey(ctx context.Context, id, expectedHash string, expectedUpdatedAt time.Time, ip string, now time.Time) error { + return scopedAdminKeyResult(r.db.ExecContext(ctx, `UPDATE scoped_admin_api_keys SET last_used_at=$5,last_used_ip=$4 WHERE id=$1 AND key_hash=$2 AND updated_at=$3 AND revoked_at IS NULL AND enabled=true AND (expires_at IS NULL OR expires_at>$5)`, id, expectedHash, expectedUpdatedAt, ip, now)) +} +func (r *scopedAdminKeyRepository) RevokeScopedAdminKey(ctx context.Context, id string, now time.Time) error { + return scopedAdminKeyResult(r.db.ExecContext(ctx, `UPDATE scoped_admin_api_keys SET revoked_at=$2,enabled=false,updated_at=$2 WHERE id=$1 AND revoked_at IS NULL`, id, now)) +} + +// 删除仅隐藏列表项;原子检查撤销状态,不删除密钥记录或历史审计。 +func (r *scopedAdminKeyRepository) DeleteScopedAdminKeyRecord(ctx context.Context, id string, now time.Time) error { + return scopedAdminKeyResult(r.db.ExecContext(ctx, `UPDATE scoped_admin_api_keys SET deleted_at=$2,updated_at=$2 WHERE id=$1 AND revoked_at IS NOT NULL AND deleted_at IS NULL`, id, now)) +} + +// 轮换按读取时的摘要进行 CAS,同一旧版本只能成功轮换一次。 +func (r *scopedAdminKeyRepository) RotateScopedAdminKeyHash(ctx context.Context, id, expectedHash, hash string, at time.Time) error { + err := scopedAdminKeyResult(r.db.ExecContext(ctx, `UPDATE scoped_admin_api_keys SET key_hash=$2,updated_at=$3 WHERE id=$1 AND key_hash=$4 AND revoked_at IS NULL`, id, hash, at, expectedHash)) + if err == service.ErrScopedAdminKeyNotFound { + return service.ErrScopedAdminKeyConflict + } + return err +} diff --git a/backend/internal/repository/custom_admin_keys_postgres_test.go b/backend/internal/repository/custom_admin_keys_postgres_test.go new file mode 100644 index 0000000000..5fe0f3d7af --- /dev/null +++ b/backend/internal/repository/custom_admin_keys_postgres_test.go @@ -0,0 +1,146 @@ +//go:build unit + +package repository + +import ( + "context" + "database/sql" + "fmt" + "os" + "path/filepath" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +// 只使用显式指定的隔离测试数据库,每次创建并清理独立 schema。 +func scopedAdminKeyTestDB(t *testing.T) *sql.DB { + t.Helper() + dsn := os.Getenv("SCOPED_ADMIN_TEST_DSN") + if dsn == "" { + t.Skip("需要独立 SCOPED_ADMIN_TEST_DSN") + } + base, err := sql.Open("postgres", dsn) + require.NoError(t, err) + schema := fmt.Sprintf("scoped_admin_test_%d", time.Now().UnixNano()) + _, err = base.Exec(`CREATE SCHEMA ` + schema) + require.NoError(t, err) + db, err := sql.Open("postgres", dsn+" search_path="+schema) + require.NoError(t, err) + t.Cleanup(func() { + _ = db.Close() + _, _ = base.Exec(`DROP SCHEMA ` + schema + ` CASCADE`) + _ = base.Close() + }) + _, err = db.Exec(`CREATE TABLE users(id BIGINT PRIMARY KEY); INSERT INTO users(id) VALUES(9)`) + require.NoError(t, err) + migration, err := os.ReadFile(filepath.Join("..", "..", "migrations", "247_scoped_admin_api_keys.sql")) + require.NoError(t, err) + _, err = db.Exec(string(migration)) + require.NoError(t, err) + return db +} + +func TestScopedAdminKeyPostgresDeleteRecordPreservesHistory(t *testing.T) { + db := scopedAdminKeyTestDB(t) + repo := NewScopedAdminKeyRepository(db) + settings := service.NewSettingService(nil, nil) + settings.SetScopedAdminKeyRepository(repo) + ctx := context.Background() + key, item, err := settings.CreateScopedAdminKey(ctx, service.ScopedAdminKeyInput{Name: "待移除记录", Enabled: true}, 9) + require.NoError(t, err) + + // 使用真实审计表,检查列表移除不会删除或改写历史日志。 + migration, err := os.ReadFile(filepath.Join("..", "..", "migrations", "180_audit_logs.sql")) + require.NoError(t, err) + _, err = db.Exec(string(migration)) + require.NoError(t, err) + _, err = db.Exec(`INSERT INTO audit_logs(actor_user_id, auth_method, action, extra) VALUES(9, 'admin_api_key', 'admin.accounts.update', jsonb_build_object('admin_key_id', $1::text))`, item.ID) + require.NoError(t, err) + var historyBefore, historyAfter string + require.NoError(t, db.QueryRow(`SELECT row_to_json(audit_logs)::text FROM audit_logs`).Scan(&historyBefore)) + + // 未撤销的 Key 即使直接调用接口也不能被隐藏,停用也不能替代撤销。 + require.ErrorIs(t, settings.DeleteScopedAdminKeyRecord(ctx, item.ID), service.ErrScopedAdminKeyNotFound) + _, err = settings.AuthenticateScopedAdminKey(ctx, key, "192.0.2.1") + require.NoError(t, err) + input := item.ScopedAdminKeyInput + input.Enabled = false + _, err = settings.UpdateScopedAdminKey(ctx, item.ID, input) + require.NoError(t, err) + require.ErrorIs(t, settings.DeleteScopedAdminKeyRecord(ctx, item.ID), service.ErrScopedAdminKeyNotFound) + require.NoError(t, settings.RevokeScopedAdminKey(ctx, item.ID)) + items, err := settings.ListScopedAdminKeys(ctx) + require.NoError(t, err) + require.Len(t, items, 1, "撤销仍保留在列表") + + require.NoError(t, settings.DeleteScopedAdminKeyRecord(ctx, item.ID)) + items, err = settings.ListScopedAdminKeys(ctx) + require.NoError(t, err) + require.Empty(t, items, "重新读取列表仍应隐藏") + stored, err := repo.GetScopedAdminKey(ctx, item.ID) + require.NoError(t, err, "底层记录保留以供追溯") + require.NotNil(t, stored.RevokedAt) + require.Equal(t, item.Name, stored.Name) + require.NoError(t, db.QueryRow(`SELECT row_to_json(audit_logs)::text FROM audit_logs`).Scan(&historyAfter)) + require.Equal(t, historyBefore, historyAfter) + _, err = settings.AuthenticateScopedAdminKey(ctx, key, "192.0.2.1") + require.ErrorIs(t, err, service.ErrScopedAdminKeyInvalid) + _, err = settings.UpdateScopedAdminKey(ctx, item.ID, input) + require.ErrorIs(t, err, service.ErrScopedAdminKeyNotFound) + _, _, err = settings.RotateScopedAdminKey(ctx, item.ID) + require.ErrorIs(t, err, service.ErrScopedAdminKeyNotFound) + require.ErrorIs(t, settings.DeleteScopedAdminKeyRecord(ctx, item.ID), service.ErrScopedAdminKeyNotFound) + require.ErrorIs(t, settings.DeleteScopedAdminKeyRecord(ctx, "不存在的Key"), service.ErrScopedAdminKeyNotFound) +} + +func TestScopedAdminKeyPostgresMigrationAndLifecycle(t *testing.T) { + db := scopedAdminKeyTestDB(t) + repo := NewScopedAdminKeyRepository(db) + settings := service.NewSettingService(nil, nil) + settings.SetScopedAdminKeyRepository(repo) + ctx := context.Background() + input := service.ScopedAdminKeyInput{Name: "隔离数据库验收", Enabled: true, AllowedIPs: []string{"192.0.2.0/24"}, Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}}}}} + key, item, err := settings.CreateScopedAdminKey(ctx, input, 9) + require.NoError(t, err) + stored, err := repo.GetScopedAdminKey(ctx, item.ID) + require.NoError(t, err) + require.NotEqual(t, key, stored.Hash) + require.Len(t, stored.Hash, 64) + _, err = settings.AuthenticateScopedAdminKey(ctx, key, "192.0.2.9") + require.NoError(t, err, "真实 PostgreSQL 时间精度下 CAS 应能成功") + _, err = settings.AuthenticateScopedAdminKey(ctx, key, "198.51.100.9") + require.Error(t, err) + + // 读出策略之后发生收权,旧读取不得通过准入 CAS。 + observed, err := repo.GetScopedAdminKey(ctx, item.ID) + require.NoError(t, err) + input.Policy = adminaccess.Policy{} + _, err = settings.UpdateScopedAdminKey(ctx, item.ID, input) + require.NoError(t, err) + require.Error(t, repo.TouchScopedAdminKey(ctx, observed.ID, observed.Hash, observed.UpdatedAt, "192.0.2.9", time.Now().UTC())) + authenticated, err := settings.AuthenticateScopedAdminKey(ctx, key, "192.0.2.9") + require.NoError(t, err) + require.False(t, adminaccess.RouteAllowed(authenticated.Policy, "GET", "/api/v1/admin/accounts")) + + rotated, _, err := settings.RotateScopedAdminKey(ctx, item.ID) + require.NoError(t, err) + _, err = settings.AuthenticateScopedAdminKey(ctx, key, "192.0.2.9") + require.Error(t, err) + _, err = settings.AuthenticateScopedAdminKey(ctx, rotated, "192.0.2.9") + require.NoError(t, err) + input.Enabled = false + _, err = settings.UpdateScopedAdminKey(ctx, item.ID, input) + require.NoError(t, err) + _, err = settings.AuthenticateScopedAdminKey(ctx, rotated, "192.0.2.9") + require.Error(t, err) + require.NoError(t, settings.RevokeScopedAdminKey(ctx, item.ID)) + input.Enabled = true + _, err = settings.UpdateScopedAdminKey(ctx, item.ID, input) + require.ErrorIs(t, err, service.ErrScopedAdminKeyNotFound) + _, _, err = settings.RotateScopedAdminKey(ctx, item.ID) + require.ErrorIs(t, err, service.ErrScopedAdminKeyNotFound) +} diff --git a/backend/internal/repository/custom_admin_keys_test.go b/backend/internal/repository/custom_admin_keys_test.go new file mode 100644 index 0000000000..1d7684035f --- /dev/null +++ b/backend/internal/repository/custom_admin_keys_test.go @@ -0,0 +1,50 @@ +//go:build unit + +package repository + +import ( + "context" + "testing" + "time" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestScopedAdminKeyRepositoryRotationAndRevocation(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer db.Close() + repo := NewScopedAdminKeyRepository(db) + now := time.Now().UTC() + ctx := context.Background() + mock.ExpectExec(`UPDATE scoped_admin_api_keys SET key_hash=\$2,updated_at=\$3 WHERE id=\$1 AND key_hash=\$4 AND revoked_at IS NULL`).WithArgs("id", "hash", now, "old-hash").WillReturnResult(sqlmock.NewResult(0, 1)) + require.NoError(t, repo.RotateScopedAdminKeyHash(ctx, "id", "old-hash", "hash", now)) + mock.ExpectExec(`UPDATE scoped_admin_api_keys SET revoked_at=\$2,enabled=false,updated_at=\$2 WHERE id=\$1 AND revoked_at IS NULL`).WithArgs("id", now).WillReturnResult(sqlmock.NewResult(0, 0)) + require.ErrorIs(t, repo.RevokeScopedAdminKey(ctx, "id", now), service.ErrScopedAdminKeyNotFound) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestScopedAdminKeyTouchUsesCASAgainstRotationAndRevocation(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer db.Close() + repo := NewScopedAdminKeyRepository(db) + now := time.Now().UTC() + mock.ExpectExec(`UPDATE scoped_admin_api_keys SET last_used_at=\$5,last_used_ip=\$4 WHERE id=\$1 AND key_hash=\$2 AND updated_at=\$3 AND revoked_at IS NULL AND enabled=true AND \(expires_at IS NULL OR expires_at>\$5\)`). + WithArgs("id", "observed-hash", now.Add(-time.Minute), "192.0.2.1", now). + WillReturnResult(sqlmock.NewResult(0, 0)) + require.ErrorIs(t, repo.TouchScopedAdminKey(context.Background(), "id", "observed-hash", now.Add(-time.Minute), "192.0.2.1", now), service.ErrScopedAdminKeyNotFound) + require.NoError(t, mock.ExpectationsWereMet()) +} +func TestScopedAdminKeyRepositoryEditDoesNotRestoreOldHash(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer db.Close() + repo := NewScopedAdminKeyRepository(db) + k := &service.ScopedAdminKey{ID: "id", Hash: "旧摘要", ScopedAdminKeyInput: service.ScopedAdminKeyInput{Name: "更新", AllowedIPs: []string{}}, UpdatedAt: time.Now().UTC()} + mock.ExpectExec(`UPDATE scoped_admin_api_keys SET name=\$2,description=\$3,enabled=\$4,expires_at=\$5,allowed_ips=\$6,policy=\$7,updated_at=\$8 WHERE id=\$1 AND revoked_at IS NULL`).WithArgs(k.ID, k.Name, k.Description, k.Enabled, k.ExpiresAt, "[]", sqlmock.AnyArg(), k.UpdatedAt).WillReturnResult(sqlmock.NewResult(0, 1)) + require.NoError(t, repo.UpdateScopedAdminKey(context.Background(), k)) + require.NoError(t, mock.ExpectationsWereMet()) +} diff --git a/backend/internal/repository/custom_proxy_options.go b/backend/internal/repository/custom_proxy_options.go new file mode 100644 index 0000000000..116421ccc7 --- /dev/null +++ b/backend/internal/repository/custom_proxy_options.go @@ -0,0 +1,56 @@ +package repository + +import ( + "context" + entsql "entgo.io/ent/dialect/sql" + "strings" + "time" + + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/ent/proxy" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/Wei-Shaw/sub2api/internal/service" +) + +// ListOptions 为受限管理密钥在数据库内分页并只投影公开字段。 +func (r *proxyRepository) ListOptions(ctx context.Context, params pagination.PaginationParams, search string) ([]service.Proxy, *pagination.PaginationResult, error) { + q := r.client.Proxy.Query().Where(proxy.StatusEQ(service.StatusActive)) + if search = strings.TrimSpace(search); search != "" { + q = q.Where(proxyOptionSearchPredicate(search)) + } + total, err := q.Count(ctx) + if err != nil { + return nil, nil, err + } + records, err := q.Select(proxy.FieldID, proxy.FieldName, proxy.FieldProtocol, proxy.FieldHost, proxy.FieldPort, proxy.FieldStatus, proxy.FieldExpiresAt).Order(dbent.Desc(proxy.FieldID)).Offset(params.Offset()).Limit(params.Limit()).All(ctx) + if err != nil { + return nil, nil, err + } + items := make([]service.Proxy, 0, len(records)) + for _, record := range records { + items = append(items, *proxyEntityToService(record)) + } + return items, paginationResultFromTotal(int64(total), params), nil +} + +// SampleOptions 先过滤全池,再由数据库随机排序取 50 条,禁止先固定分页再洗牌。 +func (r *proxyRepository) SampleOptions(ctx context.Context, search string) ([]service.Proxy, int64, error) { + q := r.client.Proxy.Query().Where(proxy.StatusEQ(service.StatusActive), proxy.Or(proxy.ExpiresAtIsNil(), proxy.ExpiresAtGT(time.Now()))) + if search = strings.TrimSpace(search); search != "" { + q = q.Where(proxyOptionSearchPredicate(search)) + } + total, err := q.Clone().Count(ctx) + if err != nil { + return nil, 0, err + } + records, err := q.Select(proxy.FieldID, proxy.FieldName, proxy.FieldProtocol, proxy.FieldHost, proxy.FieldPort, proxy.FieldStatus, proxy.FieldExpiresAt). + Order(func(s *entsql.Selector) { s.OrderExpr(entsql.Expr("RANDOM()")) }).Limit(50).All(ctx) + if err != nil { + return nil, 0, err + } + items := make([]service.Proxy, 0, len(records)) + for _, record := range records { + items = append(items, *proxyEntityToService(record)) + } + return items, int64(total), nil +} diff --git a/backend/internal/repository/custom_proxy_sample_test.go b/backend/internal/repository/custom_proxy_sample_test.go new file mode 100644 index 0000000000..aa7dfedbc6 --- /dev/null +++ b/backend/internal/repository/custom_proxy_sample_test.go @@ -0,0 +1,111 @@ +//go:build unit + +package repository + +import ( + "context" + "fmt" + "strings" + "testing" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + "github.com/DATA-DOG/go-sqlmock" + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/stretchr/testify/require" +) + +func TestProxySampleSQLRandomizesWholePoolBeforeLimit(t *testing.T) { + matcher := sqlmock.QueryMatcherFunc(func(expected, actual string) error { + if !strings.Contains(actual, `"status"`) || !strings.Contains(actual, `"expires_at"`) { + return fmt.Errorf("缺少可用池过滤: %s", actual) + } + if strings.Contains(actual, `"username"`) || strings.Contains(actual, `"password"`) { + return fmt.Errorf("抽样不应查询认证字段: %s", actual) + } + if expected == "sample" { + if !strings.Contains(actual, "ORDER BY RANDOM() LIMIT 50") || strings.Contains(actual, "OFFSET") || strings.Contains(actual, "ORDER BY \"proxies\".\"id\"") { + return fmt.Errorf("未在全池随机后限制50: %s", actual) + } + if strings.Count(actual, "SELECT") != 1 { + return fmt.Errorf("不得从预先截断的子查询抽样: %s", actual) + } + } + return nil + }) + db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(matcher)) + require.NoError(t, err) + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + t.Cleanup(func() { _ = client.Close() }) + mock.ExpectQuery("count").WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(20000)) + mock.ExpectQuery("sample").WillReturnRows(sqlmock.NewRows([]string{"id", "name", "host", "port", "status"}).AddRow(1234, "候选", "192.0.2.1", 8080, "active")) + items, total, err := newProxyRepositoryWithSQL(client, db).SampleOptions(context.Background(), "region") + require.NoError(t, err) + require.EqualValues(t, 20000, total) + require.Len(t, items, 1) + require.EqualValues(t, 1234, items[0].ID) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestProxySamplePostgresLargePoolAndEligibility(t *testing.T) { + db := scopedAdminKeyTestDB(t) + _, err := db.Exec(`CREATE TABLE proxies( + id BIGINT PRIMARY KEY,name TEXT DEFAULT 'pool',protocol TEXT DEFAULT 'http',host TEXT DEFAULT '192.0.2.1',port INT DEFAULT 8080, + username TEXT DEFAULT 'SECRET_USER',password TEXT DEFAULT 'SECRET_PASSWORD',status TEXT DEFAULT 'active', + expires_at TIMESTAMPTZ,deleted_at TIMESTAMPTZ,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW(), + fallback_mode TEXT DEFAULT 'none',backup_proxy_id BIGINT,expiry_warn_days INT DEFAULT 7); + INSERT INTO proxies(id) SELECT generate_series(1,20005); + UPDATE proxies SET status='inactive' WHERE id=1; + UPDATE proxies SET status='inactive' WHERE id=2; + UPDATE proxies SET expires_at=NOW()-INTERVAL '1 day' WHERE id=3; + UPDATE proxies SET deleted_at=NOW() WHERE id=4;`) + require.NoError(t, err) + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + repo := newProxyRepositoryWithSQL(client, db) + for i := 0; i < 2; i++ { + items, total, err := repo.SampleOptions(context.Background(), "") + require.NoError(t, err) + require.EqualValues(t, 20001, total) + require.Len(t, items, 50) + seen := map[int64]bool{} + for _, p := range items { + require.Greater(t, p.ID, int64(4)) + require.False(t, seen[p.ID]) + seen[p.ID] = true + require.Empty(t, p.Username) + require.Empty(t, p.Password) + } + } + // 用唯一匹配 ID 证明老记录在全池内可达,不依赖随机概率作断言。 + _, err = db.Exec(`UPDATE proxies SET name='only-old-record' WHERE id=5`) + require.NoError(t, err) + items, total, err := repo.SampleOptions(context.Background(), "only-old-record") + require.NoError(t, err) + require.EqualValues(t, 1, total) + require.Len(t, items, 1) + require.EqualValues(t, 5, items[0].ID) + items, total, err = repo.SampleOptions(context.Background(), "SECRET_USER") + require.NoError(t, err) + require.Zero(t, total) + require.Empty(t, items) + page1, _, err := repo.ListOptions(context.Background(), pagination.PaginationParams{Page: 1, PageSize: 50}, "") + require.NoError(t, err) + page2, _, err := repo.ListOptions(context.Background(), pagination.PaginationParams{Page: 2, PageSize: 50}, "") + require.NoError(t, err) + require.EqualValues(t, 20005, page1[0].ID) + require.EqualValues(t, 19955, page2[0].ID) + // 小池全部返回,空池返回空切片,均不填入无效代理。 + _, err = db.Exec(`UPDATE proxies SET status='inactive' WHERE id>10`) + require.NoError(t, err) + items, total, err = repo.SampleOptions(context.Background(), "") + require.NoError(t, err) + require.EqualValues(t, 6, total) + require.Len(t, items, 6) + _, err = db.Exec(`UPDATE proxies SET status='inactive'`) + require.NoError(t, err) + items, total, err = repo.SampleOptions(context.Background(), "") + require.NoError(t, err) + require.Zero(t, total) + require.Empty(t, items) +} diff --git a/backend/internal/repository/custom_proxy_search.go b/backend/internal/repository/custom_proxy_search.go new file mode 100644 index 0000000000..25570cd316 --- /dev/null +++ b/backend/internal/repository/custom_proxy_search.go @@ -0,0 +1,20 @@ +package repository + +import ( + "strconv" + + "github.com/Wei-Shaw/sub2api/ent/predicate" + "github.com/Wei-Shaw/sub2api/ent/proxy" +) + +// proxyOptionSearchPredicate 数字关键词同时匹配端口和 ID;文本搜索保持参数化。 +func proxyOptionSearchPredicate(search string) predicate.Proxy { + filters := []predicate.Proxy{proxy.NameContainsFold(search), proxy.HostContainsFold(search)} + if n, err := strconv.ParseInt(search, 10, 64); err == nil && n > 0 { + if n <= 65535 { + filters = append(filters, proxy.PortEQ(int(n))) + } + filters = append(filters, proxy.IDEQ(n)) + } + return proxy.Or(filters...) +} diff --git a/backend/internal/repository/setting_repo.go b/backend/internal/repository/setting_repo.go index 815daa54be..468d4e66c1 100644 --- a/backend/internal/repository/setting_repo.go +++ b/backend/internal/repository/setting_repo.go @@ -82,6 +82,20 @@ func (r *settingRepository) Set(ctx context.Context, key, value string) error { Exec(ctx) } +// ReplaceExistingAdminAPIKey 原子轮换仍存在的旧版管理员密钥。 +// 受影响行数为零表示密钥已被删除或不存在,绝不能通过 upsert 重新创建。 +func (r *settingRepository) ReplaceExistingAdminAPIKey(ctx context.Context, value string) (bool, error) { + n, err := r.client.Setting.Update(). + Where(setting.KeyEQ(service.SettingKeyAdminAPIKey), setting.ValueNEQ("")). + SetValue(value). + SetUpdatedAt(time.Now()). + Save(ctx) + if err != nil { + return false, err + } + return n == 1, nil +} + func (r *settingRepository) GetMultiple(ctx context.Context, keys []string) (map[string]string, error) { if len(keys) == 0 { return map[string]string{}, nil diff --git a/backend/internal/repository/wire.go b/backend/internal/repository/wire.go index ba13b0f767..f176e56eea 100644 --- a/backend/internal/repository/wire.go +++ b/backend/internal/repository/wire.go @@ -87,6 +87,7 @@ var ProviderSet = wire.NewSet( NewUsageCleanupRepository, NewDashboardAggregationRepository, NewSettingRepository, + NewScopedAdminKeyRepository, NewOpsRepository, NewAuditLogRepository, NewPasskeyRepository, diff --git a/backend/internal/server/middleware/admin_auth.go b/backend/internal/server/middleware/admin_auth.go index 741cbcf6c0..fd0f270534 100644 --- a/backend/internal/server/middleware/admin_auth.go +++ b/backend/internal/server/middleware/admin_auth.go @@ -5,9 +5,10 @@ import ( "crypto/subtle" "errors" "strings" + "time" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" "github.com/Wei-Shaw/sub2api/internal/service" - "github.com/gin-gonic/gin" ) @@ -49,6 +50,16 @@ func adminAuth( // 检查 x-api-key header(Admin API Key 认证) apiKey := c.GetHeader("x-api-key") if apiKey != "" { + if strings.HasPrefix(apiKey, "adm_sc_") { + authenticateScopedAdminRequest(c, apiKey, settingService, userService, auditService) + return + } + if strings.Contains(c.FullPath(), "/settings/admin-api-key") { + AbortWithError(c, 403, "FORBIDDEN", "仅 JWT 管理员可管理密钥") + recordAdminKeyRequest(c, auditService, nil) + return + } + if !validateAdminAPIKey(c, apiKey, settingService, userService) { return } @@ -218,3 +229,54 @@ func validateJWTForAdmin( return true } + +// 每次请求查库,未登记的管理动作默认拒绝。 +func authenticateScopedAdminRequest(c *gin.Context, key string, settings *service.SettingService, users *service.UserService, audit *service.AuditLogService) { + if settings == nil || users == nil { + AbortWithError(c, 401, "INVALID_ADMIN_KEY", "Invalid admin API key") + recordAdminKeyRequest(c, audit, nil) + return + } + item, err := settings.AuthenticateScopedAdminKey(c.Request.Context(), key, SecurityClientIP(c)) + defer func() { recordAdminKeyRequest(c, audit, item) }() + if err != nil { + AbortWithError(c, 401, "INVALID_ADMIN_KEY", "Invalid admin API key") + return + } + user, err := users.GetByID(c.Request.Context(), item.CreatedBy) + if err != nil || user == nil || !user.IsActive() || !user.IsAdmin() { + AbortWithError(c, 401, "INVALID_ADMIN_KEY", "Invalid admin API key") + return + } + principal := &adminaccess.Principal{KeyID: item.ID, KeyName: item.Name, CreatorID: item.CreatedBy, Policy: item.Policy} + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), principal)) + c.Set(string(ContextKeyUser), AuthSubject{UserID: user.ID, Concurrency: user.Concurrency}) + c.Set(string(ContextKeyUserRole), user.Role) + c.Set(ContextKeyAuthEmail, user.Email) + c.Set("auth_method", service.AuditAuthMethodAdminAPIKey) + c.Set(auditCtxKeySkip, true) + if strings.Contains(c.FullPath(), "/settings/admin-api-key") || !adminaccess.RouteAllowed(item.Policy, c.Request.Method, c.FullPath()) { + c.Set("admin_key_denial_reason", "permission_denied") + AbortWithError(c, 403, "FORBIDDEN", "管理密钥未获此操作权限") + return + } + c.Next() +} +func recordAdminKeyRequest(c *gin.Context, audit *service.AuditLogService, item *service.ScopedAdminKey) { + if audit == nil { + return + } + entry := &service.AuditLog{CreatedAt: time.Now().UTC(), AuthMethod: service.AuditAuthMethodAdminAPIKey, Action: "admin.api_key.request", Method: c.Request.Method, Path: c.Request.URL.Path, StatusCode: c.Writer.Status(), ClientIP: SecurityClientIP(c), UserAgent: c.Request.UserAgent()} + if item != nil { + entry.Extra = map[string]any{"admin_key_id": item.ID, "admin_key_name": item.Name} + uid := item.CreatedBy + entry.ActorUserID = &uid + } + if reason := c.GetString("admin_key_denial_reason"); reason != "" { + if entry.Extra == nil { + entry.Extra = map[string]any{} + } + entry.Extra["denial_reason"] = reason + } + audit.Record(entry) +} diff --git a/backend/internal/server/middleware/custom_admin_key_rate_limit_test.go b/backend/internal/server/middleware/custom_admin_key_rate_limit_test.go new file mode 100644 index 0000000000..305b7b34de --- /dev/null +++ b/backend/internal/server/middleware/custom_admin_key_rate_limit_test.go @@ -0,0 +1,170 @@ +//go:build unit + +package middleware + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestScopedAdminKeyPanelRateLimitAuthenticatedRead(t *testing.T) { + gin.SetMode(gin.TestMode) + settings := newPanelRateLimitTestService(t, `{"enabled":true,"user_rpm":1,"heavy_rpm":1,"exempt_admin":true,"public_ip_rpm":0}`) + settings.SetScopedAdminKeyRepository(&adminAuthKeyRepo{}) + key, item, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{ + Name: "读取用户", Enabled: true, Policy: adminaccess.Policy{GlobalPermissions: []string{"users.read"}}, + }, 9) + require.NoError(t, err) + users := service.NewUserService(&stubUserRepo{getByID: func(context.Context, int64) (*service.User, error) { + return &service.User{ID: 9, Role: service.RoleAdmin, Status: service.StatusActive}, nil + }}, nil, nil, nil) + allower := &fakePanelAllower{} + p := &PanelRateLimiter{limiter: allower, settingService: settings} + r := gin.New() + r.Use(gin.HandlerFunc(NewAdminAuthMiddleware(nil, users, settings, nil)), p.Global()) + r.GET("/api/v1/admin/users", func(c *gin.Context) { c.Status(http.StatusNoContent) }) + request := func() *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/users", nil) + req.Header.Set("x-api-key", key) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + return w + } + require.Equal(t, http.StatusNoContent, request().Code) + w := request() + require.Equal(t, http.StatusTooManyRequests, w.Code, "受限 Key 不应继承管理员限流豁免") + require.Equal(t, "60", w.Header().Get("Retry-After")) + require.Equal(t, int64(2), allower.counts["panel:global:admin-key:"+item.ID]) +} + +func TestScopedAdminKeyPanelRateLimitWritesAndIndependentKeys(t *testing.T) { + for _, method := range []string{http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete} { + t.Run(method, func(t *testing.T) { + allower := &fakePanelAllower{} + p := &PanelRateLimiter{limiter: allower, settingService: newPanelRateLimitTestService(t, + `{"enabled":true,"user_rpm":10,"heavy_rpm":1,"exempt_admin":true}`)} + newRouter := func(keyID string) *gin.Engine { + r := gin.New() + r.Use(func(c *gin.Context) { + c.Set(string(ContextKeyUser), AuthSubject{UserID: 9}) + c.Set(string(ContextKeyUserRole), service.RoleAdmin) + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{KeyID: keyID})) + c.Next() + }, p.Global(), p.Heavy()) + r.Handle(method, "/test", func(c *gin.Context) { c.Status(http.StatusNoContent) }) + return r + } + request := func(r *gin.Engine) int { + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(method, "/test", nil)) + return w.Code + } + a, b := newRouter("key-a"), newRouter("key-b") + require.Equal(t, http.StatusNoContent, request(a), "Global 与 Heavy 叠加时严格档只计数一次") + require.Equal(t, http.StatusTooManyRequests, request(a)) + require.Equal(t, http.StatusNoContent, request(b), "同一创建者的另一把 Key 配额独立") + require.Equal(t, int64(2), allower.counts["panel:heavy:admin-key:key-a"]) + require.Equal(t, int64(1), allower.counts["panel:heavy:admin-key:key-b"]) + require.NotContains(t, allower.counts, "panel:global:user:9") + }) + } +} + +func TestScopedAdminKeyPanelRateLimitAuthenticatedSensitiveWrite(t *testing.T) { + for _, tc := range []struct { + name string + settings string + redisErr error + wantCodes []int + }{ + {"严格档", `{"enabled":true,"user_rpm":10,"heavy_rpm":1,"exempt_admin":true}`, nil, []int{204, 429}}, + {"只开严格档", `{"enabled":true,"user_rpm":0,"heavy_rpm":1,"exempt_admin":true}`, nil, []int{204, 429}}, + {"严格档关闭", `{"enabled":true,"user_rpm":10,"heavy_rpm":0,"exempt_admin":true}`, nil, []int{204, 204}}, + {"总开关关闭", `{"enabled":false,"user_rpm":1,"heavy_rpm":1,"exempt_admin":true}`, nil, []int{204, 204}}, + {"Redis故障放行", `{"enabled":true,"user_rpm":1,"heavy_rpm":1,"exempt_admin":true}`, errors.New("redis down"), []int{204, 204}}, + } { + t.Run(tc.name, func(t *testing.T) { + settings := newPanelRateLimitTestService(t, tc.settings) + settings.SetScopedAdminKeyRepository(&adminAuthKeyRepo{}) + key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{ + Name: "调整余额", Enabled: true, Policy: adminaccess.Policy{GlobalPermissions: []string{"users.balance.write"}}, + }, 9) + require.NoError(t, err) + users := service.NewUserService(&stubUserRepo{getByID: func(context.Context, int64) (*service.User, error) { + return &service.User{ID: 9, Role: service.RoleAdmin, Status: service.StatusActive}, nil + }}, nil, nil, nil) + p := &PanelRateLimiter{limiter: &fakePanelAllower{err: tc.redisErr}, settingService: settings} + r := gin.New() + r.Use(gin.HandlerFunc(NewAdminAuthMiddleware(nil, users, settings, nil)), p.Global()) + r.POST("/api/v1/admin/users/:id/balance", func(c *gin.Context) { c.Status(http.StatusNoContent) }) + for _, want := range tc.wantCodes { + req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/users/12/balance", nil) + req.Header.Set("x-api-key", key) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, want, w.Code) + } + }) + } +} + +func TestScopedAdminKeyPanelRateLimitSafeMethods(t *testing.T) { + for _, method := range []string{http.MethodGet, http.MethodHead, http.MethodOptions} { + t.Run(method, func(t *testing.T) { + allower := &fakePanelAllower{} + p := &PanelRateLimiter{limiter: allower, settingService: newPanelRateLimitTestService(t, + `{"enabled":true,"user_rpm":2,"heavy_rpm":1,"exempt_admin":true}`)} + r := gin.New() + r.Use(func(c *gin.Context) { + c.Set(string(ContextKeyUser), AuthSubject{UserID: 9}) + c.Set(string(ContextKeyUserRole), service.RoleAdmin) + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{KeyID: "read-key"})) + c.Next() + }, p.Global()) + r.Handle(method, "/test", func(c *gin.Context) { c.Status(http.StatusNoContent) }) + for _, want := range []int{http.StatusNoContent, http.StatusNoContent, http.StatusTooManyRequests} { + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(method, "/test", nil)) + require.Equal(t, want, w.Code) + } + require.NotContains(t, allower.counts, "panel:heavy:admin-key:read-key") + }) + } +} + +func TestScopedAdminKeyPanelRateLimitPreservesUnrestrictedAdminWrites(t *testing.T) { + for _, exempt := range []string{"true", "false"} { + t.Run(exempt, func(t *testing.T) { + allower := &fakePanelAllower{} + p := &PanelRateLimiter{limiter: allower, settingService: newPanelRateLimitTestService(t, + `{"enabled":true,"user_rpm":10,"heavy_rpm":1,"exempt_admin":`+exempt+`}`)} + r := gin.New() + r.Use(func(c *gin.Context) { + // JWT 与旧全权密钥都只有管理员用户身份,没有受限 Principal。 + c.Set(string(ContextKeyUser), AuthSubject{UserID: 9}) + c.Set(string(ContextKeyUserRole), service.RoleAdmin) + c.Next() + }, p.Global()) + r.POST("/test", func(c *gin.Context) { c.Status(http.StatusNoContent) }) + for i := 0; i < 2; i++ { + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/test", nil)) + require.Equal(t, http.StatusNoContent, w.Code) + } + require.NotContains(t, allower.counts, "panel:heavy:user:9") + if exempt == "true" { + require.Empty(t, allower.counts) + } else { + require.Equal(t, int64(2), allower.counts["panel:global:user:9"]) + } + }) + } +} diff --git a/backend/internal/server/middleware/custom_admin_keys_test.go b/backend/internal/server/middleware/custom_admin_keys_test.go new file mode 100644 index 0000000000..23d40240c8 --- /dev/null +++ b/backend/internal/server/middleware/custom_admin_keys_test.go @@ -0,0 +1,117 @@ +//go:build unit + +package middleware + +import ( + "context" + "encoding/json" + "net/http/httptest" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type adminAuthKeyRepo struct { + service.ScopedAdminKeyRepository + item *service.ScopedAdminKey +} + +func (r *adminAuthKeyRepo) InsertScopedAdminKey(_ context.Context, k *service.ScopedAdminKey) error { + r.item = k + return nil +} +func (r *adminAuthKeyRepo) GetScopedAdminKey(context.Context, string) (*service.ScopedAdminKey, error) { + return r.item, nil +} +func (r *adminAuthKeyRepo) TouchScopedAdminKey(context.Context, string, string, time.Time, string, time.Time) error { + return nil +} +func TestScopedAdminKeyAuthDefaultDenyAndCreatorStatus(t *testing.T) { + gin.SetMode(gin.TestMode) + repo := &adminAuthKeyRepo{} + settings := service.NewSettingService(nil, nil) + settings.SetScopedAdminKeyRepository(repo) + key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{Name: "只读", Enabled: true, Policy: adminaccess.Policy{GlobalPermissions: []string{"users.read"}}}, 9) + require.NoError(t, err) + active := true + users := service.NewUserService(&stubUserRepo{getByID: func(context.Context, int64) (*service.User, error) { + status := service.StatusActive + if !active { + status = "disabled" + } + return &service.User{ID: 9, Role: service.RoleAdmin, Status: status}, nil + }}, nil, nil, nil) + r := gin.New() + r.Use(gin.HandlerFunc(NewAdminAuthMiddleware(nil, users, settings, nil))) + for _, path := range []string{"/api/v1/admin/users", "/api/v1/admin/unknown", "/api/v1/admin/settings/admin-api-keys"} { + r.GET(path, func(c *gin.Context) { c.Status(204) }) + } + for _, tc := range []struct { + path string + status int + }{{"/api/v1/admin/users", 204}, {"/api/v1/admin/unknown", 403}, {"/api/v1/admin/settings/admin-api-keys", 403}} { + req := httptest.NewRequest("GET", tc.path, nil) + req.Header.Set("x-api-key", key) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, tc.status, w.Code, tc.path) + } + active = false + req := httptest.NewRequest("GET", "/api/v1/admin/users", nil) + req.Header.Set("x-api-key", key) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, 401, w.Code) +} +func TestLegacyAdminKeyCannotManageKeys(t *testing.T) { + r := gin.New() + r.Use(gin.HandlerFunc(NewAdminAuthMiddleware(nil, nil, nil, nil))) + r.POST("/api/v1/admin/settings/admin-api-key/regenerate", func(c *gin.Context) { t.Fatal("不应执行 handler") }) + req := httptest.NewRequest("POST", "/api/v1/admin/settings/admin-api-key/regenerate", nil) + req.Header.Set("x-api-key", "admin-legacy") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, 403, w.Code) +} + +func TestScopedAdminKeyAuditDenialOmitsSecrets(t *testing.T) { + repo := &auditCaptureRepository{} + audit := service.NewAuditLogService(repo, nil) + audit.Start() + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest("GET", "/api/v1/admin/accounts/123/forbidden?token=private-query", nil) + c.Request.Header.Set("x-api-key", "adm_sc_private-secret") + c.Status(403) + c.Set("admin_key_denial_reason", "permission_denied") + recordAdminKeyRequest(c, audit, &service.ScopedAdminKey{ID: "key-id", Hash: "private-hash", CreatedBy: 9, ScopedAdminKeyInput: service.ScopedAdminKeyInput{Name: "审计身份"}}) + audit.Stop() + repo.mu.Lock() + defer repo.mu.Unlock() + require.Len(t, repo.logs, 1) + entry := repo.logs[0] + require.Equal(t, "/api/v1/admin/accounts/123/forbidden", entry.Path) + require.Equal(t, "permission_denied", entry.Extra["denial_reason"]) + require.Equal(t, 403, entry.StatusCode) + require.Equal(t, "key-id", entry.Extra["admin_key_id"]) + require.Equal(t, "审计身份", entry.Extra["admin_key_name"]) + data, err := json.Marshal(entry) + require.NoError(t, err) + require.NotContains(t, string(data), "private-secret") + require.NotContains(t, string(data), "private-hash") +} + +func TestScopedAdminKeyMissingDependenciesFailClosed(t *testing.T) { + r := gin.New() + r.Use(gin.HandlerFunc(NewAdminAuthMiddleware(nil, nil, nil, nil))) + r.GET("/api/v1/admin/users", func(c *gin.Context) { t.Fatal("不应执行") }) + req := httptest.NewRequest("GET", "/api/v1/admin/users", nil) + req.Header.Set("x-api-key", "adm_sc_invalid") + w := httptest.NewRecorder() + require.NotPanics(t, func() { r.ServeHTTP(w, req) }) + require.Equal(t, 401, w.Code) +} diff --git a/backend/internal/server/middleware/panel_rate_limit.go b/backend/internal/server/middleware/panel_rate_limit.go index 1d7846997a..b9f2453d0f 100644 --- a/backend/internal/server/middleware/panel_rate_limit.go +++ b/backend/internal/server/middleware/panel_rate_limit.go @@ -9,6 +9,7 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/middleware" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/gin-gonic/gin" @@ -18,6 +19,8 @@ import ( // panelRateLimitWindow 面板限流固定窗口时长(所有档位均按每分钟计数)。 const panelRateLimitWindow = time.Minute +const panelHeavyRateLimitChecked = "panel_heavy_rate_limit_checked" + // panelRateLimitAllower 抽象底层限流原语,便于单测注入。 type panelRateLimitAllower interface { Allow(ctx context.Context, key string, limit int, window time.Duration) (middleware.AllowResult, error) @@ -26,7 +29,7 @@ type panelRateLimitAllower interface { // PanelRateLimiter 面板(管理面 /api/v1)API 限流器。 // // 设计要点: -// - 认证接口按「用户 ID」维度计数:与客户端 IP 完全无关,反向代理/共享出口 +// - 认证接口按「用户 ID」维度计数,受限管理密钥按 Key ID 独立计数:与客户端 IP 完全无关,反向代理/共享出口 // (所有请求源 IP 坍缩为 127.0.0.1 等)不会互相误伤。 // - 公开接口按安全客户端 IP 计数:仅统计全局单播地址,回环/内网/链路本地 // 地址(反代内部转发地址)直接跳过,避免误拦整条反代链路的流量。 @@ -46,6 +49,7 @@ func NewPanelRateLimiter(redisClient *redis.Client, settingService *service.Sett } // Global 认证面板接口的全局按用户限流(宽松档,覆盖所有登录后端点)。 +// 受限管理密钥不享管理员豁免,变更类请求额外消耗严格档额度。 func (p *PanelRateLimiter) Global() gin.HandlerFunc { return p.userScoped("global", func(s service.PanelRateLimitSettings) int { return s.UserRPM }) } @@ -67,35 +71,52 @@ func (p *PanelRateLimiter) userScoped(scope string, limitOf func(service.PanelRa c.Next() return } - limit := limitOf(settings) - if limit <= 0 { - c.Next() - return - } subject, ok := GetAuthSubjectFromContext(c) if !ok || subject.UserID <= 0 { // 无认证主体(认证中间件缺位时的防御分支):放行,避免误伤 c.Next() return } - if settings.ExemptAdmin { + principal := adminaccess.FromContext(c.Request.Context()) + if settings.ExemptAdmin && principal == nil { if role, hasRole := GetUserRoleFromContext(c); hasRole && role == service.RoleAdmin { c.Next() return } } - key := "panel:" + scope + ":user:" + strconv.FormatInt(subject.UserID, 10) - result, err := p.limiter.Allow(c.Request.Context(), key, limit, panelRateLimitWindow) - if err != nil { - // fail-open:Redis 异常不阻断面板访问 - slog.Warn("panel rate limit check failed, allowing request", "scope", scope, "error", err) - c.Next() - return + identity := "user:" + strconv.FormatInt(subject.UserID, 10) + if principal != nil { + identity = "admin-key:" + principal.KeyID } - if !result.Allowed { - abortPanelRateLimited(c, result.RetryAfter) - return + type rateLimitCheck struct { + scope string + limit int + } + checks := []rateLimitCheck{{scope, limitOf(settings)}} + if scope == "global" && principal != nil && c.Request.Method != http.MethodGet && + c.Request.Method != http.MethodHead && c.Request.Method != http.MethodOptions { + checks = append(checks, rateLimitCheck{"heavy", settings.HeavyRPM}) + } + for _, check := range checks { + if check.limit <= 0 || (principal != nil && check.scope == "heavy" && c.GetBool(panelHeavyRateLimitChecked)) { + continue + } + if principal != nil && check.scope == "heavy" { + // Global 已为受限密钥写入计数,路由再挂 Heavy 时不能重复消耗额度。 + c.Set(panelHeavyRateLimitChecked, true) + } + key := "panel:" + check.scope + ":" + identity + result, err := p.limiter.Allow(c.Request.Context(), key, check.limit, panelRateLimitWindow) + if err != nil { + // fail-open:Redis 异常不阻断面板访问。 + slog.Warn("panel rate limit check failed, allowing request", "scope", check.scope, "error", err) + continue + } + if !result.Allowed { + abortPanelRateLimited(c, result.RetryAfter) + return + } } c.Next() } diff --git a/backend/internal/server/routes/admin.go b/backend/internal/server/routes/admin.go index 315fc20e42..fbeac5fe11 100644 --- a/backend/internal/server/routes/admin.go +++ b/backend/internal/server/routes/admin.go @@ -30,6 +30,8 @@ func RegisterAdminRoutes( // 审计中间件挂在认证之后:所有管理面变更类操作 + 敏感读取入审计日志 admin.Use(gin.HandlerFunc(auditLog)) admin.Use(middleware.AdminComplianceGuard(settingService)) + // 受限密钥的账户操作走独立资源校验,普通管理员保持原处理器。 + admin.Use(h.Admin.Account.ScopedAdminKeyAccounts) { // 部署与运营合规确认 registerAdminComplianceRoutes(admin, h) @@ -74,7 +76,7 @@ func RegisterAdminRoutes( registerPromoCodeRoutes(admin, h) // 系统设置 - registerSettingsRoutes(admin, h) + registerSettingsRoutes(admin, h, stepUpAuth) // 数据管理 registerDataManagementRoutes(admin, h, stepUpAuth) @@ -326,6 +328,7 @@ func registerUserManagementRoutes(admin *gin.RouterGroup, h *handler.Handlers) { func registerGroupRoutes(admin *gin.RouterGroup, h *handler.Handlers) { groups := admin.Group("/groups") + groups.Use(h.Admin.Group.ScopedAdminKeyGroupModels) { groups.GET("", h.Admin.Group.List) groups.GET("/all", h.Admin.Group.GetAll) @@ -564,8 +567,9 @@ func registerPromoCodeRoutes(admin *gin.RouterGroup, h *handler.Handlers) { } } -func registerSettingsRoutes(admin *gin.RouterGroup, h *handler.Handlers) { +func registerSettingsRoutes(admin *gin.RouterGroup, h *handler.Handlers, stepUpAuth middleware.StepUpAuthMiddleware) { adminSettings := admin.Group("/settings") + registerScopedAdminKeyRoutes(adminSettings, h, stepUpAuth) { adminSettings.GET("", h.Admin.Setting.GetSettings) adminSettings.PUT("", h.Admin.Setting.UpdateSettings) @@ -578,8 +582,8 @@ func registerSettingsRoutes(admin *gin.RouterGroup, h *handler.Handlers) { adminSettings.POST("/email-templates/:event/:locale/restore-official", h.Admin.Setting.RestoreOfficialEmailTemplate) // Admin API Key 管理 adminSettings.GET("/admin-api-key", h.Admin.Setting.GetAdminAPIKey) - adminSettings.POST("/admin-api-key/regenerate", h.Admin.Setting.RegenerateAdminAPIKey) - adminSettings.DELETE("/admin-api-key", h.Admin.Setting.DeleteAdminAPIKey) + adminSettings.POST("/admin-api-key/regenerate", gin.HandlerFunc(stepUpAuth), h.Admin.Setting.RegenerateAdminAPIKey) + adminSettings.DELETE("/admin-api-key", gin.HandlerFunc(stepUpAuth), h.Admin.Setting.DeleteAdminAPIKey) // 529过载冷却配置 adminSettings.GET("/overload-cooldown", h.Admin.Setting.GetOverloadCooldownSettings) adminSettings.PUT("/overload-cooldown", h.Admin.Setting.UpdateOverloadCooldownSettings) diff --git a/backend/internal/server/routes/custom_admin_key_access_test.go b/backend/internal/server/routes/custom_admin_key_access_test.go new file mode 100644 index 0000000000..32794e1b88 --- /dev/null +++ b/backend/internal/server/routes/custom_admin_key_access_test.go @@ -0,0 +1,420 @@ +//go:build unit + +package routes + +import ( + "context" + "encoding/json" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/handler" + adminhandler "github.com/Wei-Shaw/sub2api/internal/handler/admin" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type scopedRouteKeys struct { + service.ScopedAdminKeyRepository + item *service.ScopedAdminKey +} + +func (r *scopedRouteKeys) InsertScopedAdminKey(_ context.Context, item *service.ScopedAdminKey) error { + r.item = item + return nil +} +func (r *scopedRouteKeys) GetScopedAdminKey(context.Context, string) (*service.ScopedAdminKey, error) { + return r.item, nil +} +func (r *scopedRouteKeys) TouchScopedAdminKey(context.Context, string, string, time.Time, string, time.Time) error { + return nil +} + +type scopedRouteUsers struct{ service.UserRepository } + +type scopedRouteModelSettings struct{ service.SettingRepository } + +func (*scopedRouteModelSettings) Get(context.Context, string) (*service.Setting, error) { + return nil, service.ErrSettingNotFound +} + +func (*scopedRouteUsers) GetByID(context.Context, int64) (*service.User, error) { + return &service.User{ID: 9, Role: service.RoleAdmin, Status: service.StatusActive}, nil +} +func (*scopedRouteUsers) GetUserAvatar(context.Context, int64) (*service.UserAvatar, error) { + return nil, nil +} + +type scopedRouteAccounts struct { + service.AdminService + t *testing.T +} + +func (*scopedRouteAccounts) GetAccount(_ context.Context, id int64) (*service.Account, error) { + a := &service.Account{ID: id, Type: "oauth", Platform: "openai", GroupIDs: []int64{1, 2}, Credentials: map[string]any{"access_token": "绝不返回的凭证", "model_mapping": map[string]any{"custom-model": "upstream-model"}}, Extra: map[string]any{"secret": "绝不返回的扩展"}} + if id == 2 { + a.Type = "apikey" + } + if id == 3 { + a.GroupIDs = []int64{2} + } + if id == 4 { + a.Platform = "anthropic" + } + if id == 5 { + a.Credentials["auth_mode"] = service.OpenAIAuthModePersonalAccessToken + } + if id == 6 { + a.Credentials["auth_mode"] = service.OpenAIAuthModeAgentIdentity + a.Credentials["agent_private_key"] = "绝不返回的代理身份私钥" + } + return a, nil +} +func (s *scopedRouteAccounts) ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string) ([]service.Account, int64, error) { + s.t.Fatal("本测试中列表必须在权限准入阶段被拒绝") + return nil, 0, nil +} +func (s *scopedRouteAccounts) ScopedAdminWrite(context.Context, int64, string, map[string]json.RawMessage, func(context.Context, *service.Account) (*service.Account, error)) (*service.Account, error) { + s.t.Fatal("未授予写权限,不应进入写服务") + return nil, nil +} + +func TestScopedAdminRegisteredRoutesEnforceDefaultDenyAndAccountScope(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, withRead := range []bool{false, true} { + t.Run(map[bool]string{false: "仅分组不赋权", true: "只读OAuth指定组"}[withRead], func(t *testing.T) { + rule := adminaccess.Rule{GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}} + if withRead { + rule.Permissions = []string{"accounts.read"} + } + keys := &scopedRouteKeys{} + settings := service.NewSettingService(nil, nil) + settings.SetScopedAdminKeyRepository(keys) + key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{Name: "路由验收", Enabled: true, Policy: adminaccess.Policy{Rules: []adminaccess.Rule{rule}}}, 9) + require.NoError(t, err) + users := service.NewUserService(&scopedRouteUsers{}, nil, nil, nil) + auth := middleware.NewAdminAuthMiddleware(nil, users, settings, nil) + accountHandler := adminhandler.NewAccountHandler(&scopedRouteAccounts{t: t}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + r := gin.New() + RegisterAdminRoutes(r.Group("/api/v1"), &handler.Handlers{Admin: &handler.AdminHandlers{Account: accountHandler, Setting: adminhandler.NewSettingHandler(settings, nil, nil, nil, nil, nil, nil)}}, auth, middleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() }), middleware.StepUpAuthMiddleware(func(c *gin.Context) { c.Next() }), nil, nil) + RegisterPaymentRoutes(r.Group("/api/v1"), &handler.PaymentHandler{}, &handler.PaymentWebhookHandler{}, &adminhandler.PaymentHandler{}, middleware.JWTAuthMiddleware(func(c *gin.Context) { c.Next() }), auth, middleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() }), nil, nil, nil) + for _, tc := range []struct{ method, path string }{ + {"GET", "/api/v1/admin/accounts/1"}, + {"GET", "/api/v1/admin/accounts/2"}, + {"GET", "/api/v1/admin/accounts/3"}, + {"GET", "/api/v1/admin/accounts/5"}, + {"GET", "/api/v1/admin/accounts/6"}, + {"DELETE", "/api/v1/admin/accounts/1"}, + {"GET", "/api/v1/admin/users"}, + {"PUT", "/api/v1/admin/settings"}, + {"GET", "/api/v1/admin/settings/admin-api-keys"}, + {"GET", "/api/v1/admin/groups"}, + {"GET", "/api/v1/admin/payment/orders"}, + {"POST", "/api/v1/admin/payment/orders/1/refund"}, + {"PUT", "/api/v1/admin/payment/config"}, + } { + req := httptest.NewRequest(tc.method, tc.path, nil) + req.Header.Set("x-api-key", key) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + want := 403 + if withRead && tc.method == "GET" { + switch tc.path { + case "/api/v1/admin/accounts/1", "/api/v1/admin/accounts/5", "/api/v1/admin/accounts/6": + want = 200 + case "/api/v1/admin/accounts/2", "/api/v1/admin/accounts/3": + want = 404 + } + } + require.Equal(t, want, w.Code, tc.method+" "+tc.path+": "+w.Body.String()) + require.NotContains(t, w.Body.String(), "绝不返回") + require.NotContains(t, w.Body.String(), "auth_mode") + require.NotContains(t, w.Body.String(), "agent_private_key") + if want == 200 { + require.Contains(t, w.Body.String(), `"group_ids":[1]`) + } + } + }) + } +} + +func TestScopedAdminRegisteredModelDefaultsRequireExplicitPermission(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, allowed := range []bool{false, true} { + policy := adminaccess.Policy{} + if allowed { + policy.GlobalPermissions = []string{"models.defaults.read"} + } + keys := &scopedRouteKeys{} + settings := service.NewSettingService(&scopedRouteModelSettings{}, nil) + settings.SetScopedAdminKeyRepository(keys) + key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{Name: "默认模型读取", Enabled: true, Policy: policy}, 9) + require.NoError(t, err) + users := service.NewUserService(&scopedRouteUsers{}, nil, nil, nil) + auth := middleware.NewAdminAuthMiddleware(nil, users, settings, nil) + accountHandler := adminhandler.NewAccountHandler(&scopedRouteAccounts{t: t}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + r := gin.New() + RegisterAdminRoutes(r.Group("/api/v1"), &handler.Handlers{Admin: &handler.AdminHandlers{Account: accountHandler, Setting: adminhandler.NewSettingHandler(settings, nil, nil, nil, nil, nil, nil)}}, auth, middleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() }), middleware.StepUpAuthMiddleware(func(c *gin.Context) { c.Next() }), nil, nil) + for _, path := range []string{"/api/v1/admin/accounts/antigravity/default-model-mapping"} { + req := httptest.NewRequest("GET", path, nil) + req.Header.Set("x-api-key", key) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + want := 403 + if allowed { + want = 200 + } + require.Equal(t, want, w.Code, w.Body.String()) + if allowed { + require.Contains(t, w.Body.String(), `"data":{`) + } + } + } +} + +// 使用真实注册路由,验证旧 Key 的模型读写入口也能进入受限处理器。 +func TestScopedAdminRegisteredLegacyModelInterfaces(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, permission := range []string{"accounts.read", "accounts.models.write", "models.defaults.read"} { + t.Run(permission, func(t *testing.T) { + policy := adminaccess.Policy{} + if permission == "models.defaults.read" { + policy.GlobalPermissions = []string{permission} + } else { + policy.Rules = []adminaccess.Rule{{Permissions: []string{permission}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}} + } + keys := &scopedRouteKeys{} + settings := service.NewSettingService(nil, nil) + settings.SetScopedAdminKeyRepository(keys) + key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{Name: "原模型接口", Enabled: true, Policy: policy}, 9) + require.NoError(t, err) + users := service.NewUserService(&scopedRouteUsers{}, nil, nil, nil) + auth := middleware.NewAdminAuthMiddleware(nil, users, settings, nil) + accounts := &scopedRouteModelAccounts{scopedRouteAccounts: scopedRouteAccounts{t: t}, t: t} + accountHandler := adminhandler.NewAccountHandler(accounts, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + r := gin.New() + RegisterAdminRoutes(r.Group("/api/v1"), &handler.Handlers{Admin: &handler.AdminHandlers{Account: accountHandler}}, auth, middleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() }), middleware.StepUpAuthMiddleware(func(c *gin.Context) { c.Next() }), nil, nil) + for _, tc := range []struct { + method, path, body string + want int + }{ + {"GET", "/api/v1/admin/accounts/1/models", "", 200}, + {"GET", "/api/v1/admin/accounts/2/models", "", 404}, + {"GET", "/api/v1/admin/accounts/3/models", "", 404}, + {"GET", "/api/v1/admin/accounts/4/models", "", 404}, + {"GET", "/api/v1/admin/accounts/1", "", 200}, + {"POST", "/api/v1/admin/accounts/bulk-update", `{"account_ids":[1],"credentials":{"model_mapping":{"custom-model":"upstream-model"}}}`, 200}, + {"PUT", "/api/v1/admin/accounts/1", `{"credentials":{"model_mapping":{"custom-model":"upstream-model"}}}`, 200}, + } { + want := tc.want + if (tc.method == "GET" && permission != "accounts.read") || (tc.method != "GET" && permission != "accounts.models.write") { + want = 403 + } + req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body)) + req.Header.Set("x-api-key", key) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, want, w.Code, tc.method+" "+tc.path+": "+w.Body.String()) + require.NotContains(t, w.Body.String(), "绝不返回") + if tc.method == "GET" && want == 200 { + require.Contains(t, w.Body.String(), "custom-model") + } + } + if permission == "accounts.models.write" { + require.Equal(t, []int64{1, 1}, accounts.writes) + } else { + require.Empty(t, accounts.writes) + } + }) + } +} + +type scopedRouteModelAccounts struct { + scopedRouteAccounts + t *testing.T + writes []int64 +} + +func (s *scopedRouteModelAccounts) ScopedAdminWrite(_ context.Context, id int64, action string, fields map[string]json.RawMessage, run func(context.Context, *service.Account) (*service.Account, error)) (*service.Account, error) { + require.Empty(s.t, action) + require.Nil(s.t, run) + body, err := json.Marshal(fields) + require.NoError(s.t, err) + require.JSONEq(s.t, `{"credentials":{"model_mapping":{"custom-model":"upstream-model"}}}`, string(body)) + s.writes = append(s.writes, id) + return &service.Account{ID: id}, nil +} + +func TestScopedAdminCodexImportRouteReachesValidation(t *testing.T) { + gin.SetMode(gin.TestMode) + keys := &scopedRouteKeys{} + settings := service.NewSettingService(nil, nil) + settings.SetScopedAdminKeyRepository(keys) + policy := adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.create", "accounts.credentials"}, GroupIDs: []int64{2}, AccountTypes: []string{"oauth"}}}} + key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{Name: "导入回归", Enabled: true, Policy: policy}, 9) + require.NoError(t, err) + users := service.NewUserService(&scopedRouteUsers{}, nil, nil, nil) + auth := middleware.NewAdminAuthMiddleware(nil, users, settings, nil) + accountHandler := adminhandler.NewAccountHandler(&scopedRouteAccounts{t: t}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + r := gin.New() + RegisterAdminRoutes(r.Group("/api/v1"), &handler.Handlers{Admin: &handler.AdminHandlers{Account: accountHandler}}, auth, middleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() }), middleware.StepUpAuthMiddleware(func(c *gin.Context) { c.Next() }), nil, nil) + req := httptest.NewRequest("POST", "/api/v1/admin/accounts/import/codex-session", strings.NewReader(`{"content":"","group_ids":[2]}`)) + req.Header.Set("x-api-key", key) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, 400, w.Code, w.Body.String()) +} + +type scopedRouteCodexAccounts struct { + service.AdminService + created bool +} + +func (*scopedRouteCodexAccounts) ScopedAdminCodexCandidates(context.Context, service.ScopedCodexIdentity) ([]service.Account, error) { + return nil, nil +} +func (s *scopedRouteCodexAccounts) ScopedAdminCreateCodex(_ context.Context, input *service.CreateAccountInput) (*service.Account, error) { + s.created = true + return &service.Account{ID: 100, Credentials: input.Credentials}, nil +} +func (*scopedRouteCodexAccounts) ScopedAdminUpdateCodex(context.Context, int64, *service.UpdateAccountInput, func(*service.Account, *service.UpdateAccountInput) error) (*service.Account, error) { + panic("本用例不能更新已有账户") +} +func TestScopedAdminCodexImportAuthenticatedRoute(t *testing.T) { + for _, allowed := range []bool{false, true} { + t.Run(map[bool]string{false: "未勾选拒绝", true: "无读取权限可导入"}[allowed], func(t *testing.T) { + gin.SetMode(gin.TestMode) + rule := adminaccess.Rule{Permissions: []string{"accounts.credentials", "accounts.schedule"}, GroupIDs: []int64{2}, AccountTypes: []string{"oauth"}} + if allowed { + rule.Permissions = append(rule.Permissions, "accounts.create") + } + settings := service.NewSettingService(nil, nil) + settings.SetScopedAdminKeyRepository(&scopedRouteKeys{}) + key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{Name: "导入鉴权", Enabled: true, Policy: adminaccess.Policy{Rules: []adminaccess.Rule{rule}}}, 9) + require.NoError(t, err) + users := service.NewUserService(&scopedRouteUsers{}, nil, nil, nil) + auth := middleware.NewAdminAuthMiddleware(nil, users, settings, nil) + api := &scopedRouteCodexAccounts{} + h := adminhandler.NewAccountHandler(api, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + r := gin.New() + RegisterAdminRoutes(r.Group("/api/v1"), &handler.Handlers{Admin: &handler.AdminHandlers{Account: h}}, auth, middleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() }), middleware.StepUpAuthMiddleware(func(c *gin.Context) { c.Next() }), nil, nil) + req := httptest.NewRequest("POST", "/api/v1/admin/accounts/import/codex-session", strings.NewReader(`{"content":"{\"access_token\":\"test-private-access\",\"refresh_token\":\"test-private-refresh\"}","group_ids":[2]}`)) + req.Header.Set("x-api-key", key) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + if allowed { + require.Equal(t, 200, w.Code, w.Body.String()) + require.Contains(t, w.Body.String(), `"created":1`) + } else { + require.Equal(t, 403, w.Code, w.Body.String()) + } + require.Equal(t, allowed, api.created) + require.NotContains(t, w.Body.String(), "test-private") + }) + } +} + +type scopedRouteProxyOptions struct { + service.AdminService + page, size int +} + +func (s *scopedRouteProxyOptions) ListProxyOptions(_ context.Context, page, size int, _ string) ([]service.Proxy, int64, error) { + s.page = page + s.size = size + return []service.Proxy{{ID: 10, Name: "代理候选", Host: "192.0.2.1", Port: 8080, Username: "秘密用户", Password: "秘密密码", Status: service.StatusActive}}, 20001, nil +} +func (s *scopedRouteProxyOptions) SampleProxyOptions(_ context.Context, _ string) ([]service.Proxy, int64, error) { + s.page = 0 + s.size = 50 + return []service.Proxy{{ID: 12345, Name: "全池候选", Username: "秘密用户", Password: "秘密密码"}}, 20001, nil +} + +func TestScopedAdminProxyReadPermissionAndBoundedRoutes(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, allowed := range []bool{false, true} { + t.Run(map[bool]string{false: "网络权限不含列表", true: "独立代理读取"}[allowed], func(t *testing.T) { + policy := adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.network"}, AllGroups: true, AccountTypes: []string{"oauth"}}}} + if allowed { + policy.GlobalPermissions = []string{"proxies.read"} + } + settings := service.NewSettingService(nil, nil) + settings.SetScopedAdminKeyRepository(&scopedRouteKeys{}) + key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{Name: "代理读取", Enabled: true, Policy: policy}, 9) + require.NoError(t, err) + users := service.NewUserService(&scopedRouteUsers{}, nil, nil, nil) + auth := middleware.NewAdminAuthMiddleware(nil, users, settings, nil) + svc := &scopedRouteProxyOptions{} + r := gin.New() + RegisterAdminRoutes(r.Group("/api/v1"), &handler.Handlers{Admin: &handler.AdminHandlers{Proxy: adminhandler.NewProxyHandler(svc)}}, auth, middleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() }), middleware.StepUpAuthMiddleware(func(c *gin.Context) { c.Next() }), nil, nil) + for _, path := range []string{"/api/v1/admin/proxies", "/api/v1/admin/proxies/all"} { + req := httptest.NewRequest("GET", path+"?page=2&page_size=20000", nil) + req.Header.Set("x-api-key", key) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + if !allowed { + require.Equal(t, 403, w.Code, w.Body.String()) + continue + } + require.Equal(t, 200, w.Code, w.Body.String()) + require.Equal(t, 2, svc.page) + require.Equal(t, 100, svc.size) + require.NotContains(t, w.Body.String(), "username") + require.NotContains(t, w.Body.String(), "password") + require.NotContains(t, w.Body.String(), "秘密") + if strings.HasSuffix(path, "/all") { + require.Equal(t, "20001", w.Header().Get("X-Total-Count")) + require.Equal(t, "100", w.Header().Get("X-Page-Size")) + require.Contains(t, w.Body.String(), `"data":[`) + } else { + require.Contains(t, w.Body.String(), `"total":20001`) + require.Contains(t, w.Body.String(), `"page_size":100`) + } + } + req := httptest.NewRequest("GET", "/api/v1/admin/proxies/all", nil) + req.Header.Set("x-api-key", key) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + if allowed { + require.Equal(t, 200, w.Code, w.Body.String()) + require.Equal(t, 0, svc.page) + require.Equal(t, 50, svc.size) + require.Contains(t, w.Body.String(), `"id":12345`) + require.NotContains(t, w.Body.String(), "秘密") + } else { + require.Equal(t, 403, w.Code) + } + for _, path := range []string{"/api/v1/admin/proxies/data", "/api/v1/admin/proxies/10/accounts", "/api/v1/admin/proxies/10/stats"} { + req := httptest.NewRequest("GET", path, nil) + req.Header.Set("x-api-key", key) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, 403, w.Code) + } + }) + } +} + +func TestScopedAdminRegisteredRoutesExcludeForkOnlyEndpoints(t *testing.T) { + gin.SetMode(gin.TestMode) + r := gin.New() + RegisterAdminRoutes(r.Group("/api/v1"), &handler.Handlers{Admin: &handler.AdminHandlers{}}, middleware.AdminAuthMiddleware(func(c *gin.Context) { c.Next() }), middleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() }), middleware.StepUpAuthMiddleware(func(c *gin.Context) { c.Next() }), nil, nil) + paths := map[string]bool{} + for _, route := range r.Routes() { + paths[route.Method+" "+route.Path] = true + } + for _, path := range []string{"GET /api/v1/admin/model-catalog", "GET /api/v1/admin/proxies/options", "GET /api/v1/admin/groups/:id/models-list-candidates"} { + require.False(t, paths[path], path) + } + for _, path := range []string{"GET /api/v1/admin/proxies", "GET /api/v1/admin/proxies/all", "GET /api/v1/admin/groups/:id/model-allowlist-candidates", "POST /api/v1/admin/accounts/import/codex-session"} { + require.True(t, paths[path], path) + } +} diff --git a/backend/internal/server/routes/custom_admin_key_group_models_test.go b/backend/internal/server/routes/custom_admin_key_group_models_test.go new file mode 100644 index 0000000000..05657e6719 --- /dev/null +++ b/backend/internal/server/routes/custom_admin_key_group_models_test.go @@ -0,0 +1,203 @@ +//go:build unit + +package routes + +import ( + "context" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/handler" + adminhandler "github.com/Wei-Shaw/sub2api/internal/handler/admin" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type scopedRouteGroupModels struct { + service.AdminService + writes []int64 +} + +func (*scopedRouteGroupModels) GetGroup(_ context.Context, id int64) (*service.Group, error) { + if id == 99 { + return nil, service.ErrGroupNotFound + } + platform := "openai" + if id == 4 { + platform = "anthropic" + } + return &service.Group{ID: id, Name: "模型分组", Platform: platform, RateMultiplier: 9, Description: "不可泄露的分组备注", ModelAllowlist: service.GroupModelAllowlist{Enabled: true, Models: []string{"gpt-test"}}}, nil +} + +func (*scopedRouteGroupModels) GetGroupModelsListCandidates(context.Context, int64, string) ([]string, error) { + return []string{"gpt-test", "gpt-default"}, nil +} + +func (s *scopedRouteGroupModels) ScopedAdminListGroupModels(ctx context.Context, _ pagination.PaginationParams, _ bool, _, _, _ string) ([]service.Group, int64, error) { + g, err := s.GetGroup(ctx, 2) + return []service.Group{*g}, 1, err +} + +func (s *scopedRouteGroupModels) ScopedAdminUpdateGroupModels(ctx context.Context, id int64, cfg service.GroupModelAllowlist) (*service.Group, error) { + s.writes = append(s.writes, id) + g, err := s.GetGroup(ctx, id) + if err == nil { + g.ModelAllowlist = cfg + } + return g, err +} + +func TestScopedAdminRegisteredGroupModelInterfaces(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, permission := range []string{"groups.models.read", "groups.models.write", "accounts.models.write", "models.defaults.read", ""} { + t.Run(permission, func(t *testing.T) { + keys := &scopedRouteKeys{} + settings := service.NewSettingService(nil, nil) + settings.SetScopedAdminKeyRepository(keys) + policy := adminaccess.Policy{} + if permission != "" { + policy.Rules = []adminaccess.Rule{{Permissions: []string{permission}, GroupIDs: []int64{2}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}} + } + if permission == "models.defaults.read" { + policy = adminaccess.Policy{GlobalPermissions: []string{permission}} + } + key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{Name: "分组模型接口", Enabled: true, Policy: policy}, 9) + require.NoError(t, err) + users := service.NewUserService(&scopedRouteUsers{}, nil, nil, nil) + auth := middleware.NewAdminAuthMiddleware(nil, users, settings, nil) + api := &scopedRouteGroupModels{} + r := gin.New() + RegisterAdminRoutes(r.Group("/api/v1"), &handler.Handlers{Admin: &handler.AdminHandlers{Group: adminhandler.NewGroupHandler(api, nil, nil)}}, auth, middleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() }), middleware.StepUpAuthMiddleware(func(c *gin.Context) { c.Next() }), nil, nil) + for _, tc := range []struct { + method, path, body, allowed string + }{ + {"GET", "/api/v1/admin/groups", "", "groups.models.read"}, + {"GET", "/api/v1/admin/groups/all", "", "groups.models.read"}, + {"GET", "/api/v1/admin/groups/2", "", "groups.models.read"}, + {"GET", "/api/v1/admin/groups/2/model-allowlist-candidates", "", "groups.models.read"}, + {"GET", "/api/v1/admin/groups/0/model-allowlist-candidates?platform=openai", "", "models.defaults.read"}, + {"PUT", "/api/v1/admin/groups/2", `{"model_allowlist":{"enabled":true,"models":["gpt-test"]}}`, "groups.models.write"}, + } { + req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body)) + req.Header.Set("x-api-key", key) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + want := 403 + if permission == tc.allowed { + want = 200 + } + if permission == "models.defaults.read" && strings.Contains(tc.path, "/groups/2/") { + want = 404 // 默认目录权限不允许读取现有分组中的账户模型。 + } + require.Equal(t, want, w.Code, tc.method+" "+tc.path+": "+w.Body.String()) + require.NotContains(t, w.Body.String(), "不可泄露") + require.NotContains(t, w.Body.String(), "models_list_config") + require.NotContains(t, w.Body.String(), "display_only") + if want == 200 { + require.Contains(t, w.Body.String(), "gpt-test") + } + } + }) + } +} + +func TestScopedAdminGroupModelsRejectUnauthorizedGroupsAndMixedFields(t *testing.T) { + gin.SetMode(gin.TestMode) + api := &scopedRouteGroupModels{} + h := adminhandler.NewGroupHandler(api, nil, nil) + r := gin.New() + r.Use(func(c *gin.Context) { + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"groups.models.read", "groups.models.write"}, GroupIDs: []int64{2, 4}, Platforms: []string{"openai"}}}}})) + }) + r.Use(h.ScopedAdminKeyGroupModels) + r.GET("/api/v1/admin/groups/:id", h.GetByID) + r.GET("/api/v1/admin/groups/:id/model-allowlist-candidates", h.GetGroupModelAllowlistCandidates) + r.PUT("/api/v1/admin/groups/:id", h.Update) + for _, tc := range []struct { + method, path, body string + want int + }{ + {"GET", "/api/v1/admin/groups/3", "", 404}, + {"GET", "/api/v1/admin/groups/4", "", 404}, + {"GET", "/api/v1/admin/groups/99", "", 404}, + {"GET", "/api/v1/admin/groups/3/model-allowlist-candidates", "", 404}, + {"GET", "/api/v1/admin/groups/0/model-allowlist-candidates", "", 403}, + {"GET", "/api/v1/admin/groups/2/model-allowlist-candidates?platform=anthropic", "", 400}, + {"PUT", "/api/v1/admin/groups/3", `{"model_allowlist":{"models":["x"]}}`, 404}, + {"PUT", "/api/v1/admin/groups/4", `{"model_allowlist":{"models":["x"]}}`, 404}, + {"PUT", "/api/v1/admin/groups/2", `{"rate_multiplier":1,"model_allowlist":{"models":["x"]}}`, 400}, + {"PUT", "/api/v1/admin/groups/2", `{"copy_accounts_from_group_ids":[3]}`, 400}, + {"PUT", "/api/v1/admin/groups/2", `{"status":"inactive"}`, 400}, + {"PUT", "/api/v1/admin/groups/2", `{"model_allowlist":{},"models_list_config":{}}`, 400}, + {"PUT", "/api/v1/admin/groups/2", `{"model_allowlist":{"foo":true}}`, 400}, + {"PUT", "/api/v1/admin/groups/2", `{"model_allowlist":null}`, 400}, + {"PUT", "/api/v1/admin/groups/2", `{"models_list_config":{"enabled":true,"models":["x"]}}`, 400}, + } { + req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, tc.want, w.Code, tc.method+" "+tc.path+": "+w.Body.String()) + require.NotContains(t, w.Body.String(), "不可泄露") + require.NotContains(t, w.Body.String(), "模型分组") + } + require.Empty(t, api.writes) +} + +type scopedRouteAllowlistRepository struct { + service.AdminGroupRepository + config service.GroupModelAllowlist + writes int +} + +func (r *scopedRouteAllowlistRepository) GetByID(_ context.Context, id int64) (*service.Group, error) { + return &service.Group{ID: id, Platform: service.PlatformOpenAI, ModelAllowlist: r.config}, nil +} +func (r *scopedRouteAllowlistRepository) ScopedAdminUpdateGroupModels(ctx context.Context, id int64, cfg service.GroupModelAllowlist) (*service.Group, error) { + r.config = cfg + r.writes++ + return r.GetByID(ctx, id) +} + +// 注册路由与真实管理服务共同验证白名单准入语义,仓储替身仅代替持久化。 +func TestScopedAdminRegisteredGroupModelsUseUpstreamAllowlistSemantics(t *testing.T) { + gin.SetMode(gin.TestMode) + repo := &scopedRouteAllowlistRepository{} + api := service.NewAdminService(nil, nil, repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + settings := service.NewSettingService(nil, nil) + settings.SetScopedAdminKeyRepository(&scopedRouteKeys{}) + key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{Name: "白名单验证", Enabled: true, Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"groups.models.read", "groups.models.write"}, GroupIDs: []int64{2}, Platforms: []string{service.PlatformOpenAI}}}}}, 9) + require.NoError(t, err) + auth := middleware.NewAdminAuthMiddleware(nil, service.NewUserService(&scopedRouteUsers{}, nil, nil, nil), settings, nil) + r := gin.New() + RegisterAdminRoutes(r.Group("/api/v1"), &handler.Handlers{Admin: &handler.AdminHandlers{Group: adminhandler.NewGroupHandler(api, nil, nil)}}, auth, middleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() }), middleware.StepUpAuthMiddleware(func(c *gin.Context) { c.Next() }), nil, nil) + call := func(body string) *httptest.ResponseRecorder { + req := httptest.NewRequest("PUT", "/api/v1/admin/groups/2", strings.NewReader(body)) + req.Header.Set("x-api-key", key) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + return w + } + for _, body := range []string{`{"model_allowlist":{"enabled":true,"models":[]}}`, `{"models_list_config":{"enabled":true,"models":["gpt-allowed"]}}`} { + w := call(body) + require.Equal(t, 400, w.Code, w.Body.String()) + require.Zero(t, repo.writes) + } + w := call(`{"model_allowlist":{"enabled":true,"models":[" GPT-Allowed ","gpt-allowed","other-*"]}}`) + require.Equal(t, 200, w.Code, w.Body.String()) + require.Equal(t, 1, repo.writes) + require.Equal(t, []string{"GPT-Allowed", "other-*"}, repo.config.Models) + require.True(t, repo.config.Allows("gpt-allowed")) + require.True(t, repo.config.Allows("other-model")) + require.False(t, repo.config.Allows("blocked-model")) + require.Contains(t, w.Body.String(), `"model_allowlist"`) + require.NotContains(t, w.Body.String(), "models_list_config") + require.NotContains(t, w.Body.String(), "display_only") +} diff --git a/backend/internal/server/routes/custom_admin_key_payment_rate_limit_test.go b/backend/internal/server/routes/custom_admin_key_payment_rate_limit_test.go new file mode 100644 index 0000000000..7db8f6af69 --- /dev/null +++ b/backend/internal/server/routes/custom_admin_key_payment_rate_limit_test.go @@ -0,0 +1,54 @@ +//go:build unit + +package routes + +import ( + "context" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/handler" + adminhandler "github.com/Wei-Shaw/sub2api/internal/handler/admin" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/alicebob/miniredis/v2" + "github.com/gin-gonic/gin" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" +) + +type scopedPaymentRateSettings struct{ service.SettingRepository } + +func (*scopedPaymentRateSettings) GetValue(_ context.Context, key string) (string, error) { + if key == service.SettingKeyPanelRateLimitSettings { + return `{"enabled":true,"user_rpm":100,"heavy_rpm":1,"exempt_admin":true}`, nil + } + return "", service.ErrSettingNotFound +} + +func TestScopedAdminPaymentWritesUseHeavyRateLimitWithAdminExemption(t *testing.T) { + gin.SetMode(gin.TestMode) + redisServer := miniredis.RunT(t) + client := redis.NewClient(&redis.Options{Addr: redisServer.Addr()}) + t.Cleanup(func() { _ = client.Close() }) + settings := service.NewSettingService(&scopedPaymentRateSettings{}, nil) + settings.SetScopedAdminKeyRepository(&scopedRouteKeys{}) + key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{Name: "支付取消", Enabled: true, Policy: adminaccess.Policy{GlobalPermissions: []string{"payment.cancel"}}}, 9) + require.NoError(t, err) + auth := middleware.NewAdminAuthMiddleware(nil, service.NewUserService(&scopedRouteUsers{}, nil, nil, nil), settings, nil) + r := gin.New() + RegisterPaymentRoutes(r.Group("/api/v1"), &handler.PaymentHandler{}, &handler.PaymentWebhookHandler{}, &adminhandler.PaymentHandler{}, middleware.JWTAuthMiddleware(func(c *gin.Context) { c.Next() }), auth, middleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() }), nil, middleware.NewPanelRateLimiter(client, settings), client) + // 无效订单 ID 在实际支付处理器返回 400,证明首个请求已经通过认证和授权。 + // 第二次应在解析订单之前触发严格档限流,不依赖真实支付数据库。 + for _, want := range []int{400, 429} { + req := httptest.NewRequest("POST", "/api/v1/admin/payment/orders/invalid/cancel", nil) + req.Header.Set("x-api-key", key) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, want, w.Code, w.Body.String()) + if want == 429 { + require.NotEmpty(t, w.Header().Get("Retry-After")) + } + } +} diff --git a/backend/internal/server/routes/custom_admin_key_user_responses_test.go b/backend/internal/server/routes/custom_admin_key_user_responses_test.go new file mode 100644 index 0000000000..1260e79584 --- /dev/null +++ b/backend/internal/server/routes/custom_admin_key_user_responses_test.go @@ -0,0 +1,134 @@ +//go:build unit + +package routes + +import ( + "context" + "encoding/json" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/handler" + adminhandler "github.com/Wei-Shaw/sub2api/internal/handler/admin" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type scopedUserResponses struct { + service.AdminService + filters service.UserListFilters +} + +func scopedUserFixture() *service.User { + return &service.User{ + ID: 7, Email: "user@example.com", Username: "测试用户", Role: "user", Status: "active", + Balance: 123, FrozenBalance: 12, TotalRecharged: 456, Notes: "内部敏感备注", + AllowedGroups: []int64{3}, RestrictPublicGroups: true, GroupRates: map[int64]float64{3: 0.8}, + APIKeys: []service.APIKey{{ID: 8, Key: "绝不返回的用户密钥"}}, + Subscriptions: []service.UserSubscription{{ID: 2, DailyUsageUSD: 11, WeeklyUsageUSD: 22, MonthlyUsageUSD: 33, + Group: &service.Group{ID: 3, Name: "内部定价分组", RateMultiplier: 2}}}, + } +} + +func (s *scopedUserResponses) ListUsers(_ context.Context, _, _ int, filters service.UserListFilters, _, _ string) ([]service.User, int64, error) { + s.filters = filters + // 故意保留关联数据,验证输出边界本身也能防止泄露。 + return []service.User{*scopedUserFixture()}, 1, nil +} +func (*scopedUserResponses) GetUser(context.Context, int64) (*service.User, error) { + return scopedUserFixture(), nil +} +func (*scopedUserResponses) GetUserIncludeDeleted(context.Context, int64) (*service.User, error) { + return scopedUserFixture(), nil +} +func (*scopedUserResponses) UpdateUserBalance(context.Context, int64, float64, string, string) (*service.User, error) { + return scopedUserFixture(), nil +} + +func TestScopedAdminUserResponsesRequireIndependentPermissions(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, tc := range []struct { + name string + permissions []string + }{ + {"仅用户资料", []string{"users.read"}}, + {"同时授权余额", []string{"users.read", "users.balance.read"}}, + {"同时授权分组", []string{"users.read", "groups.read"}}, + {"同时授权订阅", []string{"users.read", "subscriptions.read"}}, + {"仅余额写入", []string{"users.balance.write"}}, + } { + t.Run(tc.name, func(t *testing.T) { + keys := &scopedRouteKeys{} + settings := service.NewSettingService(nil, nil) + settings.SetScopedAdminKeyRepository(keys) + key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{ + Name: "用户字段权限", Enabled: true, Policy: adminaccess.Policy{GlobalPermissions: tc.permissions}, + }, 9) + require.NoError(t, err) + auth := middleware.NewAdminAuthMiddleware(nil, service.NewUserService(&scopedRouteUsers{}, nil, nil, nil), settings, nil) + stub := &scopedUserResponses{} + r := gin.New() + RegisterAdminRoutes(r.Group("/api/v1"), &handler.Handlers{Admin: &handler.AdminHandlers{ + Account: &adminhandler.AccountHandler{}, User: adminhandler.NewUserHandler(stub, nil, nil, nil, nil, nil, nil), + Setting: adminhandler.NewSettingHandler(settings, nil, nil, nil, nil, nil, nil), + }}, auth, middleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() }), middleware.StepUpAuthMiddleware(func(c *gin.Context) { c.Next() }), nil, nil) + paths := []string{"/users", "/users?include_subscriptions=true", "/users/7", "/users/7?include_deleted=true"} + balanceWrite := tc.name == "仅余额写入" + if balanceWrite { + paths = []string{"/users/7/balance"} + } + for _, path := range paths { + t.Run(path, func(t *testing.T) { + method, body := "GET", "" + if balanceWrite { + method, body = "POST", `{"balance":1,"operation":"add"}` + } + req := httptest.NewRequest(method, "/api/v1/admin"+path, strings.NewReader(body)) + req.Header.Set("x-api-key", key) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, 200, w.Code, w.Body.String()) + var result struct { + Data map[string]json.RawMessage `json:"data"` + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result)) + data := result.Data + if strings.HasPrefix(path, "/users?") || path == "/users" { + var items []map[string]json.RawMessage + require.NoError(t, json.Unmarshal(data["items"], &items)) + require.Len(t, items, 1) + data = items[0] + require.NotNil(t, stub.filters.IncludeSubscriptions) + require.False(t, *stub.filters.IncludeSubscriptions) + } + for _, field := range []string{"subscriptions", "api_keys", "notes", "balance_notify_threshold", "balance_notify_extra_emails"} { + require.NotContains(t, data, field) + } + for _, field := range []string{"balance", "frozen_balance", "total_recharged"} { + require.Equal(t, tc.name == "同时授权余额", data[field] != nil, field) + } + for _, field := range []string{"allowed_groups", "restrict_public_groups", "group_rates"} { + require.Equal(t, tc.name == "同时授权分组", data[field] != nil, field) + } + require.Equal(t, !balanceWrite, data["email"] != nil) + require.NotContains(t, w.Body.String(), "daily_usage_usd") + require.NotContains(t, w.Body.String(), "内部定价分组") + }) + } + if tc.name == "仅用户资料" { + for _, path := range []string{"/users/7/subscriptions", "/users/7/api-keys"} { + req := httptest.NewRequest("GET", "/api/v1/admin"+path, nil) + req.Header.Set("x-api-key", key) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, 403, w.Code, path) + } + } + }) + } +} diff --git a/backend/internal/server/routes/custom_admin_keys.go b/backend/internal/server/routes/custom_admin_keys.go new file mode 100644 index 0000000000..00f09aa929 --- /dev/null +++ b/backend/internal/server/routes/custom_admin_keys.go @@ -0,0 +1,18 @@ +package routes + +import ( + "github.com/Wei-Shaw/sub2api/internal/handler" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/gin-gonic/gin" +) + +// 管理密钥生命周期只接受管理员会话;写操作沿用二次验证。 +func registerScopedAdminKeyRoutes(settings *gin.RouterGroup, h *handler.Handlers, stepUp middleware.StepUpAuthMiddleware) { + keys := settings.Group("/admin-api-keys") + keys.GET("", h.Admin.Setting.ListScopedAdminKeys) + keys.POST("", gin.HandlerFunc(stepUp), h.Admin.Setting.CreateScopedAdminKey) + keys.PUT("/:id", gin.HandlerFunc(stepUp), h.Admin.Setting.UpdateScopedAdminKey) + keys.POST("/:id/rotate", gin.HandlerFunc(stepUp), h.Admin.Setting.RotateScopedAdminKey) + keys.DELETE("/:id", gin.HandlerFunc(stepUp), h.Admin.Setting.RevokeScopedAdminKey) + keys.DELETE("/:id/record", gin.HandlerFunc(stepUp), h.Admin.Setting.DeleteScopedAdminKeyRecord) +} diff --git a/backend/internal/server/routes/custom_admin_keys_test.go b/backend/internal/server/routes/custom_admin_keys_test.go new file mode 100644 index 0000000000..0eec76fff4 --- /dev/null +++ b/backend/internal/server/routes/custom_admin_keys_test.go @@ -0,0 +1,35 @@ +//go:build unit + +package routes + +import ( + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/handler" + adminhandler "github.com/Wei-Shaw/sub2api/internal/handler/admin" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestScopedAdminKeyManagementRoutesRequireStepUp(t *testing.T) { + gin.SetMode(gin.TestMode) + r := gin.New() + stepUp := middleware.StepUpAuthMiddleware(func(c *gin.Context) { c.AbortWithStatusJSON(403, gin.H{"reason": "STEP_UP_REQUIRED"}) }) + RegisterAdminRoutes(r.Group("/api/v1"), &handler.Handlers{Admin: &handler.AdminHandlers{Setting: adminhandler.NewSettingHandler(nil, nil, nil, nil, nil, nil, nil)}}, middleware.AdminAuthMiddleware(func(c *gin.Context) { c.Set("auth_method", "jwt"); c.Next() }), middleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() }), stepUp, nil, nil) + for _, test := range []struct{ method, path string }{ + {"POST", "/api/v1/admin/settings/admin-api-key/regenerate"}, + {"DELETE", "/api/v1/admin/settings/admin-api-key"}, + {"POST", "/api/v1/admin/settings/admin-api-keys"}, + {"PUT", "/api/v1/admin/settings/admin-api-keys/key-1"}, + {"POST", "/api/v1/admin/settings/admin-api-keys/key-1/rotate"}, + {"DELETE", "/api/v1/admin/settings/admin-api-keys/key-1"}, + {"DELETE", "/api/v1/admin/settings/admin-api-keys/key-1/record"}, + } { + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(test.method, test.path, nil)) + require.Equal(t, 403, w.Code, test.method+" "+test.path) + require.Contains(t, w.Body.String(), "STEP_UP_REQUIRED") + } +} diff --git a/backend/internal/server/routes/payment.go b/backend/internal/server/routes/payment.go index 26d0fcd669..86536d67ac 100644 --- a/backend/internal/server/routes/payment.go +++ b/backend/internal/server/routes/payment.go @@ -91,6 +91,7 @@ func RegisterPaymentRoutes( // --- Admin payment endpoints (admin auth) --- adminGroup := v1.Group("/admin/payment") adminGroup.Use(gin.HandlerFunc(adminAuth)) + adminGroup.Use(panelRateLimiter.Global()) adminGroup.Use(gin.HandlerFunc(auditLog)) adminGroup.Use(middleware.AdminComplianceGuard(settingService)) { diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go index 256e488d09..b5545ee18e 100644 --- a/backend/internal/service/admin_account.go +++ b/backend/internal/service/admin_account.go @@ -546,30 +546,32 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou } } - // OAuth 账号:创建后异步设置隐私。 - // 使用 Ensure(幂等)而非 Force:新建账号 Extra 为空时效果相同,但更安全。 - if account.Type == AccountTypeOAuth { - switch account.Platform { - case PlatformOpenAI: - go func() { - defer func() { - if r := recover(); r != nil { - slog.Error("create_account_openai_privacy_panic", "account_id", account.ID, "recover", r) - } + AfterAccountCommit(ctx, func(_ context.Context) { + // OAuth 账号:创建后异步设置隐私。 + // 使用 Ensure(幂等)而非 Force:新建账号 Extra 为空时效果相同,但更安全。 + if account.Type == AccountTypeOAuth { + switch account.Platform { + case PlatformOpenAI: + go func() { + defer func() { + if r := recover(); r != nil { + slog.Error("create_account_openai_privacy_panic", "account_id", account.ID, "recover", r) + } + }() + s.EnsureOpenAIPrivacy(context.Background(), account) }() - s.EnsureOpenAIPrivacy(context.Background(), account) - }() - case PlatformAntigravity: - go func() { - defer func() { - if r := recover(); r != nil { - slog.Error("create_account_antigravity_privacy_panic", "account_id", account.ID, "recover", r) - } + case PlatformAntigravity: + go func() { + defer func() { + if r := recover(); r != nil { + slog.Error("create_account_antigravity_privacy_panic", "account_id", account.ID, "recover", r) + } + }() + s.EnsureAntigravityPrivacy(context.Background(), account) }() - s.EnsureAntigravityPrivacy(context.Background(), account) - }() + } } - } + }) return account, nil } @@ -1324,10 +1326,16 @@ func (s *adminServiceImpl) ClearAccountError(ctx context.Context, id int64) (*Ac if err := s.accountRepo.ClearTempUnschedulable(ctx, id); err != nil { return nil, err } - if s.runtimeBlocker != nil { - s.runtimeBlocker.ClearAccountSchedulingBlock(id) + account, err := s.accountRepo.GetByID(ctx, id) + if err != nil { + return nil, err } - return s.accountRepo.GetByID(ctx, id) + AfterAccountCommit(ctx, func(context.Context) { + if s.runtimeBlocker != nil { + s.runtimeBlocker.ClearAccountSchedulingBlock(id) + } + }) + return account, nil } func (s *adminServiceImpl) SetAccountError(ctx context.Context, id int64, errorMsg string) error { diff --git a/backend/internal/service/admin_service.go b/backend/internal/service/admin_service.go index a5e0ad635c..7b2d23164d 100644 --- a/backend/internal/service/admin_service.go +++ b/backend/internal/service/admin_service.go @@ -396,6 +396,7 @@ type UpdateGroupInput struct { } type CreateAccountInput struct { + ProxyMode string // 受限写入在验权后选择代理。 Name string Notes *string Platform string @@ -428,6 +429,7 @@ type ShadowOptions struct { } type UpdateAccountInput struct { + ProxyMode string // 受限写入在验权后选择代理。 Name string Notes *string Type string // Account type: oauth, setup-token, apikey diff --git a/backend/internal/service/custom_admin_key_accounts.go b/backend/internal/service/custom_admin_key_accounts.go new file mode 100644 index 0000000000..91d5131f9c --- /dev/null +++ b/backend/internal/service/custom_admin_key_accounts.go @@ -0,0 +1,366 @@ +package service + +import ( + "context" + "encoding/json" + "fmt" + "maps" + "slices" + "strings" + "unicode/utf8" + + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/domain" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" +) + +// ScopedAdminAccounts 只提供受限管理密钥需要的窄接口。 +type ScopedAdminAccounts interface { + ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string) ([]Account, int64, error) + ScopedAdminWrite(context.Context, int64, string, map[string]json.RawMessage, func(context.Context, *Account) (*Account, error)) (*Account, error) +} + +func scopedAccountResource(a *Account) adminaccess.Account { + return adminaccess.Account{ID: a.ID, GroupIDs: a.GroupIDs, Type: a.Type, Platform: a.Platform} +} + +func scopedAccountFieldPermissions(fields map[string]json.RawMessage, create bool) ([]string, error) { + permissions := []string{} + for key, raw := range fields { + permission := "" + switch key { + case "name", "notes": + permission = "accounts.update" + case "status": + var status string + if json.Unmarshal(raw, &status) != nil || !slices.Contains([]string{StatusActive, "inactive", StatusError}, status) { + return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_STATUS", "账户状态无效") + } + permission = "accounts.status" + case "schedulable": + permission = "accounts.status" + case "concurrency", "priority", "load_factor", "expires_at", "auto_pause_on_expired": + permission = "accounts.schedule" + case "proxy_id", "proxy_mode", "random_proxy": + permission = "accounts.network" + case "group_ids": + permission = "accounts.groups" + case "platform", "type": + if !create { + return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_INPUT", "禁止更改类型或平台") + } + continue + case "credentials": + var credentials map[string]json.RawMessage + if json.Unmarshal(raw, &credentials) != nil || len(credentials) == 0 { + return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_CREDENTIALS", "凭证格式无效") + } + for name, value := range credentials { + // 白名单与映射共用 model_mapping,只授予模型配置写入权限。 + if name == "model_mapping" { + var mapping map[string]json.RawMessage + if len(value) > 65536 || json.Unmarshal(value, &mapping) != nil { + return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_MODELS", "模型映射格式无效") + } + for source, target := range mapping { + var model string + if strings.TrimSpace(source) == "" || json.Unmarshal(target, &model) != nil || strings.TrimSpace(model) == "" { + return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_MODELS", "模型 ID 格式无效") + } + } + permissions = append(permissions, "accounts.models.write") + continue + } + var text string + if json.Unmarshal(value, &text) != nil || len(text) > 65536 { + return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_CREDENTIALS", "凭证值格式无效") + } + switch name { + case "api_key", "access_token", "refresh_token", "id_token", "session_key": + permissions = append(permissions, "accounts.credentials") + case "base_url": + permissions = append(permissions, "accounts.network") + default: + return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_FIELD", "请求包含不开放的凭证字段") + } + } + continue + default: + return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_FIELD", "请求包含不开放的账户字段") + } + if !create || permission == "accounts.schedule" || permission == "accounts.network" { + permissions = append(permissions, permission) + } else if key == "status" || key == "schedulable" { + return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_INPUT", "创建不支持状态字段") + } + } + return permissions, nil +} + +func (s *adminServiceImpl) ScopedAdminList(ctx context.Context, p pagination.PaginationParams, platform, kind, status, search string) ([]Account, int64, error) { + repo, ok := s.accountRepo.(interface { + ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string) ([]Account, int64, error) + }) + if !ok { + return nil, 0, fmt.Errorf("受限账户查询不可用") + } + return repo.ScopedAdminList(ctx, p, platform, kind, status, search) +} + +func (s *adminServiceImpl) ScopedAdminWrite(ctx context.Context, id int64, action string, fields map[string]json.RawMessage, run func(context.Context, *Account) (*Account, error)) (*Account, error) { + principal := adminaccess.FromContext(ctx) + if principal == nil { + return nil, infraerrors.Forbidden("SCOPED_ACCOUNT_FORBIDDEN", "缺少受限身份") + } + permissions, err := scopedAccountFieldPermissions(fields, id == 0) + if err != nil { + return nil, err + } + if id != 0 && action == "" && len(permissions) == 0 { + return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_INPUT", "缺少实际授权操作") + } + if id == 0 { + var input struct { + ProxyID *int64 `json:"proxy_id"` + ProxyMode string `json:"proxy_mode"` + RandomProxy bool `json:"random_proxy"` + Name string `json:"name"` + Notes *string `json:"notes"` + Platform string `json:"platform"` + Type string `json:"type"` + Credentials map[string]any `json:"credentials"` + GroupIDs []int64 `json:"group_ids"` + Concurrency int `json:"concurrency"` + Priority int `json:"priority"` + LoadFactor *int `json:"load_factor"` + ExpiresAt *int64 `json:"expires_at"` + AutoPause *bool `json:"auto_pause_on_expired"` + } + body, _ := json.Marshal(fields) + if err = json.Unmarshal(body, &input); err != nil { + return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_INPUT", "请求格式无效") + } + if strings.TrimSpace(input.Name) == "" || utf8.RuneCountInString(input.Name) > maxAccountNameRunes || len(input.Credentials) == 0 || fields["group_ids"] == nil { + return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_INPUT", "创建须提供名称、凭证及明确分组") + } + if !slices.Contains([]string{"oauth", "setup-token", "apikey", "upstream", "bedrock", "service_account"}, input.Type) { + return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_INPUT", "账户类型无效") + } + if !slices.Contains(domain.ConcretePlatformIDs(), input.Platform) || input.Concurrency < 0 || input.Priority < 0 { + return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_INPUT", "创建参数无效") + } + resource := adminaccess.Account{Type: input.Type, Platform: input.Platform, GroupIDs: input.GroupIDs} + if input.Type == "" || input.Platform == "" || !principal.Policy.AllowsAccount("accounts.create", resource) { + return nil, infraerrors.Forbidden("SCOPED_ACCOUNT_FORBIDDEN", "创建范围未授权") + } + for _, g := range input.GroupIDs { + if !principal.Policy.AllowsGroup("accounts.create", resource, g) { + return nil, infraerrors.Forbidden("SCOPED_ACCOUNT_FORBIDDEN", "创建分组未授权") + } + } + // 创建本身允许初始化普通字段;凭证和网络须独立授权。 + for _, p := range permissions { + if !principal.Policy.AllowsAccount(p, resource) { + return nil, infraerrors.Forbidden("SCOPED_ACCOUNT_FORBIDDEN", "字段权限不足") + } + } + proxyMode, e := NormalizeAccountProxyMode(input.ProxyMode, input.ProxyID, input.RandomProxy) + if e != nil { + return nil, e + } + return s.scopedAdminCreateTransaction(ctx, &CreateAccountInput{ProxyID: input.ProxyID, ProxyMode: proxyMode, Name: input.Name, Notes: input.Notes, Platform: input.Platform, Type: input.Type, Credentials: input.Credentials, GroupIDs: input.GroupIDs, Concurrency: input.Concurrency, Priority: input.Priority, LoadFactor: input.LoadFactor, ExpiresAt: input.ExpiresAt, AutoPauseOnExpired: input.AutoPause, SkipDefaultGroupBind: true}) + } + result, err := s.scopedAdminTransaction(ctx, id, action == "accounts.delete", func(txctx context.Context) (*Account, error) { + a, e := s.accountRepo.GetByID(txctx, id) + if e != nil { + return nil, infraerrors.NotFound("SCOPED_ACCOUNT_NOT_FOUND", "账户不存在") + } + if a == nil { + return nil, infraerrors.NotFound("SCOPED_ACCOUNT_NOT_FOUND", "账户不存在") + } + resource := scopedAccountResource(a) + // 先隐藏授权范围外的账户,再区分范围内缺少具体字段权限的情况。 + inScope := false + for _, rule := range principal.Policy.Rules { + if slices.ContainsFunc(rule.Permissions, func(permission string) bool { return strings.HasPrefix(permission, "accounts.") }) && rule.Matches(resource) { + inScope = true + break + } + } + if !inScope { + return nil, infraerrors.NotFound("SCOPED_ACCOUNT_NOT_FOUND", "账户不存在") + } + if action != "" && !principal.Policy.AllowsAccount(action, resource) { + return nil, infraerrors.NotFound("SCOPED_ACCOUNT_NOT_FOUND", "账户不存在") + } + for _, p := range permissions { + if !principal.Policy.AllowsAccount(p, resource) { + return nil, infraerrors.Forbidden("SCOPED_ACCOUNT_FORBIDDEN", "账户字段未授权") + } + } + if a.IsShadow() { + return nil, infraerrors.Forbidden("SCOPED_ACCOUNT_FORBIDDEN", "不支持修改影子账户") + } + shadows, e := s.accountRepo.ListShadowsByParent(txctx, id) + if e != nil { + return nil, e + } + if len(shadows) > 0 { + return nil, infraerrors.Forbidden("SCOPED_ACCOUNT_FORBIDDEN", "请由完整管理员管理关联影子账户") + } + + if run != nil { + return run(txctx, a) + } + if action == "accounts.delete" { + return a, s.DeleteAccount(txctx, id) + } + if action == "accounts.recover" { + return s.ClearAccountError(txctx, id) + } + var input struct { + ProxyID *int64 `json:"proxy_id"` + ProxyMode string `json:"proxy_mode"` + RandomProxy bool `json:"random_proxy"` + Name string `json:"name"` + Notes *string `json:"notes"` + Credentials map[string]any `json:"credentials"` + Concurrency *int `json:"concurrency"` + Priority *int `json:"priority"` + LoadFactor *int `json:"load_factor"` + Status string `json:"status"` + GroupIDs *[]int64 `json:"group_ids"` + ExpiresAt *int64 `json:"expires_at"` + AutoPause *bool `json:"auto_pause_on_expired"` + Schedulable *bool `json:"schedulable"` + } + body, _ := json.Marshal(fields) + if e = json.Unmarshal(body, &input); e != nil { + return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_INPUT", "请求格式无效") + } + if input.GroupIDs != nil { + groups, err := scopedAdminMergeGroups(principal.Policy, resource, a.GroupIDs, *input.GroupIDs) + if err != nil { + return nil, err + } + input.GroupIDs = &groups + } + proxyMode, e := NormalizeAccountProxyMode(input.ProxyMode, input.ProxyID, input.RandomProxy) + if e != nil { + return nil, e + } + input.ProxyID, e = s.scopedAccountProxySelection(txctx, proxyMode, input.ProxyID) + if e != nil { + return nil, e + } + // 受限更新按已授权字段补丁合并,避免上游完整编辑语义删除未授予的连接配置。 + if input.Credentials != nil { + merged := maps.Clone(a.Credentials) + if merged == nil { + merged = make(map[string]any) + } + maps.Copy(merged, input.Credentials) + input.Credentials = merged + } + updated, e := s.UpdateAccount(txctx, id, &UpdateAccountInput{ProxyID: input.ProxyID, Name: input.Name, Notes: input.Notes, Credentials: input.Credentials, Concurrency: input.Concurrency, Priority: input.Priority, LoadFactor: input.LoadFactor, Status: input.Status, GroupIDs: input.GroupIDs, ExpiresAt: input.ExpiresAt, AutoPauseOnExpired: input.AutoPause}) + if e != nil { + return nil, e + } + if input.Schedulable != nil { + return s.SetAccountSchedulable(txctx, id, *input.Schedulable) + } + return updated, nil + }) + return result, err +} + +// scopedAdminTransaction 锁住账户行,分组更改和外部操作均须在重新验权之后执行。 +func (s *adminServiceImpl) scopedAdminTransaction(ctx context.Context, id int64, deleted bool, run func(context.Context) (*Account, error)) (*Account, error) { + if s.entClient == nil { + return nil, fmt.Errorf("受限写入需要数据库事务") + } + tx, err := s.entClient.Tx(ctx) + if err != nil { + return nil, err + } + defer func() { _ = tx.Rollback() }() + txctx := dbent.NewTxContext(ctx, tx) + if err = lockScopedAdminAccount(txctx, tx, id); err != nil { + return nil, err + } + if _, err = tx.Client().ExecContext(txctx, "SELECT id FROM accounts WHERE id = $1 AND deleted_at IS NULL FOR UPDATE", id); err != nil { + return nil, err + } + if _, err = tx.Client().ExecContext(txctx, "SELECT account_id FROM account_groups WHERE account_id = $1 FOR UPDATE", id); err != nil { + return nil, err + } + result, err := run(txctx) + if err != nil { + return nil, err + } + if err = tx.Commit(); err != nil { + return nil, err + } + if repo, ok := s.accountRepo.(interface { + ScopedAdminCommitted(context.Context, int64, bool) + }); ok { + repo.ScopedAdminCommitted(ctx, id, deleted) + } + return result, nil +} + +// scopedAdminMergeGroups 只替换授权关联,保留调用者不可操作的既有分组。 +func scopedAdminMergeGroups(policy adminaccess.Policy, resource adminaccess.Account, existing, requested []int64) ([]int64, error) { + groups := []int64{} + for _, id := range existing { + if !policy.AllowsGroup("accounts.groups", resource, id) { + groups = append(groups, id) + } + } + for _, id := range requested { + if !policy.AllowsGroup("accounts.groups", resource, id) { + return nil, infraerrors.Forbidden("SCOPED_ACCOUNT_GROUP", "目标分组未授权") + } + if !slices.Contains(groups, id) { + groups = append(groups, id) + } + } + return groups, nil +} + +// scopedAdminCreateTransaction 保证创建与绑定分组一同提交或回滚。 +func (s *adminServiceImpl) scopedAdminCreateTransaction(ctx context.Context, input *CreateAccountInput) (*Account, error) { + if s.entClient == nil { + return nil, fmt.Errorf("受限写入需要数据库事务") + } + tx, err := s.entClient.Tx(ctx) + if err != nil { + return nil, err + } + defer func() { _ = tx.Rollback() }() + txctx := dbent.NewTxContext(ctx, tx) + safe := *input + safe.ProxyID, err = s.scopedAccountProxySelection(txctx, safe.ProxyMode, safe.ProxyID) + if err != nil { + return nil, err + } + // 创建以 NULL 表示直连;更新接口的 0 仅是清除既有绑定的指令。 + if safe.ProxyID != nil && *safe.ProxyID == 0 { + safe.ProxyID = nil + } + account, err := s.CreateAccount(txctx, &safe) + if err != nil { + return nil, err + } + if err = tx.Commit(); err != nil { + return nil, err + } + if repo, ok := s.accountRepo.(interface { + ScopedAdminCommitted(context.Context, int64, bool) + }); ok { + repo.ScopedAdminCommitted(ctx, account.ID, false) + } + return account, nil +} diff --git a/backend/internal/service/custom_admin_key_accounts_test.go b/backend/internal/service/custom_admin_key_accounts_test.go new file mode 100644 index 0000000000..674ef32503 --- /dev/null +++ b/backend/internal/service/custom_admin_key_accounts_test.go @@ -0,0 +1,325 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "errors" + "reflect" + "strings" + "testing" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/stretchr/testify/require" +) + +func TestScopedAdminAccountFieldsRejectUnknown(t *testing.T) { + for _, body := range []string{`{"credentials":{}}`, `{"extra":{}}`, `{"platform":"openai"}`} { + var fields map[string]json.RawMessage + _ = json.Unmarshal([]byte(body), &fields) + if _, err := scopedAccountFieldPermissions(fields, false); err == nil { + t.Fatalf("应拒绝字段: %s", body) + } + } +} + +func TestScopedAdminAccountModelMappingFieldPermissions(t *testing.T) { + for _, create := range []bool{false, true} { + for _, mapping := range []string{`{"gpt-6":"gpt-6","alias":"gpt-6"}`, `{}`, `null`} { + var fields map[string]json.RawMessage + require.NoError(t, json.Unmarshal([]byte(`{"credentials":{"model_mapping":`+mapping+`}}`), &fields)) + permissions, err := scopedAccountFieldPermissions(fields, create) + require.NoError(t, err) + require.Equal(t, []string{"accounts.models.write"}, permissions) + } + } + for _, mapping := range []string{`[]`, `"gpt-6"`, `{"gpt-6":42}`, `{"gpt-6":null}`, `{"gpt-6":{}}`, `{"":"gpt-6"}`, `{"gpt-6":" "}`, `{"gpt-6":"` + strings.Repeat("x", 65536) + `"}`} { + var fields map[string]json.RawMessage + require.NoError(t, json.Unmarshal([]byte(`{"credentials":{"model_mapping":`+mapping+`}}`), &fields)) + _, err := scopedAccountFieldPermissions(fields, false) + require.Equal(t, 400, infraerrors.Code(err), mapping) + } + var fields map[string]json.RawMessage + require.NoError(t, json.Unmarshal([]byte(`{"credentials":{"model_mapping":{},"access_token":"secret","base_url":"https://example.com"}}`), &fields)) + permissions, err := scopedAccountFieldPermissions(fields, false) + require.NoError(t, err) + require.ElementsMatch(t, []string{"accounts.models.write", "accounts.credentials", "accounts.network"}, permissions) +} + +func TestScopedAdminWriteModelMappingEnforcesScopeAndPreservesCredentials(t *testing.T) { + login, db := scopedAdminAccountTestDB(t) + _, err := db.Exec(`CREATE TABLE account_groups(account_id BIGINT,group_id BIGINT); + INSERT INTO accounts(id,name,platform,type,credentials) VALUES + (101,'共享','openai','oauth','{"access_token":"original-token","refresh_token":"original-refresh","base_url":"https://example.com","model_mapping":{"old":"old"}}'), + (102,'API','openai','apikey','{}'),(103,'其他组','openai','oauth','{}'),(104,'其他平台','anthropic','oauth','{}'); + INSERT INTO account_groups VALUES(101,1),(101,2),(102,1),(103,2),(104,1);`) + require.NoError(t, err) + repo := &scopedAdminWriteTestRepo{login: login} + admin := &adminServiceImpl{accountRepo: repo, entClient: dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))} + fields := func(body string) map[string]json.RawMessage { + var result map[string]json.RawMessage + require.NoError(t, json.Unmarshal([]byte(body), &result)) + return result + } + ctxFor := func(permissions ...string) context.Context { + return adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: permissions, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}}}}) + } + body := `{"credentials":{"model_mapping":{"gpt-6":"gpt-6","alias":"gpt-6"}}}` + _, err = admin.ScopedAdminWrite(ctxFor("accounts.credentials", "accounts.update"), 101, "", fields(body), nil) + require.Equal(t, 403, infraerrors.Code(err), "写凭证权限不能隐式修改模型") + ctx := ctxFor("accounts.models.write") + for _, id := range []int64{102, 103, 104, 999} { + _, err = admin.ScopedAdminWrite(ctx, id, "", fields(body), nil) + require.Equal(t, 404, infraerrors.Code(err)) + } + for _, forbidden := range []string{`{"credentials":{"model_mapping":{},"access_token":"changed"}}`, `{"credentials":{"model_mapping":{},"base_url":"https://evil.example"}}`} { + _, err = admin.ScopedAdminWrite(ctx, 101, "", fields(forbidden), nil) + require.Equal(t, 403, infraerrors.Code(err), "模型权限不能混写凭证或网络") + } + for _, mapping := range []string{`{"gpt-6":"gpt-6","alias":"gpt-6"}`, `{}`, `null`} { + _, err = admin.ScopedAdminWrite(ctx, 101, "", fields(`{"credentials":{"model_mapping":`+mapping+`}}`), nil) + require.NoError(t, err) + a, err := repo.GetByID(ctx, 101) + require.NoError(t, err) + require.Equal(t, "original-token", a.Credentials["access_token"]) + require.Equal(t, "original-refresh", a.Credentials["refresh_token"]) + require.Equal(t, "https://example.com", a.Credentials["base_url"]) + var want any + require.NoError(t, json.Unmarshal([]byte(mapping), &want)) + require.Equal(t, want, a.Credentials["model_mapping"]) + require.Equal(t, []int64{1, 2}, a.GroupIDs) + } +} + +// 用真实数据库事务承载最小仓储,直接验证授权服务到业务写入的完整调用链。 +type scopedAdminWriteTestRepo struct { + AccountRepository + login *scopedTestDB + failBind bool +} + +func (r *scopedAdminWriteTestRepo) GetByID(ctx context.Context, id int64) (*Account, error) { + a := &Account{ID: id} + var credentials []byte + rows, err := r.login.sql(ctx).QueryContext(ctx, `SELECT name,platform,type,status,credentials FROM accounts WHERE id=$1`, id) + if err != nil { + return nil, err + } + if !rows.Next() { + _ = rows.Close() + return nil, ErrAccountNotFound + } + err = rows.Scan(&a.Name, &a.Platform, &a.Type, &a.Status, &credentials) + _ = rows.Close() + if err != nil { + return nil, err + } + if err = json.Unmarshal(credentials, &a.Credentials); err != nil { + return nil, err + } + rows, err = r.login.sql(ctx).QueryContext(ctx, `SELECT group_id FROM account_groups WHERE account_id=$1 ORDER BY group_id`, id) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + var group int64 + if err = rows.Scan(&group); err != nil { + return nil, err + } + a.GroupIDs = append(a.GroupIDs, group) + } + return a, rows.Err() +} +func (r *scopedAdminWriteTestRepo) ListShadowsByParent(context.Context, int64) ([]*Account, error) { + return nil, nil +} +func (r *scopedAdminWriteTestRepo) Update(ctx context.Context, a *Account) error { + credentials, err := json.Marshal(a.Credentials) + if err != nil { + return err + } + _, err = r.login.sql(ctx).ExecContext(ctx, `UPDATE accounts SET name=$2,credentials=$3 WHERE id=$1`, a.ID, a.Name, string(credentials)) + return err +} +func (r *scopedAdminWriteTestRepo) Create(ctx context.Context, a *Account) error { + rows, err := r.login.sql(ctx).QueryContext(ctx, `INSERT INTO accounts(name,platform,type) VALUES($1,$2,$3) RETURNING id`, a.Name, a.Platform, a.Type) + if err != nil { + return err + } + defer rows.Close() + if !rows.Next() { + return errors.New("创建未返回 ID") + } + return rows.Scan(&a.ID) +} +func (r *scopedAdminWriteTestRepo) BindGroups(ctx context.Context, id int64, groups []int64) error { + if r.failBind { + return errors.New("模拟绑定失败") + } + if _, err := r.login.sql(ctx).ExecContext(ctx, `DELETE FROM account_groups WHERE account_id=$1`, id); err != nil { + return err + } + for _, group := range groups { + if _, err := r.login.sql(ctx).ExecContext(ctx, `INSERT INTO account_groups(account_id,group_id) VALUES($1,$2)`, id, group); err != nil { + return err + } + } + return nil +} + +type scopedAdminWriteTestGroups struct{ GroupRepository } + +func (*scopedAdminWriteTestGroups) GetByID(_ context.Context, id int64) (*Group, error) { + return &Group{ID: id}, nil +} + +func TestScopedAdminWriteEnforcesScopeAndAtomicCreate(t *testing.T) { + login, db := scopedAdminAccountTestDB(t) + _, err := db.Exec(`CREATE TABLE account_groups(account_id BIGINT,group_id BIGINT); + INSERT INTO accounts(id,name,type) VALUES(101,'共享','oauth'),(102,'API','apikey'),(103,'其他组','oauth'); + INSERT INTO account_groups VALUES(101,1),(101,2),(102,1),(103,2);`) + require.NoError(t, err) + repo := &scopedAdminWriteTestRepo{login: login} + admin := &adminServiceImpl{accountRepo: repo, groupRepo: &scopedAdminWriteTestGroups{}, entClient: dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))} + principal := &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.groups", "accounts.update", "accounts.create", "accounts.credentials"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}}}}} + ctx := adminaccess.WithPrincipal(context.Background(), principal) + fields := func(body string) map[string]json.RawMessage { + var result map[string]json.RawMessage + require.NoError(t, json.Unmarshal([]byte(body), &result)) + return result + } + _, err = admin.ScopedAdminWrite(ctx, 101, "", fields(`{"name":"已修改","group_ids":[]}`), nil) + require.NoError(t, err) + a, err := repo.GetByID(ctx, 101) + require.NoError(t, err) + require.Equal(t, "已修改", a.Name) + require.Equal(t, []int64{2}, a.GroupIDs, "移除 A 时保留无权操作的 B") + for _, tc := range []struct { + id int64 + body string + }{ + {102, `{"name":"禁止"}`}, + {103, `{"group_ids":[1]}`}, + {103, `{"name":"禁止"}`}, + } { + _, err = admin.ScopedAdminWrite(ctx, tc.id, "", fields(tc.body), nil) + require.Error(t, err) + require.Equal(t, 404, infraerrors.Code(err)) + } + // 恢复 A 仅用于验证有范围但无字段权限的拒绝。 + _, err = db.Exec(`INSERT INTO account_groups VALUES(101,1)`) + require.NoError(t, err) + _, err = admin.ScopedAdminWrite(ctx, 101, "", fields(`{"status":"inactive"}`), nil) + require.Equal(t, 403, infraerrors.Code(err)) + _, err = admin.ScopedAdminWrite(ctx, 101, "", fields(`{"extra":{"secret":"禁止"}}`), nil) + require.Equal(t, 400, infraerrors.Code(err)) + repo.failBind = true + _, err = admin.ScopedAdminWrite(ctx, 0, "", fields(`{"name":"必须回滚","type":"oauth","platform":"openai","credentials":{"access_token":"测试"},"group_ids":[1]}`), nil) + require.ErrorContains(t, err, "模拟绑定失败") + var count int + require.NoError(t, db.QueryRow(`SELECT COUNT(*) FROM accounts WHERE name='必须回滚'`).Scan(&count)) + require.Zero(t, count, "绑定失败不能留下未分组账户") +} + +func TestScopedAdminWriteHidesAccountsOutsideGrantedScope(t *testing.T) { + login, db := scopedAdminAccountTestDB(t) + _, err := db.Exec(`CREATE TABLE account_groups(account_id BIGINT,group_id BIGINT); + INSERT INTO accounts(id,name,platform,type) VALUES + (101,'范围内','openai','oauth'),(102,'其他组','openai','oauth'), + (103,'其他类型','openai','apikey'),(104,'其他平台','anthropic','oauth'), + (105,'未分组','openai','oauth'),(106,'仅分组模型权限','openai','oauth'); + INSERT INTO account_groups VALUES(101,1),(102,2),(103,1),(104,1),(106,3);`) + require.NoError(t, err) + repo := &scopedAdminWriteTestRepo{login: login} + admin := &adminServiceImpl{accountRepo: repo, entClient: dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))} + principal := &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{ + {Permissions: []string{"accounts.update"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}, + // 只有范围但未授予权限的规则不能暴露账户存在性。 + {GroupIDs: []int64{2}, IncludeUngrouped: true, AccountTypes: []string{"oauth"}}, + // 分组模型权限不能使账户进入可操作范围。 + {Permissions: []string{"groups.models.read"}, GroupIDs: []int64{3}, AccountTypes: []string{"oauth"}}, + }}} + ctx := adminaccess.WithPrincipal(context.Background(), principal) + for _, tc := range []struct { + name string + id int64 + body string + code int + }{ + {"范围内缺少字段权限", 101, `{"status":"inactive"}`, 403}, + {"其他组且仅匹配空权限规则", 102, `{"name":"禁止"}`, 404}, + {"其他账户类型", 103, `{"name":"禁止"}`, 404}, + {"其他平台", 104, `{"name":"禁止"}`, 404}, + {"未分组且仅匹配空权限规则", 105, `{"name":"禁止"}`, 404}, + {"仅匹配分组模型权限", 106, `{"name":"禁止"}`, 404}, + {"账户不存在", 999, `{"name":"禁止"}`, 404}, + } { + t.Run(tc.name, func(t *testing.T) { + var fields map[string]json.RawMessage + require.NoError(t, json.Unmarshal([]byte(tc.body), &fields)) + _, err := admin.ScopedAdminWrite(ctx, tc.id, "", fields, nil) + require.Error(t, err) + require.Equal(t, tc.code, infraerrors.Code(err)) + }) + } +} + +func TestScopedAdminGroupReplacementPreservesForeignBindings(t *testing.T) { + policy := adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.groups"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}}}} + resource := adminaccess.Account{ID: 9, Type: "oauth", GroupIDs: []int64{1}} + for _, tc := range []struct { + request []int64 + want []int64 + denied bool + }{{[]int64{1}, []int64{2, 1}, false}, {[]int64{}, []int64{2}, false}, {[]int64{2}, nil, true}} { + got, err := scopedAdminMergeGroups(policy, resource, []int64{1, 2}, tc.request) + if (err != nil) != tc.denied || (!tc.denied && !reflect.DeepEqual(got, tc.want)) { + t.Fatalf("request=%v got=%v err=%v", tc.request, got, err) + } + } +} + +func TestScopedAdminAccountCredentialsNeedIndependentPermissions(t *testing.T) { + var fields map[string]json.RawMessage + _ = json.Unmarshal([]byte(`{"credentials":{"api_key":"secret","base_url":"https://example.com"},"status":"active","concurrency":2}`), &fields) + permissions, err := scopedAccountFieldPermissions(fields, false) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{"accounts.credentials", "accounts.network", "accounts.status", "accounts.schedule"} { + found := false + for _, p := range permissions { + if p == want { + found = true + } + } + if !found { + t.Fatalf("缺少独立权限 %s", want) + } + } +} + +func TestScopedAdminCreateWithCredentialWriteDoesNotRequireRead(t *testing.T) { + login, db := scopedAdminAccountTestDB(t) + _, err := db.Exec(`CREATE TABLE account_groups(account_id BIGINT,group_id BIGINT)`) + require.NoError(t, err) + repo := &scopedAdminWriteTestRepo{login: login} + s := &adminServiceImpl{accountRepo: repo, groupRepo: &scopedAdminWriteTestGroups{}, entClient: dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))} + p := &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.create", "accounts.credentials"}, GroupIDs: []int64{2}, AccountTypes: []string{"oauth"}}}}} + ctx := adminaccess.WithPrincipal(context.Background(), p) + var fields map[string]json.RawMessage + require.NoError(t, json.Unmarshal([]byte(`{"name":"仅写凭证也可创建","platform":"openai","type":"oauth","group_ids":[2],"credentials":{"access_token":"TEST_TOKEN"}}`), &fields)) + account, err := s.ScopedAdminWrite(ctx, 0, "", fields, nil) + require.NoError(t, err) + require.Positive(t, account.ID) + var count int + require.NoError(t, db.QueryRow(`SELECT count(*) FROM accounts WHERE id=$1`, account.ID).Scan(&count)) + require.Equal(t, 1, count) + require.False(t, p.Policy.AllowsAccount("accounts.read", scopedAccountResource(account))) +} diff --git a/backend/internal/service/custom_admin_key_codex_import.go b/backend/internal/service/custom_admin_key_codex_import.go new file mode 100644 index 0000000000..8a09e7a902 --- /dev/null +++ b/backend/internal/service/custom_admin_key_codex_import.go @@ -0,0 +1,164 @@ +package service + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +// ScopedCodexIdentity 描述单次导入的身份;不携带刷新令牌或其他待写入凭证。 +type ScopedCodexIdentity struct { + AccountID string + UserID string + Email string + AccessToken string + AccessTokenOnly bool + AgentIdentity bool +} + +// ScopedAdminCodexAccounts 仅供受限导入器内部使用,候选凭证不得写入 HTTP 响应。 +type ScopedAdminCodexAccounts interface { + ScopedAdminCodexCandidates(context.Context, ScopedCodexIdentity) ([]Account, error) + ScopedAdminCreateCodex(context.Context, *CreateAccountInput) (*Account, error) + ScopedAdminUpdateCodex(context.Context, int64, *UpdateAccountInput, func(*Account, *UpdateAccountInput) error) (*Account, error) +} + +func (s *adminServiceImpl) ScopedAdminCodexCandidates(ctx context.Context, identity ScopedCodexIdentity) ([]Account, error) { + repo, ok := s.accountRepo.(interface { + ScopedAdminCodexCandidates(context.Context, ScopedCodexIdentity) ([]Account, error) + }) + if !ok { + return nil, fmt.Errorf("受限导入查询不可用") + } + return repo.ScopedAdminCodexCandidates(ctx, identity) +} + +// 只允许解析器生成的认证元数据及独立授权的模型/连接配置,禁止任意 extra 穿透。 +func scopedCodexPermissions(credentials, extra map[string]any, proxy *int64) ([]string, error) { + permissions := []string{"accounts.credentials", "accounts.schedule"} + for key, value := range credentials { + switch key { + case "access_token", "refresh_token", "id_token", "client_id", "expires_at", "email", "chatgpt_account_id", "chatgpt_user_id", "organization_id", "plan_type", "auth_mode", "agent_runtime_id", "agent_private_key", "task_id": + if _, ok := value.(string); !ok { + return nil, infraerrors.BadRequest("SCOPED_CODEX_INPUT", "认证字段格式无效") + } + case "chatgpt_account_is_fedramp": + if _, ok := value.(bool); !ok { + return nil, infraerrors.BadRequest("SCOPED_CODEX_INPUT", "认证字段格式无效") + } + case "base_url", "model_mapping": + raw, err := json.Marshal(map[string]any{key: value}) + if err != nil { + return nil, err + } + required, err := scopedAccountFieldPermissions(map[string]json.RawMessage{"credentials": raw}, false) + if err != nil { + return nil, err + } + permissions = append(permissions, required...) + default: + return nil, infraerrors.BadRequest("SCOPED_CODEX_FIELD", "导入包含未开放的凭证字段") + } + } + for key := range extra { + switch key { + case "import_source", "imported_at", "auth_provider", "session_token_present", "session_expires_at", "user_image", "user_picture", "account_structure", "account_residency_region", "compute_residency", "access_token_sha256": + case "codex_fingerprint_mode", "openai_oauth_responses_websockets_v2_enabled", "openai_oauth_responses_websockets_v2_mode": + permissions = append(permissions, "accounts.network") + default: + return nil, infraerrors.BadRequest("SCOPED_CODEX_FIELD", "导入包含未开放的扩展字段") + } + } + if proxy != nil { + permissions = append(permissions, "accounts.network") + } + return permissions, nil +} + +func requireScopedCodexPermissions(ctx context.Context, resource adminaccess.Account, permissions ...string) error { + principal := adminaccess.FromContext(ctx) + for _, permission := range permissions { + if principal == nil || !principal.Policy.AllowsAccount(permission, resource) { + return infraerrors.Forbidden("SCOPED_CODEX_FORBIDDEN", "导入权限不足") + } + } + return nil +} + +func (s *adminServiceImpl) ScopedAdminCreateCodex(ctx context.Context, input *CreateAccountInput) (*Account, error) { + if input.Platform != PlatformOpenAI || input.Type != AccountTypeOAuth || input.GroupIDs == nil || len(input.Credentials) == 0 || input.SkipMixedChannelCheck { + return nil, infraerrors.BadRequest("SCOPED_CODEX_INPUT", "导入须明确 OAuth 类型和目标分组,且不能跳过分组风险检查") + } + permissions, err := scopedCodexPermissions(input.Credentials, input.Extra, input.ProxyID) + if input.ProxyMode != "" { + permissions = append(permissions, "accounts.network") + } + if err != nil { + return nil, err + } + resource := adminaccess.Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: input.GroupIDs} + if err = requireScopedCodexPermissions(ctx, resource, append(permissions, "accounts.create")...); err != nil { + return nil, err + } + for _, group := range input.GroupIDs { + if !adminaccess.FromContext(ctx).Policy.AllowsGroup("accounts.create", resource, group) { + return nil, infraerrors.Forbidden("SCOPED_CODEX_GROUP", "目标分组未授权") + } + } + if input.RateMultiplier != nil && *input.RateMultiplier != 1 { + return nil, infraerrors.Forbidden("SCOPED_CODEX_RATE", "受限导入不能修改计费倍率") + } + safe := *input + safe.SkipDefaultGroupBind = true + return s.scopedAdminCreateTransaction(ctx, &safe) +} + +func (s *adminServiceImpl) ScopedAdminUpdateCodex(ctx context.Context, id int64, input *UpdateAccountInput, prepare func(*Account, *UpdateAccountInput) error) (*Account, error) { + permissions, err := scopedCodexPermissions(input.Credentials, input.Extra, input.ProxyID) + if input.ProxyMode != "" { + permissions = append(permissions, "accounts.network") + } + if err != nil { + return nil, err + } + result, err := s.ScopedAdminWrite(ctx, id, "accounts.credentials", nil, func(txctx context.Context, current *Account) (*Account, error) { + if !current.IsOpenAIOAuth() { + return nil, infraerrors.NotFound("SCOPED_ACCOUNT_NOT_FOUND", "账户不存在") + } + resource := scopedAccountResource(current) + if err := requireScopedCodexPermissions(txctx, resource, permissions...); err != nil { + return nil, err + } + safe := *input + if safe.SkipMixedChannelCheck { + return nil, infraerrors.Forbidden("SCOPED_CODEX_INPUT", "受限导入不能跳过分组风险检查") + } + if safe.GroupIDs != nil { + if err := requireScopedCodexPermissions(txctx, resource, "accounts.groups"); err != nil { + return nil, err + } + groups, err := scopedAdminMergeGroups(adminaccess.FromContext(txctx).Policy, resource, current.GroupIDs, *safe.GroupIDs) + if err != nil { + return nil, err + } + safe.GroupIDs = &groups + } + // 客户端常附带默认倍率;只接受与现值相同的值,绝不借导入改价。 + if safe.RateMultiplier != nil && *safe.RateMultiplier != current.BillingRateMultiplier() { + return nil, infraerrors.Forbidden("SCOPED_CODEX_RATE", "受限导入不能修改计费倍率") + } + safe.RateMultiplier = nil + if err := prepare(current, &safe); err != nil { + return nil, err + } + safe.ProxyID, err = s.scopedAccountProxySelection(txctx, safe.ProxyMode, safe.ProxyID) + if err != nil { + return nil, err + } + return s.UpdateAccount(txctx, id, &safe) + }) + return result, err +} diff --git a/backend/internal/service/custom_admin_key_codex_import_test.go b/backend/internal/service/custom_admin_key_codex_import_test.go new file mode 100644 index 0000000000..fd3e84aa9b --- /dev/null +++ b/backend/internal/service/custom_admin_key_codex_import_test.go @@ -0,0 +1,174 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "testing" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/stretchr/testify/require" +) + +type scopedCodexTestRepo struct{ *scopedAdminWriteTestRepo } + +func (r *scopedCodexTestRepo) Create(ctx context.Context, a *Account) error { + if err := r.scopedAdminWriteTestRepo.Create(ctx, a); err != nil { + return err + } + return r.Update(ctx, a) +} +func (r *scopedCodexTestRepo) Update(ctx context.Context, a *Account) error { + if err := r.scopedAdminWriteTestRepo.Update(ctx, a); err != nil { + return err + } + extra, err := json.Marshal(a.Extra) + if err != nil { + return err + } + _, err = r.login.sql(ctx).ExecContext(ctx, `UPDATE accounts SET extra=$2,rate_multiplier=$3 WHERE id=$1`, a.ID, string(extra), a.BillingRateMultiplier()) + return err +} +func (r *scopedCodexTestRepo) GetByID(ctx context.Context, id int64) (*Account, error) { + a, err := r.scopedAdminWriteTestRepo.GetByID(ctx, id) + if err != nil { + return nil, err + } + rows, err := r.login.sql(ctx).QueryContext(ctx, `SELECT extra,rate_multiplier FROM accounts WHERE id=$1`, id) + if err != nil { + return nil, err + } + defer rows.Close() + var extra []byte + var rate float64 + if rows.Next() { + if err = rows.Scan(&extra, &rate); err != nil { + return nil, err + } + } + if err = json.Unmarshal(extra, &a.Extra); err != nil { + return nil, err + } + a.RateMultiplier = &rate + return a, rows.Err() +} + +func TestScopedCodexWriteAuthorizationAndTransactions(t *testing.T) { + login, db := scopedAdminAccountTestDB(t) + _, err := db.Exec(`CREATE TABLE account_groups(account_id BIGINT,group_id BIGINT); + ALTER TABLE accounts ADD COLUMN extra JSONB DEFAULT '{}', ADD COLUMN rate_multiplier DOUBLE PRECISION DEFAULT 1; + INSERT INTO accounts(id,name,platform,type,credentials,extra) VALUES + (101,'共享','openai','oauth','{"access_token":"old","refresh_token":"keep"}','{"quota_used":7}'), + (102,'其他组','openai','oauth','{}','{}'),(103,'API','openai','apikey','{}','{}'),(104,'其他平台','anthropic','oauth','{}','{}'); + INSERT INTO account_groups VALUES(101,1),(101,2),(102,2),(103,1),(104,1);`) + require.NoError(t, err) + repo := &scopedCodexTestRepo{&scopedAdminWriteTestRepo{login: login}} + admin := &adminServiceImpl{accountRepo: repo, groupRepo: &scopedAdminWriteTestGroups{}, entClient: dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))} + ctxFor := func(permissions ...string) context.Context { + return adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: permissions, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}}}}) + } + all := []string{"accounts.create", "accounts.credentials", "accounts.schedule", "accounts.network", "accounts.groups"} + input := func() *CreateAccountInput { + rate := 1.0 + return &CreateAccountInput{Name: "导入创建", Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{1}, Credentials: map[string]any{"access_token": "new", "refresh_token": "refresh", "email": "test@example.com", "chatgpt_account_id": "acct"}, Extra: map[string]any{"import_source": "codex_session", "codex_fingerprint_mode": "off"}, Concurrency: 40, RateMultiplier: &rate} + } + for _, missing := range []string{"accounts.create", "accounts.credentials", "accounts.schedule", "accounts.network"} { + t.Run("缺少"+missing, func(t *testing.T) { + permissions := []string{} + for _, p := range all { + if p != missing { + permissions = append(permissions, p) + } + } + _, err := admin.ScopedAdminCreateCodex(ctxFor(permissions...), input()) + require.Equal(t, 403, infraerrors.Code(err)) + }) + } + ctx := ctxFor(all...) + for _, groups := range [][]int64{{1, 2}, {2}, {}, {0}} { + v := input() + v.GroupIDs = groups + _, err = admin.ScopedAdminCreateCodex(ctx, v) + require.Equal(t, 403, infraerrors.Code(err)) + } + v := input() + v.Type = AccountTypeAPIKey + _, err = admin.ScopedAdminCreateCodex(ctx, v) + require.Equal(t, 400, infraerrors.Code(err)) + v = input() + rate := 0.0 + v.RateMultiplier = &rate + _, err = admin.ScopedAdminCreateCodex(ctx, v) + require.Equal(t, 403, infraerrors.Code(err)) + v = input() + v.Extra["quota_used"] = 0 + _, err = admin.ScopedAdminCreateCodex(ctx, v) + require.Equal(t, 400, infraerrors.Code(err)) + v = input() + v.Credentials["model_mapping"] = map[string]any{"a": "b"} + _, err = admin.ScopedAdminCreateCodex(ctx, v) + require.Equal(t, 403, infraerrors.Code(err)) + repo.failBind = true + _, err = admin.ScopedAdminCreateCodex(ctx, input()) + require.Error(t, err) + var count int + require.NoError(t, db.QueryRow(`SELECT count(*) FROM accounts WHERE name='导入创建'`).Scan(&count)) + require.Zero(t, count) + repo.failBind = false + created, err := admin.ScopedAdminCreateCodex(ctx, input()) + require.NoError(t, err) + saved, err := repo.GetByID(ctx, created.ID) + require.NoError(t, err) + require.Equal(t, "new", saved.Credentials["access_token"]) + require.Equal(t, "off", saved.Extra["codex_fingerprint_mode"]) + require.Equal(t, []int64{1}, saved.GroupIDs) + // 不需要账户读取权限;无分组授权显式控制,不自动绑定默认组。 + ungrouped := input() + ungrouped.GroupIDs = []int64{} + principal := *adminaccess.FromContext(ctx) + principal.Policy.Rules = append([]adminaccess.Rule(nil), principal.Policy.Rules...) + principal.Policy.Rules[0].IncludeUngrouped = true + created, err = admin.ScopedAdminCreateCodex(adminaccess.WithPrincipal(context.Background(), &principal), ungrouped) + require.NoError(t, err) + saved, err = repo.GetByID(ctx, created.ID) + require.NoError(t, err) + require.Empty(t, saved.GroupIDs) + groups := []int64{1} + update := &UpdateAccountInput{Credentials: map[string]any{"access_token": "changed"}, Extra: map[string]any{"import_source": "codex_session"}, GroupIDs: &groups} + called := 0 + prepare := func(current *Account, safe *UpdateAccountInput) error { + called++ + require.Equal(t, "old", current.Credentials["access_token"]) + safe.Credentials = map[string]any{"access_token": "changed", "refresh_token": current.Credentials["refresh_token"]} + safe.Extra = map[string]any{"import_source": "codex_session", "quota_used": current.Extra["quota_used"]} + return nil + } + for _, id := range []int64{102, 103, 104, 999} { + _, err = admin.ScopedAdminUpdateCodex(ctx, id, update, prepare) + require.Equal(t, 404, infraerrors.Code(err)) + } + require.Zero(t, called) + _, err = admin.ScopedAdminUpdateCodex(ctxFor("accounts.credentials", "accounts.schedule"), 101, update, prepare) + require.Equal(t, 403, infraerrors.Code(err)) + require.Zero(t, called) + _, err = admin.ScopedAdminUpdateCodex(ctx, 101, update, func(_ *Account, _ *UpdateAccountInput) error { return infraerrors.Conflict("CHANGED", "身份已变") }) + require.Equal(t, 409, infraerrors.Code(err)) + _, err = admin.ScopedAdminUpdateCodex(ctx, 101, update, prepare) + require.NoError(t, err) + require.Equal(t, 1, called) + saved, err = repo.GetByID(ctx, 101) + require.NoError(t, err) + require.Equal(t, "changed", saved.Credentials["access_token"]) + require.Equal(t, "keep", saved.Credentials["refresh_token"]) + require.Equal(t, float64(7), saved.Extra["quota_used"]) + require.Equal(t, []int64{1, 2}, saved.GroupIDs) + update.RateMultiplier = &rate + _, err = admin.ScopedAdminUpdateCodex(ctx, 101, update, prepare) + require.Equal(t, 403, infraerrors.Code(err)) + require.Equal(t, 1, called) +} diff --git a/backend/internal/service/custom_admin_key_group_models.go b/backend/internal/service/custom_admin_key_group_models.go new file mode 100644 index 0000000000..d02d8af4d5 --- /dev/null +++ b/backend/internal/service/custom_admin_key_group_models.go @@ -0,0 +1,56 @@ +package service + +import ( + "context" + "strings" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" +) + +// ScopedAdminUpdateGroupModels 仅更新模型白名单;仓储在锁内重新验证分组和平台。 +func (s *adminServiceImpl) ScopedAdminUpdateGroupModels(ctx context.Context, id int64, cfg GroupModelAllowlist) (*Group, error) { + if err := s.ValidateSimpleModeGroupOperation(AdminGroupOperationCompositeRoute); err != nil { + return nil, err + } + if len(cfg.Models) > 1024 { + return nil, infraerrors.BadRequest("SCOPED_GROUP_MODELS_INVALID", "模型数量超过限制") + } + for _, model := range cfg.Models { + if strings.TrimSpace(model) == "" || len(model) > 512 { + return nil, infraerrors.BadRequest("SCOPED_GROUP_MODELS_INVALID", "模型 ID 格式无效") + } + } + repo, ok := s.groupRepo.(interface { + ScopedAdminUpdateGroupModels(context.Context, int64, GroupModelAllowlist) (*Group, error) + }) + if !ok { + return nil, infraerrors.ServiceUnavailable("SCOPED_GROUP_MODELS_UNAVAILABLE", "受限分组模型服务不可用") + } + normalized, err := normalizeGroupModelAllowlist(cfg) + if err != nil { + return nil, err + } + updated, err := repo.ScopedAdminUpdateGroupModels(ctx, id, normalized) + if err != nil { + return nil, err + } + // 仓储返回时事务已提交,避免回滚后缓存已提前失效。 + if s.authCacheInvalidator != nil { + s.authCacheInvalidator.InvalidateAuthCacheByGroupID(ctx, id) + } + return updated, nil +} + +func (s *adminServiceImpl) ScopedAdminListGroupModels(ctx context.Context, params pagination.PaginationParams, all bool, platform, status, search string) ([]Group, int64, error) { + if err := s.ValidateSimpleModeGroupOperation(AdminGroupOperationCompositeRoute); err != nil { + return nil, 0, err + } + repo, ok := s.groupRepo.(interface { + ScopedAdminListGroupModels(context.Context, pagination.PaginationParams, bool, string, string, string) ([]Group, int64, error) + }) + if !ok { + return nil, 0, infraerrors.ServiceUnavailable("SCOPED_GROUP_MODELS_UNAVAILABLE", "受限分组模型服务不可用") + } + return repo.ScopedAdminListGroupModels(ctx, params, all, platform, status, search) +} diff --git a/backend/internal/service/custom_admin_key_group_models_test.go b/backend/internal/service/custom_admin_key_group_models_test.go new file mode 100644 index 0000000000..d6d398c0bd --- /dev/null +++ b/backend/internal/service/custom_admin_key_group_models_test.go @@ -0,0 +1,48 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +type scopedGroupModelsRepo struct { + GroupRepository + config GroupModelAllowlist + writes int + err error +} + +func (r *scopedGroupModelsRepo) ScopedAdminUpdateGroupModels(_ context.Context, id int64, cfg GroupModelAllowlist) (*Group, error) { + r.writes++ + r.config = cfg + return &Group{ID: id, ModelAllowlist: cfg}, r.err +} + +func TestScopedAdminGroupModelsNormalizeAndInvalidateOnlyOnSuccess(t *testing.T) { + repo := &scopedGroupModelsRepo{} + cache := &authCacheInvalidatorStub{} + s := &adminServiceImpl{groupRepo: repo, authCacheInvalidator: cache} + cfg := GroupModelAllowlist{Enabled: true, Models: []string{" second ", "first", "second"}} + g, err := s.ScopedAdminUpdateGroupModels(context.Background(), 2, cfg) + require.NoError(t, err) + require.Equal(t, []string{"second", "first"}, g.ModelAllowlist.Models) + require.Equal(t, []int64{2}, cache.groupIDs) + repo.err = errors.New("提交失败") + _, err = s.ScopedAdminUpdateGroupModels(context.Background(), 3, cfg) + require.Error(t, err) + require.Equal(t, []int64{2}, cache.groupIDs, "仓储失败不得提前清理缓存") + writes := repo.writes + _, err = s.ScopedAdminUpdateGroupModels(context.Background(), 2, GroupModelAllowlist{Enabled: true}) + require.Error(t, err, "上游禁止启用空白名单,不能变成仅展示配置") + for _, models := range [][]string{{""}, {" "}, {strings.Repeat("x", 513)}, make([]string, 1025)} { + _, err = s.ScopedAdminUpdateGroupModels(context.Background(), 2, GroupModelAllowlist{Models: models}) + require.Error(t, err) + } + require.Equal(t, writes, repo.writes, "无效模型必须在写库前拒绝") +} diff --git a/backend/internal/service/custom_admin_key_proxy_selection.go b/backend/internal/service/custom_admin_key_proxy_selection.go new file mode 100644 index 0000000000..eb53926ca3 --- /dev/null +++ b/backend/internal/service/custom_admin_key_proxy_selection.go @@ -0,0 +1,72 @@ +package service + +import ( + "context" + "fmt" + + dbent "github.com/Wei-Shaw/sub2api/ent" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +// NormalizeAccountProxyMode 显式模式与旧 proxy_id/random_proxy 互斥,省略时保留原绑定语义。 +func NormalizeAccountProxyMode(mode string, id *int64, random bool) (string, error) { + if id != nil && *id < 0 { + return "", infraerrors.BadRequest("PROXY_SELECTION_INVALID", "代理 ID 无效") + } + if random { + if mode != "" && mode != "random" { + return "", infraerrors.BadRequest("PROXY_SELECTION_CONFLICT", "代理选择参数冲突") + } + mode = "random" + } + switch mode { + case "": + return "", nil + case "specified": + if id == nil || *id <= 0 { + return "", infraerrors.BadRequest("PROXY_SELECTION_INVALID", "指定代理须提供正数 proxy_id") + } + case "direct": + if id != nil && *id != 0 { + return "", infraerrors.BadRequest("PROXY_SELECTION_CONFLICT", "直连模式不能同时指定代理") + } + case "random", "least_used": + if id != nil && *id != 0 { + return "", infraerrors.BadRequest("PROXY_SELECTION_CONFLICT", "自动选择不能同时指定代理") + } + default: + return "", infraerrors.BadRequest("PROXY_SELECTION_INVALID", "代理模式仅支持 direct、specified、random、least_used") + } + return mode, nil +} + +func (s *adminServiceImpl) scopedAccountProxySelection(ctx context.Context, mode string, id *int64) (*int64, error) { + normalized, err := NormalizeAccountProxyMode(mode, id, false) + if err != nil { + return nil, err + } + switch normalized { + case "", "specified": + return id, nil + case "direct": + zero := int64(0) + return &zero, nil + } + if dbent.TxFromContext(ctx) == nil { + return nil, fmt.Errorf("自动代理选择需要账户写事务") + } + repo, ok := s.proxyRepo.(interface { + SelectAccountProxy(context.Context, string) (int64, error) + }) + if !ok { + return nil, fmt.Errorf("自动代理选择服务不可用") + } + selected, err := repo.SelectAccountProxy(ctx, normalized) + if err != nil { + return nil, err + } + if selected <= 0 { + return nil, infraerrors.BadRequest("PROXY_POOL_EMPTY", "没有启用且未过期的代理") + } + return &selected, nil +} diff --git a/backend/internal/service/custom_admin_key_proxy_selection_test.go b/backend/internal/service/custom_admin_key_proxy_selection_test.go new file mode 100644 index 0000000000..1280afd2aa --- /dev/null +++ b/backend/internal/service/custom_admin_key_proxy_selection_test.go @@ -0,0 +1,174 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "testing" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/stretchr/testify/require" +) + +type scopedSelectionProxyRepo struct { + ProxyRepository + calls int + mode string + id int64 +} + +func (r *scopedSelectionProxyRepo) SelectAccountProxy(ctx context.Context, mode string) (int64, error) { + if dbent.TxFromContext(ctx) == nil { + panic("选择必须位于账户事务中") + } + r.calls++ + r.mode = mode + return r.id, nil +} + +type scopedSelectionAccountRepo struct{ *scopedAdminWriteTestRepo } + +func (r *scopedSelectionAccountRepo) Create(ctx context.Context, a *Account) error { + if err := r.scopedAdminWriteTestRepo.Create(ctx, a); err != nil { + return err + } + _, err := r.login.sql(ctx).ExecContext(ctx, `UPDATE accounts SET proxy_id=$2 WHERE id=$1`, a.ID, a.ProxyID) + return err +} +func (r *scopedSelectionAccountRepo) Update(ctx context.Context, a *Account) error { + if err := r.scopedAdminWriteTestRepo.Update(ctx, a); err != nil { + return err + } + _, err := r.login.sql(ctx).ExecContext(ctx, `UPDATE accounts SET proxy_id=$2 WHERE id=$1`, a.ID, a.ProxyID) + return err +} +func (r *scopedSelectionAccountRepo) GetByID(ctx context.Context, id int64) (*Account, error) { + a, err := r.scopedAdminWriteTestRepo.GetByID(ctx, id) + if err != nil { + return nil, err + } + rows, err := r.login.sql(ctx).QueryContext(ctx, `SELECT proxy_id FROM accounts WHERE id=$1`, id) + if err != nil { + return nil, err + } + defer rows.Close() + if rows.Next() { + err = rows.Scan(&a.ProxyID) + } + if err != nil { + return nil, err + } + return a, rows.Err() +} +func TestScopedAccountProxySelectionPermissionsAndRollback(t *testing.T) { + login, db := scopedAdminAccountTestDB(t) + _, err := db.Exec(`CREATE TABLE account_groups(account_id BIGINT,group_id BIGINT)`) + require.NoError(t, err) + repo := &scopedSelectionAccountRepo{&scopedAdminWriteTestRepo{login: login}} + proxy := &scopedSelectionProxyRepo{id: 7} + s := &adminServiceImpl{accountRepo: repo, proxyRepo: proxy, groupRepo: &scopedAdminWriteTestGroups{}, entClient: dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))} + principal := &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.create", "accounts.credentials"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}}}}} + ctx := adminaccess.WithPrincipal(context.Background(), principal) + for _, field := range []string{`"proxy_id":7`, `"proxy_mode":"random"`, `"random_proxy":true`, `"proxy_mode":"least_used"`, `"proxy_mode":"direct"`} { + var body map[string]json.RawMessage + require.NoError(t, json.Unmarshal([]byte(`{"name":"代理选择","platform":"openai","type":"oauth","group_ids":[1],"credentials":{"access_token":"fixture"},`+field+`}`), &body)) + _, err = s.ScopedAdminWrite(ctx, 0, "", body, nil) + require.Equal(t, 403, infraerrors.Code(err)) + require.Zero(t, proxy.calls) + principal.Policy.Rules[0].Permissions = append(principal.Policy.Rules[0].Permissions, "accounts.network") + a, err := s.ScopedAdminWrite(ctx, 0, "", body, nil) + require.NoError(t, err) + var id *int64 + require.NoError(t, db.QueryRow(`SELECT proxy_id FROM accounts WHERE id=$1`, a.ID).Scan(&id)) + if field == `"proxy_mode":"direct"` { + require.Nil(t, id) + } else { + require.NotNil(t, id) + require.EqualValues(t, 7, *id) + } + principal.Policy.Rules[0].Permissions = principal.Policy.Rules[0].Permissions[:2] + proxy.calls = 0 + } + principal.Policy.Rules[0].Permissions = append(principal.Policy.Rules[0].Permissions, "accounts.network", "accounts.schedule", "accounts.groups") + for _, mode := range []string{"random", "least_used"} { + input := &CreateAccountInput{Name: "导入代理", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"access_token": "fixture"}, GroupIDs: []int64{1}, ProxyMode: mode} + a, err := s.ScopedAdminCreateCodex(ctx, input) + require.NoError(t, err) + require.Equal(t, mode, proxy.mode) + require.EqualValues(t, 7, *a.ProxyID) + repo.failBind = true + _, err = s.ScopedAdminCreateCodex(ctx, input) + require.Error(t, err) + repo.failBind = false + } + _, err = db.Exec(`INSERT INTO accounts(id,name,platform,type,proxy_id) VALUES(1001,'可管理','openai','oauth',7),(1002,'组外','openai','oauth',7),(1003,'类型外','openai','apikey',7); INSERT INTO account_groups VALUES(1001,1),(1002,2),(1003,1);`) + require.NoError(t, err) + fields := map[string]json.RawMessage{"proxy_mode": json.RawMessage(`"least_used"`)} + calls := proxy.calls + for _, id := range []int64{1002, 1003} { + _, err = s.ScopedAdminWrite(ctx, id, "", fields, nil) + require.Equal(t, 404, infraerrors.Code(err)) + } + require.Equal(t, calls, proxy.calls, "越权时不能进入代理选择") + denied := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.credentials", "accounts.schedule"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}}}}}) + _, err = s.ScopedAdminWrite(denied, 1001, "", fields, nil) + require.Equal(t, 403, infraerrors.Code(err)) + _, err = s.ScopedAdminUpdateCodex(denied, 1001, &UpdateAccountInput{Credentials: map[string]any{"access_token": "fixture"}, ProxyMode: "random"}, func(_ *Account, _ *UpdateAccountInput) error { + t.Fatal("缺网络权限不能执行更新回调") + return nil + }) + require.Equal(t, 403, infraerrors.Code(err)) + require.Equal(t, calls, proxy.calls) + proxy.id = 8 + updated, err := s.ScopedAdminWrite(ctx, 1001, "", fields, nil) + require.NoError(t, err) + require.EqualValues(t, 8, *updated.ProxyID) + updated, err = s.ScopedAdminWrite(ctx, 1001, "", map[string]json.RawMessage{"proxy_mode": json.RawMessage(`"direct"`)}, nil) + require.NoError(t, err) + require.Nil(t, updated.ProxyID) + updated, err = s.ScopedAdminUpdateCodex(ctx, 1001, &UpdateAccountInput{Credentials: map[string]any{"access_token": "fixture"}, ProxyMode: "random"}, func(_ *Account, _ *UpdateAccountInput) error { return nil }) + require.NoError(t, err) + require.EqualValues(t, 8, *updated.ProxyID) + // 更新后的后续分组失败应回滚代理绑定。 + repo.failBind = true + _, err = s.ScopedAdminWrite(ctx, 1001, "", map[string]json.RawMessage{"proxy_mode": json.RawMessage(`"direct"`), "group_ids": json.RawMessage(`[1]`)}, nil) + require.Error(t, err) + repo.failBind = false + stored, err := repo.GetByID(ctx, 1001) + require.NoError(t, err) + require.EqualValues(t, 8, *stored.ProxyID) + proxy.id = 0 + _, err = s.ScopedAdminCreateCodex(ctx, &CreateAccountInput{Name: "空池禁止直连", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"access_token": "fixture"}, GroupIDs: []int64{1}, ProxyMode: "random"}) + require.Equal(t, 400, infraerrors.Code(err)) + var count int + require.NoError(t, db.QueryRow(`SELECT COUNT(*) FROM accounts WHERE name='空池禁止直连'`).Scan(&count)) + require.Zero(t, count) +} + +func TestNormalizeAccountProxySelectionConflicts(t *testing.T) { + id := int64(7) + zero := int64(0) + for _, tc := range []struct { + mode string + id *int64 + random bool + want string + invalid bool + }{ + {"", &id, false, "", false}, {"specified", &id, false, "specified", false}, {"direct", nil, false, "direct", false}, {"", nil, true, "random", false}, {"random", nil, false, "random", false}, {"least_used", nil, false, "least_used", false}, + {"random", &id, false, "", true}, {"least_used", &id, false, "", true}, {"direct", &id, false, "", true}, {"specified", &zero, false, "", true}, {"unknown", nil, false, "", true}, {"least_used", nil, true, "", true}, + } { + got, err := NormalizeAccountProxyMode(tc.mode, tc.id, tc.random) + if tc.invalid { + require.Error(t, err) + } else { + require.NoError(t, err) + require.Equal(t, tc.want, got) + } + } +} diff --git a/backend/internal/service/custom_admin_key_recovery_review_test.go b/backend/internal/service/custom_admin_key_recovery_review_test.go new file mode 100644 index 0000000000..71820596ae --- /dev/null +++ b/backend/internal/service/custom_admin_key_recovery_review_test.go @@ -0,0 +1,77 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "testing" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + "github.com/DATA-DOG/go-sqlmock" + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/stretchr/testify/require" +) + +type scopedRecoveryReviewRepo struct { + accountRepoStubForClearAccountError + reads int + failRead bool +} + +func (r *scopedRecoveryReviewRepo) GetByID(ctx context.Context, id int64) (*Account, error) { + r.reads++ + if r.failRead && r.reads > 1 { + return nil, errors.New("模拟回读失败") + } + return r.accountRepoStubForClearAccountError.GetByID(ctx, id) +} +func (*scopedRecoveryReviewRepo) ListShadowsByParent(context.Context, int64) ([]*Account, error) { + return nil, nil +} + +type scopedRecoveryReviewBlocker struct { + runtimeBlockRecorder + resets int +} + +func (b *scopedRecoveryReviewBlocker) ResetOpenAI403Counter(context.Context, int64) { b.resets++ } + +func TestScopedAdminReviewRecoveryCommitBoundary(t *testing.T) { + for _, mode := range []string{"commit", "read_failure", "commit_failure"} { + t.Run(mode, func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer db.Close() + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + repo := &scopedRecoveryReviewRepo{accountRepoStubForClearAccountError: accountRepoStubForClearAccountError{account: &Account{ID: 31, Platform: "openai", Type: "oauth", Status: StatusError, GroupIDs: []int64{1}}}, failRead: mode == "read_failure"} + blocker := &scopedRecoveryReviewBlocker{} + admin := &adminServiceImpl{accountRepo: repo, entClient: client, runtimeBlocker: blocker} + mock.ExpectBegin() + mock.ExpectExec(`SELECT pg_advisory_xact_lock`).WithArgs(int64(31)).WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec(`SELECT id FROM accounts`).WithArgs(int64(31)).WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec(`SELECT account_id FROM account_groups`).WithArgs(int64(31)).WillReturnResult(sqlmock.NewResult(0, 1)) + if mode == "read_failure" { + mock.ExpectRollback() + } else if mode == "commit_failure" { + mock.ExpectCommit().WillReturnError(errors.New("模拟提交失败")) + } else { + mock.ExpectCommit() + } + ctx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.recover"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}}}}}) + _, err = admin.ScopedAdminWrite(ctx, 31, "accounts.recover", nil, nil) + if mode == "commit" { + require.NoError(t, err) + require.Equal(t, []int64{31}, blocker.clearedIDs) + require.Zero(t, blocker.resets) + } else { + require.Error(t, err) + require.Empty(t, blocker.clearedIDs, "失败事务不得清理运行态阻塞") + require.Zero(t, blocker.resets) + } + require.NoError(t, mock.ExpectationsWereMet()) + }) + } +} diff --git a/backend/internal/service/custom_admin_key_testdb_test.go b/backend/internal/service/custom_admin_key_testdb_test.go new file mode 100644 index 0000000000..1855ae00a0 --- /dev/null +++ b/backend/internal/service/custom_admin_key_testdb_test.go @@ -0,0 +1,47 @@ +//go:build unit + +package service + +import ( + "context" + "database/sql" + "fmt" + dbent "github.com/Wei-Shaw/sub2api/ent" + _ "github.com/lib/pq" + "github.com/stretchr/testify/require" + "os" + "testing" + "time" +) + +type scopedTestSQL interface { + ExecContext(context.Context, string, ...any) (sql.Result, error) + QueryContext(context.Context, string, ...any) (*sql.Rows, error) +} +type scopedTestDB struct{ db *sql.DB } + +func (s *scopedTestDB) sql(ctx context.Context) scopedTestSQL { + if tx := dbent.TxFromContext(ctx); tx != nil { + return tx.Client() + } + return s.db +} +func scopedAdminAccountTestDB(t *testing.T) (*scopedTestDB, *sql.DB) { + t.Helper() + dsn := os.Getenv("SCOPED_ADMIN_TEST_DSN") + if dsn == "" { + t.Skip("需要独立 SCOPED_ADMIN_TEST_DSN") + } + base, err := sql.Open("postgres", dsn) + require.NoError(t, err) + name := fmt.Sprintf("scoped_accounts_%d", time.Now().UnixNano()) + _, err = base.Exec(`CREATE SCHEMA ` + name) + require.NoError(t, err) + db, err := sql.Open("postgres", dsn+" search_path="+name) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close(); _, _ = base.Exec(`DROP SCHEMA ` + name + ` CASCADE`); _ = base.Close() }) + _, err = db.Exec(`CREATE TABLE accounts(id BIGSERIAL PRIMARY KEY,name TEXT DEFAULT '',platform TEXT DEFAULT 'openai',type TEXT DEFAULT 'oauth',credentials JSONB DEFAULT '{}',status TEXT DEFAULT 'active',schedulable BOOLEAN DEFAULT true,error_message TEXT,temp_unschedulable_until TIMESTAMPTZ,temp_unschedulable_reason TEXT,deleted_at TIMESTAMPTZ,parent_account_id BIGINT,proxy_id BIGINT,expires_at TIMESTAMPTZ,updated_at TIMESTAMPTZ DEFAULT NOW()); + CREATE TABLE proxies(id BIGSERIAL PRIMARY KEY,protocol TEXT,host TEXT,port INT,username TEXT,password TEXT,status TEXT DEFAULT 'active',expires_at TIMESTAMPTZ,deleted_at TIMESTAMPTZ);`) + require.NoError(t, err) + return &scopedTestDB{db: db}, db +} diff --git a/backend/internal/service/custom_admin_key_transaction.go b/backend/internal/service/custom_admin_key_transaction.go new file mode 100644 index 0000000000..ac46878a14 --- /dev/null +++ b/backend/internal/service/custom_admin_key_transaction.go @@ -0,0 +1,29 @@ +package service + +import ( + "context" + dbent "github.com/Wei-Shaw/sub2api/ent" +) + +func lockScopedAdminAccount(ctx context.Context, tx *dbent.Tx, id int64) error { + _, err := tx.Client().ExecContext(ctx, `SELECT pg_advisory_xact_lock(hashtextextended('scoped_admin_account:' || $1::text, 0))`, id) + return err +} + +// AfterAccountCommit 将不参与回滚的缓存和上游副作用延迟到事务提交成功后。 +// 普通管理员没有外层事务时立即执行,保留原有行为。 +func AfterAccountCommit(ctx context.Context, run func(context.Context)) { + if tx := dbent.TxFromContext(ctx); tx != nil { + tx.OnCommit(func(next dbent.Committer) dbent.Committer { + return dbent.CommitFunc(func(commitCtx context.Context, tx *dbent.Tx) error { + if err := next.Commit(commitCtx, tx); err != nil { + return err + } + run(dbent.NewTxContext(ctx, nil)) + return nil + }) + }) + } else { + run(ctx) + } +} diff --git a/backend/internal/service/custom_admin_key_transaction_test.go b/backend/internal/service/custom_admin_key_transaction_test.go new file mode 100644 index 0000000000..93d6a65942 --- /dev/null +++ b/backend/internal/service/custom_admin_key_transaction_test.go @@ -0,0 +1,53 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "testing" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + "github.com/DATA-DOG/go-sqlmock" + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/stretchr/testify/require" +) + +func TestScopedAdminAfterCommitEffects(t *testing.T) { + for _, mode := range []string{"commit", "rollback", "commit_failure"} { + t.Run(mode, func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer db.Close() + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + mock.ExpectBegin() + tx, err := client.Tx(context.Background()) + require.NoError(t, err) + calls := 0 + AfterAccountCommit(dbent.NewTxContext(context.Background(), tx), func(ctx context.Context) { + require.Nil(t, dbent.TxFromContext(ctx), "提交后回调不能复用已关闭的事务") + calls++ + }) + require.Zero(t, calls) + switch mode { + case "commit": + mock.ExpectCommit() + require.NoError(t, tx.Commit()) + require.Equal(t, 1, calls) + case "rollback": + mock.ExpectRollback() + require.NoError(t, tx.Rollback()) + require.Zero(t, calls) + case "commit_failure": + mock.ExpectCommit().WillReturnError(errors.New("提交失败")) + require.Error(t, tx.Commit()) + require.Zero(t, calls) + } + require.NoError(t, mock.ExpectationsWereMet()) + }) + } + calls := 0 + AfterAccountCommit(context.Background(), func(context.Context) { calls++ }) + require.Equal(t, 1, calls, "无事务时保留原管理员同步语义") +} diff --git a/backend/internal/service/custom_admin_keys.go b/backend/internal/service/custom_admin_keys.go new file mode 100644 index 0000000000..f11c31711b --- /dev/null +++ b/backend/internal/service/custom_admin_keys.go @@ -0,0 +1,253 @@ +package service + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "errors" + "net/netip" + "strings" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +var ErrScopedAdminKeyInvalid = infraerrors.Unauthorized("INVALID_ADMIN_KEY", "Invalid admin API key") +var ErrScopedAdminKeyConflict = infraerrors.Conflict("ADMIN_KEY_CONFLICT", "密钥已变化,请刷新后重试") +var ErrScopedAdminKeyNotFound = infraerrors.NotFound("ADMIN_KEY_NOT_FOUND", "Admin key not found") + +type ScopedAdminKeyInput struct { + Name string `json:"name"` + Description string `json:"description"` + Enabled bool `json:"enabled"` + ExpiresAt *time.Time `json:"expires_at"` + AllowedIPs []string `json:"allowed_ips"` + Policy adminaccess.Policy `json:"policy"` +} +type ScopedAdminKey struct { + ScopedAdminKeyInput + ID string `json:"id"` + KeyPrefix string `json:"key_prefix"` + Hash string `json:"-"` + CreatedBy int64 `json:"created_by"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + LastUsedAt *time.Time `json:"last_used_at"` + LastUsedIP string `json:"last_used_ip"` + RevokedAt *time.Time `json:"revoked_at"` +} +type ScopedAdminKeyRepository interface { + ListScopedAdminKeys(context.Context) ([]*ScopedAdminKey, error) + GetScopedAdminKey(context.Context, string) (*ScopedAdminKey, error) + InsertScopedAdminKey(context.Context, *ScopedAdminKey) error + UpdateScopedAdminKey(context.Context, *ScopedAdminKey) error + RotateScopedAdminKeyHash(context.Context, string, string, string, time.Time) error + TouchScopedAdminKey(context.Context, string, string, time.Time, string, time.Time) error + RevokeScopedAdminKey(context.Context, string, time.Time) error + DeleteScopedAdminKeyRecord(context.Context, string, time.Time) error +} + +func validateScopedAdminKeyInput(in *ScopedAdminKeyInput) error { + in.Name = strings.TrimSpace(in.Name) + if in.Name == "" || len(in.Name) > 100 || len(in.Description) > 1000 || len(in.AllowedIPs) > 100 { + return infraerrors.BadRequest("INVALID_ADMIN_KEY_INPUT", "名称、备注或 IP 列表无效") + } + if in.ExpiresAt != nil && !in.ExpiresAt.After(time.Now()) { + return infraerrors.BadRequest("INVALID_ADMIN_KEY_EXPIRY", "有效期必须在未来") + } + for _, ip := range in.AllowedIPs { + if _, e := netip.ParseAddr(ip); e != nil { + if _, e = netip.ParsePrefix(ip); e != nil { + return infraerrors.BadRequest("INVALID_ADMIN_KEY_IP", "IP 或 CIDR 无效") + } + } + } + if in.AllowedIPs == nil { + in.AllowedIPs = []string{} + } + if err := adminaccess.ValidatePolicy(in.Policy); err != nil { + return infraerrors.BadRequest("INVALID_ADMIN_KEY_POLICY", "权限策略无效") + } + return nil +} +func generateScopedAdminKey(id string) (string, string, error) { + b := make([]byte, 32) + if _, err := rand.Read(b); err != nil { + return "", "", err + } + key := "adm_sc_" + id + "_" + hex.EncodeToString(b) + hash := sha256.Sum256([]byte(key)) + return key, hex.EncodeToString(hash[:]), nil +} +func verifyScopedAdminKey(key, hash string) bool { + h := sha256.Sum256([]byte(key)) + return subtle.ConstantTimeCompare([]byte(hex.EncodeToString(h[:])), []byte(hash)) == 1 +} +func scopedAdminIPAllowed(allowed []string, ip string) bool { + if len(allowed) == 0 { + return true + } + addr, err := netip.ParseAddr(ip) + if err != nil { + return false + } + addr = addr.Unmap() + for _, s := range allowed { + if a, e := netip.ParseAddr(s); e == nil && a.Unmap() == addr { + return true + } + if p, e := netip.ParsePrefix(s); e == nil { + candidate := addr + if p.Addr().Is4In6() && addr.Is4() { + // 使用前缀的映射地址表示,保留原始位数和网段边界。 + candidate = netip.AddrFrom16(addr.As16()) + } + if p.Contains(candidate) { + return true + } + } + } + return false +} +func (s *SettingService) scopedAdminKeys() (ScopedAdminKeyRepository, error) { + if s.scopedAdminKeyRepo == nil { + return nil, errors.New("管理密钥存储未配置") + } + return s.scopedAdminKeyRepo, nil +} +func (s *SettingService) ListScopedAdminKeys(ctx context.Context) ([]*ScopedAdminKey, error) { + r, e := s.scopedAdminKeys() + if e != nil { + return nil, e + } + return r.ListScopedAdminKeys(ctx) +} +func (s *SettingService) CreateScopedAdminKey(ctx context.Context, in ScopedAdminKeyInput, creator int64) (string, *ScopedAdminKey, error) { + if e := validateScopedAdminKeyInput(&in); e != nil { + return "", nil, e + } + r, e := s.scopedAdminKeys() + if e != nil { + return "", nil, e + } + idBytes := make([]byte, 12) + if _, e = rand.Read(idBytes); e != nil { + return "", nil, e + } + id := hex.EncodeToString(idBytes) + key, hash, e := generateScopedAdminKey(id) + if e != nil { + return "", nil, e + } + now := time.Now().UTC() + item := &ScopedAdminKey{ScopedAdminKeyInput: in, ID: id, Hash: hash, KeyPrefix: "adm_sc_" + id, CreatedBy: creator, CreatedAt: now, UpdatedAt: now} + if e = r.InsertScopedAdminKey(ctx, item); e != nil { + return "", nil, e + } + return key, item, nil +} +func (s *SettingService) UpdateScopedAdminKey(ctx context.Context, id string, in ScopedAdminKeyInput) (*ScopedAdminKey, error) { + r, e := s.scopedAdminKeys() + if e != nil { + return nil, e + } + item, e := r.GetScopedAdminKey(ctx, id) + if e != nil { + return nil, e + } + if item.RevokedAt != nil { + return nil, ErrScopedAdminKeyNotFound + } + if e := validateScopedAdminKeyInputForUpdate(&in, item.ExpiresAt); e != nil { + return nil, e + } + item.ScopedAdminKeyInput = in + item.UpdatedAt = time.Now().UTC() + if e = r.UpdateScopedAdminKey(ctx, item); e != nil { + return nil, e + } + return item, nil +} + +func validateScopedAdminKeyInputForUpdate(in *ScopedAdminKeyInput, existingExpiry *time.Time) error { + if in.ExpiresAt != nil && !in.ExpiresAt.After(time.Now()) && (existingExpiry == nil || !in.ExpiresAt.Equal(*existingExpiry)) { + return infraerrors.BadRequest("INVALID_ADMIN_KEY_EXPIRY", "新的有效期必须在未来") + } + expiry := in.ExpiresAt + in.ExpiresAt = nil + err := validateScopedAdminKeyInput(in) + in.ExpiresAt = expiry + return err +} +func (s *SettingService) RotateScopedAdminKey(ctx context.Context, id string) (string, *ScopedAdminKey, error) { + r, e := s.scopedAdminKeys() + if e != nil { + return "", nil, e + } + item, e := r.GetScopedAdminKey(ctx, id) + if e != nil { + return "", nil, e + } + if item.RevokedAt != nil { + return "", nil, ErrScopedAdminKeyNotFound + } + key, hash, e := generateScopedAdminKey(id) + if e != nil { + return "", nil, e + } + previousHash := item.Hash + item.Hash = hash + item.UpdatedAt = time.Now().UTC() + if e = r.RotateScopedAdminKeyHash(ctx, item.ID, previousHash, hash, item.UpdatedAt); e != nil { + return "", nil, e + } + return key, item, nil +} +func (s *SettingService) RevokeScopedAdminKey(ctx context.Context, id string) error { + r, e := s.scopedAdminKeys() + if e != nil { + return e + } + return r.RevokeScopedAdminKey(ctx, id, time.Now().UTC()) +} + +func (s *SettingService) DeleteScopedAdminKeyRecord(ctx context.Context, id string) error { + r, e := s.scopedAdminKeys() + if e != nil { + return e + } + return r.DeleteScopedAdminKeyRecord(ctx, id, time.Now().UTC()) +} + +func (s *SettingService) AuthenticateScopedAdminKey(ctx context.Context, key, ip string) (*ScopedAdminKey, error) { + parts := strings.Split(key, "_") + if len(parts) != 4 || parts[0] != "adm" || parts[1] != "sc" || len(parts[2]) != 24 || len(parts[3]) != 64 { + return nil, ErrScopedAdminKeyInvalid + } + r, e := s.scopedAdminKeys() + if e != nil { + return nil, e + } + item, e := r.GetScopedAdminKey(ctx, parts[2]) + if e != nil { + return nil, ErrScopedAdminKeyInvalid + } + if !verifyScopedAdminKey(key, item.Hash) { + return nil, ErrScopedAdminKeyInvalid + } + if !item.Enabled || item.RevokedAt != nil || (item.ExpiresAt != nil && !item.ExpiresAt.After(time.Now())) || !scopedAdminIPAllowed(item.AllowedIPs, ip) { + return item, ErrScopedAdminKeyInvalid + } + if e = r.TouchScopedAdminKey(ctx, item.ID, item.Hash, item.UpdatedAt, ip, time.Now().UTC()); e != nil { + return nil, ErrScopedAdminKeyInvalid + } + return item, nil +} + +// SetScopedAdminKeyRepository 注入独立密钥存储。 +func (s *SettingService) SetScopedAdminKeyRepository(repo ScopedAdminKeyRepository) { + s.scopedAdminKeyRepo = repo +} diff --git a/backend/internal/service/custom_admin_keys_test.go b/backend/internal/service/custom_admin_keys_test.go new file mode 100644 index 0000000000..881ac853d0 --- /dev/null +++ b/backend/internal/service/custom_admin_keys_test.go @@ -0,0 +1,229 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +func TestScopedAdminKeyValidation(t *testing.T) { + input := ScopedAdminKeyInput{Name: "测试", Enabled: true, AllowedIPs: []string{"192.0.2.0/24"}, Policy: adminaccess.Policy{}} + if err := validateScopedAdminKeyInput(&input); err != nil { + t.Fatal(err) + } + input.AllowedIPs = []string{"invalid"} + if validateScopedAdminKeyInput(&input) == nil { + t.Fatal("应拒绝无效 IP") + } + input.AllowedIPs = nil + past := time.Now().Add(-time.Hour) + input.ExpiresAt = &past + if validateScopedAdminKeyInput(&input) == nil { + t.Fatal("应拒绝过去的有效期") + } +} +func TestScopedAdminKeySecret(t *testing.T) { + key, hash, err := generateScopedAdminKey("abc") + if err != nil { + t.Fatal(err) + } + if key == hash || !verifyScopedAdminKey(key, hash) || verifyScopedAdminKey(key+"x", hash) { + t.Fatal("密钥摘要校验错误") + } + if !scopedAdminIPAllowed([]string{"192.0.2.0/24"}, "192.0.2.5") || scopedAdminIPAllowed([]string{"192.0.2.0/24"}, "198.51.100.1") { + t.Fatal("IP 范围错误") + } +} + +type scopedKeyMemoryRepo struct { + item *ScopedAdminKey + deleted bool +} + +func (r *scopedKeyMemoryRepo) ListScopedAdminKeys(context.Context) ([]*ScopedAdminKey, error) { + if r.deleted { + return []*ScopedAdminKey{}, nil + } + return []*ScopedAdminKey{r.item}, nil +} +func (r *scopedKeyMemoryRepo) GetScopedAdminKey(_ context.Context, id string) (*ScopedAdminKey, error) { + if r.item == nil || r.item.ID != id { + return nil, ErrScopedAdminKeyNotFound + } + copy := *r.item + return ©, nil +} +func (r *scopedKeyMemoryRepo) InsertScopedAdminKey(_ context.Context, k *ScopedAdminKey) error { + copy := *k + r.item = © + return nil +} +func (r *scopedKeyMemoryRepo) UpdateScopedAdminKey(_ context.Context, k *ScopedAdminKey) error { + copy := *k + r.item = © + return nil +} +func (r *scopedKeyMemoryRepo) TouchScopedAdminKey(context.Context, string, string, time.Time, string, time.Time) error { + return nil +} +func (r *scopedKeyMemoryRepo) RevokeScopedAdminKey(_ context.Context, _ string, at time.Time) error { + r.item.RevokedAt = &at + return nil +} + +func (r *scopedKeyMemoryRepo) DeleteScopedAdminKeyRecord(_ context.Context, id string, _ time.Time) error { + if r.item == nil || r.item.ID != id || r.item.RevokedAt == nil || r.deleted { + return ErrScopedAdminKeyNotFound + } + r.deleted = true + return nil +} +func TestScopedAdminKeyLifecycle(t *testing.T) { + repo := &scopedKeyMemoryRepo{} + s := &SettingService{scopedAdminKeyRepo: repo} + ctx := context.Background() + key, item, err := s.CreateScopedAdminKey(ctx, ScopedAdminKeyInput{Name: "集成", Enabled: true, AllowedIPs: []string{"192.0.2.0/24"}}, 42) + if err != nil { + t.Fatal(err) + } + if item.CreatedBy != 42 || strings.Contains(item.Hash, key) { + t.Fatal("存储不应包含原始密钥") + } + if _, err = s.AuthenticateScopedAdminKey(ctx, key, "192.0.2.1"); err != nil { + t.Fatal(err) + } + if _, err = s.AuthenticateScopedAdminKey(ctx, key, "198.51.100.1"); err == nil { + t.Fatal("必须验证 IP") + } + next, _, err := s.RotateScopedAdminKey(ctx, item.ID) + if err != nil { + t.Fatal(err) + } + if _, err = s.AuthenticateScopedAdminKey(ctx, key, "192.0.2.1"); err == nil { + t.Fatal("轮换必须即时撤销旧密钥") + } + if _, err = s.AuthenticateScopedAdminKey(ctx, next, "192.0.2.1"); err != nil { + t.Fatal(err) + } + repo.item.Enabled = false + if _, err = s.AuthenticateScopedAdminKey(ctx, next, "192.0.2.1"); err == nil { + t.Fatal("停用必须生效") + } + repo.item.Enabled = true + if err = s.RevokeScopedAdminKey(ctx, item.ID); err != nil { + t.Fatal(err) + } + if _, err = s.AuthenticateScopedAdminKey(ctx, next, "192.0.2.1"); err == nil { + t.Fatal("撤销必须生效") + } + if _, _, err = s.RotateScopedAdminKey(ctx, item.ID); err == nil { + t.Fatal("撤销不可轮换恢复") + } +} + +func (r *scopedKeyMemoryRepo) RotateScopedAdminKeyHash(_ context.Context, _ string, expectedHash, hash string, at time.Time) error { + if r.item.Hash != expectedHash || r.item.RevokedAt != nil { + return ErrScopedAdminKeyConflict + } + r.item.Hash = hash + r.item.UpdatedAt = at + return nil +} + +func TestScopedAdminKeyPolicyValidationIsBadRequest(t *testing.T) { + in := ScopedAdminKeyInput{Name: "测试", Policy: adminaccess.Policy{GlobalPermissions: []string{"*"}}} + if err := validateScopedAdminKeyInput(&in); !infraerrors.IsBadRequest(err) { + t.Fatalf("策略错误应为400,实际 %v", err) + } +} +func TestScopedAdminKeyExpiredCanBeDisabledOrExtended(t *testing.T) { + expired := time.Now().Add(-time.Hour) + repo := &scopedKeyMemoryRepo{item: &ScopedAdminKey{ID: "expired", ScopedAdminKeyInput: ScopedAdminKeyInput{Name: "已过期", Enabled: true, ExpiresAt: &expired}}} + s := &SettingService{scopedAdminKeyRepo: repo} + in := repo.item.ScopedAdminKeyInput + in.Enabled = false + in.Description = "停用过期密钥" + if _, err := s.UpdateScopedAdminKey(context.Background(), "expired", in); err != nil { + t.Fatal(err) + } + in.ExpiresAt = ptrScopedTime(time.Now().Add(time.Hour)) + if _, err := s.UpdateScopedAdminKey(context.Background(), "expired", in); err != nil { + t.Fatal(err) + } + in.ExpiresAt = ptrScopedTime(time.Now().Add(-2 * time.Hour)) + if _, err := s.UpdateScopedAdminKey(context.Background(), "expired", in); err == nil { + t.Fatal("不允许改为另一过去时间") + } +} + +type scopedKeyCASRepo struct { + scopedKeyMemoryRepo + rotateOnTouch bool +} + +func (r *scopedKeyCASRepo) TouchScopedAdminKey(_ context.Context, id, hash string, updated time.Time, ip string, now time.Time) error { + if r.rotateOnTouch { + r.item.Hash = "new-hash" + r.item.UpdatedAt = now + return ErrScopedAdminKeyNotFound + } + if r.item.ID != id || r.item.Hash != hash || !r.item.UpdatedAt.Equal(updated) || !r.item.Enabled || r.item.RevokedAt != nil || (r.item.ExpiresAt != nil && !r.item.ExpiresAt.After(now)) { + return ErrScopedAdminKeyNotFound + } + return nil +} +func TestScopedAdminKeyConcurrentRotationRejectsStaleAuthentication(t *testing.T) { + repo := &scopedKeyCASRepo{rotateOnTouch: true} + s := &SettingService{scopedAdminKeyRepo: repo} + key, _, err := s.CreateScopedAdminKey(context.Background(), ScopedAdminKeyInput{Name: "CAS", Enabled: true}, 2) + if err != nil { + t.Fatal(err) + } + _, err = s.AuthenticateScopedAdminKey(context.Background(), key, "192.0.2.1") + if !errors.Is(err, ErrScopedAdminKeyInvalid) { + t.Fatalf("并发轮换后的旧读取必须拒绝,实际 %v", err) + } +} +func ptrScopedTime(t time.Time) *time.Time { return &t } + +func TestScopedAdminKeyMappedCIDRAuthentication(t *testing.T) { + for _, tc := range []struct { + prefix, ip string + allowed bool + }{ + {"::ffff:192.0.2.0/120", "192.0.2.9", true}, + {"::ffff:192.0.2.0/120", "::ffff:192.0.2.9", true}, + {"::ffff:192.0.2.0/120", "192.0.3.9", false}, + {"::ffff:192.0.2.0/120", "2001:db8::9", false}, + {"::ffff:192.0.2.9/128", "192.0.2.9", true}, + {"::ffff:192.0.2.9/128", "192.0.2.8", false}, + {"::ffff:0.0.0.0/96", "203.0.113.9", true}, + {"192.0.2.0/24", "::ffff:192.0.2.9", true}, + {"2001:db8::/32", "2001:db8::9", true}, + {"2001:db8::/32", "192.0.2.9", false}, + {"::ffff:192.0.2.9", "192.0.2.9", true}, + } { + t.Run(tc.prefix+"_"+tc.ip, func(t *testing.T) { + repo := &scopedKeyMemoryRepo{} + settings := &SettingService{scopedAdminKeyRepo: repo} + key, _, err := settings.CreateScopedAdminKey(context.Background(), ScopedAdminKeyInput{Name: "CIDR验收", Enabled: true, AllowedIPs: []string{tc.prefix}}, 9) + if err != nil { + t.Fatal(err) + } + _, err = settings.AuthenticateScopedAdminKey(context.Background(), key, tc.ip) + if tc.allowed && err != nil { + t.Fatalf("合法CIDR被接受但范围内地址认证失败: %v", err) + } + if !tc.allowed && !errors.Is(err, ErrScopedAdminKeyInvalid) { + t.Fatalf("范围外地址必须拒绝: %v", err) + } + }) + } +} diff --git a/backend/internal/service/custom_proxy_options.go b/backend/internal/service/custom_proxy_options.go new file mode 100644 index 0000000000..fd5839112b --- /dev/null +++ b/backend/internal/service/custom_proxy_options.go @@ -0,0 +1,35 @@ +package service + +import ( + "context" + "fmt" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" +) + +// ListProxyOptions 为受限管理密钥提供有界的代理候选。 +func (s *adminServiceImpl) ListProxyOptions(ctx context.Context, page, pageSize int, search string) ([]Proxy, int64, error) { + repo, ok := s.proxyRepo.(interface { + ListOptions(context.Context, pagination.PaginationParams, string) ([]Proxy, *pagination.PaginationResult, error) + }) + if !ok { + return nil, 0, fmt.Errorf("代理分页查询不可用") + } + proxies, result, err := repo.ListOptions(ctx, pagination.PaginationParams{Page: page, PageSize: pageSize}, strings.TrimSpace(search)) + if err != nil { + return nil, 0, err + } + return proxies, result.Total, nil +} + +// SampleProxyOptions 为不支持分页的受限客户端提供全池随机候选。 +func (s *adminServiceImpl) SampleProxyOptions(ctx context.Context, search string) ([]Proxy, int64, error) { + repo, ok := s.proxyRepo.(interface { + SampleOptions(context.Context, string) ([]Proxy, int64, error) + }) + if !ok { + return nil, 0, fmt.Errorf("随机代理候选查询不可用") + } + return repo.SampleOptions(ctx, strings.TrimSpace(search)) +} diff --git a/backend/internal/service/setting_features.go b/backend/internal/service/setting_features.go index f282761b58..6169cdd379 100644 --- a/backend/internal/service/setting_features.go +++ b/backend/internal/service/setting_features.go @@ -12,6 +12,8 @@ import ( "strconv" "strings" "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" ) // IsRegistrationEnabled 检查是否开放注册 @@ -566,7 +568,7 @@ func (s *SettingService) GetIdentityPatchPrompt(ctx context.Context) string { return value } -// GenerateAdminAPIKey 生成新的管理员 API Key +// GenerateAdminAPIKey 轮换已存在的旧版管理员 API Key,不允许新建。 func (s *SettingService) GenerateAdminAPIKey(ctx context.Context) (string, error) { // 生成 32 字节随机数 = 64 位十六进制字符 bytes := make([]byte, 32) @@ -576,10 +578,20 @@ func (s *SettingService) GenerateAdminAPIKey(ctx context.Context) (string, error key := AdminAPIKeyPrefix + hex.EncodeToString(bytes) - // 存储到 settings 表 - if err := s.settingRepo.Set(ctx, SettingKeyAdminAPIKey, key); err != nil { + // 旧版密钥只能轮换已有记录。使用条件 UPDATE,避免删除与轮换并发时被 upsert 重新创建。 + repo, ok := s.settingRepo.(interface { + ReplaceExistingAdminAPIKey(context.Context, string) (bool, error) + }) + if !ok { + return "", infraerrors.InternalServer("ADMIN_API_KEY_REPOSITORY_UNSUPPORTED", "旧版管理员密钥存储不支持原子轮换") + } + exists, err := repo.ReplaceExistingAdminAPIKey(ctx, key) + if err != nil { return "", fmt.Errorf("save admin api key: %w", err) } + if !exists { + return "", infraerrors.Forbidden("ADMIN_API_KEY_NOT_FOUND", "旧版密钥已停止新建,请创建权限管理密钥") + } return key, nil } diff --git a/backend/internal/service/setting_service.go b/backend/internal/service/setting_service.go index 7aea7c8ae9..c8c0ad1e9d 100644 --- a/backend/internal/service/setting_service.go +++ b/backend/internal/service/setting_service.go @@ -117,6 +117,7 @@ type WebSearchManagerBuilder func(cfg *WebSearchEmulationConfig, proxyURLs map[i // SettingService 系统设置服务 type SettingService struct { + scopedAdminKeyRepo ScopedAdminKeyRepository settingRepo SettingRepository defaultSubGroupReader DefaultSubscriptionGroupReader proxyRepo ProxyRepository // for resolving websearch provider proxy URLs diff --git a/backend/internal/service/wire.go b/backend/internal/service/wire.go index 688d729b31..472046b047 100644 --- a/backend/internal/service/wire.go +++ b/backend/internal/service/wire.go @@ -792,8 +792,9 @@ func ProvideOpsIngressRejectAggregator(opsRepo OpsRepository, opsService *OpsSer } // ProvideSettingService wires SettingService with group reader and proxy repo. -func ProvideSettingService(settingRepo SettingRepository, groupRepo GroupRepository, proxyRepo ProxyRepository, cfg *config.Config) *SettingService { +func ProvideSettingService(scopedKeys ScopedAdminKeyRepository, settingRepo SettingRepository, groupRepo GroupRepository, proxyRepo ProxyRepository, cfg *config.Config) *SettingService { svc := NewSettingService(settingRepo, cfg) + svc.scopedAdminKeyRepo = scopedKeys svc.SetDefaultSubscriptionGroupReader(groupRepo) svc.SetProxyRepository(proxyRepo) if err := svc.LoadForwardedClientIPSettings(context.Background()); err != nil { diff --git a/backend/migrations/247_scoped_admin_api_keys.sql b/backend/migrations/247_scoped_admin_api_keys.sql new file mode 100644 index 0000000000..2a9e2dca83 --- /dev/null +++ b/backend/migrations/247_scoped_admin_api_keys.sql @@ -0,0 +1,22 @@ +-- 管理密钥独立存储,仅保存不可逆摘要,保留撤销记录用于审计。 +CREATE TABLE IF NOT EXISTS scoped_admin_api_keys ( + id VARCHAR(24) PRIMARY KEY, + name VARCHAR(100) NOT NULL, + description TEXT NOT NULL DEFAULT '', + key_prefix VARCHAR(64) NOT NULL, + key_hash VARCHAR(64) NOT NULL, + enabled BOOLEAN NOT NULL DEFAULT TRUE, + expires_at TIMESTAMPTZ, + allowed_ips JSONB NOT NULL DEFAULT '[]', + policy JSONB NOT NULL DEFAULT '{}', + created_by BIGINT NOT NULL REFERENCES users(id), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + last_used_at TIMESTAMPTZ, + last_used_ip VARCHAR(64) NOT NULL DEFAULT '', + revoked_at TIMESTAMPTZ +); + +-- 仅将已撤销管理密钥从列表移除,保留原记录与历史审计。 +ALTER TABLE scoped_admin_api_keys + ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ; diff --git a/docs/admin-api-keys.md b/docs/admin-api-keys.md new file mode 100644 index 0000000000..c24627f9b6 --- /dev/null +++ b/docs/admin-api-keys.md @@ -0,0 +1,145 @@ +# 受限管理员 API 密钥 + +受限管理员密钥用于自动化管理指定资源。它与调用模型使用的用户 API Key 不同,也不等同于管理员登录会话。通过请求头 `x-api-key` 使用;只有权限目录明确登记的接口和操作才会开放,新增接口不会自动继承权限。 + +## 创建与配置 + +管理员登录后,在「系统设置 → 安全」的管理员访问密钥区域创建密钥。权限目录和分组加载成功后才能创建。 + +1. 填写名称、备注、到期时间及允许的 IP/CIDR。到期时间使用本地时间,留空表示永不过期;IP 列表留空表示不限制来源 IP。 +2. 添加资源规则,分别选择操作、分组、账户类型和平台。新建规则不勾选任何操作或账户类型,全站权限也全部关闭。 +3. 按需独立勾选全站权限,保存后立即复制完整密钥。完整密钥仅在创建或轮换的当前响应中出现,关闭展示后不能从列表重新读取。 + +创建、更新、停用/启用、轮换、撤销和删除记录均沿用系统二次验证流程;是否弹出验证由系统的 step-up 配置和当前授权状态决定。密钥生命周期接口只接受管理员 JWT 会话,受限密钥不能管理自身或创建其他管理员密钥。 + +已有旧版全权密钥时,页面显示兼容折叠区,可轮换或删除。页面不再提供新建旧版全权密钥的入口;应将自动化任务迁移到受限密钥。 + +## 账户规则如何匹配 + +对于同一项账户操作,一条规则内部必须同时满足以下条件(AND): + +- 该操作出现在 `permissions` 中。 +- 账户类型出现在 `account_types` 中。空列表表示没有账户操作权限,而非所有类型。 +- `platforms` 为空,或者账户平台命中其中一项。 +- 已分组账户至少命中一个所选分组,或规则启用了 `all_groups`;未分组账户必须显式启用 `include_ungrouped`。 + +多条规则之间是 OR:任一完整规则允许该项操作即可。不能将一条规则中的账户类型、另一条规则中的分组或平台拼起来授权。不同操作会分别检查其所需权限;写入凭证、修改网络、状态、调度、模型和分组关联不是「编辑名称与备注」的附带能力。 + +`all_groups` 包含未来新增的分组,但不自动包含未分组账户。新建账户的每个目标分组、以及调整关联时新增或移除的目标分组,还必须通过对应操作的分组检查。 + +**共享账户仍是一个账户资源。** 账户关联多个分组时,命中其中一个授权分组可能允许对该账户执行已授权操作。改凭证、改状态、刷新或删除会影响所有使用该账户的分组。界面会明确提示这一点;请按共享影响授予操作。受限账户响应只返回允许读取的分组关联,不代表该账户没有其他关联。 + +## 分组模型是实际准入限制 + +`groups.models.read` 和 `groups.models.write` 是资源规则中的独立权限。它们按同一规则的分组与平台检查,账户类型不限制整个分组的配置,也不要求同时授予账户操作或全站权限。 + +此处修改的是上游 `model_allowlist`,会影响整个分组可调用的模型,不能当作只改变前端展示的列表。写接口只允许单独提交 `model_allowlist`,不能借此修改费率等其他分组设置。只授予分组模型读取时,响应仅提供分组 ID、名称、平台和模型白名单;授予全站 `groups.read` 后才可读取完整分组配置。 + +读取指定分组的候选模型须有该分组的读取授权,或者全站 `groups.read`。读取默认模型候选(分组 ID 为 `0`)须独立授予 `models.defaults.read`。 + +## 全站权限和响应边界 + +`global_permissions` 与资源规则独立,不受所选分组或账户类型约束。例如 `users.read`、`dashboard.read`、`payment.read` 可读取全站相应数据。选择某个分组不会将这些权限限制为该分组;反过来,选择分组也不会隐式获得这些权限。 + +权限目录按接口与 HTTP 方法精确登记。当前不提供 `payment.mark_paid` 或退款预览权限;不要把退款、取消订单、重新履约等其他权限当作这些动作的替代。 + +受限响应按用途收窄: + +- 账户读取返回基本管理信息和模型映射,不返回 OAuth token、API 密钥、任意 `extra` 或完整凭证。`accounts.credentials` 是写入权限,不提供读取凭证的能力。 +- 代理候选包含 ID、名称、协议、主机、端口、状态与到期时间,不包含代理认证用户名或密码。 +- 用户资料采用字段白名单;联系方式需要 `users.read`,余额字段需要 `users.balance.read`,分组配置字段需要 `groups.read`。用户响应不嵌入订阅和用量关联数据,这些能力由各自接口及权限控制。 +- 订阅响应不嵌入用户、分配管理员或完整分组;仅有订阅或平台额度写权限时,成功响应只确认资源 ID,不附带独立读取权限的数据。 +- 用量记录仅返回请求自身的用量、计费快照及关联 ID,不嵌入用户 API Key、账户凭证或用户财务资料。优惠码使用记录及公告阅读记录也只返回记录字段与用户 ID。 +- 请求错误详情等敏感运维数据有单独权限。全站读取权限仍可能包含业务敏感数据,应只授予任务确实需要的项。 + +## 密钥存储、轮换与撤销 + +完整密钥由随机字节生成,数据库保存 SHA-256 摘要及用于展示和定位的前缀,不保存可供重显的完整密钥。客户端应把密钥放入密钥管理器或运行环境的秘密变量中。 + +停用可再次启用;到期或不符合允许 IP 的密钥不能认证。轮换立即使旧密钥失效并返回一次性新密钥。永久撤销不可恢复。只有已撤销密钥才可以删除列表记录;删除只移除管理列表展示,历史操作记录继续保留。 + +编辑时若没有修改到期时间,前端会保留服务端原始值,避免将秒数、微秒或时区信息截断。 + +## 代理查询与自动选择 + +`proxies.read` 是全站权限,与账户的 `accounts.network` 分开。前者用于获取安全候选信息,后者控制为授权账户设置接入地址、代理与连接选项。 + +- `GET /api/v1/admin/proxies` 使用 `page`、`page_size` 和 `search`,默认每页 50,最多 100。 +- `GET /api/v1/admin/proxies/all` 为兼容客户端返回数组;显式传入分页参数时按分页查询,分页信息在 `X-Total-Count`、`X-Page`、`X-Page-Size` 和 `X-Total-Pages` 响应头中。 +- `/proxies/all` 未传分页参数时,从全池重新随机抽样最多 50 个候选,不排除已被账户使用的代理;响应设置 `Cache-Control: no-store`。 +- `ids` 可回显已选代理,一次最多 100 个不同 ID,按请求顺序返回实际存在的记录。 + +受限账户写入与 Codex 导入支持 `proxy_mode`:`direct`(直连)、`specified`(正数 `proxy_id`)、`random`(随机)、`least_used`(最少使用)。自动选择由服务端在账户写事务内从启用且未过期的代理中完成,无可用代理则失败。自动模式不能同时指定正数 `proxy_id`;旧字段 `random_proxy: true` 兼容随机模式,不能与其他模式冲突。随机候选查询与写入时自动选择是两个独立行为。 + +## Codex 会话导入 + +受限密钥可使用 `POST /api/v1/admin/accounts/import/codex-session`,但不会回退到全权管理员导入流程。 + +- 必须明确提供 `group_ids`;新账户固定为 `openai` 平台、`oauth` 类型,目标分组逐一检查。 +- 新建需要 `accounts.create`、`accounts.credentials` 和 `accounts.schedule`。更新匹配账户会重新检查当前资源和对应写权限;调整关联还需要 `accounts.groups`。 +- `base_url`、代理、指纹或 WebSocket 连接配置需要 `accounts.network`;`model_mapping` 需要 `accounts.models.write`。 +- `credential_extras` 只接受独立授权的 `base_url`、`model_mapping`;`extra` 只开放已登记的 Codex 指纹及 WebSocket 选项,不支持任意字段透传或跳过混合渠道风险检查。 +- 导入只按当前条目的身份查询受限候选,响应不返回候选凭证。更新已有账户时仍会在写入阶段重验身份与权限。 + +## API 示例 + +以下域名、密钥、JWT、ID 和会话内容均为占位符。通用成功响应使用系统现有响应封装。 + +管理员会话创建受限密钥(如系统要求 step-up,应先完成当前二次验证流程): + +```bash +curl 'https://example.invalid/api/v1/admin/settings/admin-api-keys' \ + -H 'Authorization: Bearer ' \ + -H 'Content-Type: application/json' \ + --data '{ + "name": "只读 OAuth 工具", + "description": "读取指定分组的 OpenAI OAuth 账户", + "enabled": true, + "expires_at": null, + "allowed_ips": ["192.0.2.10/32"], + "policy": { + "rules": [{ + "permissions": ["accounts.read"], + "group_ids": [123], + "all_groups": false, + "include_ungrouped": false, + "account_types": ["oauth"], + "platforms": ["openai"] + }], + "global_permissions": [] + } + }' +``` + +使用受限密钥读取账户: + +```bash +curl 'https://example.invalid/api/v1/admin/accounts?page=1&page_size=20' \ + -H 'x-api-key: ' +``` + +已授予所选分组的 `groups.models.write` 后,单独更新其模型白名单: + +```bash +curl -X PUT 'https://example.invalid/api/v1/admin/groups/123' \ + -H 'x-api-key: ' \ + -H 'Content-Type: application/json' \ + --data '{"model_allowlist":{"enabled":true,"models":[""]}}' +``` + +具备上述导入所需权限后,新建 Codex OAuth 账户并由服务端随机选择代理: + +```bash +curl 'https://example.invalid/api/v1/admin/accounts/import/codex-session' \ + -H 'x-api-key: ' \ + -H 'Content-Type: application/json' \ + --data '{ + "content": "", + "name": "导入账户", + "group_ids": [123], + "update_existing": false, + "proxy_mode": "random" + }' +``` + +生命周期接口位于 `/api/v1/admin/settings/admin-api-keys`:`GET` 列表及目录、`POST` 创建、`PUT /` 更新、`POST //rotate` 轮换、`DELETE /` 永久撤销、`DELETE //record` 删除已撤销记录。更新请求包含完整配置与策略;不要将未提交字段当作保持原值的 PATCH 语义。 diff --git a/frontend/src/api/admin/adminAccessKeys.ts b/frontend/src/api/admin/adminAccessKeys.ts new file mode 100644 index 0000000000..3580a5f30f --- /dev/null +++ b/frontend/src/api/admin/adminAccessKeys.ts @@ -0,0 +1,37 @@ +import { apiClient } from '../client' + +export interface AccessRule { + permissions: string[] + group_ids: number[] + all_groups: boolean + include_ungrouped: boolean + account_types: string[] + platforms: string[] +} +export interface AccessPolicy { rules: AccessRule[]; global_permissions: string[] } +export interface Permission { id: string; label: string; category: string; scope: 'account' | 'group' | 'global' } +export interface AdminKeyInput { + name: string + description: string + enabled: boolean + expires_at: string | null + allowed_ips: string[] + policy: AccessPolicy +} +export interface AdminKey extends AdminKeyInput { + id: string + key_prefix: string + created_by: number + created_at: string + updated_at: string + last_used_at: string | null + last_used_ip: string + revoked_at: string | null +} +const base = '/admin/settings/admin-api-keys' +export async function list() { return (await apiClient.get<{ items: AdminKey[]; permissions: Permission[] }>(base)).data } +export async function create(input: AdminKeyInput) { return (await apiClient.post<{ key: string; item: AdminKey }>(base, input)).data } +export async function update(id: string, input: AdminKeyInput) { return (await apiClient.put(`${base}/${encodeURIComponent(id)}`, input)).data } +export async function rotate(id: string) { return (await apiClient.post<{ key: string; item: AdminKey }>(`${base}/${encodeURIComponent(id)}/rotate`)).data } +export async function revoke(id: string) { return (await apiClient.delete<{ message: string }>(`${base}/${encodeURIComponent(id)}`)).data } +export async function deleteRecord(id: string) { return (await apiClient.delete<{ message: string }>(`${base}/${encodeURIComponent(id)}/record`)).data } diff --git a/frontend/src/components/admin/settings/AdminAccessKeysSettings.vue b/frontend/src/components/admin/settings/AdminAccessKeysSettings.vue new file mode 100644 index 0000000000..bc256fc479 --- /dev/null +++ b/frontend/src/components/admin/settings/AdminAccessKeysSettings.vue @@ -0,0 +1,193 @@ +