From d4983840186290b356cfdba090228084fa2d616c Mon Sep 17 00:00:00 2001 From: akihitohyh <79531840+akihitohyh@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:43:46 +0800 Subject: [PATCH] =?UTF-8?q?feat(usage):=20=E6=96=B0=E5=A2=9E=20API=20Key?= =?UTF-8?q?=20=E9=80=90=E6=9D=A1=E7=94=A8=E9=87=8F=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E4=B8=8E=E3=80=8C=E7=94=A8=E9=87=8F=20API?= =?UTF-8?q?=E3=80=8D=E9=A1=B5=E7=AD=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增 GET /v1/usage/records:用调用方 API Key 认证,按秒级时间段 (RFC3339 带时区或 Unix 秒,半开区间,最长 7 天)+ 签名 keyset 游标 分页拉取这把 Key 自己的逐条用量记录,支持 JSON 和与面板导出一致的 CSV。 - 只返回当前 Key 的记录,字段按用户面板可见性白名单输出 - 与 /v1/usage 一样不计费,余额不足/Key 过期/额度耗尽仍可查账 - 普通鉴权通过后再做一次不走缓存的权威复核,并在分组准入之前替换 上下文,Key 删除/停用/解绑分组后立即生效;未知 Key 不增加查询 - 区域鉴权快照节点直接拒绝该接口,避免用过期快照出明细 - 限流:每 Key 每分钟 60 次 + 每用户合计 120 次,Lua 原子双桶, 本地 429 标记为客户端业务限制,不计入上游故障 - 查询只走 idx_usage_logs_api_key_created_at,LIMIT limit+1,5 秒预算 - 用户「使用记录」页新增第 4 个页签「用量 API」:参数、curl/JSON/CSV/ Python 示例(水位续拉、重叠补拉、按 id 去重、拒绝重定向)与对账说明, 登记新功能提示;切换页签时中止在途请求,避免页码与数据错位 - issue805 历史基线检查排除本次新增的测试文件 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/issue805-owner-policy.yml | 2 +- .gitignore | 1 + Makefile | 1 + backend/cmd/server/wire_gen.go | 4 +- backend/internal/handler/handler.go | 1 + backend/internal/handler/usage_records.go | 181 ++++++++ backend/internal/handler/usage_records_csv.go | 161 +++++++ .../internal/handler/usage_records_cursor.go | 139 ++++++ .../internal/handler/usage_records_test.go | 415 ++++++++++++++++++ backend/internal/handler/wire.go | 5 + backend/internal/middleware/rate_limiter.go | 110 +++++ backend/internal/repository/usage_records.go | 51 +++ .../usage_records_integration_test.go | 76 ++++ .../server/middleware/api_key_auth.go | 134 +++--- .../server/middleware/api_key_groups.go | 9 +- backend/internal/server/middleware/cors.go | 10 +- .../middleware/regional_api_key_auth.go | 4 + .../middleware/regional_api_key_auth_test.go | 24 + .../server/middleware/usage_records_test.go | 86 ++++ backend/internal/server/routes/gateway.go | 3 +- .../server/routes/usage_records_test.go | 282 ++++++++++++ backend/internal/service/setting_public.go | 8 + backend/internal/service/usage_records.go | 26 ++ docs/api-key-usage-date-range.md | 2 + docs/usage-records-api.md | 99 +++++ frontend/src/api/usage.ts | 4 +- .../common/__tests__/NewFeatureBadge.spec.ts | 1 + .../src/components/usage/UsageApiGuide.vue | 91 ++++ .../usage/__tests__/UsageApiGuide.spec.ts | 44 ++ .../src/components/usage/usage_records.py | 87 ++++ frontend/src/constants/newFeatureNotices.ts | 1 + frontend/src/i18n/locales/en/index.ts | 2 + frontend/src/i18n/locales/en/usageApi.ts | 28 ++ frontend/src/i18n/locales/zh/index.ts | 2 + frontend/src/i18n/locales/zh/usageApi.ts | 28 ++ .../src/utils/__tests__/billingMode.spec.ts | 13 + frontend/src/views/user/UsageView.vue | 117 ++++- .../views/user/__tests__/UsageView.spec.ts | 311 ++++++++++++- 38 files changed, 2467 insertions(+), 96 deletions(-) create mode 100644 backend/internal/handler/usage_records.go create mode 100644 backend/internal/handler/usage_records_csv.go create mode 100644 backend/internal/handler/usage_records_cursor.go create mode 100644 backend/internal/handler/usage_records_test.go create mode 100644 backend/internal/repository/usage_records.go create mode 100644 backend/internal/repository/usage_records_integration_test.go create mode 100644 backend/internal/server/middleware/usage_records_test.go create mode 100644 backend/internal/server/routes/usage_records_test.go create mode 100644 backend/internal/service/usage_records.go create mode 100644 docs/usage-records-api.md create mode 100644 frontend/src/components/usage/UsageApiGuide.vue create mode 100644 frontend/src/components/usage/__tests__/UsageApiGuide.spec.ts create mode 100644 frontend/src/components/usage/usage_records.py create mode 100644 frontend/src/i18n/locales/en/usageApi.ts create mode 100644 frontend/src/i18n/locales/zh/usageApi.ts diff --git a/.github/workflows/issue805-owner-policy.yml b/.github/workflows/issue805-owner-policy.yml index 95d79a2ceba5..b186f2e0304d 100644 --- a/.github/workflows/issue805-owner-policy.yml +++ b/.github/workflows/issue805-owner-policy.yml @@ -91,7 +91,7 @@ jobs: # baseline. The readable/task-rebuild fixtures import its settings and # usage helpers. Exclude this exact dependency set only in the old # Issue805 RED; GREEN and each feature's own TDD job retain them. - for omission_test in backend/internal/handler/openai_409_omit_history_test.go backend/internal/handler/openai_409_readable_continuation_test.go backend/internal/handler/openai_409_http_rebuild_test.go backend/internal/handler/openai_409_shadow_http_test.go backend/internal/handler/openai_409_shadow_race_test.go backend/internal/handler/openai_409_ws_rebuild_test.go backend/internal/handler/openai_409_ws_oracle_test.go backend/internal/handler/openai_400_omit_history_test.go backend/internal/handler/openai_issue854_continuation_test.go backend/internal/handler/openai_issue854_upstream_test.go backend/internal/handler/openai_issue854_postgres_test.go; do + for omission_test in backend/internal/handler/openai_409_omit_history_test.go backend/internal/handler/openai_409_readable_continuation_test.go backend/internal/handler/openai_409_http_rebuild_test.go backend/internal/handler/openai_409_shadow_http_test.go backend/internal/handler/openai_409_shadow_race_test.go backend/internal/handler/openai_409_ws_rebuild_test.go backend/internal/handler/openai_409_ws_oracle_test.go backend/internal/handler/openai_400_omit_history_test.go backend/internal/handler/openai_issue854_continuation_test.go backend/internal/handler/openai_issue854_upstream_test.go backend/internal/handler/openai_issue854_postgres_test.go backend/internal/handler/usage_records_test.go; do git cat-file -e "$EXPECTED_HEAD_SHA:$omission_test" rm -- "$omission_test" test ! -e "$omission_test" diff --git a/.gitignore b/.gitignore index 3b55acfcc73b..3c5c204a4266 100644 --- a/.gitignore +++ b/.gitignore @@ -145,6 +145,7 @@ docs/* !docs/stream-timing.md !docs/openai-sse-delivery.md !docs/user-traffic.md +!docs/usage-records-api.md !docs/typesafe-content-audit.md !docs/multi-host-session-owner.md !docs/security-penalties.md diff --git a/Makefile b/Makefile index 272c45c77a70..1832f65f83dc 100644 --- a/Makefile +++ b/Makefile @@ -104,6 +104,7 @@ FRONTEND_CRITICAL_VITEST := \ src/components/common/__tests__/DateRangePicker.midnight.spec.ts \ src/components/admin/usage/__tests__/UsageStatsCards.spec.ts \ src/components/admin/usage/__tests__/UsageCleanupDialog.spec.ts \ + src/components/usage/__tests__/UsageApiGuide.spec.ts \ src/views/user/__tests__/UsageView.spec.ts \ src/components/usage/__tests__/TrafficPanel.spec.ts \ src/api/__tests__/traffic.spec.ts \ diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 1dc51296aaac..c7fa42b5f137 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -12,6 +12,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/handler" "github.com/Wei-Shaw/sub2api/internal/handler/admin" + ratelimit "github.com/Wei-Shaw/sub2api/internal/middleware" "github.com/Wei-Shaw/sub2api/internal/payment" "github.com/Wei-Shaw/sub2api/internal/qqbot" "github.com/Wei-Shaw/sub2api/internal/repository" @@ -250,6 +251,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { authCacheInvalidationWorker := service.ProvideAuthCacheInvalidationWorker(authCacheInvalidationOutboxRepository, apiKeyCache, apiKeyService) opsService := service.ProvideOpsService(accountOpsService, opsRepository, settingRepository, configConfig, accountRepository, userRepository, concurrencyService, gatewayService, openAIGatewayService, geminiMessagesCompatService, antigravityGatewayService, opsSystemLogSink, settingService, authCacheInvalidationWorker, apiKeyService) usageHandler := handler.NewUsageHandler(usageService, apiKeyService, opsService, settingService) + usageRecordsHandler := handler.NewUsageRecordsHandler(usageHandler, ratelimit.NewRateLimiter(redisClient), configConfig) redeemHandler := handler.NewRedeemHandler(redeemService) subscriptionHandler := handler.NewSubscriptionHandler(subscriptionService) announcementRepository := repository.NewAnnouncementRepository(client) @@ -429,7 +431,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { idempotencyCoordinator := service.ProvideIdempotencyCoordinator(idempotencyRepository, configConfig) idempotencyCleanupService := service.ProvideIdempotencyCleanupService(idempotencyRepository, configConfig) openAIQuotaAutoResetService := service.ProvideOpenAIQuotaAutoResetService(accountRepository, openAIQuotaService, rateLimitService, idempotencyCoordinator, auditLogService, settingService, leaderLockCache, configConfig) - handlers := handler.ProvideHandlers(qqBotHandler, lotteryHandler, authHandler, userHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, announcementHandler, channelMonitorUserHandler, channelMonitorV2Handler, channelMonitorV3Handler, adminHandlers, gatewayHandler, openAIGatewayHandler, handlerSettingHandler, totpHandler, passkeyHandler, handlerPaymentHandler, paymentWebhookHandler, availableChannelHandler, pelicanShowcaseHandler, supportTicketHandler, modelPlazaHandler, asyncImageHandler, batchImageHandler, idempotencyCoordinator, idempotencyCleanupService, openAIQuotaAutoResetService) + handlers := handler.ProvideHandlers(qqBotHandler, lotteryHandler, authHandler, userHandler, apiKeyHandler, usageHandler, usageRecordsHandler, redeemHandler, subscriptionHandler, announcementHandler, channelMonitorUserHandler, channelMonitorV2Handler, channelMonitorV3Handler, adminHandlers, gatewayHandler, openAIGatewayHandler, handlerSettingHandler, totpHandler, passkeyHandler, handlerPaymentHandler, paymentWebhookHandler, availableChannelHandler, pelicanShowcaseHandler, supportTicketHandler, modelPlazaHandler, asyncImageHandler, batchImageHandler, idempotencyCoordinator, idempotencyCleanupService, openAIQuotaAutoResetService) jwtAuthMiddleware := middleware.NewJWTAuthMiddleware(authService, userService, settingService, auditLogService) optionalJWTAuthMiddleware := middleware.NewOptionalJWTAuthMiddleware(authService, userService, settingService, auditLogService) adminAuthMiddleware := middleware.NewAdminAuthMiddleware(authService, userService, settingService, auditLogService) diff --git a/backend/internal/handler/handler.go b/backend/internal/handler/handler.go index a7a85f8f5dee..bd46130b8796 100644 --- a/backend/internal/handler/handler.go +++ b/backend/internal/handler/handler.go @@ -60,6 +60,7 @@ type Handlers struct { User *UserHandler APIKey *APIKeyHandler Usage *UsageHandler + UsageRecords *UsageRecordsHandler Redeem *RedeemHandler Subscription *SubscriptionHandler Announcement *AnnouncementHandler diff --git a/backend/internal/handler/usage_records.go b/backend/internal/handler/usage_records.go new file mode 100644 index 000000000000..ea6c74315dbd --- /dev/null +++ b/backend/internal/handler/usage_records.go @@ -0,0 +1,181 @@ +package handler + +import ( + "context" + "log/slog" + "math" + "net/http" + "net/url" + "strconv" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/handler/dto" + ratelimit "github.com/Wei-Shaw/sub2api/internal/middleware" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" +) + +type UsageRecordsHandler struct { + usage *UsageHandler + limiter *ratelimit.RateLimiter + cursorSecret []byte +} + +func NewUsageRecordsHandler(usage *UsageHandler, limiter *ratelimit.RateLimiter, cfg *config.Config) *UsageRecordsHandler { + return &UsageRecordsHandler{usage: usage, limiter: limiter, cursorSecret: []byte(cfg.JWT.Secret)} +} + +// Only fields explicitly selected from the end-user DTO leave this endpoint. +type usageRecord struct { + ID int64 `json:"id"` + RequestID string `json:"request_id"` + CreatedAt time.Time `json:"created_at"` + Model string `json:"model"` + UpstreamResponseModel *string `json:"upstream_response_model,omitempty"` + ReasoningEffort *string `json:"reasoning_effort,omitempty"` + InboundEndpoint *string `json:"inbound_endpoint,omitempty"` + IPAddress *string `json:"ip_address,omitempty"` + RequestType string `json:"request_type"` + Stream bool `json:"stream"` + BillingMode *string `json:"billing_mode,omitempty"` + InputTokens int `json:"input_tokens"` + OutputTokens int `json:"output_tokens"` + CacheReadTokens int `json:"cache_read_tokens"` + CacheCreationTokens int `json:"cache_creation_tokens"` + ImageCount int `json:"image_count"` + TotalCost float64 `json:"total_cost"` + ActualCost float64 `json:"actual_cost"` + RateMultiplier float64 `json:"rate_multiplier"` + DurationMs *int `json:"duration_ms"` + FirstTokenMs *int `json:"first_token_ms"` +} + +func newUsageRecord(l *dto.UsageLog) usageRecord { + return usageRecord{ + ID: l.ID, RequestID: l.RequestID, CreatedAt: l.CreatedAt.UTC(), + Model: l.Model, UpstreamResponseModel: l.UpstreamResponseModel, ReasoningEffort: l.ReasoningEffort, + InboundEndpoint: l.InboundEndpoint, IPAddress: l.IPAddress, RequestType: l.RequestType, Stream: l.Stream, + BillingMode: l.BillingMode, InputTokens: l.InputTokens, OutputTokens: l.OutputTokens, + CacheReadTokens: l.CacheReadTokens, CacheCreationTokens: l.CacheCreationTokens, ImageCount: l.ImageCount, + TotalCost: l.TotalCost, ActualCost: l.ActualCost, RateMultiplier: l.RateMultiplier, + DurationMs: l.DurationMs, FirstTokenMs: l.FirstTokenMs, + } +} + +func usageRecordsError(c *gin.Context, status int, kind, message string) { + c.JSON(status, gin.H{"type": "error", "error": gin.H{"type": kind, "message": message}}) +} + +func (h *UsageRecordsHandler) List(c *gin.Context) { + key, keyOK := middleware.GetAPIKeyFromContext(c) + subject, userOK := middleware.GetAuthSubjectFromContext(c) + if !keyOK || key == nil || !userOK || subject.UserID <= 0 || key.ID <= 0 || key.UserID != subject.UserID { + usageRecordsError(c, http.StatusUnauthorized, "authentication_error", "Invalid API key") + return + } + c.Header("Cache-Control", "private, no-store") + if !h.allow(c, key.ID, subject.UserID) { + return + } + + values, err := url.ParseQuery(c.Request.URL.RawQuery) + if err != nil { + usageRecordsError(c, http.StatusBadRequest, "invalid_request_error", "Malformed query string") + return + } + q, err := parseUsageRecordsQuery(values, time.Now()) + if err != nil { + usageRecordsError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) + return + } + if values.Has("cursor") && !h.resumeCursor(&q, values.Get("cursor"), subject.UserID, key.ID) { + usageRecordsError(c, http.StatusBadRequest, "invalid_request_error", "Invalid cursor for this key, time range or format") + return + } + ctx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Second) + defer cancel() + showModel := false + showCacheRate := false + if h.usage.settingService != nil { + showModel = h.usage.settingService.IsUserUpstreamResponseModelVisible(ctx) + showCacheRate = h.usage.settingService.IsUserUsageCacheRateVisible(ctx) + } + if q.format == "csv" { + current := usageCSVColumns{Model: showModel, CacheRate: showCacheRate} + if q.columns == nil { + q.columns = ¤t + } else if (q.columns.Model && !current.Model) || (q.columns.CacheRate && !current.CacheRate) { + usageRecordsError(c, http.StatusConflict, "invalid_request_error", "CSV column visibility changed. Restart from the first page without a cursor.") + return + } + showModel = q.columns.Model + } + var logs []service.UsageLog + if q.start.Before(q.end) { + logs, err = h.usage.usageService.ListUsageRecords(ctx, subject.UserID, key.ID, q.start, q.end, q.after, q.limit) + if err != nil { + slog.WarnContext(ctx, "list usage records failed", "error", err) + usageRecordsError(c, http.StatusServiceUnavailable, "api_error", "Usage records temporarily unavailable") + return + } + } + hasMore := len(logs) > q.limit + if hasMore { + logs = logs[:q.limit] + } + data := make([]usageRecord, 0, len(logs)) + for i := range logs { + data = append(data, newUsageRecord(h.usage.userUsageLogDTO(c, &logs[i], showModel))) + } + var next *string + if hasMore { + token, err := h.nextCursor(q, data[len(data)-1], subject.UserID, key.ID) + if err != nil { + usageRecordsError(c, http.StatusInternalServerError, "api_error", "Failed to encode usage cursor") + return + } + next = &token + } + if q.format == "csv" { + c.Header("X-Has-More", strconv.FormatBool(hasMore)) + if next != nil { + c.Header("X-Next-Cursor", *next) + } + c.Header("Content-Disposition", `attachment; filename="usage-records.csv"`) + c.Data(http.StatusOK, "text/csv; charset=utf-8", usageRecordsCSV(data, key.Name, showModel, q.columns.CacheRate, c.GetHeader("Accept-Language"))) + return + } + c.JSON(http.StatusOK, gin.H{"object": "list", "data": data, "has_more": hasMore, "next_cursor": next, "start_time": q.start, "end_time": q.end}) +} + +func (h *UsageRecordsHandler) allow(c *gin.Context, keyID, userID int64) bool { + ctx := c.Request.Context() + bucket := "usage-records:{u:" + strconv.FormatInt(userID, 10) + "}:" + budget, err := h.limiter.AllowTogether(ctx, + bucket+"key:"+strconv.FormatInt(keyID, 10), 60, + bucket+"user", 120, + time.Minute, + ) + if err != nil { + slog.WarnContext(ctx, "usage records rate limiter unavailable", "error", err) + usageRecordsError(c, http.StatusServiceUnavailable, "api_error", "Usage records temporarily unavailable") + return false + } + if !budget.Allowed { + service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalPolicyDenied) + retryAfter := int(math.Ceil(budget.RetryAfter.Seconds())) + if retryAfter < 1 { + retryAfter = 1 + } + c.Header("Retry-After", strconv.Itoa(retryAfter)) + if budget.BlockedScope == "user" { + usageRecordsError(c, http.StatusTooManyRequests, "rate_limit_error", "Usage records limited to 120 requests per minute per user across all API keys") + } else { + usageRecordsError(c, http.StatusTooManyRequests, "rate_limit_error", "Usage records limited to 60 requests per minute per API key") + } + return false + } + return true +} diff --git a/backend/internal/handler/usage_records_csv.go b/backend/internal/handler/usage_records_csv.go new file mode 100644 index 000000000000..ff53cdde55f6 --- /dev/null +++ b/backend/internal/handler/usage_records_csv.go @@ -0,0 +1,161 @@ +package handler + +import ( + "bytes" + "encoding/csv" + "math" + "math/big" + "strconv" + "strings" + "time" + "unicode" + "unicode/utf8" + + "golang.org/x/text/language" +) + +var usageCSVLanguages = language.NewMatcher([]language.Tag{language.English, language.Chinese}) + +func usageCSVString(value *string) string { + if value == nil { + return "" + } + return *value +} + +func usageCSVLatency(value *int) string { + if value == nil { + return "" + } + return strconv.Itoa(*value) +} + +func usageCSVEffort(value *string) string { + raw := strings.TrimSpace(usageCSVString(value)) + normalized := strings.Map(func(r rune) rune { + if r == '-' || r == '_' || unicode.IsSpace(r) { + return -1 + } + return unicode.ToLower(r) + }, raw) + switch normalized { + case "", "none", "minimal": + return "-" + case "low", "medium", "high", "max": + return strings.ToUpper(normalized[:1]) + normalized[1:] + case "extrahigh", "xhigh": + return "XHigh" + default: + r, size := utf8.DecodeRuneInString(raw) + return string(unicode.ToUpper(r)) + raw[size:] + } +} + +func usageCSVCacheRate(row usageRecord) string { + total := float64(row.InputTokens) + float64(row.CacheReadTokens) + float64(row.CacheCreationTokens) + if total <= 0 || row.InputTokens < 0 || row.CacheReadTokens < 0 || row.CacheCreationTokens < 0 { + return "" + } + if row.CacheReadTokens == 0 { + return "0%" + } + tenths := math.Round(float64(row.CacheReadTokens) / total * 1000) + switch tenths { + case 0: + return "<0.1%" + case 1000: + return "100%" + default: + return strconv.FormatFloat(tenths/10, 'f', 1, 64) + "%" + } +} + +func usageCSVBillingMode(row usageRecord, zh bool) string { + mode := usageCSVString(row.BillingMode) + if mode == "" && row.ImageCount > 0 { + mode = "image" + } + switch mode { + case "per_request": + if zh { + return "按次" + } + return "Per Request" + case "image": + if zh { + return "按次(图片)" + } + return "Image" + case "video": + if zh { + return "按次(视频)" + } + return "Video" + default: + if zh { + return "按量" + } + return "Token" + } +} + +// JavaScript toFixed rounds the exact binary value, with ties away from zero. +func usageCSVCost(value float64) string { + switch { + case math.IsInf(value, 1): + return "Infinity" + case math.IsInf(value, -1): + return "-Infinity" + case math.IsNaN(value), math.Abs(value) >= 1e21: + return strconv.FormatFloat(value, 'g', -1, 64) + } + return new(big.Rat).SetFloat64(value).FloatString(8) +} + +// Keep column order, optional columns, eight decimal places, BOM and spreadsheet +// formula protection in sync with exportToCSV in the user's UsageView. +func usageRecordsCSV(data []usageRecord, keyName string, showModel, showCacheRate bool, acceptLanguage string) []byte { + var buf bytes.Buffer + _, _ = buf.WriteString("\uFEFF") + w := csv.NewWriter(&buf) + header := []string{"Time", "API Key Name", "Model"} + if showModel { + header = append(header, "Upstream Response Model") + } + header = append(header, "Reasoning Effort", "Inbound Endpoint", "IP Address", "Type", "Billing Mode", + "Input Tokens", "Output Tokens", "Cache Read Tokens", "Cache Creation Tokens") + if showCacheRate { + header = append(header, "Cache Rate") + } + header = append(header, "Rate Multiplier", "Billed Cost", "Original Cost", "First Token (ms)", "Duration (ms)") + _ = w.Write(header) // bytes.Buffer writes cannot fail. + _, locale := language.MatchStrings(usageCSVLanguages, acceptLanguage) + types := map[string]string{"cyber": "Cyber", "live": "Live", "ws_v2": "WS", "stream": "Stream", "sync": "Sync"} + for _, row := range data { + cells := []string{row.CreatedAt.Format(time.RFC3339Nano), keyName, row.Model} + if showModel { + cells = append(cells, usageCSVString(row.UpstreamResponseModel)) + } + requestType := types[row.RequestType] + if requestType == "" { + requestType = "Unknown" + } + cells = append(cells, usageCSVEffort(row.ReasoningEffort), usageCSVString(row.InboundEndpoint), usageCSVString(row.IPAddress), + requestType, usageCSVBillingMode(row, locale == 1), strconv.Itoa(row.InputTokens), strconv.Itoa(row.OutputTokens), + strconv.Itoa(row.CacheReadTokens), strconv.Itoa(row.CacheCreationTokens)) + if showCacheRate { + cells = append(cells, usageCSVCacheRate(row)) + } + cells = append(cells, strconv.FormatFloat(row.RateMultiplier, 'f', -1, 64), + usageCSVCost(row.ActualCost), usageCSVCost(row.TotalCost), + usageCSVLatency(row.FirstTokenMs), usageCSVLatency(row.DurationMs)) + for i, cell := range cells { + if cell != "" && cell != "-" && strings.ContainsRune("=+-@\t\r", rune(cell[0])) { + cells[i] = "'" + cell + } + } + _ = w.Write(cells) + } + w.Flush() + return buf.Bytes() +} diff --git a/backend/internal/handler/usage_records_cursor.go b/backend/internal/handler/usage_records_cursor.go new file mode 100644 index 000000000000..d94ef0843fa3 --- /dev/null +++ b/backend/internal/handler/usage_records_cursor.go @@ -0,0 +1,139 @@ +package handler + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net/url" + "regexp" + "strconv" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" +) + +type usageRecordsQuery struct { + start, end, requestedEnd time.Time + after *service.UsageRecordPosition + limit int + format string + columns *usageCSVColumns +} + +type usageCSVColumns struct { + Model bool `json:"m"` + CacheRate bool `json:"c"` +} + +// time.Parse also accepts a one-digit hour, a decimal comma and +24:00. +var usageRFC3339 = regexp.MustCompile(`^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]{1,9})?(Z|[+-]([01][0-9]|2[0-3]):[0-5][0-9])$`) + +func usageRecordTime(value string) (time.Time, bool) { + var t time.Time + if seconds, err := strconv.ParseInt(value, 10, 64); err == nil { + t = time.Unix(seconds, 0).UTC() + } else { + if !usageRFC3339.MatchString(value) { + return time.Time{}, false + } + t, err = time.Parse(time.RFC3339Nano, value) + if err != nil { + return time.Time{}, false + } + t = t.UTC() + } + return t, t.Year() >= 1 && t.Year() <= 9999 +} + +func parseUsageRecordsQuery(values url.Values, now time.Time) (usageRecordsQuery, error) { + q := usageRecordsQuery{limit: 500, format: "json"} + var ok bool + if q.start, ok = usageRecordTime(values.Get("start_time")); !ok { + return q, errors.New("start_time requires Unix seconds or RFC3339 with a timezone and at most 9 fractional digits") + } + if q.requestedEnd, ok = usageRecordTime(values.Get("end_time")); !ok { + return q, errors.New("end_time requires Unix seconds or RFC3339 with a timezone and at most 9 fractional digits") + } + if !q.requestedEnd.After(q.start) { + return q, errors.New("end_time must be later than start_time") + } + q.end = q.requestedEnd + if q.end.After(now) { + q.end = now.UTC() + } + if q.start.After(q.end) { + q.start = q.end + } + // Continuations restore the signed first page's already validated window. + if !values.Has("cursor") && q.end.Sub(q.start) > 7*24*time.Hour { + return q, errors.New("the effective time range must not exceed 7 days") + } + if values.Has("limit") { + limit, err := strconv.Atoi(values.Get("limit")) + if err != nil || limit < 1 || limit > 1000 { + return q, errors.New("limit must be an integer from 1 to 1000") + } + q.limit = limit + } + if values.Has("format") { + q.format = values.Get("format") + if q.format != "json" && q.format != "csv" { + return q, errors.New("format must be json or csv") + } + } + return q, nil +} + +// The first page pins its effective end even if a future end_time was supplied. +// Both the original request and the returned canonical bounds can resume it. +type usageRecordsCursor struct { + Start time.Time `json:"s"` + End time.Time `json:"e"` + RequestedEnd time.Time `json:"r"` + CreatedAt time.Time `json:"t"` + ID int64 `json:"i"` + Columns *usageCSVColumns `json:"cols,omitempty"` +} + +func (h *UsageRecordsHandler) cursorMAC(payload []byte, userID, keyID int64) []byte { + mac := hmac.New(sha256.New, h.cursorSecret) + _, _ = fmt.Fprintf(mac, "usage-records/v1/%d/%d/", userID, keyID) + _, _ = mac.Write(payload) + return mac.Sum(nil) +} + +func (h *UsageRecordsHandler) nextCursor(q usageRecordsQuery, last usageRecord, userID, keyID int64) (string, error) { + payload, err := json.Marshal(usageRecordsCursor{Start: q.start, End: q.end, RequestedEnd: q.requestedEnd, CreatedAt: last.CreatedAt, ID: last.ID, Columns: q.columns}) + if err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(append(payload, h.cursorMAC(payload, userID, keyID)...)), nil +} + +func (h *UsageRecordsHandler) resumeCursor(q *usageRecordsQuery, token string, userID, keyID int64) bool { + if len(token) > 1024 { + return false + } + raw, err := base64.RawURLEncoding.Strict().DecodeString(token) + if err != nil || len(raw) <= sha256.Size { + return false + } + payload, sig := raw[:len(raw)-sha256.Size], raw[len(raw)-sha256.Size:] + if !hmac.Equal(sig, h.cursorMAC(payload, userID, keyID)) { + return false + } + var cursor usageRecordsCursor + if json.Unmarshal(payload, &cursor) != nil || !q.start.Equal(cursor.Start) || + (!q.requestedEnd.Equal(cursor.RequestedEnd) && !q.requestedEnd.Equal(cursor.End)) || + (q.format == "csv") != (cursor.Columns != nil) || + cursor.ID <= 0 || cursor.CreatedAt.Before(q.start) || !cursor.CreatedAt.Before(cursor.End) { + return false + } + q.end, q.requestedEnd = cursor.End, cursor.RequestedEnd + q.columns = cursor.Columns + q.after = &service.UsageRecordPosition{CreatedAt: cursor.CreatedAt, ID: cursor.ID} + return true +} diff --git a/backend/internal/handler/usage_records_test.go b/backend/internal/handler/usage_records_test.go new file mode 100644 index 000000000000..9e6acd22ed7a --- /dev/null +++ b/backend/internal/handler/usage_records_test.go @@ -0,0 +1,415 @@ +//go:build unit + +package handler + +import ( + "context" + "encoding/base64" + "encoding/csv" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + ratelimit "github.com/Wei-Shaw/sub2api/internal/middleware" + "github.com/Wei-Shaw/sub2api/internal/pkg/qualityqueue/queuetest" + "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/stretchr/testify/require" +) + +type recordsTestRepo struct { + service.UsageLogRepository + onRead func(context.Context) + list func(int64, int64, time.Time, time.Time, *service.UsageRecordPosition, int) ([]service.UsageLog, error) +} + +func (r recordsTestRepo) ListUsageRecords(ctx context.Context, user, key int64, start, end time.Time, pos *service.UsageRecordPosition, limit int) ([]service.UsageLog, error) { + if r.onRead != nil { + r.onRead(ctx) + } + return r.list(user, key, start, end, pos, limit) +} + +type recordsTestSettings struct { + service.SettingRepository + values map[string]string + onRead func(context.Context) +} + +func (s recordsTestSettings) GetMultiple(ctx context.Context, _ []string) (map[string]string, error) { + if s.onRead != nil { + s.onRead(ctx) + } + return s.values, nil +} + +type recordsFixture struct { + t *testing.T + h *UsageRecordsHandler + redis *miniredis.Miniredis +} + +func newRecordsFixture(t *testing.T, repo recordsTestRepo, flags map[string]string) recordsFixture { + cache := miniredis.RunT(t) + client := queuetest.NewClient(cache.Addr()) + t.Cleanup(func() { _ = client.Close() }) + cfg := &config.Config{JWT: config.JWTConfig{Secret: "unit-test-cursor-secret"}} + settings := service.NewSettingService(recordsTestSettings{values: flags, onRead: repo.onRead}, cfg) + usage := NewUsageHandler(service.NewUsageService(repo, nil, nil, nil), nil, nil, settings) + return recordsFixture{t, NewUsageRecordsHandler(usage, ratelimit.NewRateLimiter(client), cfg), cache} +} + +func TestUsageRecordsCSVReadBudget(t *testing.T) { + var deadlines []time.Time + f := newRecordsFixture(t, recordsTestRepo{ + onRead: func(ctx context.Context) { + end, ok := ctx.Deadline() + require.True(t, ok) + deadlines = append(deadlines, end) + }, + list: func(_, _ int64, _, _ time.Time, _ *service.UsageRecordPosition, _ int) ([]service.UsageLog, error) { + return nil, nil + }, + }, nil) + before := time.Now() + require.Equal(t, 200, f.get("start_time=0&end_time=1&format=csv", 7, 5).Code) + require.Len(t, deadlines, 3) + require.Equal(t, deadlines[0], deadlines[1]) + require.Equal(t, deadlines[0], deadlines[2]) + require.False(t, deadlines[0].Before(before.Add(5*time.Second))) + require.False(t, deadlines[0].After(time.Now().Add(5*time.Second))) +} + +func (f recordsFixture) get(query string, user, key int64) *httptest.ResponseRecorder { + f.t.Helper() + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodGet, "/v1/usage/records?"+query, nil) + c.Request.Header.Set("Accept-Language", "en") + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: key, UserID: user, Name: "=private,name"}) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: user}) + f.h.List(c) + return w +} + +func TestUsageRecordsValidation(t *testing.T) { + f := newRecordsFixture(t, recordsTestRepo{}, nil) + for _, q := range []string{"", "start_time=1", "end_time=2", + "start_time=0&end_time=604801", "start_time=1&end_time=1", "start_time=2&end_time=1", "start_time=1&end_time=xyz", + "start_time=2025-01-01T00:00:00%2B24:00&end_time=2025-01-02T00:00:00Z", + "start_time=1&end_time=2&cursor=broken", "start_time=1&end_time=2&cursor=", "start_time=1&end_time=2&cursor=%zz", "start_time=1&end_time=2&format=x", + "start_time=1&end_time=2&limit=0", "start_time=1&end_time=2&limit=1001", "start_time=1&end_time=2&limit=abc"} { + t.Run(q, func(t *testing.T) { + w := f.get(q, 7, 5) + require.Equal(t, 400, w.Code) + require.Contains(t, w.Body.String(), `"type":"invalid_request_error"`) + }) + } + for _, param := range []string{"start_time", "end_time"} { + for _, invalid := range []string{"2025-01-01T01:00:00", "2025-01-01T01:00:00.0000000001Z"} { + values := url.Values{"start_time": {"2025-01-01T00:00:00Z"}, "end_time": {"2025-01-01T02:00:00Z"}} + values.Set(param, invalid) + w := f.get(values.Encode(), 7, 5) + require.Equal(t, 400, w.Code) + require.Contains(t, w.Body.String(), `"message":"`+param+` requires`) + } + } + start := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC) + v := url.Values{"start_time": {"2025-01-01T08:00:00+08:00"}, "end_time": {"2025-01-09T01:00:00Z"}} + q, err := parseUsageRecordsQuery(v, start.Add(time.Hour)) + require.NoError(t, err) + require.Equal(t, 500, q.limit) + require.Equal(t, "json", q.format) + require.Equal(t, start, q.start) + require.Equal(t, start.Add(time.Hour), q.end) + w := f.get("start_time=2099-01-01T00:00:00Z&end_time=2099-01-12T00:00:00Z", 7, 5) + var empty struct { + Start time.Time `json:"start_time"` + End time.Time `json:"end_time"` + Data []usageRecord `json:"data"` + } + require.Equal(t, http.StatusOK, w.Code) + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &empty)) + require.False(t, empty.Start.IsZero()) + require.Equal(t, empty.Start, empty.End) + require.Empty(t, empty.Data) +} + +func TestUsageRecordsPagesAndVisibility(t *testing.T) { + start := time.Now().UTC().Truncate(time.Second).Add(-time.Hour) + stamp := start.Add(time.Minute + 123456*time.Microsecond) + requested, upstream, effort := "public-model", "private-model", "low" + newRow := func(id int64) service.UsageLog { + return service.UsageLog{ID: id, CreatedAt: stamp, RequestID: "client:test", Model: upstream, RequestedModel: requested, + UpstreamResponseModel: &upstream, ReasoningEffort: &upstream, RequestedReasoningEffort: &effort, + AccountID: 55, UpstreamModel: &upstream, UpstreamRequestID: &upstream, AccountStatsCost: new(float64), + Stream: true, TotalCost: 2, ActualCost: 1, RateMultiplier: 0.5} + } + var firstEnd time.Time + repo := recordsTestRepo{list: func(user, key int64, from, to time.Time, pos *service.UsageRecordPosition, limit int) ([]service.UsageLog, error) { + require.Equal(t, int64(7), user) + require.Equal(t, int64(5), key) + require.Equal(t, 1, limit) + require.True(t, start.Equal(from)) + if pos == nil { + firstEnd = to + return []service.UsageLog{newRow(10), newRow(11)}, nil + } + require.True(t, firstEnd.Equal(to)) + require.Equal(t, int64(10), pos.ID) + require.True(t, stamp.Equal(pos.CreatedAt)) + return []service.UsageLog{newRow(11)}, nil + }} + f := newRecordsFixture(t, repo, nil) + query := "start_time=" + strconv.FormatInt(start.Unix(), 10) + "&end_time=" + strconv.FormatInt(start.Add(2*time.Hour).Unix(), 10) + "&limit=1" + w := f.get(query, 7, 5) + require.Equal(t, http.StatusOK, w.Code) + var page struct { + Object string + Data []map[string]any + More bool `json:"has_more"` + Cursor *string `json:"next_cursor"` + End time.Time `json:"end_time"` + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &page)) + require.Equal(t, "list", page.Object) + require.True(t, page.More) + require.True(t, firstEnd.Equal(page.End)) + require.Len(t, page.Data, 1) + row := page.Data[0] + fields := []string{"id", "request_id", "created_at", "model", "request_type", "stream", "reasoning_effort", "input_tokens", "output_tokens", "cache_read_tokens", "cache_creation_tokens", "image_count", "actual_cost", "total_cost", "rate_multiplier", "duration_ms", "first_token_ms"} + require.Len(t, row, len(fields)) + for _, k := range fields { + require.Contains(t, row, k) + } + require.Equal(t, "public-model", row["model"]) + require.Equal(t, "low", row["reasoning_effort"]) + require.NotContains(t, w.Body.String(), upstream) + require.NotNil(t, page.Cursor) + nextQuery := query + "&cursor=" + *page.Cursor + for _, owner := range [][2]int64{{7, 6}, {8, 5}} { + require.Equal(t, 400, f.get(nextQuery, owner[0], owner[1]).Code) + } + wire, err := base64.RawURLEncoding.DecodeString(*page.Cursor) + require.NoError(t, err) + wire[len(wire)-1] ^= 1 + require.Equal(t, 400, f.get(query+"&cursor="+base64.RawURLEncoding.EncodeToString(wire), 7, 5).Code) + w = f.get(nextQuery, 7, 5) + require.Equal(t, 200, w.Code) + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &page)) + require.False(t, page.More) + require.Nil(t, page.Cursor) + require.Equal(t, float64(11), page.Data[0]["id"]) +} + +func TestUsageRecordsCSV(t *testing.T) { + model, ip := "response", "192.0.2.1" + repo := recordsTestRepo{list: func(_, _ int64, start, _ time.Time, pos *service.UsageRecordPosition, _ int) ([]service.UsageLog, error) { + log := service.UsageLog{ID: 10, CreatedAt: start, Model: "public", UpstreamResponseModel: &model, IPAddress: &ip, + InputTokens: 3, CacheReadTokens: 1, ActualCost: 0.001953125, TotalCost: 0.25, RateMultiplier: 0.5} + if pos != nil { + log.ID++ + return []service.UsageLog{log}, nil + } + return []service.UsageLog{log, log}, nil + }} + for _, visible := range []bool{false, true} { + t.Run(strconv.FormatBool(visible), func(t *testing.T) { + flags := map[string]string{ + service.SettingKeyUsageShowCacheRateToUsers: strconv.FormatBool(visible), + service.SettingKeyUsageShowUpstreamResponseModelToUsers: strconv.FormatBool(visible), + } + f := newRecordsFixture(t, repo, flags) + query := "start_time=0&end_time=10&limit=1&format=csv" + w := f.get(query, 7, 5) + require.Equal(t, 200, w.Code) + require.Equal(t, "text/csv; charset=utf-8", w.Header().Get("Content-Type")) + require.Equal(t, "true", w.Header().Get("X-Has-More")) + require.True(t, strings.HasPrefix(w.Body.String(), "\uFEFF")) + cells, err := csv.NewReader(strings.NewReader(strings.TrimPrefix(w.Body.String(), "\uFEFF"))).ReadAll() + require.NoError(t, err) + require.Len(t, cells, 2) + header := "Time|API Key Name|Model|Reasoning Effort|Inbound Endpoint|IP Address|Type|Billing Mode|Input Tokens|Output Tokens|Cache Read Tokens|Cache Creation Tokens|Rate Multiplier|Billed Cost|Original Cost|First Token (ms)|Duration (ms)" + row := "1970-01-01T00:00:00Z|'=private,name|public|-||192.0.2.1|Sync|Token|3|0|1|0|0.5|0.00195313|0.25000000||" + if visible { + header = strings.Replace(header, "Model|", "Model|Upstream Response Model|", 1) + header = strings.Replace(header, "|Rate Multiplier", "|Cache Rate|Rate Multiplier", 1) + row = strings.Replace(row, "public|", "public|response|", 1) + row = strings.Replace(row, "|0.5|", "|25.0%|0.5|", 1) + } + require.Equal(t, strings.Split(header, "|"), cells[0]) + require.Equal(t, strings.Split(row, "|"), cells[1]) + next := query + "&cursor=" + w.Header().Get("X-Next-Cursor") + for _, flag := range []string{service.SettingKeyUsageShowUpstreamResponseModelToUsers, service.SettingKeyUsageShowCacheRateToUsers} { + flags[flag] = strconv.FormatBool(!visible) + w = f.get(next, 7, 5) + if visible { + require.Equal(t, 409, w.Code) + require.Contains(t, w.Body.String(), "Restart from the first page") + require.NotContains(t, w.Body.String(), "response") + require.Empty(t, w.Header().Get("X-Next-Cursor")) + } else { + require.Equal(t, 200, w.Code) + require.Equal(t, strings.Split(w.Body.String(), "\n")[0], "\uFEFF"+strings.ReplaceAll(header, "|", ",")) + } + flags[flag] = strconv.FormatBool(visible) + } + w = f.get(next, 7, 5) + require.Equal(t, "false", w.Header().Get("X-Has-More")) + require.Empty(t, w.Header().Get("X-Next-Cursor")) + }) + } +} + +func TestUsageRecordsCSVBillingModeLabelsMatchUserExport(t *testing.T) { + // Source of truth: frontend/src/i18n/locales/zh/admin/resources.ts, + // admin.usage.billingMode{Token,PerRequest,Image,Video}. + for _, tc := range []struct { + mode, want string + }{ + {mode: "token", want: "按量"}, + {mode: "per_request", want: "按次"}, + {mode: "image", want: "按次(图片)"}, + {mode: "video", want: "按次(视频)"}, + } { + row := usageRecord{BillingMode: &tc.mode} + require.Equal(t, tc.want, usageCSVBillingMode(row, true), tc.mode) + } +} + +func TestUsageRecordsRateLimitsOps(t *testing.T) { + for _, perUser := range []bool{false, true} { + t.Run("perUser="+strconv.FormatBool(perUser), func(t *testing.T) { + f := newRecordsFixture(t, recordsTestRepo{}, nil) + setupOpsErrorLogTestQueue(t, 32) + router := gin.New() + router.Use(OpsErrorLoggerMiddleware(service.NewOpsService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil))) + router.GET("/v1/usage/records", func(c *gin.Context) { + id, err := strconv.ParseInt(c.GetHeader("X-Test-Key"), 10, 64) + require.NoError(t, err) + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: id, UserID: 7}) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 7}) + f.h.List(c) + }) + count, maxAllowed, scope := 61, 60, "per API key" + if perUser { + count, maxAllowed, scope = 150, 120, "per user across all API keys" + } + for i := range count { + key := 1 + if perUser { + key += i % 3 + } + req := httptest.NewRequest(http.MethodGet, "/v1/usage/records?start_time=2099-01-01T00:00:00Z&end_time=2099-01-02T00:00:00Z", nil) + req.Header.Set("X-Test-Key", strconv.Itoa(key)) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + if i < maxAllowed { + require.Equal(t, 200, w.Code) + continue + } + require.Equal(t, 429, w.Code) + require.Contains(t, w.Body.String(), scope) + require.Equal(t, "60", w.Header().Get("Retry-After")) + select { + case job := <-opsErrorLogQueue: + require.True(t, job.entry.IsBusinessLimited) + require.Equal(t, "auth", job.entry.ErrorPhase) + require.Equal(t, "client", job.entry.ErrorOwner) + require.Equal(t, "client_request", job.entry.ErrorSource) + default: + t.Fatal("missing Ops error for local 429") + } + } + }) + } +} + +func TestUsageRecordsRateLimitAndErrors(t *testing.T) { + f := newRecordsFixture(t, recordsTestRepo{list: func(_, _ int64, _, _ time.Time, _ *service.UsageRecordPosition, _ int) ([]service.UsageLog, error) { + return nil, errors.New("private database detail") + }}, nil) + // Future windows are empty, while still consuming the per-key budget. + const query = "start_time=2099-01-01T00:00:00Z&end_time=2099-01-02T00:00:00Z" + for range 60 { + require.Equal(t, 200, f.get(query, 7, 5).Code) + } + w := f.get(query, 7, 5) + require.Equal(t, 429, w.Code) + require.Equal(t, "60", w.Header().Get("Retry-After")) + require.Equal(t, 200, f.get(query, 7, 6).Code) + f.redis.FastForward(time.Minute) + w = f.get("start_time=0&end_time=1", 7, 5) + require.Equal(t, 503, w.Code) + require.NotContains(t, w.Body.String(), "private database detail") + f.redis.Close() + require.Equal(t, 503, f.get(query, 7, 6).Code) +} + +func TestUsageRecordsTwoLevelLimitDoesNotConsumeOtherBucket(t *testing.T) { + f := newRecordsFixture(t, recordsTestRepo{}, nil) + const query = "start_time=2099-01-01T00:00:00Z&end_time=2099-01-02T00:00:00Z" + for range 60 { + require.Equal(t, http.StatusOK, f.get(query, 7, 1).Code) + } + keyLimited := f.get(query, 7, 1) + require.Equal(t, http.StatusTooManyRequests, keyLimited.Code) + require.Contains(t, keyLimited.Body.String(), "per API key") + userCount, err := f.redis.Get("rate_limit:usage-records:{u:7}:user") + require.NoError(t, err) + require.Equal(t, "60", userCount) + + for key := int64(2); key <= 4; key++ { + for range 20 { + require.Equal(t, http.StatusOK, f.get(query, 7, key).Code) + } + } + userLimited := f.get(query, 7, 5) + require.Equal(t, http.StatusTooManyRequests, userLimited.Code) + require.Contains(t, userLimited.Body.String(), "per user across all API keys") + keyFiveCount, err := f.redis.Get("rate_limit:usage-records:{u:7}:key:5") + require.Error(t, err) + require.Empty(t, keyFiveCount) +} + +func TestUsageRecordsRateLimitTTLBoundaries(t *testing.T) { + const query = "start_time=2099-01-01T00:00:00Z&end_time=2099-01-02T00:00:00Z" + for _, bucket := range []struct { + key, limit string + }{ + {"rate_limit:usage-records:{u:7}:key:5", "60"}, + {"rate_limit:usage-records:{u:7}:user", "120"}, + } { + t.Run(bucket.key+"/PTTL=0", func(t *testing.T) { + f := newRecordsFixture(t, recordsTestRepo{}, nil) + require.NoError(t, f.redis.Set(bucket.key, bucket.limit)) + f.redis.SetTTL(bucket.key, 500*time.Microsecond) // PTTL truncates to milliseconds. + w := f.get(query, 7, 5) + require.Equal(t, http.StatusTooManyRequests, w.Code) + require.Equal(t, "1", w.Header().Get("Retry-After")) + f.redis.FastForward(time.Millisecond) + require.Equal(t, http.StatusOK, f.get(query, 7, 5).Code) + }) + t.Run(bucket.key+"/PTTL=-1", func(t *testing.T) { + f := newRecordsFixture(t, recordsTestRepo{}, nil) + require.NoError(t, f.redis.Set(bucket.key, bucket.limit)) // Persistent, already full. + w := f.get(query, 7, 5) + require.Equal(t, http.StatusTooManyRequests, w.Code) + require.Equal(t, "60", w.Header().Get("Retry-After")) + require.Equal(t, time.Minute, f.redis.TTL(bucket.key)) + f.redis.FastForward(59 * time.Second) + require.Equal(t, "1", f.get(query, 7, 5).Header().Get("Retry-After")) + f.redis.FastForward(time.Second) + require.Equal(t, http.StatusOK, f.get(query, 7, 5).Code) + }) + } +} diff --git a/backend/internal/handler/wire.go b/backend/internal/handler/wire.go index 9ce9793e3701..d2011093c2de 100644 --- a/backend/internal/handler/wire.go +++ b/backend/internal/handler/wire.go @@ -3,6 +3,7 @@ package handler import ( "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/handler/admin" + ratelimit "github.com/Wei-Shaw/sub2api/internal/middleware" "github.com/Wei-Shaw/sub2api/internal/securityaudit" "github.com/Wei-Shaw/sub2api/internal/service" @@ -215,6 +216,7 @@ func ProvideHandlers( userHandler *UserHandler, apiKeyHandler *APIKeyHandler, usageHandler *UsageHandler, + usageRecordsHandler *UsageRecordsHandler, redeemHandler *RedeemHandler, subscriptionHandler *SubscriptionHandler, announcementHandler *AnnouncementHandler, @@ -246,6 +248,7 @@ func ProvideHandlers( User: userHandler, APIKey: apiKeyHandler, Usage: usageHandler, + UsageRecords: usageRecordsHandler, Redeem: redeemHandler, Subscription: subscriptionHandler, Announcement: announcementHandler, @@ -278,6 +281,8 @@ var ProviderSet = wire.NewSet( NewUserHandler, NewAPIKeyHandler, NewUsageHandler, + ratelimit.NewRateLimiter, + NewUsageRecordsHandler, NewRedeemHandler, NewSubscriptionHandler, NewAnnouncementHandler, diff --git a/backend/internal/middleware/rate_limiter.go b/backend/internal/middleware/rate_limiter.go index 956adeb09941..4fbc95b070fd 100644 --- a/backend/internal/middleware/rate_limiter.go +++ b/backend/internal/middleware/rate_limiter.go @@ -42,6 +42,46 @@ end return {current, repaired} `) +// rateLimitPairScript checks two fixed-window buckets before incrementing +// either count. A rejected request consumes neither quota. When both limits +// are exhausted, the second bucket is reported so the caller can surface the +// user-wide limit. +var rateLimitPairScript = redis.NewScript(` +local function window_ttl(key) + local ttl = redis.call('PTTL', key) + if ttl == -1 then + redis.call('PEXPIRE', key, ARGV[1]) + return tonumber(ARGV[1]) + end + return ttl +end + +local key_count = tonumber(redis.call('GET', KEYS[1]) or '0') +local user_count = tonumber(redis.call('GET', KEYS[2]) or '0') +local key_limit = tonumber(ARGV[2]) +local user_limit = tonumber(ARGV[3]) +local key_ttl = window_ttl(KEYS[1]) +local user_ttl = window_ttl(KEYS[2]) + +if key_count >= key_limit or user_count >= user_limit then + local blocked = 1 + if user_count >= user_limit then + blocked = 2 + end + return {0, blocked, key_count, user_count, key_ttl, user_ttl} +end + +key_count = redis.call('INCR', KEYS[1]) +if key_ttl == -2 then + redis.call('PEXPIRE', KEYS[1], ARGV[1]) +end +user_count = redis.call('INCR', KEYS[2]) +if user_ttl == -2 then + redis.call('PEXPIRE', KEYS[2], ARGV[1]) +end +return {1, 0, key_count, user_count, redis.call('PTTL', KEYS[1]), redis.call('PTTL', KEYS[2])} +`) + // rateLimitRun 允许测试覆写脚本执行逻辑 var rateLimitRun = func(ctx context.Context, client *redis.Client, key string, windowMillis int64) (int64, bool, error) { values, err := rateLimitScript.Run(ctx, client, []string{key}, windowMillis).Slice() @@ -86,6 +126,16 @@ type AllowResult struct { RetryAfter time.Duration } +// PairAllowResult is the atomic result for two related fixed-window buckets. +// BlockedScope is "key" or "user" when Allowed is false. +type PairAllowResult struct { + Allowed bool + BlockedScope string + KeyCount int64 + UserCount int64 + RetryAfter time.Duration +} + // Allow 对给定 key(不含 "rate_limit:" 前缀)执行一次固定窗口计数判定。 // 供需要自定义限流维度(如按用户 ID)的调用方使用;Redis 错误由调用方决定 fail-open/close。 func (r *RateLimiter) Allow(ctx context.Context, key string, limit int, window time.Duration) (AllowResult, error) { @@ -110,6 +160,66 @@ func (r *RateLimiter) Allow(ctx context.Context, key string, limit int, window t return result, nil } +// AllowTogether checks and increments a per-key and a per-user bucket in one +// Redis Lua transaction. If either bucket is exhausted, neither count changes. +func (r *RateLimiter) AllowTogether(ctx context.Context, key string, keyLimit int, userKey string, userLimit int, window time.Duration) (PairAllowResult, error) { + windowMillis := windowTTLMillis(window) + values, err := rateLimitPairScript.Run(ctx, r.redis, + []string{r.prefix + key, r.prefix + userKey}, windowMillis, keyLimit, userLimit).Slice() + if err != nil { + return PairAllowResult{}, err + } + if len(values) < 6 { + return PairAllowResult{}, fmt.Errorf("rate limit pair script returned %d values", len(values)) + } + allowed, err := parseInt64(values[0]) + if err != nil { + return PairAllowResult{}, err + } + blocked, err := parseInt64(values[1]) + if err != nil { + return PairAllowResult{}, err + } + keyCount, err := parseInt64(values[2]) + if err != nil { + return PairAllowResult{}, err + } + userCount, err := parseInt64(values[3]) + if err != nil { + return PairAllowResult{}, err + } + keyTTL, err := parseInt64(values[4]) + if err != nil { + return PairAllowResult{}, err + } + userTTL, err := parseInt64(values[5]) + if err != nil { + return PairAllowResult{}, err + } + result := PairAllowResult{Allowed: allowed == 1, KeyCount: keyCount, UserCount: userCount} + if result.Allowed { + return result, nil + } + if blocked == 2 { + result.BlockedScope = "user" + result.RetryAfter = retryAfterFromPTTL(userTTL, window) + } else { + result.BlockedScope = "key" + result.RetryAfter = retryAfterFromPTTL(keyTTL, window) + } + return result, nil +} + +func retryAfterFromPTTL(ttl int64, fallback time.Duration) time.Duration { + if ttl == 0 { + return time.Second + } + if ttl > 0 { + return time.Duration(ttl) * time.Millisecond + } + return fallback +} + // clientIPForRateLimit 返回 IP 维度限流使用的客户端地址。 // 与审计日志/会话绑定/API Key IP ACL 共用同一套安全客户端 IP 解析 // (SessionBindingContext 快照:兼容开关开启时信任反代转发头,关闭时走 diff --git a/backend/internal/repository/usage_records.go b/backend/internal/repository/usage_records.go new file mode 100644 index 000000000000..b23d67c162f0 --- /dev/null +++ b/backend/internal/repository/usage_records.go @@ -0,0 +1,51 @@ +package repository + +import ( + "context" + "database/sql" + "strconv" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" +) + +var _ service.UsageRecordsReader = (*usageLogRepository)(nil) + +func (r *usageLogRepository) ListUsageRecords(ctx context.Context, userID, keyID int64, start, end time.Time, after *service.UsageRecordPosition, limit int) ([]service.UsageLog, error) { + // PostgreSQL timestamps have microsecond precision. Round both exclusive-end + // and inclusive-start bounds upwards to preserve fractional RFC3339 inputs. + ceilMicro := func(t time.Time) time.Time { return t.Add(time.Microsecond - 1).Truncate(time.Microsecond) } + // Keep ownership as a residual boolean check. On accounts with many keys, + // intersecting the much larger user index makes every page scan unrelated keys. + query := `SELECT id, created_at, COALESCE(request_id, ''), model, requested_model, + upstream_response_model, reasoning_effort, requested_reasoning_effort, inbound_endpoint, ip_address, + request_type, stream, openai_ws_mode, billing_mode, input_tokens, output_tokens, cache_read_tokens, + cache_creation_tokens, COALESCE(image_count, 0), rate_multiplier, actual_cost, total_cost, first_token_ms, duration_ms + FROM usage_logs WHERE api_key_id = $1 AND (user_id = $2) IS TRUE AND created_at >= $3 AND created_at < $4` + args := []any{keyID, userID, ceilMicro(start), ceilMicro(end)} + if after != nil { + query += " AND (created_at, id) > ($5, $6)" + args = append(args, after.CreatedAt, after.ID) + } + args = append(args, limit+1) + rows, err := r.sql.QueryContext(ctx, query+" ORDER BY created_at ASC, id ASC LIMIT $"+strconv.Itoa(len(args)), args...) + if err != nil { + return nil, err + } + defer func() { _ = rows.Close() }() + var records []service.UsageLog + for rows.Next() { + var row service.UsageLog + var requestedModel sql.NullString + if err := rows.Scan(&row.ID, &row.CreatedAt, &row.RequestID, &row.Model, &requestedModel, + &row.UpstreamResponseModel, &row.ReasoningEffort, &row.RequestedReasoningEffort, &row.InboundEndpoint, &row.IPAddress, + &row.RequestType, &row.Stream, &row.OpenAIWSMode, &row.BillingMode, &row.InputTokens, &row.OutputTokens, + &row.CacheReadTokens, &row.CacheCreationTokens, &row.ImageCount, &row.RateMultiplier, &row.ActualCost, &row.TotalCost, + &row.FirstTokenMs, &row.DurationMs); err != nil { + return nil, err + } + row.RequestedModel = coalesceTrimmedString(requestedModel, row.Model) + records = append(records, row) + } + return records, rows.Err() +} diff --git a/backend/internal/repository/usage_records_integration_test.go b/backend/internal/repository/usage_records_integration_test.go new file mode 100644 index 000000000000..4c9227f55781 --- /dev/null +++ b/backend/internal/repository/usage_records_integration_test.go @@ -0,0 +1,76 @@ +//go:build integration + +package repository + +import ( + "context" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/google/uuid" + "github.com/stretchr/testify/require" +) + +func TestUsageRecordsKeysetIsolation(t *testing.T) { + tx := testEntTx(t) + client := tx.Client() + repo := newUsageLogRepositoryWithSQL(client, tx) + ctx := context.Background() + start := time.Date(2026, 8, 13, 12, 0, 0, 0, time.UTC) + end := start.Add(time.Hour) + owner := mustCreateUser(t, client, &service.User{Email: "records-owner@example.test"}) + other := mustCreateUser(t, client, &service.User{Email: "records-other@example.test"}) + account := mustCreateAccount(t, client, &service.Account{Name: "usage-records"}) + key := func(uid int64) int64 { + return mustCreateApiKey(t, client, &service.APIKey{UserID: uid, Name: "records", Key: uuid.NewString()}).ID + } + keyID := key(owner.ID) + insert := func(uid, kid int64, at time.Time) int64 { + log := &service.UsageLog{UserID: uid, APIKeyID: kid, AccountID: account.ID, RequestID: uuid.NewString(), Model: "example", CreatedAt: at, ActualCost: 0.01} + inserted, err := repo.Create(ctx, log) + require.NoError(t, err) + require.True(t, inserted) + return log.ID + } + insert(owner.ID, key(owner.ID), start) + insert(other.ID, key(other.ID), start) + insert(other.ID, keyID, start) // Malformed historical attribution must also be excluded. + insert(owner.ID, keyID, start.Add(-time.Microsecond)) + stamp := start.Add(time.Minute) + first := insert(owner.ID, keyID, stamp) + second := insert(owner.ID, keyID, stamp) + lateTime := end.Add(-time.Microsecond) + last := insert(owner.ID, keyID, lateTime) + insert(owner.ID, keyID, end) + ids := func(logs []service.UsageLog) []int64 { + var out []int64 + for _, l := range logs { + out = append(out, l.ID) + } + return out + } + page, err := repo.ListUsageRecords(ctx, owner.ID, keyID, start, end, nil, 1) + require.NoError(t, err) + require.Equal(t, []int64{first, second}, ids(page)) + added := insert(owner.ID, keyID, stamp) + lateEarlier := insert(owner.ID, keyID, start) // Restored after page one, before its cursor. + _, err = tx.ExecContext(ctx, "UPDATE usage_logs SET image_count = NULL, requested_model = $1 WHERE id = $2", " \t ", lateEarlier) + require.NoError(t, err) + pos := &service.UsageRecordPosition{CreatedAt: page[0].CreatedAt, ID: page[0].ID} + page, err = repo.ListUsageRecords(ctx, owner.ID, keyID, start, end, pos, 2) + require.NoError(t, err) + require.Equal(t, []int64{second, added, last}, ids(page)) + pos = &service.UsageRecordPosition{CreatedAt: page[1].CreatedAt, ID: page[1].ID} + page, err = repo.ListUsageRecords(ctx, owner.ID, keyID, start, end, pos, 2) + require.NoError(t, err) + require.Equal(t, []int64{last}, ids(page)) + page, err = repo.ListUsageRecords(ctx, owner.ID, keyID, start, end, nil, 10) + require.NoError(t, err) + require.Equal(t, []int64{lateEarlier, first, second, added, last}, ids(page)) + require.Zero(t, page[0].ImageCount) + require.Equal(t, "example", page[0].RequestedModel) + page, err = repo.ListUsageRecords(ctx, owner.ID, keyID, stamp.Add(time.Nanosecond), lateTime.Add(time.Nanosecond), nil, 10) + require.NoError(t, err) + require.Equal(t, []int64{last}, ids(page)) +} diff --git a/backend/internal/server/middleware/api_key_auth.go b/backend/internal/server/middleware/api_key_auth.go index d8aeb7a36dce..c6eb0259b215 100644 --- a/backend/internal/server/middleware/api_key_auth.go +++ b/backend/internal/server/middleware/api_key_auth.go @@ -117,28 +117,17 @@ func apiKeyAuthWithSubscription(apiKeyService *service.APIKeyService, subscripti } apiKey, err := lookup(c.Request.Context(), apiKeyString) if err != nil { - if errors.Is(err, service.ErrUserNotFound) { - AbortWithError(c, 401, "USER_NOT_FOUND", "User associated with API key not found") - return - } - if errors.Is(err, service.ErrAPIKeyNotFound) { - if rejectAnonymousCredentialFailure(c, apiKeyService, "unknown", false) { - return - } - MarkIngressRejected(c, IngressRejectInvalidAPIKey) - AbortWithError(c, 401, "INVALID_API_KEY", "Invalid API key") - return - } - if errors.Is(err, service.ErrAPIKeyAuthOverloaded) { - MarkIngressRejected(c, IngressRejectAPIKeyAuthOverloaded) - AbortWithError(c, http.StatusServiceUnavailable, "API_KEY_AUTH_OVERLOADED", "API key authentication is temporarily unavailable") - return - } - if abortIfAPIKeyLookupClientGone(c, err) { + abortAPIKeyLookupError(c, err, apiKeyService) + return + } + // Detailed usage needs current permissions. Resolve the authenticated + // identity before any policy check or context write uses the key. + if c.Request.Method == http.MethodGet && c.FullPath() == gatewayUsageRecordsPath { + apiKey, err = revalidateUsageRecordsKey(c.Request.Context(), apiKeyService, apiKeyString, apiKey) + if err != nil { + abortAPIKeyLookupError(c, err, nil) return } - AbortWithError(c, 500, "INTERNAL_ERROR", "Failed to validate API key") - return } // apiKey 已加载(含 User/Group)。即便后续因分组停用/Key 停用/用户停用/ @@ -148,43 +137,10 @@ func apiKeyAuthWithSubscription(apiKeyService *service.APIKeyService, subscripti // ── 3. 基础鉴权(始终执行) ───────────────────────────────── // disabled / 未知状态 → 无条件拦截(expired 和 quota_exhausted 留给计费阶段) - if !apiKey.IsActive() && - apiKey.Status != service.StatusAPIKeyExpired && - apiKey.Status != service.StatusAPIKeyQuotaExhausted { - if apiKey.Status == service.StatusAPIKeyDisabled && rejectAnonymousCredentialFailure(c, apiKeyService, "disabled", false) { - return - } - MarkIngressRejected(c, IngressRejectAPIKeyDisabled) - AbortWithError(c, 401, "API_KEY_DISABLED", "API key is disabled") + if apiKey.Status == service.StatusAPIKeyDisabled && rejectAnonymousCredentialFailure(c, apiKeyService, "disabled", false) { return } - - // 检查 IP 限制(白名单/黑名单) - // 注意:错误信息故意模糊,避免暴露具体的 IP 限制机制 - if len(apiKey.IPWhitelist) > 0 || len(apiKey.IPBlacklist) > 0 { - clientIP := ip.GetSecurityClientIP(c, cfg.TrustForwardedIPForAPIKeyACL()) - allowed, _ := ip.CheckIPRestrictionWithCompiledRules(clientIP, apiKey.CompiledIPWhitelist, apiKey.CompiledIPBlacklist) - if !allowed { - if clientIP == "" { - clientIP = "unknown" - } - service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonIPRestriction) - MarkIngressRejected(c, IngressRejectIPRestricted) - AbortWithError(c, 403, "ACCESS_DENIED", fmt.Sprintf("Access denied. Your IP is %s", clientIP)) - return - } - } - - // 检查关联的用户 - if apiKey.User == nil { - AbortWithError(c, 401, "USER_NOT_FOUND", "User associated with API key not found") - return - } - - // 检查用户状态 - if !apiKey.User.IsActive() { - MarkIngressRejected(c, IngressRejectUserInactive) - AbortWithError(c, 401, "USER_INACTIVE", "User account is not active") + if !validateAPIKeyPrincipal(c, apiKey, cfg) { return } anonymousCredentialSuccess(c) @@ -224,7 +180,7 @@ func apiKeyAuthWithSubscription(apiKeyService *service.APIKeyService, subscripti // Async image task polling only reads data that already belongs to the // authenticated key and must remain available after the completed // generation consumes the key's remaining balance. - skipBilling := c.Request.URL.Path == "/v1/usage" || metadataReadRequest || isAsyncImageTaskRead(c.Request.Method, c.Request.URL.Path) + skipBilling := IsGatewayUsagePath(c.Request.URL.Path) || metadataReadRequest || isAsyncImageTaskRead(c.Request.Method, c.Request.URL.Path) // ── 4. SimpleMode → early return ───────────────────────────── @@ -358,6 +314,72 @@ func apiKeyAuthWithSubscription(apiKeyService *service.APIKeyService, subscripti return authenticate } +// Only initial authentication classifies unknown credentials for abuse tracking. +func abortAPIKeyLookupError(c *gin.Context, err error, anonymousGuard *service.APIKeyService) { + switch { + case errors.Is(err, service.ErrUserNotFound): + AbortWithError(c, http.StatusUnauthorized, "USER_NOT_FOUND", "User associated with API key not found") + case errors.Is(err, service.ErrAPIKeyNotFound): + if anonymousGuard != nil && rejectAnonymousCredentialFailure(c, anonymousGuard, "unknown", false) { + return + } + MarkIngressRejected(c, IngressRejectInvalidAPIKey) + AbortWithError(c, http.StatusUnauthorized, "INVALID_API_KEY", "Invalid API key") + case errors.Is(err, service.ErrAPIKeyAuthOverloaded): + MarkIngressRejected(c, IngressRejectAPIKeyAuthOverloaded) + AbortWithError(c, http.StatusServiceUnavailable, "API_KEY_AUTH_OVERLOADED", "API key authentication is temporarily unavailable") + default: + if !abortIfAPIKeyLookupClientGone(c, err) { + AbortWithError(c, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to validate API key") + } + } +} + +func validateAPIKeyPrincipal(c *gin.Context, apiKey *service.APIKey, cfg *config.Config) bool { + if !apiKey.IsActive() && apiKey.Status != service.StatusAPIKeyExpired && apiKey.Status != service.StatusAPIKeyQuotaExhausted { + MarkIngressRejected(c, IngressRejectAPIKeyDisabled) + AbortWithError(c, http.StatusUnauthorized, "API_KEY_DISABLED", "API key is disabled") + return false + } + if len(apiKey.IPWhitelist) > 0 || len(apiKey.IPBlacklist) > 0 { + clientIP := ip.GetSecurityClientIP(c, cfg.TrustForwardedIPForAPIKeyACL()) + allowed, _ := ip.CheckIPRestrictionWithCompiledRules(clientIP, apiKey.CompiledIPWhitelist, apiKey.CompiledIPBlacklist) + if !allowed { + if clientIP == "" { + clientIP = "unknown" + } + service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonIPRestriction) + MarkIngressRejected(c, IngressRejectIPRestricted) + AbortWithError(c, http.StatusForbidden, "ACCESS_DENIED", fmt.Sprintf("Access denied. Your IP is %s", clientIP)) + return false + } + } + if apiKey.User == nil { + AbortWithError(c, http.StatusUnauthorized, "USER_NOT_FOUND", "User associated with API key not found") + return false + } + if !apiKey.User.IsActive() { + MarkIngressRejected(c, IngressRejectUserInactive) + AbortWithError(c, http.StatusUnauthorized, "USER_INACTIVE", "User account is not active") + return false + } + return true +} + +func revalidateUsageRecordsKey(ctx context.Context, keys *service.APIKeyService, credential string, cached *service.APIKey) (*service.APIKey, error) { + if cached == nil || cached.ID <= 0 || cached.UserID <= 0 || cached.User == nil || cached.User.ID != cached.UserID { + return nil, service.ErrAPIKeyNotFound + } + fresh, err := keys.GetByKeyUncached(ctx, credential) + if err != nil { + return nil, err + } + if fresh == nil || fresh.ID != cached.ID || fresh.UserID != cached.UserID || (fresh.User != nil && fresh.User.ID != cached.UserID) { + return nil, service.ErrAPIKeyNotFound + } + return fresh, nil +} + func apiKeyHeadersTooLarge(c *gin.Context) bool { if c == nil { return false diff --git a/backend/internal/server/middleware/api_key_groups.go b/backend/internal/server/middleware/api_key_groups.go index 924c22fd38a7..020f7f1d887b 100644 --- a/backend/internal/server/middleware/api_key_groups.go +++ b/backend/internal/server/middleware/api_key_groups.go @@ -18,6 +18,13 @@ func isMultiGroupBillingInfoRequest(c *gin.Context, key *service.APIKey) bool { return c.Request.URL.Path == "/v1/sub2api/billing" && len(key.ConfiguredGroupIDs()) > 1 } +const gatewayUsageRecordsPath = "/v1/usage/records" + +// IsGatewayUsagePath identifies the two read-only accounting endpoints. +func IsGatewayUsagePath(path string) bool { + return path == "/v1/usage" || path == gatewayUsageRecordsPath +} + const modelListingGroupsKey = "api_key.model_listing_groups" const modelListingRefreshKey = "api_key.model_listing_refresh" const modelListingClientPolicyKey = "api_key.model_listing_client_policy" @@ -82,7 +89,7 @@ func selectAPIKeyRequestGroup(c *gin.Context, keys *service.APIKeyService, subsc if target, ok := c.Get("security_penalty.original_group_id"); ok && target != nil { return key, nil } - if len(key.ConfiguredGroupIDs()) < 2 || isMultiGroupBillingInfoRequest(c, key) || c.Request.URL.Path == "/v1/usage" || isAsyncImageTaskRead(c.Request.Method, c.Request.URL.Path) { + if len(key.ConfiguredGroupIDs()) < 2 || isMultiGroupBillingInfoRequest(c, key) || IsGatewayUsagePath(c.Request.URL.Path) || isAsyncImageTaskRead(c.Request.Method, c.Request.URL.Path) { return key, nil } var models []string diff --git a/backend/internal/server/middleware/cors.go b/backend/internal/server/middleware/cors.go index 1ca5c54a82ff..c70ecb054ce6 100644 --- a/backend/internal/server/middleware/cors.go +++ b/backend/internal/server/middleware/cors.go @@ -103,9 +103,15 @@ func CORS(cfg config.CORSConfig) gin.HandlerFunc { if allowCredentials { c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") } - c.Writer.Header().Set("Access-Control-Allow-Headers", allowHeadersValue) + allowedHeaders := allowHeadersValue + exposedHeaders := "ETag, Server-Timing, X-Client-Request-ID, X-Sub2api-Usage-Id, X-Request-Id" + if c.Request.URL.Path == "/v1/usage/records" { + allowedHeaders += ", X-Goog-API-Key" + exposedHeaders += ", X-Next-Cursor, X-Has-More, Retry-After" + } + c.Writer.Header().Set("Access-Control-Allow-Headers", allowedHeaders) c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE, PATCH") - c.Writer.Header().Set("Access-Control-Expose-Headers", "ETag, Server-Timing, X-Client-Request-ID") + c.Writer.Header().Set("Access-Control-Expose-Headers", exposedHeaders) c.Writer.Header().Set("Access-Control-Max-Age", "86400") } // 处理预检请求 diff --git a/backend/internal/server/middleware/regional_api_key_auth.go b/backend/internal/server/middleware/regional_api_key_auth.go index 1177b8c7db8d..d15e4e18e46c 100644 --- a/backend/internal/server/middleware/regional_api_key_auth.go +++ b/backend/internal/server/middleware/regional_api_key_auth.go @@ -22,6 +22,10 @@ type regionalAPIKeyAuthenticator interface { func RegionalAPIKeyAuth(svc regionalAPIKeyAuthenticator, cfg *config.Config) gin.HandlerFunc { return func(c *gin.Context) { + if c.Request != nil && c.Request.URL != nil && c.Request.URL.Path == "/v1/usage/records" { + AbortWithError(c, http.StatusServiceUnavailable, "REGIONAL_USAGE_RECORDS_UNAVAILABLE", "Usage records are available on the primary site. Please use the primary site address.") + return + } if apiKeyHeadersTooLarge(c) { AbortWithError(c, http.StatusUnauthorized, "INVALID_API_KEY", "Invalid API key") return diff --git a/backend/internal/server/middleware/regional_api_key_auth_test.go b/backend/internal/server/middleware/regional_api_key_auth_test.go index f796f6471b04..9606ae906f56 100644 --- a/backend/internal/server/middleware/regional_api_key_auth_test.go +++ b/backend/internal/server/middleware/regional_api_key_auth_test.go @@ -69,6 +69,30 @@ func TestRegionalAuthMiddlewareLocalIdentityAndIP(t *testing.T) { } } +func TestRegionalAuthRejectsUsageRecordsBeforeReadingSnapshot(t *testing.T) { + called := false + auth := regionalAuthStub{} + r := gin.New() + r.Use(RegionalAPIKeyAuth(regionalAuthAuthenticatorFunc(func(context.Context, string) (*service.APIKey, error) { + called = true + return auth.GetRegionalByKey(context.Background(), "valid") + }), &config.Config{})) + r.GET("/v1/usage/records", func(c *gin.Context) { c.Status(http.StatusNoContent) }) + req := httptest.NewRequest(http.MethodGet, "/v1/usage/records?start_time=0&end_time=1", nil) + req.Header.Set("Authorization", "Bearer valid") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, http.StatusServiceUnavailable, w.Code) + require.Contains(t, w.Body.String(), "primary site") + require.False(t, called, "regional usage records must not consult the potentially stale snapshot") +} + +type regionalAuthAuthenticatorFunc func(context.Context, string) (*service.APIKey, error) + +func (f regionalAuthAuthenticatorFunc) GetRegionalByKey(ctx context.Context, key string) (*service.APIKey, error) { + return f(ctx, key) +} + type regionalRevocationStub struct { calls int limit int diff --git a/backend/internal/server/middleware/usage_records_test.go b/backend/internal/server/middleware/usage_records_test.go new file mode 100644 index 000000000000..9f4e9df677fc --- /dev/null +++ b/backend/internal/server/middleware/usage_records_test.go @@ -0,0 +1,86 @@ +//go:build unit + +package middleware + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strconv" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestUsageRecordsReadMiddleware(t *testing.T) { + r := gin.New() + r.Use(CORS(config.CORSConfig{AllowedOrigins: []string{"https://client.example"}})) + r.Use(func(c *gin.Context) { + c.Set(string(ContextKeyAPIKey), &service.APIKey{Group: &service.Group{Platform: service.PlatformOpenAI}}) + }) + r.Use(GroupAntiDistillation(func(context.Context, *service.APIKey) (time.Duration, error) { + t.Fatal("a usage query must not consult generation admission") + return time.Minute, nil + })) + r.GET("/v1/usage/records", func(c *gin.Context) { c.Status(204) }) + for _, method := range []string{http.MethodGet, http.MethodOptions} { + req := httptest.NewRequest(method, "/v1/usage/records", nil) + req.Header.Set("Origin", "https://client.example") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, 204, w.Code) + for _, name := range []string{"X-Next-Cursor", "X-Has-More", "Retry-After", "X-Sub2api-Usage-Id", "X-Request-Id"} { + require.Contains(t, w.Header().Get("Access-Control-Expose-Headers"), name) + } + require.Contains(t, w.Header().Get("Access-Control-Allow-Headers"), "X-Goog-API-Key") + } +} + +func TestUsageRecordsUnknownKeysUseInvalidAuthAbuseGuard(t *testing.T) { + var repoCalls int + repo := &stubApiKeyRepo{getByKey: func(context.Context, string) (*service.APIKey, error) { + repoCalls++ + return nil, service.ErrAPIKeyNotFound + }} + cfg := invalidAuthAbuseTestConfig(10) + cfg.APIKeyAuth.L1Size = 100 + cfg.APIKeyAuth.NegativeTTLSeconds = 30 + svc := service.NewAPIKeyService(repo, nil, nil, nil, nil, nil, cfg) + r := gin.New() + r.Use(gin.HandlerFunc(NewAPIKeyAuthMiddleware(svc, nil, cfg))) + r.GET("/v1/usage/records", func(c *gin.Context) { t.Fatal("unknown key passed authentication") }) + for i := 0; i < 10; i++ { + req := httptest.NewRequest(http.MethodGet, "/v1/usage/records?start_time=0&end_time=1", nil) + req.RemoteAddr = "8.8.8.8:1234" + req.Header.Set("Authorization", "Bearer random-"+strconv.Itoa(i)) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, http.StatusUnauthorized, w.Code) + } + req := httptest.NewRequest(http.MethodGet, "/v1/usage/records?start_time=0&end_time=1", nil) + req.RemoteAddr = "8.8.8.8:1234" + req.Header.Set("Authorization", "Bearer random-blocked") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, http.StatusTooManyRequests, w.Code) + require.Contains(t, w.Body.String(), "INVALID_AUTH_RATE_LIMITED") + require.Equal(t, 11, repoCalls, "one ordinary cold lookup per credential and zero additional authoritative lookups") + + // Ristretto admits L1 entries asynchronously. Wait for a confirmed negative hit, + // then repeat the actual request and verify that neither lookup touches the repo. + require.Eventually(t, func() bool { + before := repoCalls + _, err := svc.GetByKey(context.Background(), "random-blocked") + return errors.Is(err, service.ErrAPIKeyNotFound) && before == repoCalls + }, time.Second, time.Millisecond) + before := repoCalls + w = httptest.NewRecorder() + r.ServeHTTP(w, req.Clone(context.Background())) + require.Equal(t, http.StatusTooManyRequests, w.Code) + require.Equal(t, before, repoCalls, "a cached miss must not reach authoritative revalidation") +} diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index 361319fc65c9..afcf33c9225f 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -103,7 +103,7 @@ func RegisterGatewayRoutes( original := groupModelAllowlist groupModelAllowlist = func(c *gin.Context) { path := c.Request.URL.Path - discovery := c.Request.Method == http.MethodGet && (strings.Contains(path, "/models") || strings.HasSuffix(path, "/usage")) + discovery := c.Request.Method == http.MethodGet && (strings.Contains(path, "/models") || strings.HasSuffix(path, "/usage") || middleware.IsGatewayUsagePath(path)) generation := (c.Request.Method == http.MethodPost && (strings.HasSuffix(path, "/responses") || strings.HasSuffix(path, "/chat/completions"))) || (c.Request.Method == http.MethodGet && strings.HasSuffix(path, "/responses")) key, ok := middleware.GetAPIKeyFromContext(c) if !discovery && (!generation || !ok || key.Group == nil || key.Group.Platform != service.PlatformOpenAI) { @@ -324,6 +324,7 @@ func RegisterGatewayRoutes( // Single-model discovery never selects the Codex client_version manifest. gateway.GET("/models/:model", h.Gateway.Models) gateway.GET("/usage", h.Gateway.Usage) + gateway.GET("/usage/records", h.UsageRecords.List) gateway.POST("/live", h.OpenAIGateway.Live) gateway.GET("/live/:call_id", h.OpenAIGateway.LiveSideband) // OpenAI Responses API: auto-route based on group platform diff --git a/backend/internal/server/routes/usage_records_test.go b/backend/internal/server/routes/usage_records_test.go new file mode 100644 index 000000000000..04ca9c3e9df5 --- /dev/null +++ b/backend/internal/server/routes/usage_records_test.go @@ -0,0 +1,282 @@ +//go:build unit + +package routes + +import ( + "context" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/handler" + ratelimit "github.com/Wei-Shaw/sub2api/internal/middleware" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "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 recordsRouteKeys struct { + keyBillingRouteAPIKeyRepo + lookups int +} + +func (r *recordsRouteKeys) GetByKeyForAuth(ctx context.Context, credential string) (*service.APIKey, error) { + r.lookups++ + return r.keyBillingRouteAPIKeyRepo.GetByKeyForAuth(ctx, credential) +} + +func (*recordsRouteKeys) UpdateLastUsed(context.Context, int64, time.Time) error { return nil } + +type recordsRouteSubscriptions struct { + service.UserSubscriptionRepository +} + +func (recordsRouteSubscriptions) GetActiveByUserIDAndGroupID(_ context.Context, userID, groupID int64) (*service.UserSubscription, error) { + return &service.UserSubscription{UserID: userID, GroupID: groupID, Status: service.StatusActive}, nil +} + +type recordsRouteLogs struct { + service.UsageLogRepository + userID, keyID int64 +} + +func (r *recordsRouteLogs) ListUsageRecords(_ context.Context, userID, keyID int64, _, _ time.Time, _ *service.UsageRecordPosition, _ int) ([]service.UsageLog, error) { + r.userID, r.keyID = userID, keyID + return nil, nil +} + +func registerRecordsRoute(t *testing.T, r *gin.Engine, keys *service.APIKeyService, subs *service.SubscriptionService, settings *service.SettingService, cfg *config.Config) *recordsRouteLogs { + t.Helper() + logs := &recordsRouteLogs{} + usage := handler.NewUsageHandler(service.NewUsageService(logs, nil, nil, nil), keys, nil, nil) + client := redis.NewClient(&redis.Options{Addr: miniredis.RunT(t).Addr()}) + t.Cleanup(func() { _ = client.Close() }) + h := &handler.Handlers{ + Gateway: &handler.GatewayHandler{}, OpenAIGateway: &handler.OpenAIGatewayHandler{}, + UsageRecords: handler.NewUsageRecordsHandler(usage, ratelimit.NewRateLimiter(client), cfg), + } + RegisterGatewayRoutes(r, h, middleware.NewAPIKeyAuthMiddleware(keys, subs, cfg), keys, subs, nil, settings, nil, cfg) + return logs +} + +// Exercise actual route ordering, authentication and regional discovery. A multi-group +// key has no group resolver in the fixture, so generation group selection cannot succeed. +func TestGatewayUsageRecordsReadOnlyAdmission(t *testing.T) { + for _, tc := range []struct { + name, status, header string + code int + }{ + {"empty balance", service.StatusActive, "Authorization", 200}, + {"expired", service.StatusAPIKeyExpired, "x-api-key", 200}, + {"exhausted", service.StatusAPIKeyQuotaExhausted, "x-goog-api-key", 200}, + {"disabled", service.StatusAPIKeyDisabled, "x-api-key", 401}, + {"missing key", service.StatusActive, "", 401}, + {"unknown key", service.StatusActive, "unknown-key", 401}, + {"deleted after warmup", service.StatusActive, "x-api-key", 401}, + {"disabled after warmup", service.StatusActive, "x-api-key", 401}, + {"owner changed after warmup", service.StatusActive, "x-api-key", 401}, + {"key replaced after warmup", service.StatusActive, "x-api-key", 401}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := &config.Config{RunMode: config.RunModeStandard, JWT: config.JWTConfig{Secret: "local-test"}} + cfg.Runtime.RegionalFundsFile = "test-discovery" + cfg.APIKeyAuth = config.APIKeyAuthCacheConfig{L1Size: 100, L1TTLSeconds: 60} + group := &service.Group{ID: 6, Status: service.StatusActive, Platform: service.PlatformOpenAI, Hydrated: true} + user := &service.User{ID: 7, Status: service.StatusActive, Role: service.RoleUser} + past := time.Now().Add(-time.Hour) + key := &service.APIKey{ID: 5, UserID: user.ID, User: user, Key: "local-records-key", Status: tc.status, + Group: group, GroupID: &group.ID, GroupIDs: []int64{group.ID, 8}, Quota: 1, QuotaUsed: 1, ExpiresAt: &past} + repo := &recordsRouteKeys{keyBillingRouteAPIKeyRepo: keyBillingRouteAPIKeyRepo{apiKey: key}} + keys := service.NewAPIKeyService(repo, nil, nil, nil, nil, nil, cfg) + r := gin.New() + logs := registerRecordsRoute(t, r, keys, nil, nil, cfg) + req := httptest.NewRequest(http.MethodGet, "/v1/usage/records?start_time=0&end_time=1&api_key_id=88&user_id=99", nil) + switch tc.header { + case "Authorization": + req.Header.Set(tc.header, "Bearer "+key.Key) + case "unknown-key": + req.Header.Set("Authorization", "Bearer deleted") + case "": + default: + req.Header.Set(tc.header, key.Key) + } + if strings.HasSuffix(tc.name, "after warmup") { + // Exercise the ordinary cached authentication path with the same credential. + warm := gin.New() + warm.GET("/v1/usage", gin.HandlerFunc(middleware.NewAPIKeyAuthMiddleware(keys, nil, cfg)), func(c *gin.Context) { c.Status(204) }) + require.Eventually(t, func() bool { + before := repo.lookups + w := httptest.NewRecorder() + warmReq := httptest.NewRequest(http.MethodGet, "/v1/usage", nil) + warmReq.Header.Set(tc.header, key.Key) + warm.ServeHTTP(w, warmReq) + return w.Code == 204 && repo.lookups == before + }, time.Second, time.Millisecond) + w := httptest.NewRecorder() + before := repo.lookups + r.ServeHTTP(w, req.Clone(context.Background())) + require.Equal(t, 200, w.Code) + require.Equal(t, before+1, repo.lookups, "one authoritative lookup after a cache hit") + logs.keyID = 0 + // Another instance changes the credential without notifying this instance's L1. + switch tc.name { + case "deleted after warmup": + repo.apiKey = nil + case "disabled after warmup": + repo.apiKey.Status = service.StatusAPIKeyDisabled + case "owner changed after warmup": + repo.apiKey.UserID = 42 + repo.apiKey.User = &service.User{ID: 42, Status: service.StatusActive, Role: service.RoleUser} + case "key replaced after warmup": + repo.apiKey.ID++ + } + stale, err := keys.GetByKey(context.Background(), key.Key) + require.NoError(t, err) + require.Equal(t, service.StatusActive, stale.Status) + require.Equal(t, int64(5), stale.ID) + require.Equal(t, user.ID, stale.UserID) + } + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, tc.code, w.Code, w.Body.String()) + if tc.code == 200 { + require.Equal(t, user.ID, logs.userID) + require.Equal(t, key.ID, logs.keyID) + require.Contains(t, w.Body.String(), `"data":[]`) + } else { + require.Zero(t, logs.keyID) + if strings.HasSuffix(tc.name, "after warmup") { + wantBody := `{"code":"INVALID_API_KEY","message":"Invalid API key"}` + if tc.name == "disabled after warmup" { + wantBody = `{"code":"API_KEY_DISABLED","message":"API key is disabled"}` + } + require.JSONEq(t, wantBody, w.Body.String()) + } + } + }) + } +} + +func TestGatewayUsageRecordsAuthoritativeAdmission(t *testing.T) { + newKey := func() *service.APIKey { + group := &service.Group{ID: 6, Hydrated: true, Platform: service.PlatformOpenAI, Status: service.StatusActive} + user := &service.User{ID: 7, Status: service.StatusActive, Role: service.RoleAdmin, Concurrency: 1} + return &service.APIKey{ID: 5, Key: "local-records-key", Name: "cached", Status: service.StatusActive, UserID: user.ID, User: user, GroupID: &group.ID, Group: group} + } + unassign := func(k *service.APIKey) { k.GroupID, k.Group = nil, nil } + restrict := func(k *service.APIKey) { k.Group.CodexCLIOnly = true } + subscribe := func(k *service.APIKey) { k.Group.SubscriptionType = service.SubscriptionTypeSubscription } + rebindSubscription := func(k *service.APIKey) { + subscribe(k) + k.Group.ID = 12 + k.GroupID = &k.Group.ID + } + denyIP := func(k *service.APIKey) { k.IPBlacklist = []string{"192.0.2.1"} } + disable := func(k *service.APIKey) { k.Status = service.StatusAPIKeyDisabled } + for _, tc := range []struct { + name string + cached, current func(*service.APIKey) + allowUngrouped bool + simpleMode bool + rejection middleware.IngressRejectReason + }{ + {name: "unassigned while ungrouped keys forbidden", current: unassign, rejection: middleware.IngressRejectGroupUnassigned}, + {name: "Codex restriction enabled", current: restrict, rejection: middleware.IngressRejectCodexClientRequired}, + {name: "Codex restriction lifted", cached: restrict}, + {name: "subscription group assigned", current: subscribe}, + {name: "subscription group changed", cached: subscribe, current: rebindSubscription}, + {name: "subscription group removed while ungrouped keys allowed", cached: subscribe, current: unassign, allowUngrouped: true}, + {name: "simple mode uses current identity", cached: restrict, current: subscribe, simpleMode: true}, + {name: "client IP newly denied", current: denyIP, rejection: middleware.IngressRejectIPRestricted}, + {name: "client IP allowed again", cached: denyIP}, + {name: "key enabled again", cached: disable}, + } { + t.Run(tc.name, func(t *testing.T) { + cached, current := newKey(), newKey() + if tc.cached != nil { + tc.cached(cached) + } + if tc.current != nil { + tc.current(current) + } + current.Name, current.User.Role, current.User.Concurrency = "current", service.RoleUser, 8 + current.ConcurrencyLimit = 2 + cfg := &config.Config{RunMode: config.RunModeStandard, APIKeyAuth: config.APIKeyAuthCacheConfig{L1Size: 100, L1TTLSeconds: 60}} + if tc.simpleMode { + cfg.RunMode = config.RunModeSimple + } + repo := &recordsRouteKeys{keyBillingRouteAPIKeyRepo: keyBillingRouteAPIKeyRepo{apiKey: cached}} + keys := service.NewAPIKeyService(repo, nil, nil, nil, nil, nil, cfg) + settings := service.NewSettingService(&channelMonitorRouteSettingRepoStub{values: map[string]string{ + service.SettingKeyAllowUngroupedKeyScheduling: strconv.FormatBool(tc.allowUngrouped), + }}, cfg) + subs := service.NewSubscriptionService(nil, recordsRouteSubscriptions{}, nil, nil, cfg) + t.Cleanup(subs.Stop) + r := gin.New() + var observed *gin.Context + r.Use(func(c *gin.Context) { c.Next(); observed = c.Copy() }) + logs := registerRecordsRoute(t, r, keys, subs, settings, cfg) + + require.Eventually(t, func() bool { + before := repo.lookups + _, err := keys.GetByKey(context.Background(), cached.Key) + return err == nil && repo.lookups == before + }, time.Second, time.Millisecond) + repo.apiKey = current + before := repo.lookups + stale, err := keys.GetByKey(context.Background(), cached.Key) + require.NoError(t, err) + require.Equal(t, cached.Name, stale.Name) + require.Equal(t, before, repo.lookups) + + req := httptest.NewRequest(http.MethodGet, "/v1/usage/records?start_time=0&end_time=1", nil) + req.RemoteAddr = "192.0.2.1:1234" + req.Header.Set("x-api-key", current.Key) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, before+1, repo.lookups, "exactly one primary lookup after the L1 hit") + fallback, ok := middleware.GetOpsFallbackAPIKey(observed) + require.True(t, ok) + require.Equal(t, current.Name, fallback.Name) + if tc.rejection != "" { + require.Equal(t, http.StatusForbidden, w.Code, w.Body.String()) + reason, rejected := middleware.GetIngressRejectReason(observed) + require.True(t, rejected) + require.Equal(t, tc.rejection, reason) + require.Zero(t, logs.keyID) + return + } + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + require.Equal(t, current.ID, logs.keyID) + require.Equal(t, current.UserID, logs.userID) + key, ok := middleware.GetAPIKeyFromContext(observed) + require.True(t, ok) + require.Same(t, fallback, key) + subject, ok := middleware.GetAuthSubjectFromContext(observed) + require.True(t, ok) + require.Equal(t, middleware.AuthSubject{UserID: current.UserID, Concurrency: current.User.Concurrency}, subject) + role, ok := middleware.GetUserRoleFromContext(observed) + require.True(t, ok) + require.Equal(t, current.User.Role, role) + ctx := observed.Request.Context() + require.Equal(t, current.UserID, ctx.Value(ctxkey.UserID)) + require.True(t, service.HasAPIKeyQueueAuthRevalidator(ctx)) + group, _ := ctx.Value(ctxkey.Group).(*service.Group) + require.Equal(t, current.Group, group) + subscription, hasSubscription := middleware.GetSubscriptionFromContext(observed) + require.Equal(t, !tc.simpleMode && current.Group != nil && current.Group.IsSubscriptionType(), hasSubscription) + if hasSubscription { + require.Equal(t, current.Group.ID, subscription.GroupID) + require.Equal(t, current.UserID, subscription.UserID) + } + }) + } +} diff --git a/backend/internal/service/setting_public.go b/backend/internal/service/setting_public.go index c7ee69492574..d1e686e3ffd8 100644 --- a/backend/internal/service/setting_public.go +++ b/backend/internal/service/setting_public.go @@ -619,6 +619,14 @@ func (s *SettingService) IsUserUpstreamResponseModelVisible(ctx context.Context) return vals[SettingKeyUsageShowUpstreamResponseModelToUsers] == "true" } +func (s *SettingService) IsUserUsageCacheRateVisible(ctx context.Context) bool { + if s == nil || s.settingRepo == nil { + return false + } + vals, err := s.settingRepo.GetMultiple(ctx, []string{SettingKeyUsageShowCacheRate, SettingKeyUsageShowCacheRateToUsers}) + return err == nil && vals[SettingKeyUsageShowCacheRate] != "false" && vals[SettingKeyUsageShowCacheRateToUsers] == "true" +} + // PublicSettingsInjectionPayload is the JSON shape embedded into HTML as // `window.__APP_CONFIG__` so the frontend can hydrate feature flags & site // config before the first XHR finishes. diff --git a/backend/internal/service/usage_records.go b/backend/internal/service/usage_records.go new file mode 100644 index 000000000000..f354480a4024 --- /dev/null +++ b/backend/internal/service/usage_records.go @@ -0,0 +1,26 @@ +package service + +import ( + "context" + "errors" + "time" +) + +// UsageRecordPosition is the exclusive lower bound for a subsequent page. +type UsageRecordPosition struct { + CreatedAt time.Time + ID int64 +} + +// UsageRecordsReader is intentionally separate from the aggregate/panel queries. +type UsageRecordsReader interface { + ListUsageRecords(ctx context.Context, userID, keyID int64, start, end time.Time, after *UsageRecordPosition, limit int) ([]UsageLog, error) +} + +func (s *UsageService) ListUsageRecords(ctx context.Context, userID, keyID int64, start, end time.Time, after *UsageRecordPosition, limit int) ([]UsageLog, error) { + reader, ok := s.usageRepo.(UsageRecordsReader) + if !ok { + return nil, errors.New("usage record reader unavailable") + } + return reader.ListUsageRecords(ctx, userID, keyID, start, end, after, limit) +} diff --git a/docs/api-key-usage-date-range.md b/docs/api-key-usage-date-range.md index 80599c666ab2..688b7c5928fd 100644 --- a/docs/api-key-usage-date-range.md +++ b/docs/api-key-usage-date-range.md @@ -30,3 +30,5 @@ `GET /api/v1/keys` 支持 `sort_by=usage&sort_order=desc`,并接收相同的 `start_date`、`end_date`、`timezone` 参数,在分页前按该时段的 `actual_cost` 总和排序。未指定 `sort_order` 时使用降序,没有使用记录的 Key 按零处理。不传日期时使用滚动 30 天;未指定 `sort_by` 的旧客户端保持原有的创建时间排序。 管理员日期选择旁登记的新功能提示 ID 为 `api-key-usage-date-range-initial-announcement`,关闭状态沿用按管理员、按浏览器保存的提示机制。 + +需要用脚本按小时导入逐条记录时,使用网关的 API Key 明细查询。 [逐条用量 API](usage-records-api.md) diff --git a/docs/usage-records-api.md b/docs/usage-records-api.md new file mode 100644 index 000000000000..650d592a5885 --- /dev/null +++ b/docs/usage-records-api.md @@ -0,0 +1,99 @@ +# 用 API Key 按时间段读取用量明细 + +在用户面板的“使用记录”打开“用量 API”,可复制本站完整地址,curl 和可运行的 Python 3 示例。每把 Key 只能读取归属于这把 Key **且属于其当前用户**的记录。每行的 `id` 用于去重,`request_id` 用于关联原请求。查询免费。 + +## 请求和分页 + +`GET /v1/usage/records` 支持 `Authorization: Bearer sk-...`,`x-api-key` 和 `x-goog-api-key` 请求头。沿用网关的 Key,用户,IP 和分组访问规则。余额不足,额度耗尽或 Key 到期后仍可查询,已删除或停用的 Key 会被拒绝。 + +| 参数 | 规则 | +| --- | --- | +| `start_time` | 必填,包含此时刻。使用带 `Z` 或明确时区偏移的 RFC3339 时间(小数秒最多 9 位),或整数 Unix 秒。 | +| `end_time` | 必填,不含此时刻。原始终点须晚于起点。先将未来终点截到服务器当前时间,再校验有效跨度最多 7 × 24 小时。全在未来时返回空页,起止时间均等于服务器当前时间。 | +| `limit` | 每页 1 到 1000 条,默认 500。 | +| `cursor` | 首页省略。后续页原样传回上一页给出的游标,使用同一把 Key、同一时间窗和同一格式。 | +| `format` | 默认 `json`,或使用 `csv`。 | + +```bash +curl -sS --fail-with-body -G "$SUB2API_BASE/v1/usage/records" \ + -H "Authorization: Bearer $SUB2API_KEY" \ + --data-urlencode 'start_time=2026-11-20T13:00:00+08:00' \ + --data-urlencode 'end_time=2026-11-20T14:00:00+08:00' +``` + +`SUB2API_BASE` 填站点网关根地址。`--data-urlencode` 会保留偏移量里的加号。数据按 `(created_at, id)` 升序返回。第一页固定实际终点,后续页沿用原始参数或响应中的 UTC 起止时间。 + +```json +{ + "object": "list", + "data": [{ + "id": 42, "request_id": "client:example", "created_at": "2026-11-20T05:12:00.123456Z", + "model": "example-model", "request_type": "stream", "stream": true, + "input_tokens": 120, "output_tokens": 30, "cache_read_tokens": 0, "cache_creation_tokens": 0, + "image_count": 0, "total_cost": 0.002, "actual_cost": 0.001, "rate_multiplier": 0.5, + "duration_ms": 730, "first_token_ms": 95 + }], + "has_more": false, "next_cursor": null, + "start_time": "2026-11-20T05:00:00Z", "end_time": "2026-11-20T06:00:00Z" +} +``` + +`model` 是用户面板展示的模型,历史行沿用面板的回退规则。`total_cost` 为标准价,`actual_cost` 为用户用量行的实际计费金额,金额单位为 USD。订阅消费和简易模式按各自的记账规则处理。`rate_multiplier` 为该行的倍率快照。`duration_ms` 和 `first_token_ms` 缺少测量值时为 `null`。可选字段有 `reasoning_effort`,`inbound_endpoint`,`ip_address`,`billing_mode`。管理员允许用户查看上游响应模型且有值时,另有 `upstream_response_model`。 + +每把 Key 每分钟最多 60 次,同一用户的所有 Key 合计每分钟最多 120 次,翻页也计次。429 错误消息区分 Key 级和用户级。 参数或游标无效时返回 `400`,鉴权或访问被拒绝时返回 `401` 或 `403`,超限时返回 `429` 及 `Retry-After` 秒数。查询或限流存储暂时不可用时返回 `503`。参数错误响应形如 `{"type":"error","error":{"type":"invalid_request_error","message":"..."}}`。鉴权失败沿用对应网关中间件的错误体。 + +## CSV + +为同一请求添加 `--data-urlencode 'format=csv' -D usage.headers -o usage.csv`。每页是完整的 UTF-8 BOM CSV。响应头 `X-Has-More: true` 表示还有下一页,用 `X-Next-Cursor` 的值继续请求。末页返回 `X-Has-More: false` 并省略游标头。合并多页时逐页按 `utf-8-sig` 解码并只保留一行表头。 + +列名及顺序与用户面板 CSV 一致,金额按面板的 `toFixed(8)` 舍入。 方括号中的两列由首页的可见性开关决定,布局写入签名游标。后续开放的列留到下次导出。原可见列关闭或其权限读取失败时返回 `409`,请丢弃本轮部分 CSV,用同一窗口从首页重读。 + +```text +Time, API Key Name, Model, [Upstream Response Model], Reasoning Effort, +Inbound Endpoint, IP Address, Type, Billing Mode, Input Tokens, Output Tokens, +Cache Read Tokens, Cache Creation Tokens, [Cache Rate], Rate Multiplier, +Billed Cost, Original Cost, First Token (ms), Duration (ms) +``` + +`Billing Mode` 默认使用英文,`Accept-Language: zh` 对应中文面板的单元格值。需要 `id`,`request_id` 或图片数时选 JSON。 + +中文计费模式逐字沿用 `frontend/src/i18n/locales/zh/admin/resources.ts` 的值,包括 `按量`、`按次`、`按次(图片)` 和 `按次(视频)`。 + +启用区域鉴权快照的节点返回 HTTP 503,错误码为 `REGIONAL_USAGE_RECORDS_UNAVAILABLE`。仅启用区域调度预览的节点返回通用 HTTP 503。这两种情况请使用主站地址查询。沿用主库鉴权的区域资金模式可以正常查询。 + +## 每小时对账 + +[可运行的 Python 3 示例](../frontend/src/components/usage/usage_records.py) 使用标准库。建议每小时第 10 分钟运行,定时任务使用固定的 SQLite 路径。 + +| 环境变量 | 说明 | +| --- | --- | +| `SUB2API_USAGE_URL` | 独立脚本必填,填本站最终完整 HTTPS 地址,包含 `/v1/usage/records`。页签复制的脚本已填入本站默认地址。所有重定向都会中止导入。 | +| `SUB2API_KEY` | 必填,填要对账的 API Key。水位按完整端点地址和 Key 的 SHA-256 指纹隔离,水位表只保存指纹。 | +| `SUB2API_USAGE_DB` | SQLite 文件路径,默认是当前目录下的 `usage-records.sqlite3`。已有记录继续按站点和行 id 去重。 | +| `SUB2API_USAGE_OVERLAP_HOURS` | 非负整数,默认 2 小时。已有完整导入水位时从水位减去该时长开始。 | +| `SUB2API_USAGE_START` | 可选整数 Unix 秒,指定该站点和 Key 首次建档时的起点,默认当前 UTC 整点往前 1 小时。 | + +- 首次在 14:10 UTC 运行时读取 `[13:00, 14:00)`。若 15:10 漏跑,16:10 从 14:00 水位向前重叠 2 小时,读取 `[12:00, 16:00)`。跨度超过 7 天时自动拆成相邻的半开窗口。每段读完末页后,水位与末页一起提交。中途退出会从上个完整水位恢复。 +- 翻页期间才入库、排序位置早于当前游标的记录,本轮后续页会跳过。补拉时以同一窗口从首页重读,省略 `cursor`,并按 `id` 去重。遇到较长的计费积压,请重读所有受影响的小时。 +- 普通请求在转发结束后构建计费行时写 `created_at`。长流可以跨小时。异步队列可能推迟构建或落库,#559 恢复已暂存的计费事件时沿用原时间,较早的行可在翻页经过该位置后才出现。Live 会话在关闭时写入会话开始时间,批量图片使用结算时刻。没有固定的最迟入库时间,短重叠窗口只覆盖日常延迟。 +- 只查询已持久化的 `usage_logs`。未写用量行的转发失败,未计量请求及单纯的错误日志均不出现。已写入的零费用行仍然出现,包括免费 Live 会话和部分策略拒绝。简易模式也可只记录用量。 +- 普通持久化计费在同一事务确认扣费和用量行,恢复重试沿用同一事件。`actual_cost` 和 `total_cost` 保存该行金额。退款和冻结余额释放单独记账。面板 `settled-debits` 读取已确认的钱包扣款凭证,不回写用量行。因此本接口适合请求成本对账,计算钱包现金流需另取钱包凭证。 +- 历史长度受后台“请求日志保留天数”控制。设为 0 时跳过按天自动清理。已被保留策略或手动清理删除的记录查不到。 + +## 将一行对应到自己的请求 + +同时保存响应头 `X-Sub2api-Usage-Id` 和 `X-Request-Id`,任一值匹配 `request_id` 即可对账。普通 HTTP 转发使用生成请求响应头 `X-Sub2api-Usage-Id`,按原值匹配 `request_id`。该值为 `client:` 加响应头 `X-Client-Request-ID`。Claude,Gemini 原生生成和 Antigravity 普通生成均沿用此次请求的上下文。收到头后仍需等到用量行写入。 + +| 路径或计费模式 | 对账标识 | +| --- | --- | +| 普通同步图片,`/v1/images/{generations,edits}/async` | 异步任务保留提交时的上下文。保存提交响应的用量 ID。轮询头只标识本次查询。 | +| OpenAI Responses WebSocket,含 HTTP 入口经 WebSocket 桥转发 | 上游提供轮次响应 ID 时优先以它记账,可从对应响应事件保存该 ID。一个握手可包含多轮。 | +| OpenAI HTTP 因 `cyber_policy` 失败且写入用量行 | 该行使用 `X-Request-Id`,缺少该头时使用本地请求 ID。 | +| OpenAI Live | 会话关闭时以通话哈希记一行。 | +| 批量图片 | 使用 `batch_image_capture:`。 | +| 独立网页搜索,Grok 音频和实时会话 | 使用 `web_search:`,`grok_audio:`,`grok_realtime:` 操作 ID。普通生成中附带的搜索沿用该生成请求的计费路径。 | +| 异步视频 | 视频计费使用稳定的 `grok-video:` 形式,保存任务 ID。 | +| Gemini 显式缓存 | 创建和延长存储的费用分别使用 `gcache:create:`,`gcache:patch:` 操作 ID。 | +| 区域资金计量 | 使用账本的独立事件 ID 和完成时间。 | + +少数历史或内部任务缺少客户端上下文,可使用 `local:`,上游原值或 `generated:`。当响应没有提供对应操作标识时,使用记录 ID 去重,保留原始任务 ID,UTC 时间,模型和用量供核对。 diff --git a/frontend/src/api/usage.ts b/frontend/src/api/usage.ts index 255489d9cd1f..5702325e8d21 100644 --- a/frontend/src/api/usage.ts +++ b/frontend/src/api/usage.ts @@ -363,9 +363,11 @@ export async function getDashboardApiKeysUsage( } export async function listMyErrorRequests( - params: UserErrorListParams + params: UserErrorListParams, + config: { signal?: AbortSignal } = {} ): Promise> { const { data } = await apiClient.get>('/usage/errors', { + ...config, params }) return data diff --git a/frontend/src/components/common/__tests__/NewFeatureBadge.spec.ts b/frontend/src/components/common/__tests__/NewFeatureBadge.spec.ts index 39983fd117ed..d2b2ac319ada 100644 --- a/frontend/src/components/common/__tests__/NewFeatureBadge.spec.ts +++ b/frontend/src/components/common/__tests__/NewFeatureBadge.spec.ts @@ -28,6 +28,7 @@ describe('NewFeatureBadge', () => { ['image usage billing', NEW_FEATURE_NOTICES.imageUsageBilling], ['channel UltraFast pricing', NEW_FEATURE_NOTICES.channelUltrafastPricing], ['user live load', NEW_FEATURE_NOTICES.userLiveLoad], + ['usage records API', NEW_FEATURE_NOTICES.usageRecordsApi], ['Free UltraFast', NEW_FEATURE_NOTICES.groupFreeUltrafast], ['force UltraFast', NEW_FEATURE_NOTICES.groupForceUltrafast], ['passthrough model filter', NEW_FEATURE_NOTICES.passthroughModelFilter], diff --git a/frontend/src/components/usage/UsageApiGuide.vue b/frontend/src/components/usage/UsageApiGuide.vue new file mode 100644 index 000000000000..0fc79035fc52 --- /dev/null +++ b/frontend/src/components/usage/UsageApiGuide.vue @@ -0,0 +1,91 @@ + + + diff --git a/frontend/src/components/usage/__tests__/UsageApiGuide.spec.ts b/frontend/src/components/usage/__tests__/UsageApiGuide.spec.ts new file mode 100644 index 000000000000..ee9945eb3d7f --- /dev/null +++ b/frontend/src/components/usage/__tests__/UsageApiGuide.spec.ts @@ -0,0 +1,44 @@ +import { mount } from '@vue/test-utils' +import { createI18n } from 'vue-i18n' +import { describe, expect, it, vi } from 'vitest' +import en from '@/i18n/locales/en/usageApi' +import zh from '@/i18n/locales/zh/usageApi' +import UsageApiGuide from '../UsageApiGuide.vue' + +const { settings, copy } = vi.hoisted(() => ({ settings: { api_base_url: '' }, copy: vi.fn() })) +vi.mock('@/stores/app', () => ({ useAppStore: () => ({ cachedPublicSettings: settings }) })) +vi.mock('@/composables/useClipboard', () => ({ useClipboard: () => ({ copyToClipboard: copy }) })) + +describe('UsageApiGuide', () => { + it.each([ + ['en', 'https://api.example/relay/v1/', 'https://api.example/relay/v1/usage/records'], + ['zh', '', window.location.origin + '/v1/usage/records'], + ])('renders and copies the localized examples (%s)', async (locale, base, endpoint) => { + settings.api_base_url = base + copy.mockClear() + const i18n = createI18n({ legacy: false, locale, messages: { + en: { usageApi: en, common: { copy: 'Copy' } }, zh: { usageApi: zh, common: { copy: '复制' } }, + } }) + const wrapper = mount(UsageApiGuide, { global: { plugins: [i18n] } }) + expect(wrapper.text()).toContain(locale === 'en' ? en.intro : zh.intro) + expect(wrapper.text()).not.toContain('usageApi.') + expect(wrapper.get('article > div code').text()).toBe('GET ' + endpoint) + expect(wrapper.findAll('tbody th').map(cell => cell.text())).toEqual(['start_time', 'end_time', 'limit', 'cursor', 'format']) + for (const text of ['X-Request-Id', 'X-Sub2api-Usage-Id', 'cyber_policy', '60', '120', '409', 'SUB2API_USAGE_OVERLAP_HOURS']) { + expect(wrapper.text()).toContain(text) + } + const examples = wrapper.findAll('pre code').map(el => el.element.textContent) + const buttons = wrapper.findAll('button') + expect(buttons).toHaveLength(4) + for (const [index, button] of buttons.entries()) { + await button.trigger('click') + expect(copy).toHaveBeenLastCalledWith(examples[index]) + } + expect(examples[0]).toContain(endpoint) + expect(JSON.parse(examples[1]!)).toMatchObject({ object: 'list', next_cursor: null, data: [{ id: 42 }] }) + expect(examples[2]).toContain('format=csv') + expect(examples[3]).toContain(endpoint) + expect(examples[3]).toContain('page["next_cursor"]') + wrapper.unmount() + }) +}) diff --git a/frontend/src/components/usage/usage_records.py b/frontend/src/components/usage/usage_records.py new file mode 100644 index 000000000000..f0e0ce48dad4 --- /dev/null +++ b/frontend/src/components/usage/usage_records.py @@ -0,0 +1,87 @@ +import hashlib +import json +import os +import sqlite3 +import time +from contextlib import closing +from datetime import datetime, timezone +from urllib.error import HTTPError +from urllib.parse import urlencode +from urllib.request import HTTPRedirectHandler, Request, build_opener + +REDIRECT_ERROR = "请把 SUB2API_USAGE_URL 配成最终的 HTTPS 地址" + + +class RejectRedirects(HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + fp.close() + raise SystemExit(REDIRECT_ERROR) + + +def get_page(opener, endpoint, key, params): + request = Request(endpoint + "?" + urlencode(params), + headers={"Authorization": "Bearer " + key}) + while True: + try: + with opener.open(request, timeout=30) as response: + return json.load(response) + except HTTPError as exc: + with exc: + if 300 <= exc.code < 400: + raise SystemExit(REDIRECT_ERROR) from exc + if exc.code != 429: + raise + wait = int(exc.headers.get("Retry-After", "60")) + time.sleep(wait) + + +def import_records(db, endpoint, key, end): + hour = 3600 + overlap = int(os.environ.get("SUB2API_USAGE_OVERLAP_HOURS", "2")) * hour + if overlap < 0: + raise ValueError("SUB2API_USAGE_OVERLAP_HOURS must be nonnegative") + scope = (endpoint, hashlib.sha256(key.encode()).hexdigest()) + opener = build_opener(RejectRedirects()) + db.execute("""CREATE TABLE IF NOT EXISTS usage_records ( + endpoint TEXT, id INTEGER, record TEXT NOT NULL, PRIMARY KEY (endpoint, id) + )""") + db.execute("""CREATE TABLE IF NOT EXISTS usage_imports ( + endpoint TEXT, key_fingerprint TEXT, first_start INTEGER NOT NULL, + complete_until INTEGER, PRIMARY KEY (endpoint, key_fingerprint) + )""") + with db: + # Keep the first window recoverable even if the very first run fails. + first_start = int(os.environ.get("SUB2API_USAGE_START", end - hour)) + db.execute("INSERT OR IGNORE INTO usage_imports VALUES (?, ?, ?, NULL)", + (*scope, first_start)) + first_start, complete = db.execute( + "SELECT first_start, complete_until FROM usage_imports WHERE endpoint=? AND key_fingerprint=?", + scope).fetchone() + start = first_start if complete is None else complete - overlap + while start < end: + stop = min(start + 7 * 24 * hour, end) + params = {"start_time": start, "end_time": stop, "limit": 500} + while True: + page = get_page(opener, endpoint, key, params) + with db: + db.executemany("INSERT OR IGNORE INTO usage_records VALUES (?, ?, ?)", + [(endpoint, row["id"], json.dumps(row)) for row in page["data"]]) + if not page["has_more"]: + # Commit the last page and watermark together. Overlapping jobs + # may finish out of order, so only advance a previous watermark. + db.execute("""UPDATE usage_imports SET complete_until=? + WHERE endpoint=? AND key_fingerprint=? + AND (complete_until IS NULL OR complete_until < ?)""", (stop, *scope, stop)) + break + params["cursor"] = page["next_cursor"] + if not params["cursor"]: + raise ValueError("Missing next_cursor on a non-final page") + start = stop + + +if __name__ == "__main__": + endpoint = os.environ["SUB2API_USAGE_URL"] + key = os.environ["SUB2API_KEY"] + end = datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0) + with closing(sqlite3.connect(os.environ.get("SUB2API_USAGE_DB", "usage-records.sqlite3"))) as db: + import_records(db, endpoint, key, int(end.timestamp())) diff --git a/frontend/src/constants/newFeatureNotices.ts b/frontend/src/constants/newFeatureNotices.ts index 03ada7d0986e..fab11801e6ec 100644 --- a/frontend/src/constants/newFeatureNotices.ts +++ b/frontend/src/constants/newFeatureNotices.ts @@ -71,6 +71,7 @@ export const NEW_FEATURE_NOTICES = { apiKeyModelPolicy: 'api-key-model-policy-initial-announcement', apiKeyLongContext: 'api-key-long-context-control-initial-announcement', apiKeyContextTokenLimit: 'api-key-context-token-limit-initial-announcement', + usageRecordsApi: 'usage-records-api-initial-announcement', apiKeyUsageDateRange: 'api-key-usage-date-range-initial-announcement', providerProfit: 'profit-operations-provider-reconciliation', profitOperationsToday: 'profit-operations-today-filter-initial-announcement', diff --git a/frontend/src/i18n/locales/en/index.ts b/frontend/src/i18n/locales/en/index.ts index 99a9498f7bc9..f4c415a8d13d 100644 --- a/frontend/src/i18n/locales/en/index.ts +++ b/frontend/src/i18n/locales/en/index.ts @@ -15,6 +15,7 @@ import upstreamOps from './upstreamOps' import channelOps from './channelOps' import ipAudit from './ipAudit' import traffic from './traffic' +import usageApi from './usageApi' import connections from './connections' import securityRecords from './securityRecords' import siwc from './siwc' @@ -57,6 +58,7 @@ export default { openaiAuth, upstreamEntities, traffic, + usageApi, ipAudit, connections, securityRecords, diff --git a/frontend/src/i18n/locales/en/usageApi.ts b/frontend/src/i18n/locales/en/usageApi.ts new file mode 100644 index 000000000000..e537d96af234 --- /dev/null +++ b/frontend/src/i18n/locales/en/usageApi.ts @@ -0,0 +1,28 @@ +export default { + title: 'Usage API', + intro: 'Reconcile each request automatically. Fetch the usage and billed cost recorded for this API key in a time window.', + auth: 'Set SUB2API_KEY to your API key. Send Authorization: Bearer sk-..., x-api-key or x-goog-api-key in a request header.', + parameters: 'Query parameters', + name: 'Parameter', + description: 'Description', + params: { + start_time: 'Required. Inclusive start, as Unix seconds or an RFC3339 timestamp with Z or an explicit offset and up to 9 fractional digits.', + end_time: 'Required. Exclusive end, later than start_time. Future times are capped at the current time before checking the 7-day maximum. A wholly future window returns an empty page with equal UTC bounds.', + limit: 'Records per page, 1 to 1000. Default 500.', + cursor: 'For the next page, send next_cursor with the same key and window. Omit on the first page. Rows are ordered by created_at, then id.', + format: 'json (default) or csv.', + }, + examples: { curl: 'Fetch the last complete hour', json: 'JSON response', csv: 'Download one CSV page', python: 'Hourly import in Python 3' }, + csvHelp: 'Each page has a UTF-8 BOM and the dashboard’s English column headers. The first page fixes the response-model and cache-rate columns for that cursor. If visibility is reduced, HTTP 409 means discard the partial CSV and restart from page one. Keep format=csv and send X-Next-Cursor while X-Has-More is true. Keep one header when merging pages. Set Accept-Language: zh for Chinese billing labels. Use JSON for id and request_id.', + pythonHelp: 'Set SUB2API_KEY and schedule the script at 10 minutes past each hour using the same SQLite file. The first run imports the last complete UTC hour. Later runs start 2 hours before the last completed endpoint for this site and key, catch up in windows of up to 7 days, and deduplicate by id. Set SUB2API_USAGE_OVERLAP_HOURS to change the overlap or SUB2API_USAGE_START (Unix seconds) to choose the first start. Set SUB2API_USAGE_URL to the final HTTPS endpoint. Redirects stop the import.', + matchTitle: 'Match a request to your records', + match: 'Save both X-Sub2api-Usage-Id and X-Request-Id from the gateway response and compare request_id with either value. Ordinary HTTP generation, including Claude, Gemini and Antigravity, uses X-Sub2api-Usage-Id (client: followed by X-Client-Request-ID). An OpenAI HTTP cyber_policy failure that writes a usage row uses X-Request-Id or the local request ID. For async images, save the submission headers. Polls have their own IDs.', + exceptions: 'Responses WebSocket turns, including HTTP calls bridged to WebSocket, can use the upstream response ID. Live uses the call hash. Batch images, standalone web search, explicit Gemini cache charges, Grok audio/realtime and async video use operation, session or task IDs. Regional metering uses a ledger event ID. Save the corresponding result or task identifier when available.', + reconcileTitle: 'Hourly reconciliation', + availability: 'The query is free. Each key can make 60 requests per minute. All keys of a user share a limit of 120 requests per minute, including pagination. HTTP 429 identifies the limit reached. Wait the Retry-After number of seconds.', + regional: 'Nodes using regional authentication snapshots return HTTP 503 with the code REGIONAL_USAGE_RECORDS_UNAVAILABLE. Nodes using only the regional scheduler preview return a generic HTTP 503. Use the primary site in either case. Regional funds mode supports this query when it authenticates against the primary database.', + delays: 'Ordinary created_at is assigned when usage is prepared after forwarding. Long streams can fall in a later hour. Queued writes and billing recovery can make earlier records appear later. Live sessions use their start time.', + overlap: 'A late row with a position earlier than the cursor is skipped for the rest of that pass. To backfill, re-read the same window from page one without a cursor and deduplicate by id. After a backlog, re-read all affected hours, even those outside the regular overlap.', + settlement: 'Only persisted usage rows appear. An ordinary failed or unmetered attempt with no row is absent. Recorded free sessions and some policy rejections can have zero cost. total_cost is the standard price and actual_cost is the recorded billed amount. Simple mode can record usage without a debit. Ordinary refunds and wallet settlement evidence do not revise the row amounts.', + retention: 'The administrator’s request-log retention controls available history. Once a row has been cleaned up it is unavailable here. Keep your own copy for longer reconciliation periods.', +} diff --git a/frontend/src/i18n/locales/zh/index.ts b/frontend/src/i18n/locales/zh/index.ts index 99a9498f7bc9..f4c415a8d13d 100644 --- a/frontend/src/i18n/locales/zh/index.ts +++ b/frontend/src/i18n/locales/zh/index.ts @@ -15,6 +15,7 @@ import upstreamOps from './upstreamOps' import channelOps from './channelOps' import ipAudit from './ipAudit' import traffic from './traffic' +import usageApi from './usageApi' import connections from './connections' import securityRecords from './securityRecords' import siwc from './siwc' @@ -57,6 +58,7 @@ export default { openaiAuth, upstreamEntities, traffic, + usageApi, ipAudit, connections, securityRecords, diff --git a/frontend/src/i18n/locales/zh/usageApi.ts b/frontend/src/i18n/locales/zh/usageApi.ts new file mode 100644 index 000000000000..e81289655b65 --- /dev/null +++ b/frontend/src/i18n/locales/zh/usageApi.ts @@ -0,0 +1,28 @@ +export default { + title: '用量 API', + intro: '按时间段拉取当前 API Key 的逐条用量和扣费,用于自动对账。', + auth: '将 API Key 写入环境变量 SUB2API_KEY。请求头支持 Authorization: Bearer sk-...、x-api-key 或 x-goog-api-key。', + parameters: '查询参数', + name: '参数', + description: '说明', + params: { + start_time: '必填,包含起点。支持整数 Unix 秒或带 Z 或时区偏移的 RFC3339 时间,小数秒最多 9 位。', + end_time: '必填,不含终点。终点须晚于 start_time,未来终点先截到当前时间,再校验有效跨度是否超过 7 天。窗口全在未来时返回空页,起止时间相同。响应时间统一为 UTC。', + limit: '每页 1 到 1000 条,默认 500 条。', + cursor: '首页省略。下一页使用上页的 next_cursor,沿用同一把 Key、同一格式和时间段。结果按 created_at 和 id 升序排列。', + format: 'json(默认)或 csv。', + }, + examples: { curl: '拉取上一个完整小时', json: 'JSON 响应', csv: '下载一页 CSV', python: '用 Python 3 每小时导入' }, + csvHelp: '每页为带 BOM 的 UTF-8 CSV,英文列名和顺序与面板导出一致。首页根据权限确定上游响应模型和缓存命中率两列,后续页沿用该布局。权限收紧时返回 HTTP 409,请丢弃本轮已下载的部分,从首页重读。请求头 Accept-Language: zh 可切换中文计费模式。X-Has-More 为 true 时,使用 X-Next-Cursor 继续请求。合并时只保留一行表头。需要 id 和 request_id 时使用 JSON。', + pythonHelp: '设置 SUB2API_KEY,使用同一 SQLite 文件,定时在每小时第 10 分钟运行。首次拉取上一个完整 UTC 小时,以后从本站、本 Key 上次完整导入的终点向前重叠 2 小时,自动按最多 7 天分段补齐并按 id 去重。SUB2API_USAGE_OVERLAP_HOURS 可调整重叠小时数,SUB2API_USAGE_START(Unix 秒)可指定首次起点。SUB2API_USAGE_URL 应指向最终 HTTPS 地址,遇到重定向会停止导入。', + matchTitle: '关联自己的请求', + match: '同时保存网关响应头 X-Sub2api-Usage-Id 和 X-Request-Id,任一值与 request_id 相同即可对账。普通 HTTP 生成请求(含 Claude、Gemini 和 Antigravity)使用前者,其值为 client: 加 X-Client-Request-ID。OpenAI HTTP 因 cyber_policy 失败但写入用量行时,使用 X-Request-Id 或本地请求 ID。异步生图保存提交时的响应头,每次轮询有独立的 ID。', + exceptions: 'Responses WebSocket 各轮(含 HTTP 经 WebSocket 桥转发)优先使用上游响应 ID,Live 使用通话哈希。批量图片、独立网页搜索、Gemini 显式缓存费用、Grok 音频和实时会话、异步视频使用各自的操作、会话或任务 ID。区域资金计量使用账本事件 ID。响应提供任务或轮次标识时请一并保存。', + reconcileTitle: '每小时对账', + availability: '查询免费。每把 Key 每分钟最多 60 次,同一用户所有 Key 合计每分钟最多 120 次,翻页也计次。HTTP 429 会说明触发了哪一层限流,请按 Retry-After 指定的秒数等待。', + regional: '启用区域鉴权快照的节点返回 HTTP 503,错误码为 REGIONAL_USAGE_RECORDS_UNAVAILABLE。仅启用区域调度预览的节点返回通用 HTTP 503。这两种情况请使用主站地址查询。沿用主库鉴权的区域资金模式可以正常查询。', + delays: '普通请求在转发完成后准备用量行时设置 created_at。长流式请求可能落入下一小时。队列积压和计费恢复会延迟入库,Live 会话按开始时间归档。', + overlap: '翻页期间才入库、排序位置早于当前游标的记录,本轮后续页会跳过。补拉时用同一窗口从首页重读,省略 cursor,按 id 去重。积压恢复后,补拉所有受影响的小时,包括超出日常重叠范围的部分。', + settlement: '这里只返回已写入的用量行。普通失败或未计量且无用量行的请求不会出现。已记录的免费会话或部分策略拒绝可以是零费用。total_cost 为标准价,actual_cost 为记录的实际计费金额。简易模式可只记用量。常规退款和钱包结算凭证单独记录,已入库的该行金额保持原值。', + retention: '历史范围取决于管理员设置的请求日志保留天数。已清理的记录查不到,长期对账请保留本地副本。', +} diff --git a/frontend/src/utils/__tests__/billingMode.spec.ts b/frontend/src/utils/__tests__/billingMode.spec.ts index d7009b0eeaa9..224f8bfe5a74 100644 --- a/frontend/src/utils/__tests__/billingMode.spec.ts +++ b/frontend/src/utils/__tests__/billingMode.spec.ts @@ -3,9 +3,11 @@ import { BILLING_MODE_IMAGE, BILLING_MODE_TOKEN, BILLING_MODE_VIDEO, + getBillingModeLabel, getDisplayBillingMode, isImageUsage } from '../billingMode' +import zhAdminResources from '@/i18n/locales/zh/admin/resources' describe('billingMode helpers', () => { it('prefers explicit video mode over image_count', () => { @@ -24,4 +26,15 @@ describe('billingMode helpers', () => { getDisplayBillingMode({ image_count: 1, billing_mode: BILLING_MODE_TOKEN }) ).toBe(BILLING_MODE_TOKEN) }) + + it('uses the Chinese labels from the user CSV locale', () => { + const t = (key: string) => { + const leaf = key.split('.').pop() as keyof typeof zhAdminResources.usage + return zhAdminResources.usage[leaf] as string + } + expect(getBillingModeLabel(BILLING_MODE_TOKEN, t)).toBe('按量') + expect(getBillingModeLabel('per_request', t)).toBe('按次') + expect(getBillingModeLabel(BILLING_MODE_IMAGE, t)).toBe('按次(图片)') + expect(getBillingModeLabel(BILLING_MODE_VIDEO, t)).toBe('按次(视频)') + }) }) diff --git a/frontend/src/views/user/UsageView.vue b/frontend/src/views/user/UsageView.vue index e99a6c94b8d7..3b1cab2be774 100644 --- a/frontend/src/views/user/UsageView.vue +++ b/frontend/src/views/user/UsageView.vue @@ -1,9 +1,9 @@